id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4802169 | import argparse
#from pytlv.TLV import *
from TLV import *
from smartcard.System import readers
from smartcard.util import toHexString,toASCIIString
from smartcard.Exceptions import NoCardException
import Crypto
from Crypto.PublicKey import RSA
import json
import rocatest
import sys
r=readers()
GET_RESPONSE = [0X00... |
4802214 | import os
from os import path
from flask import Flask
from flask import g
from flask import request
from werkzeug.utils import import_string
from werkzeug.utils import ImportStringError
from jinja2 import ChoiceLoader, FileSystemLoader
from flask_wtf import CSRFProtect
from boiler.config import DefaultConfig
from boil... |
4802220 | try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
class Base:
module_types = []
name = ""
active = True
# if module can send requests
request = None
should_run = True
input = ""
output = ""
severity = 0
verify = True
scope = ... |
4802250 | from petlib.ec import *
from petlib.bn import *
from hashlib import sha256
from Commitment import *
from LPoly import*
import numpy as np
import math
def bigint(x):
return Bn.from_decimal(str(x))
def parse_vector(V,m,zero=0):
V+=[zero]*(-len(V)%m)
V_parsed=[[V[i+k*(m)]for i in xrange(m)]for k in xrange(le... |
4802251 | from portality.core import app
from portality.tasks.ingestarticles import IngestArticlesBackgroundTask
from portality.background import BackgroundApi
from portality.models.background import StdOutBackgroundJob
from werkzeug import FileStorage
if __name__ == "__main__":
if app.config.get("SCRIPTS_READ_ONLY_MODE", F... |
4802303 | from biicode.common.edition.parsing.conf.main_conf_file_parser import (EntryPointConfiguration,
parse_mains_conf)
from biicode.common.test.bii_test_case import BiiTestCase
class TestEntryPointConfigurationFileParser(BiiTestCase):
def test_simp... |
4802306 | import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap import utility
utility.enable_high_dpi_awareness()
root = tk.Tk()
style = ttk.Style()
frame = ttk.Frame(padding=10)
frame.pack(padx=10, pady=10)
top_frame = ttk.Frame(frame)
top_frame.pack(fill=tk.BOTH)
bot_frame = ttk.Frame(frame)
bot_frame.pack(fil... |
4802319 | from django.db import models
from crm import models as crm_models
# Create your models here.
class FlowTemplate(models.Model):
"""流程模版"""
name = models.CharField(max_length=128, unique=True)
description = models.TextField(blank=True, null=True)
flow_type_choices = (('FlowVaction', '请假流程'),
... |
4802328 | list_1 = [1, 2, 3] # lists can be created using square brakets
type(list_1) == list # ==> True
list_2 = [ # lists can contain different types
1, # an integer
'a string', # a string
int # a type
]
list_3 = list(list_2) # lists can be created from other iterables using the list() constructor
list_1... |
4802343 | import sys
import os
import htpasswd
if "INFRABOX_DOCKER_REGISTRY_ADMIN_USERNAME" not in os.environ:
print("INFRABOX_DOCKER_REGISTRY_ADMIN_PASSWORD not set")
sys.exit(1)
if "INFRABOX_DOCKER_REGISTRY_ADMIN_PASSWORD" not in os.environ:
print("INFRABOX_DOCKER_REGISTRY_ADMIN_PASSWORD not set")
sys.exit(1)... |
4802380 | from fastapi import FastAPI
app = FastAPI()
@app.get("/users")
async def get_user(page: int = 1, size: int = 10):
return {"page": page, "size": size}
|
4802383 | HEIGHT = 64
WIDTH = 64
COLORS = 8
BITS = 12288
BPP = 3
PALETTE = [0x0000,0xb6b5,0x00b0,0x6d6b,0x4082,0x494a,0xffff,0x2000]
_bitmap =\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x... |
4802387 | from PhotochemPy import PhotochemPy
#######################
##### ModernEarth #####
#######################
template = '../input/templates/ModernEarth'
star = 'Sun_now.txt'
pc = PhotochemPy(template+'/species.dat', \
template+'/reactions.rx', \
template+'/settings.yaml', \
... |
4802390 | from random import shuffle
"""Contains the Maze class which is the array-represented maze."""
class Maze:
def __init__(self, rows=30, cols=40):
self.rows = rows
self.cols = cols
self.keep_going = 1
self.maze = {}
for y in range(rows):
for x in range(cols):
cell = {'south' : 1, 'e... |
4802450 | from itertools import islice
from typing import *
from airflow.hooks.base import BaseHook
from clickhouse_driver import Client
class ClickHouseHook(BaseHook):
conn_name_attr = 'clickhouse_conn_id'
default_conn_name = 'clickhouse_default'
def __init__(
self,
clickhouse_conn_id: st... |
4802519 | from __future__ import division
import numpy as np
import os, pygame, time
class Display:
def __init__(self, parent):
'''
Display Class is a class for visualizing the vehiles in the specefied regions and their queuing status; member, head or not in queue
'''
# Initiating pygame
pygame... |
4802578 | from dataloaders.dataset1d import EcgDataset1D
from dataloaders.dataset2d import EcgDataset2D
from models import models1d, models2d
from runners.base_runner import BaseRunner
class Runner2D(BaseRunner):
def __init__(self, config):
super().__init__(config)
def _init_net(self):
model = getattr(... |
4802579 | import logging
import operator
from collections import Counter
from django.db.models import Q
from ephios.core.consequences import QualificationConsequenceHandler
from ephios.core.models import AbstractParticipation, LocalParticipation
from ephios.plugins.eventautoqualification.models import EventAutoQualificationCon... |
4802583 | import logging
from pathlib import Path
from typing import Optional
from classy.utils.experiment import Experiment
logger = logging.getLogger(__name__)
def unzip(zip_path: str, target: Path):
import zipfile
"""
Unzip the contents of `zip_path` into `target`.
"""
logger.debug(f"Unzipping {zip_pa... |
4802617 | import re
from docutils import nodes, utils
from docutils.parsers.rst import roles
pubmed_uri_pattern = "http://www.ncbi.nlm.nih.gov/pubmed/%i"
doi_uri_pattern = "http://dx.doi.org/%s"
def pmid_reference_role(role, rawtext, text, lineno, inliner,
options={}, content=[]):
try:
pmid... |
4802638 | import os
from twilio.rest import Client
# put your own credentials here
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
client.messages.create(
to="+15558675310",
... |
4802651 | def get_network(network_name):
network_name = network_name.lower()
# Original GR-ConvNet
if network_name == 'grconvnet':
from .grconvnet import GenerativeResnet
return GenerativeResnet
# Configurable GR-ConvNet with multiple dropouts
elif network_name == 'grconvnet2':
from .g... |
4802652 | import unittest
from katas.kyu_6.validate_credit_card_number import validate
class ValidateCreditCardNumberTestCase(unittest.TestCase):
def test_true(self):
self.assertTrue(validate(26))
def test_true_2(self):
self.assertTrue(validate(91))
def test_true_3(self):
self.assertTrue(... |
4802702 | import requests
headers = {
'Content-Type': 'application/json',
}
with open('my_file.txt', 'rb') as f:
data = f.read()
response = requests.put('http://localhost:28139/twitter/_mapping/user?pretty', headers=headers, data=data)
|
4802705 | from maze.zeolite import PerfectZeolite
def main():
cif_dir = "/Users/dda/Code/MAZE-sim/data/BEA.cif"
zeolite = PerfectZeolite.build_from_cif_with_labels(cif_dir)
print('t_site_to_atom_indices', zeolite._site_to_atom_indices)
print('atom_indices_to_t_site', zeolite._atom_indices_to_site)
atom_types... |
4802740 | x = 0
if 1 == 1:
x += 5
else:
x += 3
assert x == 5
y = 0
if 1 == 2:
y += 5
else:
y += 3
assert y == 3
|
4802767 | from .attention import Attention
from .attention import BidirectionalAttention
from .attention import MatchModule
from .dropout import RNNDropout
from .stacked_brnn import StackedBRNN
from .gaussian_kernel import GaussianKernel
from .matching import Matching
from .bert_module import BertModule
from .character_embedding... |
4802778 | from .onmanager import ONProcess
from xml.etree import cElementTree
import os
# Check for the existing of ON_COM32_VERSION environment variable,
# Default value is set to 15
# Existing value 14 may be used
ON_COM32_VERSION = os.environ.get("ON_COM32_VERSION", 15)
namespace = ""
class OneNote():
def __init__(sel... |
4802813 | description = "IK Pose where x, y translation, rot y and z are close to extreme"
# ********************************
# Dimensions
# ********************************
given_dimensions = {
"front": 73,
"side": 100,
"middle": 130,
"coxia": 75,
"femur": 129,
"tibia": 154,
}
# **********************... |
4802863 | import os
import sys
from setuptools import setup, find_packages
if 'bsd' in sys.platform:
examplesdir = "/usr/local/share/examples/zabbix-smartmontools"
sudoersfile = "Unix/sudoers.d/zabbix"
elif sys.platform.startswith("linux"):
examplesdir = "/usr/local/share/doc/zabbix-smartmontools/examples"
sudo... |
4802885 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import svm, tree
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
from sklearn.metrics import silhouette_score
from skle... |
4802946 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import metrics
from sklearn.cluster import DBSCAN
from sklearn.manifold import TSNE
def fit_dbscan(X_fit, eps=0.55, min_samples=8, plot=False, n_jobs=None):
"""Runs DBSCAN based clustering.
Args:
X_fit (array):
Array of featu... |
4803011 | import numpy as np
import joblib
import os
from rlkit.data_management.simple_replay_buffer import SimpleReplayBuffer
# get the original
her_demos_path = '/ais/gobi6/kamyar/oorl_rlkit/expert_demos/her_fetch_pick_and_place/debug_fetch_reach/data_for_debug_fetch_reach_random_100.npz'
rlkit_buffer_save_dir = '/ais/gobi6/k... |
4803015 | import albumentations as A
import colorednoise as cn
import librosa
import numpy as np
from albumentations.core.transforms_interface import ImageOnlyTransform
def get_transforms(config: dict, phase: str):
transforms = config.get('transforms')
if transforms is None:
return None
else:
if tr... |
4803018 | import torch
from allennlp.training.metrics import F1Measure, Metric
from overrides import overrides
from typing import Dict, Optional
@Metric.register('binary-f1')
class BinaryF1Measure(F1Measure):
"""
The BinaryF1Measure allows for computing the standard F1 metric using
two binary vectors, the ground-tr... |
4803036 | import argparse
import json
import multiprocessing
import time
from abc import ABCMeta, abstractmethod
from pprint import pprint
from typing import Tuple, Optional, Dict, Any
import os.path
import sys
import h5py
from keras import optimizers
import keras.backend
import numpy as np
import gym
from kerl.common.agent im... |
4803048 | import pytest
import datetime
import json
import pandas as pd
import numpy as np
from tabloo.backend import Backend, to_json, convert_column
@pytest.fixture
def df_simple():
df = pd.DataFrame({
"A": [1, 3, 2],
"B": [6, 5, 4],
})
df = df[sorted(df.columns)]
return df
@pytest.fixtur... |
4803050 | import os.path
from setuptools import setup, find_packages
path = os.path.split(__file__)[0]
with open(os.path.join(path, "picogeojson/__init__.py")) as f:
version = f.readline().split("=")[1].strip().strip('"')
setup(
name="picogeojson",
version=version,
author="<NAME>",
author_em... |
4803072 | import unittest
from pyapprox.first_order_stochastic_dominance import *
from pyapprox.second_order_stochastic_dominance import *
from pyapprox.optimization import check_gradients, check_hessian
from pyapprox.rol_minimize import has_ROL
from functools import partial
skiptest_rol = unittest.skipIf(
not has_ROL, rea... |
4803088 | from . import OAuth2
class OAuth2Okta(OAuth2):
name = "oauth2okta"
label = "Okta"
login_url = "https://XXX.okta.com/oauth2/default/v1/authorize"
token_url = "https://XXX.okta.com/oauth2/default/v1/token"
userinfo_url = "https://XXX.okta.com/oauth2/default/v1/revoke"
revoke_url = "https://XXX.... |
4803090 | class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
i, j = 0, len(numbers) - 1
while True:
t = numbers[i] + numbers[j]
if t == target:
return [i + 1, j ... |
4803124 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import fan, output
from esphome.const import (
CONF_OSCILLATION_OUTPUT,
CONF_OUTPUT,
CONF_DIRECTION_OUTPUT,
CONF_OUTPUT_ID,
CONF_SPEED,
CONF_SPEED_COUNT,
)
from .. import speed_ns
SpeedFan = speed_ns.cla... |
4803161 | import numpy as np
import pandas as pd
import random
import math
import warnings
warnings.filterwarnings("ignore")
warnings.filterwarnings("ignore",category=FutureWarning)
import tensorflow as tf
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Dropout, Flatten, Ac... |
4803224 | from __future__ import absolute_import
import random
import socket
from datetime import datetime
import mock
from django.test import TestCase
from rest_framework import serializers
from celery_rpc.base import DRF3
from .. import config, utils
from ..client import Client
from .utils import SimpleModelTestMixin
clas... |
4803227 | from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()
#config.General.requestName = 'commonmode_zerobias_278509_278770_278808_v3'
config.General.requestName = 'commonmode_zerobias_277194_v3'
config.General.workArea = '/afs/cern.ch/work/v/venturia/crab'
config.General.transferOutputs = Tr... |
4803250 | import os
import random
import string
from pathlib import Path
from typing import Union
from functools import wraps
import numpy as np
from trescope.core import ELog
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[c... |
4803319 | from __future__ import absolute_import
from version_information.version import version as __version__
from version_information.version_information import *
|
4803327 | import builtins
import contextlib
import inspect
import re
import subprocess
import sys
import types
import typing
import unittest
from contextlib import ExitStack
from enum import Enum
from io import StringIO
from pathlib import Path
from tempfile import TemporaryDirectory
import defopt
from defopt import __version__... |
4803387 | from random import randint as randomrandint
from goopylib.maths.interpolations import *
# -------------------------------------------------------------------------
# COLOUR CLASSES
class Colour:
colour = None
string = "colour"
red = 0
green = 0
blue = 0
def __init__(self):
pass
... |
4803414 | from gerencianet import Gerencianet
from credentials import CREDENTIALS
gn = Gerencianet(CREDENTIALS)
params = {
"inicio": "2021-03-22T00:00:00.000Z",
"fim": "2021-03-31T00:00:00.000Z"
}
response = gn.pix_location_list(params=params)
print(response)
|
4803462 | import os
import sys
sys.path.append('./../')
import math
import mxnet as mx
import numpy as np
from common.IR.IR_graph import IRGraph
import common.IR.model_pb2 as model_pb2
from common.IR.recover import Recover
class MXNetRecover(Recover):
dtype_map = {
model_pb2.FLOAT16 : "float16",
model_pb... |
4803485 | from pygments import highlight
from pygments.formatter import Formatter
from pygments.lexers import get_lexer_by_name
from pygments.styles import get_style_by_name
from .textparser import NEWLINE_1, normalize_tokens
from .textstyle import TextStyle
class MyFormatter(Formatter):
def __init__(self):
super(... |
4803529 | from jug import TaskGenerator
from jug.task import return_tuple
@TaskGenerator
def zero():
return 0
@TaskGenerator
def range10():
return list(range(10))
@TaskGenerator
def double(x):
return 2*x
@return_tuple(2)
@TaskGenerator
def plus1(x):
return x, 1+x
r = range10()
z = zero()
r0 = r[z]
z2 = doub... |
4803648 | import inspect
import unittest
from src.masoniteorm.models import Model
from src.masoniteorm.scopes import (
SoftDeleteScope,
SoftDeletesMixin,
TimeStampsMixin,
scope,
)
class UserSoft(Model, SoftDeletesMixin):
__dry__ = True
class User(Model):
__dry__ = True
class TestMySQLGlobalScopes(... |
4803649 | from access.utils import emailify
from labour.models import Signup
def requested_alias(person):
signup = Signup.objects.filter(event__slug='aicon2016', person=person).first()
if signup and signup.signup_extra.email_alias:
return emailify(signup.signup_extra.email_alias.replace('@aicon.fi', ''))
r... |
4803660 | from django import forms
from django.utils.translation import ugettext as _
class LoginForm(forms.Form):
username = forms.CharField(label=_("Username"), max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('Username'),
... |
4803677 | import cv2
from PIL import Image
import requests
import numpy as np
from io import BytesIO
url='https://i.pinimg.com/736x/56/60/ba/5660ba6529611cee23af24c608312f2b--motion-sexy-girls.jpg'
response = requests.get(url)
img = np.array(Image.open(BytesIO(response.content)))
cv2.imwrite('porn.jpg',img)
cv2.wait... |
4803685 | from .empatica import get_features_for_empatica_archive
__all__ = [
"get_features_for_empatica_archive",
]
|
4803701 | from matern import Matern52
from sum_kernel import SumKernel
from product_kernel import ProductKernel
from noise import Noise
from scale import Scale
from transform_kernel import TransformKernel
__all__ = ["Matern52", "SumKernel", "ProductKernel", "Noise", "Scale", "TransformKer... |
4803715 | import pytest
import jet
# pylint: disable=unused-argument
@pytest.mark.parametrize("dtype", ["complex64", "complex128"])
class TestTensor:
def test_default_constructor(self, dtype):
"""Tests that the default constructor is called."""
tensor = jet.Tensor(dtype=dtype)
assert tensor.indices... |
4803736 | from configparser import ConfigParser
from unittest import mock
import json
import asyncio
import pytest
from zake.fake_client import FakeClient
from kazoo.client import KazooState
from zgres import deadman
from . import FakeSleeper
@pytest.mark.asyncio
async def test_functional():
"""Test as much of the whole s... |
4803753 | from theforce.calculator.socketcalc import SocketCalculator
from ase.build import bulk
calc = SocketCalculator(script='calc.py')
atoms = bulk('Au')
atoms.set_calculator(calc)
e = atoms.get_potential_energy()
print(f'potential energy = {e}')
|
4803768 | import sys
sys.path.insert(0, '../')
import torch
from torch import nn
from torch.autograd import Variable
from holder import *
from util import *
from constr_utils import *
# A content word in the hypothesis should align to a content word that is in relation set.
# Let R denote the set of content alignments appear ... |
4803789 | import pyOcean_cpu as ocean
import ctypes
t = ocean.tensor([3,4])
FLOAT_PTR = ctypes.POINTER(ctypes.c_float)
ptr = ctypes.cast(t.ptr, FLOAT_PTR)
for i in range(12) :
ptr[i] = i
print(t)
|
4803797 | from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^load_note/(?P<guid>.+)$', 'familybook.views.load_note',
name='load_note'),
url(r'^save_note/$', 'familybook.views.save_note', name='save_note'),
url(r'^list_notes/(?P<notebook_guid>.+)$', 'familybook.views.list_notes',
... |
4803816 | from __future__ import print_function
import logging
from abc import ABCMeta, abstractmethod
from .. import exceptions
try:
# Python 2
from urlparse import urlparse
except ImportError:
# Python 3
from urllib.parse import urlparse
LOG = logging.getLogger(__name__)
def install_missing_requirements... |
4803861 | import geopandas as gpd
import momepy as mm
tess = gpd.read_file('files/prg.gpkg', layer='queen')
blg = gpd.read_file('files/prg.gpkg', layer='buildings')
streets = gpd.read_file('files/streets.gpkg', layer='streets')
streets['nID'] = mm.unique_id(streets)
blg['nID'] = mm.get_network_id(blg, streets, 'uID', 'nID', ... |
4803865 | from torchvision.datasets import CIFAR10
from .ssl_datamodule import SSLDataModule
from .datasets import LabeledDataset
from .utils import per_class_random_split
# for type hint
from typing import Optional, Tuple, List
from torch.utils.data import Dataset
from torchvision.datasets import VisionDataset
class CIFAR10... |
4803936 | from openchem.models.SiameseModel import SiameseModel
from openchem.modules.embeddings.basic_embedding import Embedding
from openchem.modules.encoders.rnn_encoder import RNNEncoder
from openchem.modules.encoders.gcn_encoder import GraphCNNEncoder
from openchem.modules.mlp.openchem_mlp import OpenChemMLP, OpenChemML... |
4803968 | from .get_column_width import get_column_width
from ..dashutils import center_line
from ..dashutils import add_cushions
from ..dashutils import multis_2_mono
from ..dashutils import ensure_table_strings
import copy
def data2md(table):
"""
Creates a markdown table. The first row will be headers.
Paramete... |
4803972 | import numpy
from numba import jit, prange
from numpy.typing import ArrayLike
from scipy.ndimage import correlate as scipy_ndimage_correlate
__fastmath = {'contract', 'afn', 'reassoc'}
__error_model = 'numpy'
def numba_cpu_correlate(image: ArrayLike, kernel: ArrayLike, output=None):
# Kernel must have odd dimeni... |
4803996 | from build.management.commands.build_structure_extra_proteins import Command as BuildStructureExtraProteins
class Command(BuildStructureExtraProteins):
pass |
4804007 | import numpy as np
import cv2
import caffe
import os
import random
from pandas.io.parsers import read_csv
lm_name = '../../data/CelebA/list/train_full.txt'
ln_name = '../../data/CelebA/list/val_full.txt'
mean_file = '../../data/pretrained/ResNet_mean.binaryproto'
prefix = '../../data/'
proto_data = open(mean_file, "rb... |
4804016 | import os
from os import path as osp
import joblib
import numpy as np
base_path = '/scratch/hdd001/home/kamyar/output'
for exp in ['dagger-halfcheetah', 'dagger-ant', 'dagger-hopper', 'dagger-walker']:
rets = {}
exp_path = osp.join(base_path, exp)
rets['exp'] = []
rets['test'] = []
for sub in os.li... |
4804050 | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='wagtailpress',
version='0.1',
packages=['wagtailpress'],
... |
4804066 | from __future__ import print_function
import unittest
from Helpers.Commands import ThreadedCommandFactory, Command, Kwargs
from SiteAutomations.Examples import GoogleExample
from Project import Models
class KwargsTest(unittest.TestCase):
def setUp(self):
self.test_dict = {
'test1': 'hello wor... |
4804117 | import torch
from torch_geometric.data import Data
from torch_geometric.datasets import TUDataset
from torch_geometric.datasets import Planetoid
from torch_geometric.data import DataLoader
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from torch_geometric.nn import GATConv
from torch_geometric.... |
4804135 | from typing import Optional, List, Callable
from functools import partial
from urllib.request import parse_http_list as _parse_list_header
from urllib.parse import urlparse
from werkzeug.datastructures import Headers
from quart import Request
from quart_trio.asgi import TrioASGIHTTPConnection
class ASGIProxyFix(Trio... |
4804189 | import csv
import json
import sys
def load_csv(fp_in, delimiter=',', quotechar='"', remove_empty=False,
custom_headers=None, **kwargs):
r = csv.DictReader(fp_in, delimiter=delimiter, quotechar=quotechar,
fieldnames=custom_headers)
rows = [row_dct for row_dct in r]
if remove_empty:
... |
4804203 | from gqa_dataset import *
def calc_statistics():
with open('{}/full_vocab.json'.format('meta_info/'), 'r') as f:
vocab = json.load(f)
ivocab = {v: k for k, v in vocab.items()}
with open('{}/answer_vocab.json'.format('meta_info/'), 'r') as f:
answer = json.load(f)
inv_answer = ... |
4804221 | import random
import functools
import matplotlib.pyplot as plt
import numpy as np
import copy
# default functions ----------------------------------------------------------------------
def random_individual():
"""Generate a random individual phenotype"""
return [random.randrange(0,2) for i in range(10)]
def... |
4804265 | import humanize
import pathlib
from typing import Coroutine
async def async_progress(path: pathlib.Path, reader: Coroutine) -> bytes:
def progress(loaded, total, bar_len=30):
filled_len = int(round(bar_len * loaded / total))
empty_len = bar_len - filled_len
loaded = humanize.naturalsize(... |
4804300 | import decimal, logging
import re
from django import template
from sell.models import Payment, Cart
register = template.Library()
@register.filter
def total_pending(shop, user):
cart = Cart.objects.filter(shop=shop).filter(bidder=user).get()
total_cart = cart.total()
try:
payment = Payment.objects... |
4804340 | from __future__ import print_function
from __future__ import absolute_import
import argparse
import io
from PIL import Image
from sciencebeam_gym.utils.tf import FileIO
def get_args_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--image_width',
type=int,
required=... |
4804344 | import threading
class TransactionPool:
def __init__(self):
print('Initializing TransactionPool...')
self.transactions = []
self.lock = threading.Lock()
def set_new_transaction(self, transaction):
with self.lock:
print('set_new_transaction is called', transaction)
... |
4804370 | import unittest
import numpy as np
import scipy.sparse
from autotabular.pipeline.components.feature_preprocessing.random_trees_embedding import RandomTreesEmbedding
from autotabular.pipeline.util import _test_preprocessing, get_dataset
class RandomTreesEmbeddingComponentTest(unittest.TestCase):
def test_default... |
4804431 | from django.urls import path, include
from devilry.devilry_account import crinstance_account
urlpatterns = [
path('', include(crinstance_account.CrAdminInstance.urls()))
]
# from django.conf.urls import include, url
# from devilry.devilry_account import crinstance_account
# urlpatterns = [
# url(r'^', inc... |
4804442 | from astropy import config as _config
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""NSF's OIR Lab Astro Data Archive(Beta)
-----------------------------------------
The NSF's OIR Lab Astro Data Archive (formerly NOAO Science Archive)
provides access to data taken with more than 40 telescope and
in... |
4804450 | import sys, os
from Package import Package
import sconsconfig as config
##
##
##
class libhpc(Package):
def __init__(self, **kwargs):
defaults = {
'download_url': 'http://github.com/furious-luke/libhpc/tarball/master',
}
defaults.update(kwargs)
super(libhpc, self).__ini... |
4804458 | from spacy.language import Language
def attach_sklearn_categoriser(nlp, pipe_name, estimator):
"""
This function will attach a scikit-learn compatible estimator to
the pipeline which will feed predictions to the `.cats` property.
This is useful if you're interesting in added a pre-trained sklearn
... |
4804467 | from __future__ import absolute_import, division, print_function
class Node(object):
"""
A node that allows setting arbitrary attributes
"""
def dummy(value):
return value
# Extractions
class Value(object):
"""
Extract text from elem
"""
def __init__(self, attribute, conversion = dummy):
self.... |
4804511 | from manga_py.provider import Provider
from .helpers.std import Std
class MangaOnNet(Provider, Std):
__has_ch = False
def get_archive_name(self) -> str:
idx = self.get_chapter_index().split('-')
if self.__has_ch:
var = {'vol': idx[0], 'ch': idx[1]}
else:
var = ... |
4804512 | from flask import abort
from flask_login import current_user
def assert_rights_to_problem(problem):
if not problem:
abort(404)
if not current_user.can_access_problem(problem):
abort(403)
|
4804549 | from setuptools import setup
setup(
name='isoparser',
version='0.3',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/barneygale/isoparser',
license='MIT',
description='Parser for the ISO 9660 disk image format',
install_requires=['six'],
packages=["isoparser"],
)
|
4804566 | commit_comments = [{'name': 'html_url',
'type': 'varchar'},
{'name': 'id',
'type': 'int'},
{'name': 'updated_at',
'type': 'varchar'},
{'name': 'url',
'type': 'varchar'},
... |
4804576 | from random import Random
from unittest import TestCase
from numpy import median
from sklearn import linear_model
from examples.trivial_model import TrivialModel
class TestModelTraining(TestCase):
@staticmethod
def _train_test_split(func, model_class=TrivialModel, **kwargs):
model, score = model_cl... |
4804595 | for n in range (2,10):
for x in range(2,n):
if n%x==0:
print(n,'equals',x,'*',n//x)
break
else:
#loop fell without finding a factor
print(n,'is a prime number') |
4804636 | from PyObjCTools.TestSupport import *
from Quartz import *
from CoreFoundation import CFArrayRef
from Foundation import NSMutableData
try:
unicode
except NameError:
unicode = str
try:
long
except NameError:
long = int
import sys, os
if sys.version_info[0] != 2:
def buffer(value):
if isi... |
4804638 | import pyOcean_cpu as ocean
a = ocean.asTensor([1,2,3])
s = a.storage
b = ocean.int8(9)
x = ocean.cast(a, a.dtype, ocean.cpu)
print(x.obj == a.obj)
print(x.storage.obj == a.storage.obj)
print(x)
x = ocean.cast(s, s.dtype, ocean.cpu)
print(x is s)
print(x.obj == s.obj)
print(x)
x = ocean.cast(b, b.dtype)
print(x)
p... |
4804644 | import pickle
from .monitor import *
from .context import text_model_filename
from .textset import *
from .utils.text_encoders import *
from .spaces.process import space_textset_bow, space_textset_w2v, space_textset_d2v
log = logging.getLogger(__name__)
def get_textset_w2v(textset_id, model, size):
"""
get ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.