text
string
size
int64
token_count
int64
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 11 21:36:32 2021 @author: rachel """ import numpy as np from scipy import interpolate import matplotlib.pyplot as plt def interpolateMetm(uxsg, ufsg, uxl, ufl, m, M, fact1, fact2): #%%%%% interpolate on [m,M]; xss = uxsg yss = ufsg ...
2,008
985
import os import sys import codecs import itertools sys.stdout = codecs.getwriter('utf=8')(sys.stdout.buffer) sys.stderr = codecs.getwriter('utf=8')(sys.stderr.buffer) fname = os.sep.join(["D:", "Users", "Warren", "python3", "squirrels_on_caffeine", "src", "sedecordle", "answ...
3,036
1,083
# Generated by Django 2.2.4 on 2019-08-04 21:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('jobHistory', '0002_auto_20190106_0202'), ] operations = [ migrations.AlterField( model_name='em...
9,491
2,675
from Logic.Data.DataManager import Writer from Logic.Client.ClientsManager import ClientsManager class LobbyInfoMessage(Writer): def __init__(self, client, player): super().__init__(client) self.id = 23457 self.client = client self.player = player def encode(self): self...
518
166
from django.shortcuts import render from django.http import HttpResponse from article.models import Article from datetime import datetime # Create your views here. def home(request): post_list = Article.objects.all() #获取全部的Article对象 return render(request, 'home.html', {'post_list' : post_list}) def detail(re...
1,560
500
#Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. #O programa será interronpido quando o número solicitado for negativo. c = 0 while True: print(30*'-') num = int(input('Quer ver a tabuada de qual valor ?')) print(30*'-') if num < 0: ...
405
150
#!/usr/bin/env python # -*- encoding: utf-8 -*- # copyright 2016 twitter. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2...
1,251
425
import os class Config: data_dir = os.path.abspath('../data/input/') models_dir = os.path.abspath('../models') logs_dir = os.path.abspath('../logs') train_data_dir = os.path.abspath('../data/input/train_images') test_data_dir = os.path.abspath('../data/input/test_images') num_epochs = 15 l...
534
236
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('midburn', '0006_auto_20160116_0842'), ] operations = [ migrations.AlterField( model_name='camp', nam...
1,265
373
from bs4 import BeautifulSoup import requests text = input("text : ") text.replace(" ", "+") params = {"q": text} content = requests.get("https://duckduckgo.com/?q=", params=params) soup = BeautifulSoup(content.text, 'html.parser') res = soup.find_all('div', class_="result__snippet js-result-snippet") for r in res: ...
329
118
import sys #### CONFIG OPTIONS # replicates = 50 #Will be dynamically determined roll_q_dir = './' if len(sys.argv) < 2: print('Must pass one argument, the number of jobs in the queue!') exit(-1) jobs_in_queue = int(sys.argv[1]) if len(sys.argv) >= 3: roll_q_dir = sys.argv[2] do_resub = True if le...
2,771
1,055
# Generated by Django 2.0.4 on 2018-05-08 12:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('courses', '0013_auto_20180426_0754'), ('exercises', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='GeneralE...
390
150
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import Http404 from infinite_scroll_pagination.paginator import SeekPaginator, EmptyPage def paginate(request, query_set, lookup_field, per_page=15, page_var='value'): # TODO: remove page_pk = request.GET.get(page_var, None) ...
777
277
# encoding: utf-8 """ configuration.py Created by Thomas Mangin on 2011-11-29. Copyright (c) 2011-2013 Exa Networks. All rights reserved. """ # NOTE: reloading mid-program not possible import os import sys import logging import pwd import math import socket import struct _application = None _config = None _defaul...
10,172
3,978
from typing import AnyStr from typing import NoReturn class Error(Exception): """ This is the basis of all errors.\n Basically the same as Exception. """ def __init__(self, msg: AnyStr) -> NoReturn: self.msg: str = msg def __str__(self) -> str: return self.msg class FileExt...
1,009
409
# -*- coding: utf-8 -*- from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score from sklearn.ensemble import AdaBoostClassifier iris = load_iris() clf = AdaBoostClassifier(n_estimators=1000) scores = cross_val_score(clf, iris.data, iris.target) print scores.mean()
301
112
import os import sys import time from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys class IndeedBot: def __init__(self): """ Initilializes the Chrome webdriver. Sets the job search quer...
4,720
1,489
import traceback from pycompss.api.task import task from pycompss.api.constraint import constraint from pycompss.api.parameter import FILE_IN, FILE_OUT from biobb_common.tools import file_utils as fu from biobb_md.gromacs_extra import append_ligand import os import sys @constraint(computingUnits="1") @task(input_top_z...
1,266
431
import requests import json from pprint import pprint import re import time import sys #getdata = requests.get(geturl) #pprint (vars(getdata)) from bs4 import BeautifulSoup from geopy.geocoders import Nominatim if len(sys.argv) != 4: print(sys.argv[0]+" <item> <location> <num items>") exit() #get list of prod...
3,277
1,244
from __future__ import print_function import numpy as np from copy import copy import torch import torch.nn.functional as F from torch.autograd import Variable import torch.nn as nn def apply_var(v, k): if isinstance(v, Variable) and v.requires_grad: v.register_hook(inves(k)) def apply_dict(dic): fo...
5,670
1,985
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Feb 19 20:41:09 2017 @author: pd """ #from IPython import get_ipython #get_ipython().magic('reset -sf') import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier X, Y = datasets.make_classification(n...
776
350
# -*- coding: utf-8 -*- # Copyright (c) 2015, Neil Lasrado and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils import now class MonthlyReport(Document): def on_submit(self): self.date =...
327
105
""" Fragments of project version mutations """ PROJECT_VERSION_FRAGMENT = ''' content id name projectId '''
109
39
# Code apapted from https://github.com/mseitzer/pytorch-fid """Calculates the Frechet Inception Distance (FID) to evalulate GANs The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while the 2nd dist...
6,037
1,865
from flask import Flask, current_app, request, Request app = Flask(__name__) ctx = app.app_context() ctx.push() current_app.static_floder = 'static' ctx.pop() app.run
169
62
import scipy.ndimage import cv2 import numpy as np class flip_augmentation(object): def __init__(self, chance=0.5, image_x_axis=-1, semantics_x_axis=-1): ''' The standard parameters will flip the image along the x axis, assuming a 'bc01' format for the image and a 'b01' format for ...
4,108
1,409
# -*- coding: utf-8 -*- # # Copyright (c) 2016 Juniper Networks, Inc. All rights reserved. # from __future__ import unicode_literals from builtins import str from builtins import range import logging from netaddr import IPNetwork from random import randint, choice import uuid from .resource import Resource from ..util...
9,653
2,607
from flask import Blueprint bp = Blueprint('admin', __name__) @bp.record_once def register(state): from sopy.admin import views
135
44
import os import torch from torch.utils import cpp_extension from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension # ninja build does not work unless include_dirs are abs path this_dir = os.path.dirname(os.path.abspath(__file__)) cc_flag = [] ext_modules = [] cc_flag.append(...
1,790
672
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-24 23:01 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depe...
5,708
1,599
"""ЗАДАЧА: Разгледайте дадения по-долу код и направете необходимите промени, така че след приключването на двата процеса променливата x да има стойност 20. Използвайте multiprocessing.Queue() за да обмените текущата стойност на x между процесите. """ import multiprocessing as mp def increment(r): global x for ...
800
327
numero_int = input('Digite um numero inteiro') if numero_int.isdigit(): numero_int = int(numero_int) if numero_int % 2 == 0: print('o numero e par') elif numero_int % 1 == 0: print('o numero e impar') else:
241
88
"""Ejercicio Decimal a Binario """ import math numero = int(input('Ingresa un número: \n')) binario = '' while (numero > 0): if (numero%2 == 0): binario = '0' + binario else: binario = '1' + binario numero = int(math.floor(numero/2)) print(f'El número en binario es {binario...
327
137
import flask ; from flask import * def Serve(email_form, password_form, rd, dic, host="0.0.0.0", port="8080"): app = Flask(__name__, template_folder="../clone") # login storage class Login: email = "" pwd = "" ip = "" # forms @app.get("/") def index(): retu...
743
251
from django.contrib import admin from .models import Block @admin.register(Block) class ActionAdmin(admin.ModelAdmin): list_filter = ('created',)
152
44
import re,io,os.path,os def remove_tag(str): alldigit = re.compile(r"^<.+") if alldigit.search(str) != None: return False return True for line in open('./../text_list', "r"): filename = './../TXT/tragedies/'+line.rstrip() print filename f = open("./../TXT/test_"+line.rstrip(),"w") ...
593
222
def TestInstall(): from ..base import DeltaBasisFeatures, TriangBasisFeatures, HistBasisFeatures from ..models import PoissonElasticNet from ..model_selection import PoissonElasticNetCV from ..simulator import StretchedExponentialDistribution, Simulator import numpy as np # generate st_exp...
1,736
650
from flask import Flask from flask import request app = Flask(__name__) @app.route("/readCookie") def readCookie(): print(request.cookies) print(request.cookies.get('MyCookie')) return "hello world" @app.route("/writeCookie") def writeCookie(): response = app.make_response('write cookie') respo...
422
141
import torch import torch.nn as nn import numpy as np import cv2 import os import shutil from matplotlib import pyplot as plt from Model_Definition import VC3D from mypath import NICKNAME, DATA_DIR, PATH # TODO: Now can display images with plt.show(), need to solve display on cloud instance OUT_DIR = PATH + os.path....
3,691
1,355
text = input() punc_remove = [",", ".", "!", "?"] for i in punc_remove: text = text.replace(i, "") print(text.lower())
123
50
import logging import re import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2CallbackView, OAuth2LoginView, ) from allauth.socialaccount.providers.salesforce.views import ( SalesforceOAuth2Adapter as SalesforceOAuth2BaseAdapter, ) from allauth.utils import get_request_param fro...
5,519
1,695
''' Student: Dan Grecoe Assignment: Homework 1 Submission of the first homework assignment. The assignment was to create a python file with 2 functions multiply - Takes two parameters x and y and returns the product of the values provided. noop - Takes 0 parameters and returns...
475
130
""" Copyright 2016 Platform9 Systems Inc. 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. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
31,533
10,232
#!/usr/bin/env python # this script runs all examples and checks that they all # run without throwing an exception from __future__ import print_function import os import sys from glob import glob import subprocess as subp from datetime import timedelta from timeit import default_timer as timer # Modify the following t...
3,132
1,236
# Copyright (c) 2012-2018, NECOTIS # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, # this list of conditions and th...
5,888
1,973
# -*- coding: utf-8 -*- # # Copyright (C) 2014-2020 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://trac.edgewall.org/wiki/TracLicense. # # This soft...
2,007
664
import torch import Network import Network_res3d from data_handler import * import cProfile import io import pstats parser = utils.create_parser() args = parser.parse_args() def worker_init_fn(worker_id): np.random.seed(np.random.get_state()[1][0] + worker_id) def main(): # read json return config = ut...
5,814
1,724
# `name` is the name of the package as used for `pip install package` name = "package-name" # `path` is the name of the package for `import package` path = name.lower().replace("-", "_").replace(" ", "_") version = "0.1.0" author = "Author Name" author_email = "" description = "" # summary license = "MIT"
308
99
"""Transform signaling data to smoothed trajectories.""" import sys import numpy import pandas as pd import geopandas as gpd import shapely.geometry import matplotlib.patches import matplotlib.pyplot as plt import mobilib.voronoi SAMPLING = pd.Timedelta('00:01:00') STD = pd.Timedelta('00:05:00') def smoothen(arr...
1,826
701
#!/usr/bin/env python import logging import logging.handlers import os # Logging to file dir_path = os.path.dirname(os.path.realpath(__file__)) logging.basicConfig(filename=dir_path + "/test.log", format='%(asctime)s - %(message)s', level=logging.INFO, filemode='w') # Logging messages to the console console = loggin...
440
143
import os from slack_sdk.web import WebClient from slack_sdk.socket_mode import SocketModeClient # Initialize SocketModeClient with an app-level token + WebClient client = SocketModeClient( # This app-level token will be used only for establishing a connection app_token=os.environ.get("SLACK_APP_TOKEN") # ...
1,556
439
import os import time import random import logging import torch import numpy as np import yaml from easydict import EasyDict from logging import Logger from tqdm.auto import tqdm class BlackHole(object): def __setattr__(self, name, value): pass def __call__(self, *args, **kwargs): return self ...
1,968
687
from idbase.api import RESTDispatch, LoginStatus from idbase import exceptions from django.http import HttpResponse from mock import MagicMock import pytest import json @pytest.fixture def req(rf): request = rf.get('/') request.user = MagicMock() request.user.is_authenticated.return_value = True retur...
2,928
946
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your o...
5,885
1,744
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Author @55-AA 19 July, 2016 ''' import copy def gcd(a, b): """ Return the greatest common denominator of integers a and b. gmpy2.gcd(a, b) """ while b: a, b = b, a % b return a def lcm(a, b): return a * b / (gcd(a, b)) def egcd(a, b)...
14,165
6,638
#!/usr/bin/env python # -*- coding:utf8 -*- import sys import argparse from lantis.webradio.commands import bind_subparsers parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() bind_subparsers(subparsers) def main(argv=None): if argv is None: argv = sys.argv[1:] args = parser.pars...
451
164
from typing import List, Dict from datetime import datetime import numpy as np from vnpy.app.portfolio_strategy import StrategyTemplate, StrategyEngine from vnpy.trader.utility import BarGenerator, ArrayManager from vnpy.trader.object import BarData from vnpy.trader.constant import Interval class AmplitudeVolitilit...
6,304
2,163
# Pathfinding algorithm. import pygame import random class HotTile( object ): def __init__( self ): self.heat = 9999 self.cost = 0 self.block = False class HotMap( object ): DELTA8 = [ (-1,-1), (0,-1), (1,-1), (-1,0), (1,0), (-1,1), (0,1), (1,1) ] EXPENSIVE = 9999 def __init__...
7,065
2,487
import json import jsonpickle from pprint import pprint class Object(object): pass prods = Object() prods.accountId="5c76ae99c6489f0001bc6b0a" prods.locationId="5db938536d49b300017efcc3" prods.products=[] prods.categories=[] with open ('pl.json', 'r') as f: products_dict = json.load(f) for item in product...
960
376
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-18 04:11 from __future__ import unicode_literals import CareerTinder.listfield from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('CareerTinder', '0001_initial'), ] operations = [ ...
2,489
740
class TestClient: """ Test before_request and after_request decorators in __init__.py. """ def test_1(self, client): # disallowed methods res = client.put("/") assert res.status_code == 405 assert b"Method Not Allowed" in res.content res = client.options("/api/post/add...
910
284
import datetime import logging import json from cadence.activity import ActivityContext from cadence.cadence_types import PollForActivityTaskRequest, TaskListMetadata, TaskList, PollForActivityTaskResponse, \ RespondActivityTaskCompletedRequest, RespondActivityTaskFailedRequest from cadence.conversions import json...
4,259
1,077
#!/usr/bin/env python3 # import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import argparse import datetime import time import requests import Libraries.arguments as ar import Classes.AppConfig as AppConfig import Classes.LiteClient as LiteClient import Classes.TonNetwo...
3,666
1,188
# Copyright 2020 Toyota Research Institute. All rights reserved. # Adapted from Pytorch-Lightning # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/loggers/wandb.py from argparse import Namespace from collections import OrderedDict import numpy as np import torch.nn as nn import w...
8,324
2,363
from tkinter import * from tkinter import ttk import numpy as np from PIL import ImageGrab from PIL import Image from pytesseract import * import re import cv2 from googletrans import Translator as google_translator from pypapago import Translator as papago_translator from kakaotrans import Translator as kakao_translat...
5,781
2,242
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 3 17:20:06 2018 @author: chrispedder A routine to crop sections from the images of different manuscripts in the two datasets to the same size, and with the same magnification, so that the average script size doesn't create a feature that the neura...
7,869
2,424
from typing import Optional, Union, List, Dict # local import ivy from ivy.container.base import ContainerBase # noinspection PyMissingConstructor class ContainerWithGradients(ContainerBase): @staticmethod def static_optimizer_update( w, effective_grad, lr, inplace=None, ...
7,934
2,584
from __future__ import with_statement from contextlib import contextmanager from test import TemplateTest, eq_, raises, template_base, mock import os from mako.cmd import cmdline class CmdTest(TemplateTest): @contextmanager def _capture_output_fixture(self, stream="stdout"): with mock.patch("sys.%s" % ...
2,848
918
import uuid from django.db import models class Module(models.Model): """ Defines the information related to the application module that is stored to the database, not as a Django application """ uuid = models.UUIDField(db_index=True, editable=False, primary_key=True, default=uuid.uuid4, ...
1,920
467
from LightPipes import * import matplotlib.pyplot as plt def TheExample(N): fig=plt.figure(figsize=(11,9.5)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) labda=1000*nm; size=10*mm; f1=10*m f2=1.11111111*m z=1.0*...
1,986
1,027
from delira import get_backends as _get_backends if "CHAINER" in _get_backends(): from delira.models.backends.chainer.abstract_network import \ AbstractChainerNetwork from delira.models.backends.chainer.data_parallel import \ DataParallelChainerNetwork from delira.models.backends.chainer.da...
598
175
import re for train in [2, 4, 8]: for test in [8, 64]: for mode in ["train", "test", "dev"]: with open("train{}_test{}/{}.txt".format(train, test, mode)) as f: text = f.read() matches = re.findall("\[([0-9 ]*)\]\t\[([0-9 ]*) (\d) (\d*)\]", text) text = li...
1,071
332
import re import requests from bs4 import BeautifulSoup import time from urllib import parse from selenium import webdriver from location.models import Pension, RoomImage, PensionImage, Room, Location, SubLocation # 가격에 string, 100,00 표현 맞지 않는 경우 0넣고 아니면 int로 바꿔서 출력 def get_int_only(string): a= re.findall( '(\d*...
16,519
7,152
from argparse import ArgumentParser from ucca import constructions from ucca.ioutil import read_files_and_dirs if __name__ == "__main__": argparser = ArgumentParser(description="Extract linguistic constructions from UCCA corpus.") argparser.add_argument("passages", nargs="+", help="the corpus, given as...
1,181
343
import hashlib import os import pickle import tempfile import zlib from threading import Lock from time import time from multicache.base import BaseCache try: from multicache.redis import RedisCache except ImportError: pass lock = Lock() class DummyCache(BaseCache): """ Fake cache class to allow a "no c...
3,870
1,154
x = 1 #x recebe 1 #print irá printar(mostrar) o valor desejado; print(x) # resultado: 1 print(x + 4) # é possível somar uma variável com um número, desde que a variável tenha um valor definido - resultado: 5 print(2 * 2) #um asterisco é usado para multiplicar - resultado: 4 print(3 ** 3) #dois asterisco é usado para el...
754
289
# -*- coding: utf-8 -*- # Copyright 2016 Yelp Inc. # # 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 ag...
3,648
999
# -*- coding: utf-8 -*- from collections import OrderedDict from gluon import current from gluon.storage import Storage def config(settings): """ Template for WA-COP + CAD Cloud Integration """ T = current.T # ========================================================================= # S...
50,707
12,132
import kivy from kivy.app import App from kivy.uix.button import Button import android import os import time from android.permissions import Permission, request_permission, check_permission from kivy.clock import Clock class MyApp(App): def second_thread(self, data): print("starting second thread") ...
1,185
359
""" 继承调用关系 """ class A: def a_say(self): print('执行A:', self) class B(A): def b_say(self): A.a_say(self) # 效果与下面的语句相同 super().a_say() # super()方法调用父类的定义, # 默认传入当前对象的引用self A().a_say() # 类对象的直接使用,先创建一个类对象A print('执行B:', self) a = A() b = B() a.a_say()...
401
247
#!/usr/bin/env python # Copyright (C) 2015 Swift Navigation Inc. # Contact: https://support.swiftnav.com # # This source is subject to the license found in the file 'LICENSE' which must # be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WA...
8,852
3,031
import argparse ''' Example commands for the command line: - Select directory to save checkpoints in: python train.py data_directory --save_dir save_directory - Select training architecture: python train.py data_directory --arch "densenet121" - Set hyperparameters: python train.py data_directory --learning...
2,453
712
''' Created on Jun 23, 2015 @author: alexandru-m-g ''' import logging import mock import ckan.model as model import ckan.common as common import ckan.lib.helpers as h import ckan.lib.mailer as mailer import ckanext.hdx_users.controllers.mailer as hdx_mailer import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_b...
12,878
4,281
from datetime import timedelta import random from django.utils import timezone import factory class BulletinFactory(factory.DjangoModelFactory): class Meta: model = 'bulletin.Bulletin' url = factory.Sequence(lambda n: f'https://www.sitepage.com/{n}') latitude = factory.Faker( ...
1,044
365
# -*- coding: utf-8 -*- import numpy as np def pz_theta_model(x, theta_r): # x can be np.array of size 2 or a list of two np.array x1 and x2 # x = x[0] a = theta_r[0] b = theta_r[1] pyx = np.exp(x)/(1+np.exp(x))*0.6+0.2 #average center cx = a*np.exp(-x**2)+b*(np.exp(-(x-4)**2)+np.exp(-(x...
792
375
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # python3 -m pip install --force -U --user PlexAPI """ Metadata to be handled: * Audiobooks * Playlists -- https://github.com/pkkid/python-plexapi/issues/551 """ import copy import json import time import logging import collections from urllib.parse import urlparse ...
14,153
4,547
from datetime import datetime from decimal import Decimal from src.models import db, Required, Optional class Product(db.Entity): name = Required(str, unique=True) price = Required(Decimal) description = Optional(str) create_time = Required(datetime, default=datetime.now, precision=6) update_time...
414
118
#!/usr/bin/env python3 from .color import Color import shutil import os std_none = "#FF000000" class Themer: def __init__(self, primary=std_none, secondary=std_none, accent=std_none, mode=None, ttype="dark"): self.primary = Color(primary) self.ttype = ttype if mode is No...
32,397
9,709
class Graph(object): """ A simple undirected, weighted graph """ def __init__(self): self.nodes = set() self.edges = {} self.distances = {} def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): ...
2,081
681
class Config(object): """Configuration primitives. Inherit from or instantiate this class and call configure() when you've got a dictionary of configuration values you want to process and query. Would be nice to have _expand_cidrlist() so blacklists can specify ranges. """ def __init__(self, ...
3,063
845
import _plotly_utils.basevalidators class ConstraintowardValidator( _plotly_utils.basevalidators.EnumeratedValidator ): def __init__( self, plotly_name='constraintoward', parent_name='layout.xaxis', **kwargs ): super(ConstraintowardValidator, self).__init__( ...
662
190
""" Testing group-level finite difference. """ import unittest import numpy as np from openmdao.components.param_comp import ParamComp from openmdao.core.component import Component from openmdao.core.group import Group from openmdao.core.problem import Problem from openmdao.test.converge_diverge import ConvergeDiverg...
4,057
1,308
from __future__ import absolute_import import ujson from rsbroker.core.upstream import RTCWebSocketClient class BaseUserManager(object): room_to_uid = {} uid_to_handler = {} def register(self, obj): """ Dispatch all resource which user need! :param obj: :return: "...
2,235
651
from pgm.pgmplayer import PGMPlayer import cps_constraints as con from operator import itemgetter import uuid import os class ConstraintSolver: def __init__(self, my_con_collector, my_con_scoper, SHOULD_USE_CONSTRAINT_SCOPING=False): self.con_collector = my_con_collector self.con_scoper = my_con_s...
12,756
3,971
import numpy as np import itertools as it from funkyyak import grad from copy import copy def nd(f, *args): unary_f = lambda x : f(*x) return unary_nd(unary_f, args) def unary_nd(f, x): eps = 1e-4 if isinstance(x, np.ndarray): nd_grad = np.zeros(x.shape) for dims in it.product(*map(ran...
1,901
737
import time import random import pygame import pygame.midi import numpy as np from typing import Tuple __author__ = "Thomas Heller" AV_SIZE = 20 WIN_X = 30 * AV_SIZE WIN_Y = 30 * AV_SIZE DIFF_MAX = np.sqrt(WIN_X**2 + WIN_Y**2) def adapt_avatar_position(event, user_x_pos:int, user_y_pos:int) -> Tuple[int, int]...
2,772
1,033
from typing import Dict, List def match(string, candidates) -> str: for c in candidates: if c[0].lower() in string.lower() or c[1].lower() in string.lower(): return c for c in candidates: if string.lower() in c[0].lower() or string.lower() in c[1].lower(): return c ...
4,806
1,531
#!/usr/bin/python # -*- coding: utf-8 -*- # # FILE: Update.py # # This class provides mechanisms to update, reply to, retweet status # messages and send direct messages # # Copyright by Author. All rights reserved. Not for reuse without # express permissions. # import sys, time, json, logging from sochi.twit...
12,181
3,641
# coding=utf-8 from __future__ import unicode_literals, absolute_import from datetime import datetime from pytz import UTC from dateutil.parser import parse fmt = '%Y-%m-%d %H:%M:%S' utc_fmt = "%Y-%m-%dT%H:%M:%SZ" def get_utcnow(): at = datetime.utcnow() at = at.replace(tzinfo=UTC) return at def isotime...
654
263
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Build Geo Database for PaisajesSonorosTB ---------------------------------------- This script compiles output from multiple scripts that should be executed previously: - audio_metadata - acoustic_indices - graphical_soundscapes - soundscape_composition...
5,612
1,972