content stringlengths 5 1.05M |
|---|
#scrap temptalia brands and check if mongodb has it already, if not insert
from html_scraping import Temptalia_Scrapping
from mongodb import Makeup_MongoDB
from color_analyse import Color_Class
from color_analyse import Color_Analysis
from write_results import Write_Results_Class
from os import system, name
from subpr... |
from abc import ABC, abstractmethod
from typing import NoReturn
class DistributionInterface(ABC):
@abstractmethod
def __init__(self, mean: float, stdev: float, *args, **kwargs):
raise NotImplementedError
@abstractmethod
def __add__(self, other):
raise NotImplementedError
@abstrac... |
from .business_delegate import ServiceDelegate
class Client(object):
def __init__(self, business_delegate: ServiceDelegate):
self.business_delegate = business_delegate
def to_call(self):
return self.business_delegate.to_call()
|
import unittest
from nymms import utils
class TestBase(unittest.TestCase):
def test_load_class_from_string(self):
from logging import Logger
cls = utils.load_object_from_string('logging.Logger')
self.assertIs(cls, Logger)
def test_parse_time(self):
base_time = 1415311935
... |
import csv
import logging
import secrets
import string
from camps.mixins import CampViewMixin
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from django.shortcuts import redirect
from ... |
import csv
import copy
import sys
from Aries.table import TableCSVFile
class VCFVariant:
def __init__(self, chrom, pos, ref, alt, info=None, annotation=None, raw_data=None):
self.chrom = chrom
self.pos = pos
self.ref = ref
self.alt = alt
self.raw_data = raw_data
se... |
#!/usr/bin/python
#By Sun Jinyuan and Cui Yinglu, 2021
import pandas as pd
import argparse
parser = argparse.ArgumentParser(description=
'Process files from previous foldx scan')
parser.add_argument("-sn", '--subdirnum', help="Total number of subdirectories")
parser.add_argument("-fn... |
# Copyright The IETF Trust 2007, 2009, All Rights Reserved
from django.conf import settings
from django.conf.urls import patterns, include, handler500, handler404
from django.contrib import admin
from django.views.generic import TemplateView
from ietf.liaisons.sitemaps import LiaisonMap
from ietf.ipr.sitemaps import ... |
"""Home Assistant Switcher Component."""
from asyncio import QueueEmpty, TimeoutError as Asyncio_TimeoutError, wait_for
from datetime import datetime, timedelta
from logging import getLogger
from typing import Dict, Optional
import voluptuous as vol
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN... |
import tempfile
import numpy as np
import du
from du.numpy_utils import (expand_dim,
memmap_concatenate,
constant_value_array)
from du._test_utils import equal
def test_expand_dim():
z = np.zeros((2, 2))
x = np.arange(4).reshape(2, 2)
assert np.alltr... |
"""cubelab_notebook - Jupyter Notebook-based web frontend for CubeViz operations"""
__version__ = '0.1.0'
__author__ = 'Nicholas Earl <nearl@stsci.edu>'
__all__ = []
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-12 18:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mathswizard', '0030_auto_20180330_1159'),
]
operations = [
mi... |
import copy
import threading
import queue
class SingleTaskListener():
def __init__(self):
self.ev = threading.Event()
def wait(self):
self.ev.wait()
def notify(self, _id, _data):
self.ev.set()
class MultipleTaskListener():
def __init__(self, count):
self.count = 0
self.expected = co... |
from spock.plugins import DefaultPlugins
class PluginLoader:
def __init__(self, client, settings):
self.plugins = settings['plugins']
del settings['plugins']
self.plugin_settings = settings['plugin_settings']
del settings['plugin_settings']
self.announce = {}
self.extensions = {
'Client': client,
'S... |
import json
import os
import confuse
import boto3
from botocore.exceptions import ClientError
from cachetools import Cache
class MissingCredentials(Exception):
"""
Credentials are missing, see the error output to find possible causes
"""
pass
class CredentialProvider:
credentials = None
cach... |
'''Implements the `java_compiler_toolchain` rule.
Java compiler toolchain instances are created with `java_compiler_toolchain`
rule instances. A separate `toolchain` rule instance is used to declare a
`java_compiler_toolchain` instance has the type
`@dwtj_rules_java//java/toolchains/java_compiler_toolchain:toolchain_t... |
# Creating a system of authenticating users based on EEG data collected from the Physionet EEGBCI Dataset
import os
import keras
import mne
from mne.preprocessing import ICA, create_ecg_epochs
from mne import pick_types
from mne.channels import make_standard_montage
from mne.io import concatenate_raws, read_ra... |
import plotly
import plotly.graph_objects as go
import dash
from dash.dependencies import Input, Output, State
import numpy as np
import pandas as pd
import ipdb
from igraph import Graph
import networkx as nx
import colorlover as cl
from itertools import chain, combinations
from collections import Counter, OrderedDict
... |
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
# Generated by Django 2.0.9 on 2018-12-18 13:38
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20181218_0846'),
]
operations = [
migrations.AddField(
model_name='user',
name='a... |
#!/bin/env python
import unittest
from unittest.mock import Mock
from pyats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError,\
SchemaMissingKeyError
from genie.libs.parser.iosxe.show_run import ShowRunPolicyMap, ShowRunInterface
class T... |
import pigpio
import time
import cwiid
import os
import sys
from timeout import timeout, TimeoutError
pi = pigpio.pi()
is_debug = "debug" in sys.argv
class Skateboard(object):
motor = 18
led = 17
button = 27
min_speed = 2000
max_speed = 1000
servo_smooth = 1.8
smooth_sleep = 0.005
accel_sleep = 0.08
def... |
"""
Motion Decoder model for OmniDet.
# author: Varun Ravi Kumar <rvarun7777@gmail.com>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; Authors provide no warranty with the software
and are not liable for anything.
"""
import numpy as np
import torch
import torch.nn as nn
f... |
from argparse import ArgumentParser
from threading import Lock
from queue import Queue
from smartmirror.messages_handler import MessagesHandler
from smartmirror.ui_thread import UiThread
from smartmirror.uc_thread import UcThread
from smartmirror.Logger import Logger, init_logger
"""
Init program properties
- ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019 RedLotus <ssfdust@gmail.com>
# Author: RedLotus <ssfdust@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:/... |
from time import sleep
from time import time
import threading
import pygame
import random
import subprocess
import hashlib
import datetime
from Security.SerialReader import SerialReader
from Security.PhoneDetect import PhoneDetect
from Security.Camera import Camera
from Messenger.Messenger import Messenger
class Secu... |
import numpy as np
import matplotlib.pyplot as plt
plt.figure()
data = np.loadtxt("temperaturas.dat")
plt.show(data)
plt.savefig("calor.png") |
import django.forms as forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext
from django.contrib import admin
from django.template import Template, Context
from polymorphic.admin import (
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, Polymorphi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .dedicated_cloud_node import *
from .dedicated_cloud_service import *
from .get_dedicated_cloud_node i... |
"""Parser for loading config file
"""
import configparser
import os.path
from utils.consts import *
def load_configs(config_file, config_section, config_keys):
"""Loads configurations from config file based on given config section and values
Arguments:
config_file {string} -- configuration sectio... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 22 19:28:35 2021
@author: Arya
"""
# imports
import cv2
import glob
import skimage.transform as trans
import numpy as np
import model
from tensorflow.keras.models import save_model
# loading data
x_train = []
y_train = []
x_test = []
y_test = []
pa... |
from .xpath_condition import XPathCondition
from .xpath_condition_equals import XPathConditionEquals
from .xpath_condition_contains import XPathConditionContains
from .xpath_condition_starts_with import XPathConditionStartsWith
from .xpath_attribute_value import XpathAttributeValue
from .xpath_attribute_value_equals i... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
#!/usr/bin/env python3
import unittest
from text_to_image.utilities import convert_char_to_int
class ConvertCharToIntTestCase(unittest.TestCase):
def test_letters_to_8bit_value(self):
letters = sorted(("a", "b", "c", "i", "h", "o", "v", "x", "y", "q",
"A", "B", "C", "D", "I", "... |
#!/usr/bin/env python3
import random
random.seed(1) # comment-out this line to change sequence each time
# Write a program that stores random DNA sequence in a string
# The sequence should be 30 nt long
# On average, the sequence should be 60% AT
# Calculate the actual AT fraction while generating the sequence
# Repo... |
# -*- coding: utf-8 -*-
"""
Copyright () 2019
All rights reserved
FILE: duration_calculate.py
AUTHOR: tianyuningmou
DATE CREATED: @Time : 2019-06-23 15:49
DESCRIPTION: .
VERSION: : #1
CHANGED By: : tianyuningmou
CHANGE: :
MODIFIED: : @Time : 2019-06-23 15:49
"""
import datetime
from math import *
class Du... |
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
def send_email(user, request, mail_subject, message_template):
current_site = get_current_site(re... |
from __future__ import absolute_import
try:
import tensorflow as tf
except ImportError:
# The lack of tensorflow will be caught by the low-level routines.
pass
class Pyramid(object):
"""A tensorflow representation of a transform domain signal.
An interface-compatible version of
:py:class:`dt... |
#---------------------------
# Title: File orthogrid_op.py
#---------------------------
############################
# IMPORT MODULES
############################
import bpy
from bpy.types import (
Panel,
Operator,
)
from bpy.props import IntProperty, BoolProperty, StringPro... |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 18 12:59:20 2018
@author: gamer
"""
from ale_python_interface import ALEInterface
import utils.env as utils
import numpy as np
import collections
OPTIONS = {"IMAGES_SIZE":(80,80)}
CROP = {"breakout":(32,10,8,8)}
class ALE(ALEInterface):
def __init__(self,game_n... |
import collections
import csv
import os
import re
import subprocess
import sys
import tempfile
def rename_benchmark(bm):
if "hd-d0" in bm:
return "%02d-d0" % int(re.match("\(.+ ([0-9]+)\)", bm).group(1))
elif "hd-d5" in bm:
return "%02d-d5" % int(re.match("\(.+ ([0-9]+)\)", bm).group(1))
el... |
import os
import os.path
import errno
################################################################
def create_dir(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
#######################################################... |
import os, logging, json, threading, pygame, random, math, sys
from random import randint
import punchykickgravityflipwarz.colours
from punchykickgravityflipwarz.sprite_sheet import SpriteSheet
from punchykickgravityflipwarz.entity import Entity
from punchykickgravityflipwarz.vector import Vector
from punchykickgravit... |
import os
import sys
import logging
from typing import Iterable, Type
from types import TracebackType
import discord
def catch_all(type_: Type[BaseException], value: BaseException, traceback: TracebackType) -> None:
# Log an error for Discord
logging.error("Uncaught exception:", exc_info=(type_, value, traceb... |
"""Step definitions for behavioural tests."""
from behave import given, then # pylint:disable=no-name-in-module
@given(u"the user visits {path}")
def visit(context, path):
"""Code for the user visiting a path on the web site."""
url = "http://localhost:8000{}".format(path)
context.response = context.cli... |
import datetime
from bs4 import BeautifulSoup
import utils
import requests
URL = 'https://www.sports-reference.com/cbb/boxscores/index.cgi?month=MONTH&day=DAY&year=YEAR'
DATA_FOLDER = utils.DATA_FOLDER
def scrape_scores(date_obj):
'''
scrape and return stats in the form of a list of lists where each sublist is info... |
# -*- coding: utf-8 -*-
print '-' * 10
print "List"
a = ['0', '1', '2', '3', '4', '5']
print "a = %r" % a
print "len(a) = %r" % len(a)
print "a[0] = %r, %s" % (a[0], a[0])
print "a[-len(a)] = %r, %s" % (a[-len(a)], a[-len(a)])
print "a[0:3] = %r" % a[0:3]
print "a[::2] = %r" % a[::2]
a.append('7')
print "a = %r" % a
... |
#!/usr/bin/env python
"""
Python interface to MAGMA toolkit.
"""
from __future__ import absolute_import, division, print_function
import sys
import ctypes
import atexit
import numpy as np
from . import cuda
# Load MAGMA library:
if 'linux' in sys.platform:
_libmagma_libname_list = ['libmagma.so']
elif sys.plat... |
# Generated by Django 3.2.5 on 2021-08-20 18:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='tGuild_Bank',
fields=[
... |
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from .models import Question, Essay
from .forms import AnswerForm
import joblib
from .utils.helpers import *
import os
current_path = os.path.abspath(os.path.di... |
from django.contrib import admin
from .models import *
admin.site.register(Board)
admin.site.register(Player)
admin.site.register(State)
admin.site.register(Piece)
admin.site.register(Message) |
"""Validation of Yaml configuration files against json schema files.
Typical usage example:
validator = Validator(json_schema_file_object)
validator.validate(yaml_file_object)
"""
import io
import json
import jsonschema
import ruamel.yaml
from ostorlab import exceptions
class Error(exceptions.OstorlabE... |
import fun
import numpy
#-*- coding: utf-8 -*-
"""
算法描述:ISODATA算法:
"""
###预定义数据
#------------------------------------------------
#定义数据集
X = {'X1':(0,0),'X2':(1,1),'X3':(2,2),'X4':(4,3),'X5':(5,3),'X6':(4,4),'X7':(5,4),'X8':(6,5)}
#预期的聚类中心数目
K = 2
#每一聚类域中最少的样本数目
Qn = 1
#一个聚类中样本距离分布的标准差
Qs = 4
#两个聚类中心间的最小距离,若小于,则需要合并
... |
#!/usr/bin/env python3
# Copyright 2020 John Alamina
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED *AS IS* BASIS, ... |
import scrapy
class TmoocSpider(scrapy.Spider):
name = 'tmooc'
allowed_domains = ['tts.tmooc.cn','c.it211.com.cn']
start_urls = ['https://c.it211.com.cn/aid20101106am/aid20101106am.m3u8?_time=1618722481205&sign=87BFA989C7B3E007811E80B4C35C62E4']
def parse(self, response):
pass
|
#coding:utf-8
'''
UDP服务端创建和运行
#coding:utf-8
import socket
#创建Socket,绑定指定的ip和端口
#SOCK_DGRAM指定了这个Socket的类型是UDP。绑定端口和TCP一样。
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('127.0.0.1', 9999))
print('Bind UDP on 9999...')
while True:
# 直接发送数据和接收数据
data, addr = s.recvfrom(1024)
print('Received fro... |
import panflute as pf
from panflute import ( # pylint: disable=unused-import
Null, HorizontalRule, Space, SoftBreak, LineBreak, Str,
Code, BlockQuote, Note, Div, Plain, Para, Emph, Strong, Strikeout,
Superscript, Subscript, SmallCaps, Span, RawBlock, RawInline, Math,
CodeBlock, Link, Image, BulletList,... |
from lxml import etree
from jinja2 import Environment, FileSystemLoader
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import time
def fetch_object(url):
"""
Fetch single BrAPI object by path
"""
print(' GET ' + url)
session = requests.Session()
... |
# -------------------------------------------
# import
# -------------------------------------------
import os
import sys
import re
import codecs
import random
from PIL import Image
import numpy as np
from keras.applications.vgg16 import VGG16, preprocess_input
from keras.preprocessing import image
import matplotlib.py... |
import os
import unittest
from unittest import mock
from core.e2e.validators import masterfile_validator
from core.e2e.handlers.exceptions import MasterFileError
class TestMasterFileValidator(unittest.TestCase):
@mock.patch('os.path')
def test_check_master_file_path(self, mock_os):
mock_os.exists.return_val... |
# -*- encoding:utf-8 -*-
from commands import SelectorMixin, Commands
from ui import component_ui, component_commands
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
# -*- coding: utf-8 -*-
"""
@author: Zheng Fang
This is a unit test. If you would like to further develop pahmc_ode_gpu, you
should visit here frequently.
"""
import os
from pathlib import Path
from numba import cuda, jit
import numpy as np
import torch as th
os.chdir(Path.cwd().parent)
from pahm... |
from django import forms
from database.models import Configuration
from mysite.forms import *
class EmailsForm(forms.ModelForm):
sender_email = forms.CharField(required=False, label="Email para pedidos")
password = forms.CharField(widget=forms.PasswordInput(), required=False, label="Password del email para pe... |
from pyzabbix import ZabbixMetric, ZabbixSender
from pyzabbix.api import ZabbixAPI
import os
import json
# --- config acesso
def config():
configfile_name = "conf/config.json"
# Verifique se já existe um arquivo de configuração
if not os.path.isfile(configfile_name):
print("Arquivo config.j... |
# Generated by Django 3.2.2 on 2021-05-14 04:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0022_urlaction'),
]
operations = [
migrations.AddField(
model_name='coresettings',
name='clear_faults_days',... |
from django import forms
from django.utils.translation import pgettext_lazy
from ....widget.models import Benefit
from ...product.widgets import ImagePreviewWidget
from ....widget.thumbnails import create_benefit_thumbnails
class BenefitForm(forms.ModelForm):
class Meta:
model = Benefit
fields = ... |
from django.contrib.auth.models import User
from django.db import models
from products.models import Product
class CartManager(models.Manager):
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
qs = Cart.objects.filter(id=cart_id)
if qs.count()==1:
new_obj = False
cart_obj = q... |
from filter_tokens import filter_tokens
def test_filter_tokens():
filtd = filter_tokens(['\\int', '\\text', '{', 'x', '}', '\\text', '{', 'h', 'i', 't', 'h', 'e', 'r', 'e', '}', 'x', '+', 'y'])
assert filtd == ['\\int', '\\text', '{', 'x', '}', 'x', '+', 'y']
s = "b_1(u) = \\frac{1 - u q^{1/2} }{1 - u q^{-1/2}} \m... |
# coding: utf-8
#
# This file is part of Sequana software
#
# Copyright (c) 2016 - Sequana Development Team
#
# File author(s):
# Dimitri Desvillechabrol <dimitri.desvillechabrol@pasteur.fr>,
# <d.desvillechabrol@gmail.com>
#
# Distributed under the terms of the 3-clause BSD license.
# The full licen... |
#!/bin/python
import numpy as np
import MDAnalysis
import time
import math
import sys
#Timing
start = time.time()
#Input values
topo = "ADI.prmtop"
traj=[]
for i in range(30):
traj.append("belly/ADI.belly{:02d}.xyz.nc".format(i))
rMax=12.
binSize=0.1
d0=0.09
#Read in atom type
fcrd=open("ADI.crd","r")
l=fcrd.re... |
#!/usr/bin/env python
#
# wamplite is free software; you can redistribute it and/or modify
# it under the terms of the MIT license. See LICENSE for details.
#
import wamplite
import logging
import sys
import threading
import time
import websocket
# Connection & authentication details. Use ws:// for websocket, or ws... |
import argparse
import os
import sys
import torch
from torch import nn, optim
from torch.optim import optimizer
from torchvision import datasets, models, transforms
parser = argparse.ArgumentParser(description="Trains a neural network")
parser.add_argument('data_dir', metavar='dir', type=str,
help... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from brainstorm.tests.test_layers import (
spec_list, test_deltas_calculation_of_layer, test_layer_add_to_deltas,
test_layer_backward_pass_insensitive_to_internal_state_init,
test_layer_forward_pass_insen... |
def roboVet(modShift):
"""Run the Model-Shift test
Inputs:
-------------
modshift
The dictionary returned by ModShift.runModshift
Returns:
-------------
A dictionary containing the following keys:
disp
The disposition of the DOI --- either "candidate" or "false positiv... |
import logging
from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from pydantic import BaseModel
from jose import JWTErro... |
try:
from . import generic as g
except BaseException:
import generic as g
class RasterTest(g.unittest.TestCase):
def test_rasterize(self):
p = g.get_mesh('2D/wrench.dxf')
origin = p.bounds[0]
pitch = p.extents.max() / 600
resolution = g.np.ceil(p.extents / pitch).astype(i... |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import app, gl, glo... |
import os
import weakref
__version__ = "0.0.2"
def formatted_value(value, array=True):
"""Format a given input value to be compliant for USD
Args:
array (bool): If provided, will treat iterables as an array rather than a tuple
"""
if isinstance(value, str):
value = '"{}"'.format(val... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.login_index, name='login_index'),
path('register', views.register, name='register'),
path('logout', views.user_logout, name='user_logout'),
] |
import numpy as np
from collections import OrderedDict
from os import path
def load(filename, max_rank=None, vocabulary=None):
"""Load word vector data.
Args:
filename: name of file to load.
max_rank: maximum number of embeddings to load (None for no limit)
vocabulary: words to load e... |
import reversion
from django.db import models
from django.core.exceptions import ValidationError
from .tracked_model import TrackedModel
from .derived_sample import DerivedSample
from ._utils import add_error as _add_error
__all__ = ["DerivedBySample"]
@reversion.register()
class DerivedBySample(TrackedModel):
... |
import os
from mai.adsorbate_constructor import adsorbate_constructor
from ase.io import read, write
starting_mof_path = os.path.join('example_MOFs','Ni-BTP.cif') #path to CIF of MOF
#Get all Ni indices in ASE Atoms object of MOF
start_mof = read(starting_mof_path)
Ni_idx = [atom.index for atom in start_mof if atom.s... |
import pandas as pd
df_input_food = pd.read_csv("input_food.csv")
print(df_input_food.head())
df_food = pd.read_csv("food.csv")
print(df_food.describe())
print(df_food.head())
|
# -*- coding: utf-8 -*-
"""Wavefront Python SDK.
This library provides support for sending metrics, histograms and opentracing
spans to Wavefront via proxy or direct ingestion.
@author Hao Song (songhao@vmware.com)
"""
import pkg_resources
from .direct import WavefrontDirectClient
from .proxy import WavefrontProxyC... |
from functools import wraps
def ints_only(func):
@wraps(func):
def wrapper(*args, **kawrgs):
args = [int(x) for x in args]
kwargs = {n: int(v)
for n, v
in kwargs.items()}
return func(*args, **kwargs)
return wrapper
@ints_only
def add(left, right)... |
from rest_framework import serializers
from clientes.models import Cliente
from .validators import *
class ClienteSerializer(serializers.ModelSerializer):
class Meta:
model = Cliente
fields = '__all__'
# primeiro modo de fazer validações
def validate(self, data):
if not cpf_valido... |
"""Fetch weather information
Usage:
weather (-h | --help)
weather [--country=COUNTRY] <city>
Options:
-h, --help Show a brief usage summary.
--country=COUNTRY Restrict cities to an ISO 3166 country code.
An OpenWeatherMap API key MUST be provided via the OPENWEATHERMAP_KEY environment variable.
"""
... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""Define a common data structure to represent external packages and a
function to update packages.yaml given a list of det... |
import os
import torch
torch.manual_seed(int(os.environ.get('SPLINE_MANUAL_SEED', 7)))
|
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(UserRole)
admin.site.register(RoleType)
admin.site.register(UserDetail)
admin.site.register(Question)
admin.site.register(Choice)
admin.site.register(School)
admin.site.register(School_post)
admin.site.register(Car_... |
import json, datetime, time
import jwt
import hashlib
import time
import os, sys, base64
import uuid
from .sql import sql
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors
from reportlab.lib.units import ... |
from decimal import Decimal
import pytest
from bitcart.utils import bitcoins, convert_amount_type, satoshis
@pytest.mark.parametrize("btc,expected", [(0.1, 10000000), (1, 100000000), (0.00000001, 1), (5, 500000000)])
def test_satoshis(btc, expected):
result = satoshis(btc)
assert isinstance(result, int)
... |
import tnetwork as dn
import os
import subprocess
import time
###############################
######For this class, it is necessary to have Matlab installed
######And to set up the matlab for python engine, see how to there
###### https://fr.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-pyt... |
# coding=utf-8
# Copyright 2018 The Microsoft Research Asia LayoutLM Team Authors, The Hugging Face Team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import time
import threading
class Philosopher(threading.Thread):
def __init__(self, name, leftFork, rightFork):
print("{} Has Sat Down At the Table".format(name))
threading.Thread.__init__(self, name=name)
self.leftFork = leftF... |
"""
Minimum Description Length Principle (MDLP) binning
- Original paper: http://sci2s.ugr.es/keel/pdf/algorithm/congreso/fayyad1993.pdf
- Implementation inspiration: https://www.ibm.com/support/knowledgecenter/it/SSLVMB_21.0.0/com.ibm.spss.statistics.help/alg_optimal-binning.htm
"""
import collections
import math
i... |
import os
import numpy as np
import random
import argparse
import json
def check_info_all(annotations):
print("Element 0: ", annotations[0])
print("Keys of 0 -> end: ", annotations[1].keys())
print("The whole of annotations: ", annotations )
# for annotation in annotations:
# print(type(annotat... |
from .Adding_Simple import AddSimple
from .Criteria import ArgsCriteria
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.