text
string
size
int64
token_count
int64
import unittest import os from dao.guild_roles_dao import GuildRolesDAO from dao.guild_role_categories_dao import GuildRoleCategoriesDAO class TestGuildRolesDAO(unittest.TestCase): def setUp(self): self.db_addr = "database/test_db.db" os.popen(f"sqlite3 {self.db_addr} < database/schema.sql") ...
3,690
1,567
import picamera import datetime import os delcount = 2 def check_fs(): global delcount st = os.statvfs('/') pct = 100 - st.f_bavail * 100.0 / st.f_blocks print pct, "percent full" if pct > 90: # less than 10% left, delete a few minutes files = os.listdir('.') files.so...
1,115
400
class Allergies(object): def __init__(self, score): pass def allergic_to(self, item): pass @property def lst(self): pass
164
55
from .handle import ForgeHandle class MockHandle(ForgeHandle): def __init__(self, forge, mock, behave_as_instance=True): super(MockHandle, self).__init__(forge) self.mock = mock self.behaves_as_instance = behave_as_instance self._attributes = {} self._is_hashable = False ...
4,398
1,366
import FWCore.ParameterSet.Config as cms from CondCore.DBCommon.CondDBCommon_cfi import * PoolDBESSourceMistag110118 = cms.ESSource("PoolDBESSource", CondDBCommon, toGet = cms.VPSet( # # working points # cms.PSet( record = cms.string('Per...
4,599
1,871
''' Created on Nov 22, 2018 @author: kjnether methods that evaluate the given schedule ''' import logging import FMEUtil.FMEServerApiData import re class EvaluateSchedule(object): def __init__(self, schedulesData): self.logger = logging.getLogger(__name__) if not isinstance(sc...
7,423
2,022
from PyQt5 import QtWidgets, QtCore from podcastista.ShowEpisodeWidget import ShowEpisodeWidget from podcastista.FlowLayout import FlowLayout class FillThread(QtCore.QThread): """ Worker thread for loading up episodes """ def __init__(self, spotify, shows): super().__init__() self._spotify = ...
3,319
996
import pyparsing as pp #relationship will refer to 'track' in all of your examples relationship = pp.Word(pp.alphas).setResultsName('relationship') number = pp.Word(pp.nums + '.') variable = pp.Word(pp.alphas) # an argument to a relationship can be either a number or a variable argument = number | variable # argument...
866
261
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # this script tests vtkImageReslice with various axes permutations, # in order to cover a nasty set of "if" statements that check # the intersections of the raster lines with the input bounding box. # Image pipel...
4,496
2,027
import collections from itertools import repeat import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils def _ntuple(n): def parse(x): if isinstance(x, collections.Iterable): return x return tuple(repeat(x, n)) return parse _single = _ntuple(1) _pair = _ntuple(2) ...
2,916
958
import pandas as pandas_Pandas_Module class Script: @staticmethod def main(): food_info = pandas_Pandas_Module.read_csv("../food_info.csv") print(str(food_info.dtypes)) Script.main()
194
77
############################################################################# # # Copyright (c) 2008 by Casey Duncan and contributors # All Rights Reserved. # # This software is subject to the provisions of the MIT License # A copy of the license should accompany this distribution. # THE SOFTWARE IS PROVIDED "AS IS", W...
2,176
932
# coding=utf-8 """ Command Line Interface ====================== """ import argparse import logging import os from os import path import sys from landspout import core, __version__ LOGGER = logging.getLogger('landspout') LOGGING_FORMAT = '[%(asctime)-15s] %(levelname)-8s %(name)-15s: %(message)s' def exit_applicat...
3,810
1,047
import sys sys.path.append('../') import numpy as np import tt d = 30 n = 2 ** d b = 1E3 h = b / (n + 1) #x = np.arange(n) #x = np.reshape(x, [2] * d, order = 'F') #x = tt.tensor(x, 1e-12) x = tt.xfun(2, d) e = tt.ones(2, d) x = x + e x = x * h sf = lambda x : np.sin(x) / x #Should be rank 2 y = tt.multifuncrs([x]...
474
267
import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.auth import tornado.escape import os.path import logging import sys import urllib import json from uuid import uuid4 from tornado.options import define, options define("port", default=8000, help="run on the given...
26,434
7,243
import matplotlib.pyplot as plt import netCDF4 import numpy nc = netCDF4.Dataset("data/ructemps.nc") data = nc.variables["tmpc"][17, :, :] nc.close() (fig, ax) = plt.subplots(1, 1) ax.imshow(numpy.flipud(data)) fig.savefig("test.png")
239
106
import matplotlib import matplotlib.pyplot as plt import numpy as np import math from matplotlib.ticker import FormatStrFormatter from matplotlib import scale as mscale from matplotlib import transforms as mtransforms # z = [0,0.1,0.3,0.9,1,2,5] z = [7.8, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 6...
3,031
1,656
import discord from discord.ext.commands import Bot TOKEN = "<discordtoken>" client = discord.Client() bot = Bot(command_prefix="!") @bot.event async def on_ready(): print("Bot Hazır " + str(bot.user)) @bot.event async def on_message(message): if message.author == client.user: ret...
432
165
import pandas as pd # Global variable to set the base path to our dataset folder base_url = '../dataset/' def update_mailing_list_pandas(filename): """ Your docstring documentation starts here. For more information on how to proper document your function, please refer to the official PEP...
653
194
#!/usr/bin/env python3 # "This service will check your statement that a directed graph you provide us admits an eulerian walk (of the specified type)"" from os import EX_TEMPFAIL from sys import stderr, exit import collections from multilanguage import Env, Lang, TALcolors from TALinputs import TALinput from euler...
7,357
2,518
import sys import argparse from hgraph import * from rdkit import Chem from multiprocessing import Pool def process(data): vocab = set() for line in data: s = line.strip("\r\n ") hmol = MolGraph(s) for node,attr in hmol.mol_tree.nodes(data=True): smiles = attr['smiles'] ...
1,047
378
# -*- coding: utf-8 -*- """ test """ from __future__ import unicode_literals from django.template.loader import get_template from django.contrib import messages # Create your views here. from django.http import HttpResponse def index(request): """ index """ template = get_template('cornwall/index.html') m...
612
176
# coding = utf-8 # env = python3.5.2 # author = lujianxin # time = 201x-xx-xx # purpose= - - - from django.urls import re_path from . import views urlpatterns = [ # 此模块下的路径映射 re_path(r'usercenter$', views.UserCenter.as_view()), re_path(r'details/(\d+)$', views.UserDetails.as_view()), re_path(r'...
838
364
import math oxygen_rating = 0 co2_rating = 0 length = 0 n_bits = 12 common = [0] * n_bits anti = [0] * n_bits numbers = [] def new_bitmap(old_list): new_list = [0] * n_bits for num in old_list: for j, bit in enumerate(num): new_list[j] += bit return new_list wit...
1,825
709
import math import numpy as np from munch import Munch from transformers import GPT2LMHeadModel, GPT2TokenizerFast import torch from copy import deepcopy ######################################################################### ### compute perplexity ###################################################################...
7,838
2,725
from tdw.controller import Controller from tdw.tdw_utils import TDWUtils from tdw.add_ons.image_capture import ImageCapture from tdw.backend.paths import EXAMPLE_CONTROLLER_OUTPUT_PATH """ Get the _flow pass. """ c = Controller() object_id_0 = c.get_unique_id() object_id_1 = c.get_unique_id() object_id_2 = c.get_uniq...
2,030
746
# Copyright 2013 Google, 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 agreed to in w...
2,844
888
from sys import platform try: from yaml import CSafeLoader as Loader # use the C loader when possible except ImportError: from yaml import SafeLoader as Loader import yaml with open("config.yml") as f: config = yaml.load(f, Loader=Loader) # load the config yaml if platform in ("linux", "linux2", "win32...
586
181
# # PySNMP MIB module CISCO-IETF-PW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-PW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:43:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
25,609
12,472
_base_ = [ '../_base_/models/fpn_r50.py', '../_base_/datasets/onaho.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] model = dict(decode_head=dict(num_classes=2))
200
93
def get_default_convnet_setting(): net_width, net_depth, net_act, net_norm, net_pooling = 128, 3, 'relu', 'instancenorm', 'avgpooling' return net_width, net_depth, net_act, net_norm, net_pooling def get_loops(ipc): # Get the two hyper-parameters of outer-loop and inner-loop. # The following values are ...
1,955
728
""" Expression Dataset for analysis of matrix (RNASeq/microarray) data with annotations """ import pandas as PD import numpy as N from matplotlib import pylab as P from collections import OrderedDict from ast import literal_eval # from ..plot.matrix import matshow_clustered class ExpressionSet(object): def...
4,324
1,548
from __future__ import annotations from django_perf_rec.sql import sql_fingerprint def test_empty(): assert sql_fingerprint("") == "" assert sql_fingerprint("\n\n \n") == "" def test_select(): assert sql_fingerprint("SELECT `f1`, `f2` FROM `b`") == "SELECT ... FROM `b`" def test_select_show_column...
8,377
3,176
from rest_framework import serializers from user_auth_api.models import User # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'user_name', 'email', 'current_jamb_score', 'phone_num', 'last_name', ...
1,198
351
"""Main module.""" import json import os import re import shutil import subprocess import sys from pathlib import Path from typing import List, Optional import yaml ENV_FILE = "environment.yml" class CondaEnvException(Exception): pass def find_environment_file(): p = Path(os.getcwd()).resolve() while...
9,653
2,834
import sys import rospy import types #from std_msgs.msg import String from sensor_msgs.msg import Image from cibr_img_processing.msg import Ints from cv_bridge import CvBridge, CvBridgeError #make int msgs #TODO: get the img size from camera_indo topics class CVUtilNode: # abstarct this, it can easily work with other ...
2,671
869
# DO NOT EDIT: File is generated by code generator. from pokepay_partner_python_sdk.pokepay.request.request import PokepayRequest from pokepay_partner_python_sdk.pokepay.response.shop_with_accounts import ShopWithAccounts class GetShop(PokepayRequest): def __init__(self, shop_id): self.path = "/shops" + ...
448
146
from abc import abstractproperty from ..backend_config.bucket_config import S3BucketConfig from ..storage.helper import StorageHelper class SetupUploadMixin(object): log = abstractproperty() storage_uri = abstractproperty() def setup_upload( self, bucket_name, host=None, access_key=None, sec...
2,191
585
import os import unittest import pandas as pd from application.ParcelsParser import ParcelsParser class TestPracelsParser(unittest.TestCase): def setUp(self): self.parser = ParcelsParser("./test_cadastral_parcels.tsv", "cadastral_parcel_identifier") def test_if_file_exist(self): file_path = ...
2,872
974
import binTree import queue def complete(tree): q = queue.Queue() nonFull = False q.enqueue(tree) while (not q.isEmpty()): t = q.dequeue() if (t.getLeftChild()): if (nonFull): return False q.enqueue(t.getLeftChild()) if (t.getLeftChild() ...
726
232
# -*- encoding: utf-8 """ Copyright (c) 2014, Philipp Krähenbühl 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 ...
3,322
1,421
import pickle import pandas as pd # cat aa ab ac > dataset.pkl from https://github.com/zhougr1993/DeepInterestNetwork with open('dataset.pkl', 'rb') as f: train_set = pickle.load(f, encoding='bytes') test_set = pickle.load(f, encoding='bytes') cate_list = pickle.load(f, encoding='bytes') user_count, i...
1,473
565
from email_extras.settings import USE_GNUPG if USE_GNUPG: from django.contrib import admin from email_extras.models import Key, Address from email_extras.forms import KeyForm class KeyAdmin(admin.ModelAdmin): form = KeyForm list_display = ('__str__', 'email_addresses') ...
656
212
# ----------------------------------------------------------------------------- # # This file is the copyrighted property of Tableau Software and is protected # by registered patents and other applicable U.S. and international laws and # regulations. # # You may adapt this file and modify it to fit into your context an...
6,265
1,683
import boto3 import argparse import os,sys def main(argv=None): argv = (argv or sys.argv)[1:] parser = argparse.ArgumentParser(description='dump all aws log streams into files') parser.add_argument("--profile", dest="aws_profile", type=str, ...
2,234
647
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import make_blobs from sklearn.mixture import GaussianMixture from sklearn.cluster import KMeans from matplotlib.patches import Ellipse # For reproducibility np.random.seed(1000) nb_samples = 300 nb_centers = 2 if __na...
5,239
2,461
__all__ = [ 'DEFAULT_FILTERS', 'DEFAULT_XAR_FILTERS', 'merge_image', ] import contextlib import logging import tempfile from pathlib import Path from g1 import scripts from g1.containers import models from g1.containers import scripts as ctr_scripts from . import utils LOG = logging.getLogger(__name__) ...
5,771
1,871
""" Space : O(1) Time : O(n) """ class Solution: def maxProfit(self, prices: List[int]) -> int: start, dp = 10**10, 0 for i in prices: print(start) start = min(start, i) dp = max(dp, i-start) return dp
289
105
# Created by Giuseppe Paolo # Date: 27/08/2020 from gym.envs.registration import register register( id='CollectBall-v0', entry_point='gym_collectball.envs:CollectBall' )
175
71
import logging import threading from concurrent.futures import ThreadPoolExecutor from multiprocessing import Queue from foreverbull.worker.worker import WorkerHandler from foreverbull_core.models.finance import EndOfDay from foreverbull_core.models.socket import Request from foreverbull_core.models.worker import Inst...
3,534
932
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `AffiliationSearch` module.""" from collections import namedtuple from nose.tools import assert_equal, assert_true import scopus s = scopus.AffiliationSearch('af-id(60021784)', refresh=True) def test_affiliations(): received = s.affiliations asser...
704
233
''' ''' import struct class Int: ''' ''' def __init__(self): ''' ''' #construct the message format self.message_constructor = 'i' #number of bytes for this message self.size = 4 def _pack(self, message): ''' ''' encoded_message = ...
566
158
#from math import hypot import math print('='*5, 'Cálculo triângulo retângulo', '='*5) cat_op = float(input('Digite o comprimento do cateto oposto: ')) cat_adj = float(input('Digite o comprimento do cateto adjacente: ')) hip = math.hypot(cat_op, cat_adj) print(f'O comprimento da hipotenusa do triângulo retângulo, cujos...
377
154
from random import randint numeros = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10)) print(f'Os cinco números são: ', end='') for n in numeros: # Exibe números sorteados print(n, end=' ') print(f'\nO MAIOR número é {max(numeros)}') print(f'O MENOR número é {min(numeros)}')
312
133
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Maxwell Macros v0.7.0 by Sam Neurohack from /team/laser Launchpad set a "current path" """ from OSC3 import OSCServer, OSCClient, OSCMessage import time import numpy as np import rtmidi from rtmidi.midiutil import open_midiinput from threading import Thread from r...
10,832
4,131
import numpy as np import matplotlib.pyplot as plt from pylab import * #import pyspeckit as ps from scipy import io from scipy import stats from scipy.optimize import leastsq #from lmfit import minimize, Parameters, Parameter, report_fit #from lmfit.models import GaussianModel import scipy.optimize as optimization impo...
11,660
5,895
# Copyright 2013 Daniel Narvaez # # 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 writi...
1,762
556
# node to capture and communicate game status # written by Russell on 5/18 class Game_state(): node_weight = 1 # node_bias = 1 # not going to use this for now, but may need it later list_of_moves = [] def __init__(self, node_list): self.node_list = node_list def num_moves(self): ...
1,194
408
""" """ import sqlite3 import numpy as np import math class SQL: def __init__(self): self.path = None self.connexion = None self.cursor = None self.verbose = False def to_SQL_type(self, type_, mode = "format"): """ Function allowing to...
13,340
3,383
from .lattice import skew_normal_density, center_density,\ state_prices_from_offsets, densities_and_coefs_from_offsets, winner_of_many,\ expected_payoff, densities_from_offsets, implicit_state_prices, densitiesPlot import pandas as pd # todo: get rid of this dependency import numpy as np def dividend_implied_...
4,705
1,519
# Copyright 2013-2021 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) import re class Autoconf(AutotoolsPackage, GNUMirrorPackage): """Autoconf -- system configuration part of autotools"...
4,832
1,947
from aiohttp_micro.web.handlers.openapi import PayloadSchema, ResponseSchema from marshmallow import fields, post_load, Schema from wallet.core.entities.categories import CategoryFilters from wallet.web.schemas.abc import CollectionFiltersSchema class CategorySchema(Schema): key = fields.Int(required=True, data_...
1,096
300
SConscript('Mkdocs/Common/SConscript.py') SConscript('Pandoc/Common/SConscript.py') SConscript('Doxygen/Common/SConscript.py')
127
53
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Donny You(youansheng@gmail.com) # Some methods used by main methods. from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import os from collections import OrderedDict import torch import torch...
11,563
3,432
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import pickle import scipy.stats as stats data_path = '../data/het_average.dat' output_dir = '../figures/' # Configure matplotlib environment helvetica_scale_factor = 0.92 # rescale Helvetica to other fonts of same size mpl.rcParams['font.siz...
1,861
707
from random import random, choice, seed, shuffle, randint from math import ceil import copy target = [ 2, 2, 3, 1, 4, 5 ] consonants_base = [ 'p', 't', 'k', 'm', 'n' ] vowels = [ [ 'a', 'i', 'u' ], [ 'a', 'i', 'u', 'e', 'o' ], [ 'a', 'A', 'i', 'I', 'u', 'U', 'e', 'E', 'o', 'O' ] ] consonants_ex...
7,532
2,612
from django import template from week.models import SidebarContentPage,SidebarImagePage register = template.Library() @register.inclusion_tag('week/announcement.html') def sidebar(): sidebar_data = SidebarContentPage.objects.get() return {'sidebar_data':sidebar_data} @register.inclusion_tag('week/advertise...
446
139
#------------------------------------------------------------------------------- # A mock physics package to mess around with the CRKSPH corrections. #------------------------------------------------------------------------------- from Spheral1d import * class CRKSPH_mod_package(Physics): def __init__(self): ...
1,097
349
import os import requests import time import uuid import configparser import datetime import fbchat import re from fbchat import Client, ImageAttachment from fbchat import FBchatException from pathlib import Path politeness_index = 0.5 # ;) epoch = datetime.datetime(1970, 1, 1) # Hack to get the login to work, see:...
8,452
2,367
from django.contrib.auth.models import AbstractUser from django.db.models import (BooleanField, CASCADE, CharField, FloatField, IntegerField, ManyToManyField, Model, OneToOneField, PositiveSmallIntegerField) from django.contrib.postgres.fields import ArrayFiel...
1,565
452
import os,time ## File Variable (USER INPUT) ## ========================== ## if multiple files are being accessed to create movie... ## ...specify the beginning and ending of the file names... ## ...and the date list text file in the variables below ## Please use True or False to set whether multiple files will be a...
7,676
2,536
#!/usr/bin/env python # -*- coding: utf-8 -*- """gaetk2.tools.auth0.py Tools for working with auth0 Created by Maximillian Dornseif on 2017-12-05. Copyright 2017 HUDROA. MIT Licensed. """ from __future__ import unicode_literals import logging from google.appengine.api import memcache from auth0.v3.authentication ...
4,544
1,392
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if len(intervals) <= 1: ...
705
209
#!/usr/bin/env python3 from sys import argv from pathlib import Path from re import compile as re_compile PACKAGE_RE = re_compile("symbiflow-arch-defs-([a-zA-Z0-9_-]+)-([a-z0-9])") with (Path(__file__).parent.parent.parent / 'packages.list').open('r') as rptr: for artifact in rptr.read().splitlines(): m ...
843
284
from django.conf.urls import url, include urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/viet_ocr/', include('viet_ocr.api.urls', namespace="viet_ocr-api")), url(r'^api/post_process/', include('post_process.api.urls', namespace="post_process-api"...
500
184
import torch import torch.nn as nn import neuron.ops as ops from neuron.config import registry @registry.register_module class ReID_Metric(nn.Module): def __init__(self, metric_cls, metric_rank): super(ReID_Metric, self).__init__() self.metric_cls = metric_cls self.metric_rank = metr...
839
250
class myIntSynthProvider(object): def __init__(self, valobj, dict): self.valobj = valobj self.val = self.valobj.GetChildMemberWithName("theValue") def num_children(self): return 0 def get_child_at_index(self, index): return None def get_child_index(self, name): ...
1,028
316
from pyspark.sql import SparkSession from pyspark.sql.types import DateType from pyspark.sql.functions import col from pyspark.sql import types as t import sys from pyspark.sql.window import Window from pyspark.sql.functions import spark_partition_id from pyspark.sql import Row def show_partition_id(df): return d...
3,198
1,105
from django.contrib import admin from .models import Asset # Register your models here. admin.site.register(Asset)
116
32
from .mapper import ApiResponse, ApiResponseInterface from .mapper.types import Timestamp, AnyType __all__ = ['SendConfirmEmailResponse'] class SendConfirmEmailResponseInterface(ApiResponseInterface): title: AnyType is_email_legit: AnyType body: AnyType class SendConfirmEmailResponse(ApiResponse, SendC...
360
100
from django.shortcuts import render, redirect from django.contrib import messages from .models import Contact from django.contrib.auth.decorators import login_required def home(request): if request.user.is_authenticated: return render(request, 'webpages/home.html') else: return render(request,...
1,256
345
# # (C) Copyright 2003,2004 Hewlett-Packard Development Company, L.P. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later ...
3,281
1,010
#!/usr/bin/env python3* import unicodedata class Word: """ Object representation for a word Parameters ---------- text : str word text formatedText : str word text without accent, punctuation, etc (UTF-8) color : List of integers pixel color values in rgb for th...
1,723
528
# Say you have an array for which the ith element is the price of a given stock on day i. # Design an algorithm to find the maximum profit. You may complete at most two transactions. # Note: You may not engage in multiple transactions at the same time # (i.e., you must sell the stock before you buy again). # Example ...
2,605
1,138
import robotconn.rpc.baxterrobot.baxter_server_pb2 as bxtsp import robotconn.rpc.baxterrobot.baxter_server_pb2_grpc as bxtspgc import grpc import pickle import numpy as np class BaxterClient(object): def __init__(self, host = "localhost:18300"): channel = grpc.insecure_channel(host) self.stub = b...
2,719
1,202
# Copyright 2021 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
5,232
1,528
""" Copyright 2018 Globo.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://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writ...
1,248
390
# -*- encoding: utf-8 -*- # # 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, sof...
5,354
1,556
""" fit1d package is designed to provide an organized toolbox for different types of 1D fits that can be performed. It is easy to add new fits and other functionalities """ from abc import ABC, abstractmethod import numpy as np from typing import List,Tuple from fit1d.common.model import Model, ModelMock from fit1d.co...
3,644
1,187
# -*- coding: utf-8 -*- """Module init code.""" __version__ = '0.0.0' __author__ = 'Your Name' __email__ = 'your.email@mail.com'
133
61
# Blueprint for user management in /admin/users and /admin/users/delete from tv import login_manager, db from flask_login import LoginManager, current_user, login_user, logout_user, login_required from flask import Blueprint, flash, redirect, render_template, request from data import User from forms import Registratio...
2,669
788
from django.db.models import CharField from django.utils.translation import ugettext_lazy as _ import validators class CURPField(CharField): default_validators = [validators.CURPValidator()] description = _("CURP") def __init__(self, *args, **kwargs): kwargs['max_length'] = 18 super(CURPField, self).__init__(...
337
116
# coding: utf-8 # python libs from __future__ import absolute_import import os # salt testing libs from tests.support.unit import TestCase, skipIf from tests.support.mock import patch, call, mock_open, NO_MOCK, NO_MOCK_REASON, MagicMock # salt libs import salt.utils import salt.utils.files from salt import crypt # ...
5,646
3,429
import unittest from gubbins.utils import append_params class UtilsTest(unittest.TestCase): def test_append_params(self): url = 'http://www.fish.com/dir/page.html' url = append_params(url, {'a': 1, 'b': 'a i'}) expected = 'http://www.fish.com/dir/page.html?a=1&b=a+i' self.asse...
628
233
"""Tests for the power output classes.""" from typing import List, Optional, Type from j5.backends import Backend from j5.boards import Board from j5.components.power_output import PowerOutput, PowerOutputInterface class MockPowerOutputDriver(PowerOutputInterface): """A testing driver for power outputs.""" ...
2,804
758
# Software License Agreement (BSD License) # # Copyright (c) 2009, Willow Garage, Inc. # 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...
11,660
4,092
#!/usr/bin/env python3 from html.parser import HTMLParser import inquirer import requests # Parser for HTML input class InputParser(HTMLParser): def __init__(self, input_name): super().__init__() self._input_name = input_name self._value = None @property def value(self): ...
4,118
1,212
import chardet import sys import codecs import os def findEncoding(s): file = open(s, mode='rb') buf = file.read() result = chardet.detect(buf) file.close() return result['encoding'] def convertEncoding(s): if os.access(s,os.W_OK): encoding = findEncoding(s) ...
1,480
525
import unittest from asyncio import sleep from async_unittest import TestCase from aio_counter import AioCounter from aio_counter.exceptions import AioCounterException class TestAioCounter(TestCase): TIK = float(0.3) TAK = float(0.6) TTL = int(1) @classmethod def setUpClass(cls) -> None: ...
4,547
1,384
from dexp.processing.remove_beads.beadsremover import BeadsRemover
67
23