id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
501608 | import os
import warnings
import sys
if sys.version_info[0] == 2:
from ConfigParser import SafeConfigParser
else:
from configparser import SafeConfigParser
__masked__ = False
def set_masked_default(choice):
'Set whether tables should be masked or not by default (True or False)'
global __masked__
... |
501611 | import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
from transformers import BertModel, BertConfig
from utils import CMD, MSE
class LanguageEmbeddingLayer(nn.Module):
"""Embed input text with "glove" or "Bert"
... |
501615 | from easy_select2.utils import apply_select2, select2_modelform, select2_modelform_meta
from easy_select2.widgets import Select2, Select2Mixin, Select2Multiple
__all__ = ['Select2', 'Select2Mixin', 'Select2Multiple', 'apply_select2',
'select2_modelform', 'select2_modelform_meta']
|
501631 | import itertools as it
def longest_consecutive_seq_len(a):
s = set(a)
best_len = 0
for x in a:
if x not in s: continue
current_len = 1
for step in (1, -1):
for i in it.count(x+step, step):
if i in s: current_len += 1
else: s -= set(range(x... |
501656 | import os
import pandas as pd
import openmatrix as omx
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='check activitysim raw_data')
parser.add_argument('raw_data_directory', metavar='raw_data_directory', type=str, nargs=1,
help=f"path to raw data directory")
pars... |
501694 | import paginate
import requests
from bs4 import BeautifulSoup
from flask import request, url_for, render_template, jsonify, flash
from flask.views import MethodView
from flask_login import login_required
from paginate_sqlalchemy import SqlalchemyOrmWrapper
from sqlalchemy import desc
from nanumlectures.common import i... |
501711 | import threading
from oauth2client.client import Storage as BaseStorage
from oauth2client.client import Credentials
from oauth2client.anyjson import simplejson
def from_dict(container):
"""
Create a Credentials object from a dictionary.
The dictionary is first converted to JSON by the native implementati... |
501738 | import binascii
import string
import random
import struct
import time
from OpenSSL import *
from Crypto.PublicKey.RSA import construct
import rdp_crypto
def connect_req(name):
packet = binascii.unhexlify('0300002e29e00000000000436f6f6b69653a206d737473686173683d')
packet += name ... |
501741 | from abc import ABCMeta, abstractmethod
from datetime import timedelta
from examples.cluster_grain_hello_world.messages.protos_pb2 import HelloRequest, HelloResponse
from protoactor.actor.actor_context import Actor, AbstractContext, RootContext, GlobalRootContext
from protoactor.actor.cancel_token import CancelToken
f... |
501744 | import pandas as pd
import swifter # noqa
from nlp_profiler.constants import DEFAULT_PARALLEL_METHOD, SWIFTER_METHOD
from nlp_profiler.generate_features.parallelisation_methods \
import get_progress_bar, using_joblib_parallel, using_swifter
def generate_features(main_header: str,
high_leve... |
501747 | import os, argparse, imageio
import jittor as jt
from jittor import nn
from lib.Network_Res2Net_GRA_NCD import Network
from utils.data_val import test_dataset
jt.flags.use_cuda = 1
parser = argparse.ArgumentParser()
parser.add_argument('--testsize', type=int, default=352, help='testing size')
parser.add_argument('-... |
501770 | from utils.load_snips import SNIPS
from collections import defaultdict
import json
from tqdm import tqdm
def predict(args,tokenizer,model,train, test, slots):
base_prefixes = defaultdict(str)
for slot in slots:
for _, b in enumerate(train[slot]):
base_prefixes[slot] += f"{b[0]}=>{slot}={b[1... |
501792 | import numpy as np
import cv2
import tensorflow as tf
class Evaluator(object):
def __init__(self, config):
self.mutual_check = True
self.err_thld = config['err_thld']
self.matches = self.bf_matcher_graph()
self.stats = {
'i_eval_stats': np.array((0, 0, 0, 0, 0, 0, 0, 0)... |
501804 | import os.path as osp
import cv2
import numpy as np
from detecting.datasets import transforms, utils
import glob
import xml.etree.ElementTree as ET
class VocDataSet(object):
def __init__(self, dataset_dir, subset,
flip_ratio=0,
pad_mode='fixed',
mean=(0, 0, 0),
... |
501839 | import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Layer
from tensorflow.keras import Sequential
import tensorflow.keras.layers as nn
from einops import rearrange, repeat
from vit import ViT
from t2t import T2TViT
from efficient import ViT as EfficientViT
def exists(val):
... |
501841 | from tequila.circuit.pyzx import convert_to_pyzx, convert_from_pyzx
from tequila.circuit.gates import *
from tequila.simulators.simulator_api import simulate
from tequila import TequilaException
import numpy
import pytest
HAS_PYZX = True
try:
import pyzx
HAS_PYZX = True
except ImportError:
HAS_PYZX = False
... |
501872 | from functools import partial
import numpy as np
import torch
import torch.nn as nn
# Taken from: https://github.dev/computational-imaging/ACORN/
class Sine(nn.Module):
def __init__(self, w0=30):
super().__init__()
self.w0 = w0
def forward(self, input):
return torch.sin(self.w0 * inp... |
501875 | from ipaddress import IPv4Address, IPv4Network
import jsonschema
import os
import subprocess
import yaml
import command
import resource
import template
import util
def get_project(create_dir_if_missing=False) -> str:
project_dir = os.getenv("HOMEWORLD_DIR")
if project_dir is None:
command.fail("no HO... |
501890 | import wx
def main():
a = wx.PySimpleApp()
f = wx.Frame(None)
b = wx.Button(f, -1, 'showmodal')
f2 = wx.Dialog(f)
b2 = wx.Button(f2, -1, 'wut')
def onsubbutton(e):
print 'IsModal ', f2.IsModal()
print 'IsShown ', f2.IsShown()
b2.Bind(wx.EVT_BUTTON, onsubbutton)
def ... |
501893 | from typing import List, Optional, Sequence
from draftjs_exporter.command import Command
from draftjs_exporter.constants import ENTITY_TYPES
from draftjs_exporter.dom import DOM
from draftjs_exporter.error import ExporterException
from draftjs_exporter.options import Options, OptionsMap
from draftjs_exporter.types imp... |
501948 | import string
from ctypes import pointer
from tempfile import NamedTemporaryFile
from collections import defaultdict
from assertpy.assertpy import assert_that
from assertpy import assert_that
import numpy as np
from torch.utils.data import Dataset
from ffcv import DatasetWriter
from ffcv.fields import IntField, JSONFi... |
501998 | from django.contrib import admin
from .models import Blacklist, MessageLog
class BlacklistAdmin(admin.ModelAdmin):
list_display = ('email', 'type', 'created_at')
list_filter = ('type',)
search_fields = ('email',)
admin.site.register(Blacklist, BlacklistAdmin)
class MessageLogAdmin(admin.ModelAdmin):
... |
502013 | import heapq
import collections
class Solution(object):
def findCheapestPrice(self, n, flights, src, dst, K):
graph = collections.defaultdict(dict)
for u, v, w in flights:
graph[u][v] = w
best = {}
pq = [(0, 0, src)]
while pq:
cost, k, place = heapq.h... |
502082 | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def paginate(request, objects, ipp):
paginator = Paginator(objects, ipp)
page = request.GET.get('p')
try:
return paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
... |
502085 | from data import load_data_gse
from contextlib import closing
import os
import shutil
import numpy as np
import pandas as pd
import urllib.request as request
def processing_gse96058(clinical):
assert isinstance(clinical, pd.DataFrame), 'Invalid clinical type. It should be a pandas data frame.'
# cleaning ... |
502099 | from subprocess import check_call
import os
import sys
import shutil
SCRIPT_DIR = os.path.dirname(__file__)
REPO_DIR = os.path.abspath(os.getcwd())
ROOT_DIR = os.path.abspath(os.path.join(REPO_DIR, '..'))
print('ROOT_DIR: %s' % ROOT_DIR)
print('REPO_DIR: %s' % REPO_DIR)
from wheel_build_utils import push_dir, push_e... |
502111 | from flask_restful import marshal_with
from flask_login import current_user
from flask_restful import fields, abort
from appname.api import Resource, BaseAPISchema, API_VERSION
class CurrentUserInfoSchema(BaseAPISchema):
get_fields = {
'id': fields.String,
'email': fields.String,
'full_nam... |
502114 | import numpy as np
import scipy as sp
import pylab as pl
import glob
import json
import re
from matplotlib.widgets import Slider
def loaddata(alphas=[]):
files = glob.glob("dat-alpha-?.*.json")
alphas, xs, ys = [],[],[]
for f in files:
g = re.search(r"dat-alpha-([0-9]\.[0-9]{1,}).json", f)
... |
502125 | from torch import nn
class Wrapper:
@staticmethod
def get_args(parser):
parser.add('--l1_weight', type=float, default=30.0)
@staticmethod
def get_net(args):
criterion = Criterion(args.l1_weight)
return criterion.to(args.device)
class Criterion(nn.Module):
def __init__(self... |
502151 | import os
import xgboost as xgb
import lightgbm as lgb
import shap
from ml.utils import get_algo_dir
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
def visualize_model(model, X, idx, configuration, namespace, name):
if configuration['enabled'] and idx % configuration['n_iterations'] ==... |
502245 | import difflib
import pdb
import gensim
from time import time
from scipy.spatial.distance import pdist, squareform
import scipy
from numpy import dot
from numpy.linalg import norm
import numpy as np
import pickle
embedding_path = '/scratchd/home/satwik/embeddings/'
print('Loading Word2Vec')
st_time = time()
with open(... |
502255 | from django.conf import settings
from django.template import Library
register = Library()
@register.filter('theme_path')
def theme_path(user):
theme = getattr(user, 'theme', None) or settings.THEMES[0]
return 'bootswatch/dist/%s/bootstrap.min.css' % theme
@register.simple_tag
def has_perm(perm, user, obj=N... |
502276 | from .errors import log_error, slack_error
from .ssh import ssh_connect
from .pyspark_udf import udf as pyspark_udf
from .fs_cache import s3_cache, json_file, pickle_file
from .timeout import time_limit
from .regres_test import regress
from .sklearn_dec import SKTransform, SKClassify
|
502354 | from userreport.models import UserReport, GraphicsDevice, GraphicsExtension, GraphicsLimit
from django.contrib import admin
class UserReportAdmin(admin.ModelAdmin):
readonly_fields = ['uploader', 'user_id_hash', 'upload_date', 'generation_date', 'data_type', 'data_version',
'data']
fiel... |
502360 | from abc import ABC, abstractmethod
from typing import Optional
from eth.abc import AtomicDatabaseAPI
from eth2.beacon.db.abc import BaseBeaconChainDB
from eth2.beacon.fork_choice.abc import BaseForkChoice
from eth2.beacon.state_machines.abc import BaseBeaconStateMachine
from eth2.beacon.types.attestations import Att... |
502406 | import torch
# from typed_args import TypedArgs
import argparse
import os
from typing import Dict, List, NewType, Tuple
from tqdm import tqdm
from numpy.lib.format import open_memmap
import numpy as np
from utils.npy_file import NpyFile
from utils.io import dump_pickle
# class Args(TypedArgs):
# def __init__(sel... |
502429 | from xstate.machine import Machine
lights = Machine(
{
"id": "lights",
"initial": "green",
"states": {
"green": {"on": {"TIMER": "yellow"}, "entry": [{"type": "enterGreen"}]},
"yellow": {"on": {"TIMER": "red"}},
"red": {
"initial": "walk",... |
502485 | from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
import webbrowser
class ExceptionScreen(Screen):
Builder.load_file('uix/kv/exceptionscreen/exceptionscreen.kv')
def __init__(self, exception_text, **kwargs):
self.exception_text = exception_text
super(ExceptionScreen, se... |
502498 | import os
import yaml
import argparse
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--archs', type = str, choices=['TSA'], help = 'our approach')
parser.add_argument('--benchmark', type = str, choices=['FineDiving'], help = 'dataset')
parser.add_argument('--prefix', type = str... |
502518 | import warnings
from typing import Dict
import torch
from torch import nn, optim as optim
from rl_multi_agent import MultiAgent
from utils.misc_util import ensure_shared_grads
def compute_losses_no_backprop(agent: MultiAgent):
full_loss = None
last_losses = {}
for k, loss in agent.loss().items():
... |
502532 | import scipy as sp
import numpy as np
from scipy import stats as st
from scipy import linalg as la
import solutions as sol
data=sol.sim_data(sp.array([[108,200],[206,400],[74,140],[4,8]]),100000)
probs=sol.probabilities(data)
pulls=sol.numPulls(probs,1300)
if(sum(pulls)!=1300):
print("Total pulls does not equal to ... |
502545 | import peewee
import sqlite3
file = 'Paises.db'
db = peewee.SqliteDatabase(file)
class Pais(peewee.Model):
name = peewee.TextField()
capital = peewee.TextField()
region = peewee.TextField()
languages = peewee.TextField()
flag = peewee.TextField()
class Meta:
database = db
db_t... |
502553 | import os
def watch_templates(directory):
def wrapper(f):
f.TEMPLATES_DIRECTORY = directory
f.TEMPLATE_FILES = [f for f in os.listdir(directory) if f.endswith('tpl')]
return f
return wrapper
|
502568 | from enum import Enum
class ControlInputEnum(Enum):
@classmethod
def allowedValues(cls):
return []
class ControlOperation(ControlInputEnum):
START = 'start'
STOP = 'stop'
NONE = 'none'
SETTINGS = 'settings'
UNKNOWN = 'unknown'
@classmethod
def allowedValues(cls):
... |
502603 | import argparse
import pyperclip
from .pickuplinesgalore import PickuplinesGalore
from .pickuplinegen import Pickuplinegen
def say_sorry():
print("Sorry buddy! couldn't found any pickupline ¯\_(ツ)_/¯")
def run(args):
if args.list:
pick = PickuplinesGalore()
print("\n".join(pick.get_list_of_ca... |
502606 | from virtool.users.fake import create_fake_bob_user
async def test_create_fake_bob_user(snapshot, app, dbi, static_time, mocker):
mocker.patch("virtool.db.utils.get_new_id", return_value="abc123")
await create_fake_bob_user(app)
assert await dbi.users.find_one({}, {"password": False}) == snapshot
|
502690 | from typing import Optional
from mstrio.utils.helper import Dictable
class Node(Dictable):
def __init__(self, name: str, address: Optional[str] = None,
service_control: Optional[bool] = None) -> None:
self.name = name
self.address = address
self.service_control = service... |
502850 | from plex.lib.six.moves.urllib_parse import urlparse as std_urlparse
def try_convert(value, value_type, default=None):
try:
return value_type(value)
except ValueError:
return default
except TypeError:
return default
def urlparse(url):
scheme = None
scheme_pos = url.find('... |
502926 | import math
import numpy as np
import string
import random
import json
import argparse
import torch as T
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from transformers import *
import sys
sys.path.append("../")
from DataLoader.bucket_and_batch import bucket_and_batch
from model.B... |
502994 | title = "All my commands, peko!"
description = "If you have any problems with me, feel free to contact the creator on Discord (bemxio#5847) or on Reddit (u/bemxioo) peko!"
invite = "Here's my invite link peko! https://discord.com/api/oauth2/authorize?client_id=817481976797069383&permissions=116736&scope=bot"
dm_check =... |
503014 | import re
from datetime import datetime, timedelta
import json
from flask import request, Response
from flask_restful import Resource, abort
from lxml import etree
from common import util
from common import objects
class Processes(Resource):
"""Lists processes (data update)."""
def get(self):
list_... |
503124 | import json
corpus = {}
with open("final.json","r") as fh:
corpus = json.load(fh)
act_tags = []
topics = []
for season_episode in corpus:
season,episode = season_episode.split("_")
for scene in corpus[season_episode]:
for turn in scene["Turns"]:
print(turn["Speaker"])
if t... |
503156 | import unittest
import numpy as np
import scipy.stats as st
from ..data import Vector
from ..analysis import TwoSampleKSTest
from ..analysis.exc import MinimumSizeError, NoDataError
class TestTwoSampleKS(unittest.TestCase):
def test_two_sample_KS_matched(self):
"""Test the Two Sample KS Test with matched... |
503164 | import numpy as np
from typing import Callable, Union, List, Tuple, Any
def keep_bounds(population: np.ndarray,
bounds: np.ndarray) -> np.ndarray:
"""
Constrains the population to its proper limits.
Any value outside its bounded ranged is clipped.
:param population: Current population ... |
503172 | fname = r"h:\tmp.txt"
import win32security, win32file, win32api, ntsecuritycon, win32con
new_privs = (
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SECURITY_NAME),
win32con.SE_PRIVILEGE_ENABLED,
),
(
win32security.LookupPrivilegeValue("", ntsecuritycon.SE_SHUTDOWN_NAME... |
503188 | from typing import Set, Type
from arrakisclient.types.namespace import ArrakisNamespace, Relation
class ReferenceableNamespace(ArrakisNamespace):
ellipsis = Relation(relation_name="...")
class User(ReferenceableNamespace):
__namespace__ = "testtenant/user"
class UserGroup(ArrakisNamespace):
__namespa... |
503195 | import time
from typing import Optional, Union, Dict, Any, List
from algoliasearch.exceptions import AlgoliaUnreachableHostException, RequestException
from algoliasearch.http.hosts import Host
from algoliasearch.http.request_options import RequestOptions
from algoliasearch.configs import Config
from algoliasearch.http... |
503203 | import sys
sys.setrecursionlimit(2000000000)
def factoring(n, lst, count):
if (count > n):
print "The factors are", lst
elif (n % count == 0):
lst.append(count)
print "list is", lst
factoring(n, lst, count+1)
else:
factoring(n, lst, count+1)
k = [1]
factoring(472822,k,2) |
503207 | import torch
import sys
_, a, b = sys.argv
x, y = torch.load(a), torch.load(b)
x, y = x.squeeze(), y.squeeze()
x = x / x.norm(dim = -1, keepdim = True)
y = y / y.norm(dim = -1, keepdim = True)
x = x[:1203]
y = y[:1203]
sim = (x*y).sum(dim=-1)
print(sim)
print(sim.mean()) |
503224 | import numpy as np
from astropy import units as u
from ..cube import SEDCube
def test_roundrip(tmpdir):
n_models = 30
n_ap = 3
n_wav = 10
s = SEDCube()
s.names = ['name_{0:02d}'.format(i) for i in range(n_models)]
s.apertures = np.linspace(10, 100, n_ap) * u.au
s.wav = np.linspace(0.0... |
503234 | from requests.exceptions import ConnectionError
class MediaWikiError(Exception):
"""
Raised when the MediaWiki API returns an error.
"""
def __init__(self, message, errors):
super(MediaWikiError, self).__init__(message)
self.errors = errors
class LoopException(Exception):
"""
... |
503296 | import ast
from sklearn.preprocessing import LabelEncoder
from keras.preprocessing import sequence
import numpy as np
from keras.models import load_model
from optparse import OptionParser
from keras.layers import Average, Input
from keras.models import Model
def toEvaluationFormat(all_doc_ids, all_prediction):
ev... |
503303 | from .scope import scope
from .BaseScope import BaseScope
from .SoftDeletesMixin import SoftDeletesMixin
from .SoftDeleteScope import SoftDeleteScope
from .TimeStampsMixin import TimeStampsMixin
from .TimeStampsScope import TimeStampsScope
from .UUIDPrimaryKeyScope import UUIDPrimaryKeyScope
from .UUIDPrimaryKeyMixin i... |
503326 | import datetime
import pytz
from django.utils import timezone
from connect.moderation.models import ModerationLogMsg
def log_moderator_event(msg_type, user, moderator, comment=''):
"""
Log a moderation event.
"""
message = ModerationLogMsg.objects.create(
msg_type=msg_type,
comment=c... |
503332 | import torch
import os
from argparse import ArgumentParser
from logire import LogiRE, RelationExtractor
from dataset import BackboneDataset, get_backbone_collate_fn
from torch.utils.data import DataLoader
def main():
parser = ArgumentParser()
parser.add_argument('--mode', default='train')
parser.add_argum... |
503341 | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# from core.encoders import *
import json
from torch import optim
from cortex_DIM.nn_modules.mi_networks import MIFCNet, MI1x1ConvNet
from losses import *
class GlobalDiscriminator(nn.Module):
... |
503402 | import os
# To import anything we need to add the backend directory into sys.path
import sys
BACKEND_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if BACKEND_DIR not in sys.path:
sys.path.append(BACKEND_DIR) |
503412 | import sys
from girder_worker.utils import TeeStdOutCustomWrite
def test_TeeStdOutCustomWrite(capfd):
nonlocal_ = {'data': ''}
def _append_to_data(message, **kwargs):
nonlocal_['data'] += message
with TeeStdOutCustomWrite(_append_to_data):
sys.stdout.write('Test String')
sys.stdo... |
503434 | import os
from unittest import TestCase
import psutil
import glcontext
class ContextTestCase(TestCase):
def test_create(self):
"""Basic context testing"""
# Create a standalone context
# os.environ['GLCONTEXT_WIN_LIBGL'] = 'moo.dll'
# os.environ['GLCONTEXT_LINUX_LIBGL'... |
503444 | from apscheduler.schedulers.blocking import BlockingScheduler
from multiprocessing.dummy import Pool as ThreadPool
from bs4 import BeautifulSoup as bs
import requests
import timeit
import datetime
import time
import sys
import re
from getconf import *
# TO DO: scrape for early links
# Constants
base_url = 'http://www... |
503469 | XX_train = np.concatenate((X_train, np.sin(4 * X_train)), axis=1)
XX_test = np.concatenate((X_test, np.sin(4 * X_test)), axis=1)
regressor.fit(XX_train, y_train)
y_pred_test_sine = regressor.predict(XX_test)
plt.plot(X_test, y_test, 'o', label="data")
plt.plot(X_test, y_pred_test_sine, 'o', label="prediction with sine... |
503520 | import seaborn as sns
from pudzu.charts import *
from pudzu.sandbox.bamboo import *
FONT, fg, bg = sans, "white", "black"
atlas = pd.read_csv("datasets/countries.csv").split_columns(('nationality', 'tld', 'country'), "|").explode('country').set_index('country')
df = pd.read_csv("datasets/eu_foreignleaders.csv")
def ... |
503525 | from typing import List, Union
import pandas as pd
from exceldriver.columns import get_n_cols_after_col
def write_df_to_ws_values(df: pd.DataFrame, ws, begin_col: str = 'A', begin_row: int = 1):
# TODO: multi-index
num_cols = len(df.columns) + 1 # add 1 as index will automatically be converted to col
end... |
503574 | from datetime import datetime
import logging
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
from edx_rest_api_client.client import EdxRestApiClient
from requests import RequestException
from slumber.exceptions import HttpClientError
from api.backends.base_api_client import B... |
503650 | from leapp.models import Model, fields
from leapp.topics import SystemInfoTopic
class QuaggaToFrrFacts(Model):
"""
Model for quagga to frr actors.
A list of configuration files used by quagga. This list is used to add yes/no to
/etc/frr/daemons file. It indicates which daemons from frr should be run.... |
503663 | from glob import glob
import os
for file in glob("*/smri/warped_image/fwhm_6.0/*_wtsimt.nii.gz"):
if not os.path.exists(file.replace(".nii.gz", "_2mm.nii.gz")):
os.system("flirt -interp nearestneighbour -in %s -ref %s -applyisoxfm 2 -out %s"%(file, file, file.replace(".nii.gz", "_2mm.nii.gz")))
#os.r... |
503702 | import requests
import datetime
import pandas as pd
from ..app import app
from ..utils import config
from .sqlalchemy_declarative import strydSummary
from ..api.database import engine
from sqlalchemy import func
def auth_stryd_session():
requestJSON = {"email": config.get('stryd', 'username'), "password": config.... |
503762 | import logging
from logging import config
import json
import random
from random import shuffle
import argparse
from pprint import pprint
from pathlib import Path
import sys
import os
import gc
import math
import ipdb
from tqdm import tqdm
import numpy as np
import pandas as pd
import adabound
from sklearn.metrics impor... |
503781 | from collections import namedtuple
import os, socket
Message = namedtuple('Message', 'data, response')
class Socket(object):
def __init__(self, host, port, dispatch, max_size = 1024):
self.host = host
self.port = port
self.max_size = max_size
self.dispatch = dispatch
def list... |
503785 | import argparse
import pickle
import os
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.models import inception_v3, Inception3
import numpy as np
from tqdm import tqdm
from inception import InceptionV3
... |
503842 | import torch
from torch.utils import data
import json
from pytorch_transformers.tokenization_bert import BertTokenizer
import numpy as np
import random
from utils.data_utils import list2tensorpad, encode_input, encode_image_input
from utils.image_features_reader import ImageFeaturesH5Reader
class VisdialDataset(data.Da... |
503847 | import pandas as pd
from sklearn import datasets
iris = datasets.load_iris()
iris_df = pd.DataFrame(iris.data, columns = iris.feature_names)
iris_df.head()
iris_df.describe()
|
503921 | from .worker import Worker
from .queue_manager import QueueManager
from .constants import RETRY_TYPE
from .job_queue import JobQueue
from .exceptions import *
from .scheduling_time import SchedulingTime
|
503931 | import pandas as pd
import numpy as np
import nltk
import multiprocessing
import difflib
import time
import gc
import xgboost as xgb
import category_encoders as ce
import itertools
from collections import Counter
from sklearn.metrics import log_loss
from sklearn.cross_validation import train_test_split
def labelcou... |
503936 | def gamify(self):
'''Will apply reduction changes based on edits on the
the produced .json file in the experiment folder'''
if self.param_object.round_counter == 1:
# create the gamify object
from .GamifyMap import GamifyMap
g = GamifyMap(self)
# keep in scan_object
... |
503944 | from main import db
from sqlalchemy import Column, Integer, ForeignKey, DateTime
from sqlalchemy.orm import relationship
import datetime
class Follower(db.Model):
# 用户source对用户target的关注
source = Column(
Integer,
ForeignKey("user.id", ondelete="CASCADE"),
primary_key=True,
... |
503989 | from imagededup.utils import general_utils
"""Run from project root with: python -m pytest -vs tests/test_general_utils.py"""
def test_get_files_to_remove():
from collections import OrderedDict
dict_a = OrderedDict({'1': ['2'], '2': ['1', '3'], '3': ['4'], '4': ['3'], '5': []})
dups_to_remove = general_... |
504024 | import logging
from django.http import HttpResponse
from openunipay.models import PAY_WAY_ALI
from openunipay.paygateway import unipay
_logger = logging.getLogger('openunipay_ali_pay_notificaiton')
def process_notify(request):
_logger.info('received ali pay notification.body:{}'.format(request.body))
... |
504033 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.zone_airflow import ZoneCrossMixing
log = logging.getLogger(__name__)
class TestZoneCrossMixing(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.m... |
504055 | Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution:
# @param {integer} n
# @return {integer}
def totalNQueens(self, n):
if n == 0: return 0
self.result = 0 # Here we should use the global variable, o... |
504064 | import asyncio
import collections
import json
import logging
import os
import time
import ssl
from aiohttp import web
from aiohttp.web_urldispatcher import Response
from aiohttp.web_ws import WebSocketResponse
from certstream.util import pretty_date, get_ip
WebsocketClientInfo = collections.namedtuple(
'Websocke... |
504085 | import numpy as np
from environments.mujoco.rand_param_envs import gym
from environments.mujoco.rand_param_envs.gym.spaces import prng
class MultiBinary(gym.Space):
def __init__(self, n):
self.n = n
def sample(self):
return prng.np_random.randint(low=0, high=2, size=self.n)
def contains... |
504126 | from PIL import Image
from PIL import ImageDraw
import numpy as np
import matplotlib.pyplot as plt
from Utils import joinPath, saveData, setDir
from PlotTools import plotMyFigureOnAxes
def extractSelectedRegion(selected_data):
img_array = selected_data['image_array']
W_R = int(selected_data['W_R'])
H_R = i... |
504129 | from beet import Context, Function
def beet_default(ctx: Context):
message = "potato"
with ctx.generate.draft() as draft:
draft.data["demo:foo"] = Function(["say hello"])
with ctx.generate.draft() as draft:
draft.cache("demo", f"{message=}", zipped=True)
draft.data["demo:message"... |
504143 | class Config():
def __init__(self, koji_host, koji_storage_host, arch, result_dir):
self.koji_host = koji_host
self.koji_storage_host = koji_storage_host
self.arch = arch
self.result_dir = result_dir
|
504160 | import pymorph
import numpy as np
def test_cthin():
f = np.arange(16*16).reshape((16,16))%8
g = (f > 2)
f = (f > 3)
t = pymorph.cthin(f,g)
assert not np.any( ~g & t )
|
504171 | from remo.remozilla.models import Bug, Status
def get_last_updated_date():
"""Get last successful Bugzilla sync datetime."""
status, created = Status.objects.get_or_create(pk=1)
return status.last_updated
def set_last_updated_date(date):
"""Set last successful Bugzilla sync datetime."""
status,... |
504184 | from .random_forest_oracle import RandomForestOracle
from .gaussian_process_oracle import GaussianProcessOracle
|
504188 | from datetime import datetime
class csv_utils:
def coalesce_date(date):
return "" if date is None else datetime.strftime(date, '%Y-%m-%d %H:%M:%S')
def coalesce_bool(field):
return "" if field is None else "true" if field is True else "false"
def coalesce_int(num):
return "" if nu... |
504270 | from __future__ import print_function, unicode_literals
import unittest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from base import SeleniumBaseTest
import os
print ("[DBG]: Running test from: {0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.