text
string
size
int64
token_count
int64
import redis def set(key, value, expired): #use None if don't want to use expired time try: r = redis.Redis() r.set(name=key, value=value, ex=expired) return True, None except Exception as e: return False, f'{e}' def get(key): #key to get value r = redis.Redis() ...
526
176
from pyftdi.spi import SpiController from pyftdi.gpio import GpioSyncController import serial import time import sys import JSONFile dbg = False def createByteList(addrList, dataList): newBytes = [] for byte in addrList: newBytes.append(byte) for byte in dataList: newBytes.append(byte) ...
18,185
5,594
from morepath import redirect from onegov.core.security import Private from onegov.gazette import _ from onegov.gazette import GazetteApp from onegov.gazette.forms import EmptyForm from onegov.gazette.layout import Layout from onegov.user import UserGroup from onegov.user import UserGroupCollection from onegov.user.for...
3,417
1,022
from . import utils from . import pth from . import proc from . import log from . import json from . import time from . import importer
136
39
import numpy as np class SimpleFourierFilter(object): """ Class to apply simple Fourier Filtration to a vector Filter types: 'fraction' (requires kwarg: 'fraction' to be set) 'rule 36' (can set kwarg: 'power' but not necessary) """ def __init__(self, modes, filter_type, **kwargs):...
1,466
479
# ---------------------------------------------------------------------------- # Copyright (c) 2020 Legorooj <legorooj@protonmail.com> # Copyright (c) 2020 FluffyKoalas <github.com/fluffykoalas> # This file and all others in this project are licensed under the MIT license. # Please see the LICENSE file in the root of t...
1,178
404
import netifaces import argparse import os import zmq import threading def recieve(message): ctx = zmq.Context.instance() reciever = ctx.socket(zmq.SUB) for last in range(1, 255): reciever.connect("tcp://{0}.{1}:9000".format(message, last)) reciever.setsockopt(zmq.SUBSCRIBE, b'') while T...
1,385
478
class PlayerProfile: def __init__(self, id): self.cities = [] self.resources = { "SHEEP": 0, "WOOD": 0, "WHEAT": 0, "CLAY": 0, "IRON": 0 } self.current_builder_intersection_position_id = None self.id = id sel...
1,822
538
a = [1, 2, 3] b = a a[0] = 'gouliguojiashengsiyi' print('a =', a) print('b =', b)
83
51
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Time : 2021/12/1 13:27 import numpy as np from numpy import random import matplotlib.pyplot as plt from trajectory import Trajectory from rnd import stable_rnd, skewed_stable_rnd class CTRW(Trajectory): def __init__(self, t_len, ind_waiting, ind_jump, init_positi...
2,267
882
import aiofiles import asyncstdlib from pydantic.types import PositiveFloat from conversion_parameters import ConversionParameters from conversion_spec import ConversionSpec, Currency from conversion_spec_provider import ConversionSpecProvider class ConversionSpecFileReader(ConversionSpecProvider): async def pro...
901
226
from sqlite3 import Date from twilio.rest import Client from datetime import datetime from playsound import playsound from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import csv import time ################################ "PREFCTURE DE PARIS" ###########################...
3,931
1,186
#!/usr/bin/env python import rospy import math import tf import geometry_msgs.msg from geometry_msgs.msg import PoseStamped from si_utils.lx_transformerROS import my_transformer if __name__ == '__main__': rospy.init_node('my_tf_listener') listener = tf.TransformListener() # my_trans = my_transformer() ...
3,022
1,038
#!/usr/bin/env python import argparse, subprocess, json, os, os.path, urllib2, sys, base64, binascii, time, \ hashlib, re, copy, textwrap #CA = "https://acme-staging.api.letsencrypt.org" CA = "https://acme-v01.api.letsencrypt.org" def get_crt(account_key, csr, acme_dir): # helper function base64 encode for j...
8,661
2,868
class Tags: class Thematic: ACC_NOTE = "account:note" DELIMITER = "delimiter:thematic" FAM_SIBLINGS = "fam:siblings" FAM_CHILDREN = "fam:children" FAM_PARENTS = "fam:parents" FAM_SPOUSE = "fam:spouse" META_NO_REMARK = "meta:no-remarks" META_PARENT...
3,667
1,667
''' imput1: exome capture, biallelic indel matrix input2: exome capture, biallelic SNP matrix input3: GBS, biallelic indel matrix input4: GBS, biallelic SNP matrix input5: allele count file for exome homozygous or heterozygous genotype input6: allele count file for GBS homozygous or heterozygous genotype input7: tetrap...
14,691
7,534
from pyradioconfig.parts.bobcat.calculators.calc_frame import Calc_Frame_Bobcat class calc_frame_viper(Calc_Frame_Bobcat): pass
132
47
import glob import subprocess import os import argparse import shutil input_parser = argparse.ArgumentParser( description="Run RegTools stats script", ) input_parser.add_argument( 'tag', help="Variant tag parameter used to run RegTools.", ) args = input_parser.parse_args() tag = args.tag cwd = os.getcwd(...
1,940
609
import numpy as np import matplotlib.pyplot as plt import os def plt_loss(epoch, dir_, name, value): if not os.path.exists(dir_): os.makedirs(dir_) axis = np.linspace(1,epoch,epoch) label = '{}'.format(name) fig = plt.figure() plt.title(label) plt.plot(axis, value) # plt.legend() ...
451
172
# Copyright (C) 2018-2019 Tormod Landet # SPDX-License-Identifier: Apache-2.0 """ A timeout context manager based on SIGALRM, Permits multiple SIGALRM events to be queued. Uses a `heapq` to store the objects to be called when an alarm signal is raised, so that the next alarm is always at the top of the heap. Note: SI...
3,267
1,072
import folium import altair as alt import leafmap.foliumap as leafmap import pandas as pd import streamlit as st def app(): st.title("InSAR") option = st.radio("Choose an option", ("Marker Cluster", "Circle Marker")) m = leafmap.Map( center=[29.7029, -95.3335], latlon_control=False, zoom=16, he...
2,549
836
from utils import LOG_INFO import numpy as np def data_iterator(x, y, batch_size, shuffle=True): indx = range(len(x)) if shuffle: np.random.shuffle(indx) for start_idx in range(0, len(x), batch_size): end_idx = min(start_idx + batch_size, len(x)) yield x[start_idx: end_idx], y[sta...
2,105
594
# ----------- # User Instructions # # Modify the valid_month() function to verify # whether the data a user enters is a valid # month. If the passed in parameter 'month' # is not a valid month, return None. # If 'month' is a valid month, then return # the name of the month with the first letter # capitalized. # ...
1,199
447
import sys import weakref import json import logging from .utils import opt_json, Response2JSONLinesIterator from six import StringIO log = logging.getLogger(__name__) class Logs: def __init__(self, client): self.client = weakref.proxy(client) def read(self, url, raw=False, raw_data=True, **opts): ...
2,274
656
#-*- coding:utf-8 -*- #''' # Created on 19-7-16 下午2:14 # # @Author: Greg Gao(laygin) #''' from .synth_text import SynthTextConfig, SynthTextDataset from .icdar13 import IcdarConfig, IcdarDataset from .img_aug import resize_image
228
101
from alberto.annotation import annotation_set from pandas import np from deepposekit.io import TrainingGenerator, DataGenerator from deepposekit.augment import FlipAxis import imgaug.augmenters as iaa import imgaug as ia from deepposekit.models import StackedHourglass from deepposekit.models import load_model import ...
6,376
2,332
from .base import * from dotenv import load_dotenv load_dotenv(dotenv_path='northpole/.staging.env', verbose=True) ALLOWED_HOSTS = ['*'] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.get...
763
305
#!/usr/bin/env python # # Copyright 2014 Corgan Labs # See LICENSE.txt for distribution terms # from bc4py.bip32.base58 import check_decode, check_encode from bc4py_extension import PyAddress from ecdsa.curves import SECP256k1 from ecdsa.keys import SigningKey, VerifyingKey, square_root_mod_prime as mod_sqrt from ecds...
12,587
4,166
import random from loguru import logger from lib.vars.vars import conf, th, paths from lib.vars.ua import UA_LIST def get_random_agent(): return random.sample(UA_LIST, 1)[0] def firefox(): return 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0' def ie(): return 'Mozilla/5.0 (compatibl...
1,167
550
import numpy as np from sympy import * from math import * from timeit import default_timer as timer start = None end = None def maxXi(Xn,X): n = None d = None for i in range(Xn.shape[0]): if(np.copy(Xn[i,0]) != 0): nk = abs(np.copy(Xn[i,0]) - np.copy(X[i,0]))/abs(np.copy(Xn[i,0])) ...
1,378
641
import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np class Plotter: synth_tr: np.ndarray synth_te: np.ndarray pima_tr: np.ndarray pima_te: np.ndarray def __init__(self, synth_tr: np.ndarray, synth_te: np.ndarray, pima_tr: np.ndarray, pim...
8,139
3,200
import sys def square_sum(numbers): return sum([n ** 2 for n in numbers]) if __name__ == "__main__": if len(sys.argv) == 1: nums = [int(e) for e in input('>>> Enter the numbers with comma-separeted: ').split(',')] print(square_sum(numbers=nums)) else: sys.exit(1)
303
111
import os import pickle from abc import ABC, abstractmethod import h5py import numpy as np from .folders import get_pickle_lazy_loader_data_path, hdf5_lazy_loader_data_path from .unpickler import CustomUnpickler class LazyLoaderAssociatedInstance: # when implementing this method in a derived class add an unique...
5,710
1,774
# @date 2020-01-31 # @author Frederic Scherma, All rights reserved without prejudices. # @license Copyright (c) 2020 Dream Overflow # Binance Websocket connector. import json import threading import traceback from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS from twiste...
27,270
7,835
def list_slicing(nums, row, col): new_matrix = [] minimal = row * col if nums is []: return None elif (len(nums) % minimal is 0) and (len(nums) >= minimal): for r in range(row): new_matrix.append(nums[r * col : (r + 1) * col]) return new_matrix else: retur...
669
327
from OnePy.sys_module.metabase_env import OnePyEnvBase class RiskManagerBase(OnePyEnvBase): def __init__(self): self.env.risk_managers.update({self.__class__.__name__: self}) def run(self): pass
225
79
""" Test cases for the regi0.geographic.duplicates.find_grid_duplicates function. """ import numpy as np import pandas as pd from regi0.geographic.duplicates import find_grid_duplicates def test_records_bounds_high_res(records): result = find_grid_duplicates( records, "scientificName", re...
3,057
910
import platform from django.core.exceptions import ObjectDoesNotExist from morango.models import InstanceIDModel import kolibri def get_device_info(): """Returns metadata information about the device""" instance_model = InstanceIDModel.get_or_create_current_instance()[0] try: device_name = koli...
772
226
import os import json import logging # cellcraft node CELLCRAFT_NODE_URL="http://192.168.178.29:4534" # path to cache where pickle files will be stored PATH_RESOURCES='cellcraft/resources' PATH_CACHE='cellcraft/resources/cache/' PATH_TEST_CACHE='test/fixtures/cache/' # path to fixtures PATH_TO_FIXTURES="test/fixtu...
1,372
479
# -*- coding: utf-8 -*- """ Simple folder synchronization using FTP. (c) 2012-2021 Martin Wendt; see https://github.com/mar10/pyftpsync Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php Usage examples: > pyftpsync.py --help > pyftpsync.py upload . ftps://example.com/myfo...
9,123
2,863
from django.shortcuts import render, render_to_response, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, FileResponse from django.urls import reverse import os from django.contrib.auth import authenticate, login, logout # 两个默认的用户认证和管理应用中的方法 from django.contrib import auth from django...
9,678
3,531
#!/usr/bin/env python3 from Spot import * import time from bosdyn.client import math_helpers if __name__ == '__main__': spot = Spot() try: # It's ALIVE! spot.power_on() spot.move_to(1.0, 0.0, 0.0, math_helpers.Quat(), duration=5.0) time.sleep(5.0) spot.move_to(0.0, 1...
781
329
import pytest from tennis_probability import set, InvalidInput, InvalidProbability, NegativeNumber def test_set(): assert set(0, 0, 0) == 0 assert set(0, 0, 0.50) == 0.5 assert set(0, 0, 1) == 1 # Test valid inputs assert set(5, 3, 0.13) == 0.008146509339015371 assert set(2, 2, 0.37) == 0.024...
837
391
from abc import ABC, abstractmethod from typing import Dict, Any, Callable from kombu import Message from classic.components import component MessageBody = Dict[str, Any] @component class MessageHandler(ABC): @abstractmethod def handle(self, message: Message, body: MessageBody): pass @component...
626
178
""" byceps.services.shop.order.event_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from __future__ import annotations from datetime import datetime from typing import Sequence from ....database import db from .d...
1,440
472
from attr import attrs, attrib import enum from .enum import EnumColumn class Suit(EnumColumn): class Enum(enum.Enum): @attrs(frozen=True) class _Suit(): suit_name = attrib() ascii_icon = attrib() spades = _Suit( suit_name="Spades", ascii_i...
637
225
import config import os import pandas as pd import numpy as np from torch.utils.data import Dataset, DataLoader from PIL import Image from tqdm import tqdm class DRDataset(Dataset): def __init__(self, images_folder, path_to_csv, train=True, transform=None): super().__init__() self.data = pd.read_cs...
1,881
585
from flask import Flask, request, jsonify import util app= Flask(__name__) @app.route("/classify_image",methods=["GET","POST"]) def classify_image(): image_data=request.form["image_data"] response=jsonify(util.classify_image(image_data)) response.headers.add("Access-Control-Allow-Origin","*") ...
507
175
from blogsley_site.app import create_app
41
14
# Generated by Django 3.2 on 2021-12-12 18:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('awards', '0002_profile_profile_photo'), ] operations = [ migrations.AddField( model_name='project', name='project_phot...
421
138
""" Test to measure pvc scale creation time. Total pvc count would be 50, 1 clone per PVC Total number of clones in bulk will be 50 """ import logging import pytest from ocs_ci.utility import utils from ocs_ci.ocs.perftests import PASTest from ocs_ci.framework.testlib import performance from ocs_ci.helpers import help...
7,827
2,406
from .database import db from .user import User from .post import Post
72
20
import argparse from genericpath import exists import os import time import re from tqdm import tqdm import numpy as np from scipy.io import wavfile from wiener_scalart import wienerScalart TIME = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) WORKPLACE_DI...
3,520
1,321
#Import libraries import random import os import noise import numpy import math import sys from chunks import Chunks as chk from PIL import Image import subprocess from scipy.misc import toimage import threading random.seed(os.urandom(6)) #Delete old chunks filelist = [ f for f in os.listdir("world/") if f.endswith...
7,779
2,835
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import numpy.testing as npt from reagent.core.parameters import ProblemDomain from reagent.gym.envs import Gym from reagent.gym.envs.wrappers.simple_minigrid import SimpleObsWrapper from reagent.gym.utils impo...
4,363
1,390
class Solution(object): def XXX(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ def dfs(res, state, n): if n == 0: res.append(list(state)) return for a in nums: if a not in...
515
152
from parser.readfile import ReadFile
37
10
#!/usr/bin/env python # coding: utf-8 # In[1]: import requests from datetime import timezone from datetime import timedelta from datetime import datetime import hhu import os # In[2]: utc_time = datetime.utcnow().replace(tzinfo=timezone.utc) sh_tz = timezone(timedelta(hours=8),name='Asia/Shanghai') beijing_now = ...
535
218
import pickle import stanza import test_stuff from datetime import datetime from dictionary import cd, dictionary, nlp_dictionary, ph_outcome, ph_key, ph_value, ph_dvalue, ph_subject import eric_nlp #does not do preprocessing def depparse(sentences, pipeline): output = ["OUTPUT:\n"] roots = dict() for sen...
30,573
9,335
# coding: utf-8 import torch.nn as nn class SimpleCBOW(nn.Module): def __init__(self, vocab_size, hidden_size): super(SimpleCBOW, self).__init__() V, H = vocab_size, hidden_size self.in_layer = nn.Linear(V, H, bias=False) self.out_layer = nn.Linear(H, V, bias=False) self....
706
265
# coding=utf-8 #! /usr/bin/env python3.4 """ MIT License Copyright (c) 2018 NLX-Group Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights...
7,814
2,554
"""Module for testing formats on resources entities""" from raviewer.src.core import (get_displayable, load_image, parse_image) from terminaltables import AsciiTable from raviewer.image.color_format import AVAILABLE_FORMATS import os import pkg_resources import time import pytest @pytest.fixture def formats(): r...
1,599
457
from flask import request from flask import redirect from flask import session from flask import url_for from functools import wraps def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get('user', {}).get('id', None): return redirect(url_for('ui.login',...
702
210
import math import torch from typing import Union, Optional, Tuple from dqc.utils.datastruct import ZType eps = 1e-12 ########################## safe operations ########################## def safepow(a: torch.Tensor, p: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: if torch.any(a < 0): raise Runtime...
4,089
1,442
import numpy as np import gym from gym import spaces from gym.utils import seeding class PointEnv(gym.Env): metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second' : 30} def __init__(self, mass=1., target_dist=5., xlim=2.5, cost_smoothing=0.): self.mass = mass ...
4,713
1,591
from __future__ import print_function, division, absolute_import from odin import nnet as N, backend as K import tensorflow as tf @N.ModelDescriptor def fnn(X, gender, topic, y, nb_classes): f = N.Sequence([ N.Flatten(outdim=2), N.Dense(num_units=1024, b_init=None), N.BatchNorm(activation...
2,855
1,236
active_account = None def reload_account(): global active_account if not active_account: return # TODO: pull owner account from the database. pass
174
48
from orator import Model import pendulum class AbstractModel(Model): __guarded__ = [] @classmethod def find_or_new_by(cls, options): entity = cls.find_by(options) if not entity: entity = cls() for k in options: v = options[k] setattr...
550
169
import os import sys joinp = os.path.join sys.path.insert(0, 'whitgl') sys.path.insert(0, joinp('whitgl', 'input')) import build sys.path.insert(0, 'input') import ninja_syntax build.do_game('Game', '', ['png','ogg'])
220
88
import hashlib import struct from dataclasses import dataclass, field from typing import Dict, List, Union from factom_core.block_elements.balance_increase import BalanceIncrease from factom_core.block_elements.chain_commit import ChainCommit from factom_core.block_elements.entry_commit import EntryCommit from factom_...
9,018
2,712
test = { 'name': 'q0', 'points': 0, 'suites': []}
59
28
#========================================================================= # inst_utils #========================================================================= # Includes helper functions to simplify creating assembly tests. from pymtl import * from tests.context import lizard #------------------------------------...
24,208
7,209
def func(arg1, arg2=dict()): print('entering func') # arg3 is evaluated at compile time of inner # so it capture arg3 as {} def inner(arg3=arg2): # arg1 is evaluted when inner is called # so it uses the value of arg1 at that time # whic is None print("arg1", arg1, "arg3", arg3) arg1 = arg2 ...
365
133
import boto3 from .. import logging logger = logging.getFormattedLogger() lambda_client = boto3.client('lambda', region_name='us-west-2') def invoke(function_name, message): try: response = lambda_client.invoke( FunctionName=function_name, InvocationType='Event', Payl...
487
132
import unittest from transducer.functional import compose from transducer.lazy import transduce from transducer.transducers import (mapping, filtering, taking, dropping_while, distinct) class TestComposedTransducers(unittest.TestCase): def test_chained_transducers(self): result = transduce(transducer=com...
766
225
# -*- coding: utf-8 -*- # Copyright 2021 Damien Nguyen # # 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...
2,246
680
from django.db import models from django.conf import settings from django.core.urlresolvers import reverse_lazy from django.utils import timezone from django.forms.util import to_current_timezone from model_utils import Choices class TimeStampedModel(models.Model): """ An abstract model for the common fields ...
4,468
1,181
from django.apps import AppConfig from django.db.models.signals import post_save, post_delete from . import signals class BoardsAppConfig(AppConfig): name = 'apps.boards' def ready(self): Board = self.get_model('Board') Thread = self.get_model('Thread') Post = self.get_model('Post') ...
521
161
''' 利用斗鱼弹幕 api 尝试抓取斗鱼tv指定房间的弹幕 ''' import multiprocessing import socket import time import re import signal # 构造socket连接,和斗鱼api服务器相连接 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostbyname("openbarrage.douyutv.com") port = 8601 client.connect((host, port)) # 弹幕查询正则表达式 danmu_re = re.co...
2,445
1,153
# -*- coding: utf-8 -*- # @Time : 2020/4/1 0:48 # @Author : Nixin # @Email : nixin@foxmail.com # @File : spider_douyin.py # @Software: PyCharm import requests, re, sys, os, time, random, socket import http.client from bs4 import BeautifulSoup def get_html(url, data=None): header = { 'Accept': '...
3,828
1,637
from charms.reactive import RelationBase from charms.reactive import scopes from charms.reactive import hook from charms.reactive import when class TestRelation(RelationBase): scope = scopes.GLOBAL @hook('{requires:test}-relation-joined') def joined(self): self.set_state('{relation_name}.ready') ...
479
161
from __future__ import print_function import unittest import filestore class PruneTestCase(unittest.TestCase): def test_parse_age(self): self.assertEqual(filestore.parse_age("1s"), 1) self.assertEqual(filestore.parse_age("1m"), 60) self.assertEqual(filestore.parse_age("1h"), 3600) ...
593
201
# This is a little bit clunky, but is a better solution than writing passwords into import os from cryptography.fernet import Fernet # cred_dir = os.path.join(os.path.dirname(os.getcwd()), "settings") cred_dir = '/Users/cdowns/work/imac_local/CoronalHoles/mysql_credentials' key_file = os.path.join(cred_dir, "e_key.bi...
1,027
353
settings = """ try: AUTHENTICATION_BACKENDS += [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] except NameError: AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.Aut...
663
221
#coding=utf-8 ''' Created on 2015-10-10 @author: Devuser ''' class LogcatPagePath(object): left_nav_template_path="home/home_left_nav.html" logger_page_path="logcat/logcat_index.html" logger_list_page="logcat/logcat_list_page.html" logger_list_controll="logcat/logcat_loger_list_controll.html" ...
475
186
s = 0 problems = input().strip().split(';') for p in problems: if '-' in p: a, b = map(int, p.split('-')) s += b - a + 1 else: s += 1 print(s)
176
74
#!/usr/bin/python from fusesoc.capi2.generator import Generator import subprocess class IcepllGenerator(Generator): def run(self): fin = self.config.get('freq_in', 12) fout = self.config.get('freq_out', 60) module = self.config.get('module', False) filename = self.config....
745
252
from checkcel import Checkplate from checkcel.validators import SetValidator, NoValidator from collections import OrderedDict class MyTemplate(Checkplate): validators = OrderedDict([ ("name@Population", NoValidator()), ("Picture", NoValidator()), ("Type", SetValidator(valid_values=["whole ...
351
91
# Copyright 2022 Thomas Woodruff # 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 agr...
2,823
831
# Author-kantoku # Description-コンポーネント毎に分割してクローン作るよ! # Fusion360API Python import adsk.core import traceback try: from . import config from .apper import apper from .commands.BUNKUROCore import BUNKUROCore # Create our addin definition object my_addin = apper.FusionApp(config.app_name, config.co...
1,059
394
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import os PROJECT_PATH = "/mnt/e/dev/test/hp_steam_data/" DATA_PATH = os.path.join(PROJECT_PATH, "data") RESULT_PATH = os.path.join(PROJECT_PATH, "result") def get_origin_data(): """ origin data """ # raw data ...
2,004
888
#!python3 """ Simulation experiment for our AAAI 2020 paper, with recipes that are vectors of ones. Comparing McAfee's double auction to our SBB auctions. Author: Dvir Gilor Since: 2020-08 """ from experiment_stock import experiment from mcafee_protocol import mcafee_trade_reduction from trade_reduction_protocol ...
621
217
from random import randint print('=-' * 15) print('ADIVINHE EM QUE NUMERO ESTOU PENÇANDO') print('=-' * 15) pc = randint(0, 10) num = 11 cont = 0 while pc != num: num = int(input('Sera que voce consegue acertar o numero que pensei, entre 0, 10: ')) if num == pc: print('PARABES!!! VOCE ACERTOU') e...
556
220
""" ex20170108_model_PC.py Create Model PC (Godley & Lavoie Chapter 4). Copyright 2017 Brian Romanchuk 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-...
3,172
1,106
import re import flask import flask.views from functools import wraps def camel_case_to_snake_case(word): """very simple mechanism for turning CamelCase words into snake_case""" return re.sub(r"(?<!^)(?=[A-Z])", "_", word).lower() def camel_case_to_slug_case(word): """very simple mechanism for turning ...
4,087
1,214
# ========================================================================= # Copyright 2012-present Yunify, Inc. # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the Licens...
2,287
602
import datetime from datetime import timedelta from typing import Callable, Collection, TYPE_CHECKING import pytz from tsutils.formatting import normalize_server_name from tsutils.time import JP_TIMEZONE, KR_TIMEZONE, NA_TIMEZONE from padevents.enums import DungeonType, EventLength if TYPE_CHECKING: from dbcog.m...
5,022
1,695
class Config(object): """ Represents configuration of network training """ pass
92
28
# allows to import RSA lib from different dir import sys # inserts path to access RSA encryption lib # sys.path.insert(0, '../RSAEncryption') import socket import json from libs.communication import sendEncrypted, recvEncrypted, sendData, readData from libs.RSAKeys import readPrivateKey from libs.EncryptedSocket imp...
1,409
520
import taichi as ti import numpy as np from functools import partial from itertools import combinations from billiard_game_dual_ball import normalize_vector, two_ball_collides, calc_next_pos_and_velocity, \ calc_after_collision_velocity, rectify_positions_in_collision, rectify_positions_and_velocities # Constants...
7,085
2,891