id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1684457 | from das.parsers import IAddPortscanOutput
class AddPortscanOutput(IAddPortscanOutput):
"""Child class for processing Nmap output."""
def parse(self):
"""
Nmap raw output parser.
:return: a pair of values (portscan raw output filename, number of hosts added to DB)
:rtype: tuple
"""
hosts = set()
for... |
1684470 | from .gcn import GCNConv
from .sgc import SGConv
from .gat import GATConv
from .gwnn import WaveletConv
from .robustgcn import GaussionConvF, GaussionConvD
from .graphsage import SAGEAggregator, GCNAggregator
from .chebynet import ChebConv
from .densegcn import DenseConv
from .lgcn import LGConv
from .edgeconv... |
1684532 | import tensorflow as tf
import numpy as np
import pyomo.environ as pyo
from relumip import AnnModel
from relumip.utils.visualization import plot_results_2d
# Load the trained tensorflow model which will be embedded into the optimization problem.
tf_model = tf.keras.models.load_model('data/peaks_3x10.h5')
# Create a ... |
1684536 | from tkinter import *
from moviepy.editor import VideoFileClip
from moviepy.editor import AudioFileClip
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
import threading
# Variables for video and audio files
video_file = ''
audio_file = ''
def get_video_file():
"""
Functi... |
1684541 | SIGNATURE = '<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">' \
'<SignedInfo>' \
'<CanonicalizationMethod Algorithm="http://www.w3.org/2006/12/xml-c14n11"/>' \
'<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>' \
'<Reference>' \
... |
1684561 | from setuptools import setup
import os
def _read(fn):
path = os.path.join(os.path.dirname(__file__), fn)
data = open(path).read()
return data
setup(name='cluster-workers',
version='0.1.0',
description='a client/master/worker system for distributing '
'jobs in a cluster',
... |
1684572 | from analyzer.syntax_kind import SyntaxKind
from tests.utils import TestCaseLexer
class TestLexerComparisonOperatorToken(TestCaseLexer):
def test_less_than_token(self):
self.tokenize_source("<", 2)
self.assertToken(0, SyntaxKind.LessThanToken, [], [])
self.assertToken(1, SyntaxKind.EndOfFi... |
1684607 | import uuid
import time
from sdc11073 import pmtypes
from sdc11073.namespaces import domTag
from sdc11073.sdcdevice import SdcDevice
from sdc11073.mdib import DeviceMdibContainer
from sdc11073.pysoap.soapenvelope import DPWSThisModel, DPWSThisDevice
from sdc11073.location import SdcLocation
from sdc11073.wsdiscovery im... |
1684614 | def cadena(N):
C1 = 'ESTA ES NUESTRA CADENA DE PRUEBA '
C = ''
for j in range(N):
C += C1*100
return C
|
1684628 | import numpy
from ..codecs.InflTCorpFileCodec import InflTCorpFileCodec
from ..slexicon.SKey import *
class ModelInflInData(object):
WVEC_LEN = 9 # keep 8 letters from the lemma + 1 for the category
MAX_LETTER_IDX = 28 # a-z plus <oov> and <>
def __init__(self, fn):
self.entries... |
1684634 | import unittest
from binascii import a2b_hex
import wincrypto
from wincrypto.algorithms import symmetric_algorithms, hash_algorithms
from wincrypto.api import CryptImportKey, CryptExportKey, CryptCreateHash, CryptDeriveKey, \
CryptHashData
from wincrypto.constants import bType_PLAINTEXTKEYBLOB, CALG_MD5, CALG_RC4,... |
1684649 | from conekt import db, whooshee
from conekt.models.species import Species
from conekt.models.gene_families import GeneFamilyMethod
SQL_COLLATION = 'NOCASE' if db.engine.name == 'sqlite' else ''
@whooshee.register_model('name')
class XRef(db.Model):
__tablename__ = 'xrefs'
id = db.Column(db.Integer, primary_... |
1684679 | from unittest import TestCase
from unittest.mock import patch, Mock
from tornado import httpclient
from comms.common_https import CommonHttps
from utilities.test_utilities import async_test, awaitable
URL = "ABC.ABC"
METHOD = "GET"
HEADERS = {"a": "1"}
BODY = "hello"
CLIENT_CERT = "client.cert"
CLIENT_KEY = "client.... |
1684695 | from typing import Dict, List, Union
import torch
from torch import Tensor
from deepstochlog.term import Term
class Context:
""" Represents the context of a query: maps logic terms to tensors """
def __init__(self, context: Dict[Term, Tensor], map_default_to_term=False):
self._context = context
... |
1684706 | class Observavel:
def __init__(self):
self._observers = []
def adicionar_observer(self, observador):
self._observers.append(observador)
def notificar_observers(self, mensagem):
for observador in self._observers:
observador(mensagem)
def observador_email(mensagem):
... |
1684737 | from shexer.consts import JSON, FIXED_SHAPE_MAP
from shexer.io.shape_map.shape_map_parser import JsonShapeMapParser, FixedShapeMapParser
def get_shape_map_parser(format, sgraph, namespaces_prefix_dict):
if format == JSON:
return JsonShapeMapParser(sgraph=sgraph,
namespaces... |
1684750 | self.description = "Scriptlet test (pre/post remove)"
p1 = pmpkg("dummy")
p1.files = ['etc/dummy.conf']
p1.install['pre_remove'] = "echo foobar > pre_remove"
p1.install['post_remove'] = "echo foobar > post_remove"
self.addpkg2db("local", p1)
self.args = "-R %s" % p1.name
self.addrule("PACMAN_RETCODE=0")
self.addrule... |
1684759 | import pytest
from app.models.organisation import Organisation
from tests import organisation_json
@pytest.mark.parametrize("purchase_order_number,expected_result", [
[None, None],
["PO1234", [None, None, None, "PO1234"]]
])
def test_organisation_billing_details(purchase_order_number, expected_result):
o... |
1684762 | from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import ForumUser
class ForumUserCreationForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = ForumUser
fields = ('username', 'nickname', 'email', '<PASSWORD>', '<PASS... |
1684774 | from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
from boost_adaptbx.boost.python import streambuf
ext = bp.import_ext("boost_adaptbx_python_streambuf_test_ext")
import subprocess
import sys
def exercise():
proc = subprocess.Popen(args='libtbx.python %s --core'... |
1684787 | import os
import numpy as np
import torch
from .alignment import load_net, batch_detect
def get_project_dir():
current_path = os.path.abspath(os.path.join(__file__, "../"))
return current_path
def relative(path):
path = os.path.join(get_project_dir(), path)
return os.path.abspath(path)
class Ret... |
1684816 | import logging
from oic.oic import Client, RegistrationResponse
from oic.utils.authn.client import CLIENT_AUTHN_METHOD
DATAPORTEN_PROVIDER_CONFIG = "https://auth.dataporten.no/"
def client_setup(client_id, client_secret):
"""Sets up an OpenID Connect Relying Party ("client") for connecting to Dataporten"""
... |
1684820 | from typing import Tuple
import pytest
import torch
from ludwig.modules import reduction_modules
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
@pytest.mark.parametrize("reduce_mode", ["last", "sum", "mean", "avg", "max", "concat", "attention", None])
@pytest.mark.parametrize("test_input_shape", [(16, 1, ... |
1684825 | nama_hewan = ["gajah", "sapi", "kuda", "buaya"]
# menampilkan isi list
print(nama_hewan)
# menampilkan isi list dengan index
print(nama_hewan[0])
print(nama_hewan[1])
# mengganti satu index list
nama_hewan[0] = "kucing"
print(nama_hewan)
# menghitung jumlah list
print(len(nama_hewan))
# campur beberapa tipe data d... |
1684869 | def plot():
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
x = np.ma.arange(0, 2 * np.pi, 0.4)
y = np.ma.sin(x)
y1 = np.sin(2 * x)
y2 = np.sin(3 * x)
ym1 = np.ma.masked_where(y1 > 0.5, y1)
ym2 = np.ma.masked_where(y2 < -0.5, y2)
lines = plt.plot(x, ... |
1684889 | from radixlib.network import Network
from radixlib.actions import (
CreateTokenDefinition,
UnregisterValidator,
RegisterValidator,
TransferTokens,
UnstakeTokens,
StakeTokens,
MintTokens,
BurnTokens,
ActionType
)
from typing import Union, List, overload, Optional
import radixlib as ra... |
1684894 | import warnings
import numpy as np
import copy
from skopt.space import space as skopt_space
from skopt.learning import GaussianProcessRegressor
from scipy.linalg import cho_solve
from sklearn.utils.validation import check_array
from utils import check_parameter_count
class BoundedGaussianProcessRegressor(GaussianP... |
1684904 | class TheSwapsDivTwo:
def find(self, sequence):
l, s = len(sequence), set()
for i in xrange(l):
for j in xrange(i + 1, l):
s.add(
tuple(
sequence[:i]
+ (sequence[j],)
+ sequence[i ... |
1684916 | from train_nih import *
if __name__ == "__main__":
confs = []
# main experiments
for seed in [0]:
confs += nih_baseline(seed, 256)
confs += nih_li2018(seed, 256)
confs += nih_unet(seed, 256)
confs += nih_fpn(seed, 256)
confs += nih_deeplabv3(seed, 256)
confs... |
1684931 | import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
def scrape_divs():
"""This function scrapes all the proposal elements and stores them
in a list.
"""
response = requests.get("https://in.pycon.org/cfp/2020/proposals/")
soup = bs(response.content, "html.parser")
mydivs = s... |
1684946 | class SimIo:
def __init__(self, sim, name, getter, setter):
self.sim = sim
self.name = name
self.getter = getter
self.setter = setter
def get(self):
if self.getter is None:
raise NotImplementedError
return self.getter()
def set(self, ... |
1684957 | import logger as log
import mail
import json
def read_json(threatJasonPath):
try:
# read the Threat Dragon JSON file
JSON_file = open(threatJasonPath, 'r')
dataTM = JSON_file.read()
JSON_file.close()
# return a dictionary
obj = json.loads(dataTM)
return ob... |
1684962 | def count_parameters(model):
"""Counts the number of parameters in a model."""
return sum(param.numel() for param in model.parameters() if param.requires_grad_)
class AttrDict(dict):
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, item):
return self[item]
|
1684965 | import os
import yaml
import pandas as pd
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', default = os.path.join('configs', 'data_preparation.yaml'), help = 'Config File', type = str)
FLAGS = parser.parse_args()
CFG_FILE = FLAGS.cfg
with open(CFG_FILE, 'r') as cfg_file:
cfg_dict =... |
1684972 | import tensorflow as tf
__all__ = ['get_sess']
def get_sess(sess=None):
"""Get default session if sess is None.
Args:
sess: Valid sess or None.
Returns:
Valid sess or get default sess.
"""
if sess is None:
sess = tf.get_default_session()
assert sess, 'sess should n... |
1684980 | import claripy
from . import MemoryMixin
from ...errors import SimMemoryError
class SimpleInterfaceMixin(MemoryMixin):
def load(self, addr, size=None, endness=None, condition=None, fallback=None, **kwargs):
tsize=self._translate_size(size, None)
return super().load(
self._translate_add... |
1685017 | import os
import sys
sys.path.append("../../../../")
import swhlab
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
class ABF2(swhlab.ABF):
def phasicTonic(self,m1=None,m2=None,chunkMs=50,quietPercentile=10,
histResolution=.5,plotToo=False):
"""
... |
1685023 | from PIL import Image
import cv2
import numpy as np
from PySide2.QtGui import QImage
# https://github.com/Mugichoko445/Fast-Digital-Image-Inpainting/blob/master/sources/FastDigitalImageInpainting.hpp
def convertPIL2CV(img:Image):
return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
def convertCV2PIL(img)->Im... |
1685066 | import logging
import numpy as np
from gym.spaces import Discrete
from ray.rllib.utils.annotations import override
from ray.rllib.env.vector_env import VectorEnv
from ray.rllib.evaluation.rollout_worker import get_global_worker
from ray.rllib.env.base_env import BaseEnv
from ray.rllib.utils.typing import EnvType
logge... |
1685102 | from Bio.PDB import *
# Exclude disordered atoms.
class NotDisordered(Select):
def accept_atom(self, atom):
return not atom.is_disordered() or atom.get_altloc() == 'A'
def extractHelix(helix, infilename, outfilename, chain_ids=None, includeWaters=False,\
invert=False):
pa... |
1685150 | import click
import re
from .base import Prompter
from agent.modules.tools import infinite_retry
from agent import source
class MongoPrompter(Prompter):
def prompt(self, default_config, advanced=False):
self.prompt_connection(default_config)
self.prompt_auth(default_config)
self.prompt_db... |
1685218 | import pyodbc
def select_all_entries_from_column(table_name, cursor, column_name):
"""Select all entries from a column.
Args:
table_name (str): Table name.
cursor (object): pyobdc cursor.
column_name (str): Column name.
Returns:
list: List with the selected entrie... |
1685231 | import logging
from pandas import DataFrame
from dbnd import parameter, task
from targets import target
from targets.target_config import FileFormat
logger = logging.getLogger(__name__)
@task(result=parameter.save_options(FileFormat.csv, header=False)[DataFrame])
def read_first_lines(lines=parameter.load_options(... |
1685262 | from django.db import models
class PriceHistory(models.Model):
date = models.DateTimeField(auto_now_add=True)
price = models.DecimalField(max_digits=7, decimal_places=2)
volume = models.DecimalField(max_digits=7, decimal_places=3)
|
1685263 | import os
import re
import sys
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties
from matplotlib.offsetbox import HPacker, TextArea, AnnotationBbox
from matplotlib.patches import FancyArrowPatch, ArrowStyle, Polygon
from matplot... |
1685267 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from django.test.testcases import TestCase
from .base import Hook
from kolibri.plugins.hooks import register_hook
class KolibriTagNavigationTestCase(TestCase):
def setUp(self):
super(Koli... |
1685312 | import os
import argparse
import pickle
import numpy as np
import torch
import torch.nn.functional as F
import dnnlib
import legacy
from util.utilgan import basename, calc_init_res
try: # progress bar for notebooks
get_ipython().__class__.__name__
from util.progress_bar import ProgressIPy as ProgressBar
exc... |
1685326 | import math
from typing import List, Any
from . import *
class Collection(TopLevel):
"""The Collection class is a class that groups together a set of
TopLevel objects that have something in common.
Some examples of Collection objects:
* Results of a query to find all Component objects in a reposito... |
1685358 | from django.db import models, migrations
import core.models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20150126_1611'),
]
operations = [
migrations.AlterField(
model_name='person',
name='birth_date',
field=models.DateFi... |
1685362 | import torch.nn as nn
from .utils import register_model
@register_model('DomainFactorBackbone')
class DomainFactorBackbone(nn.Module):
def __init__(self):
super(DomainFactorBackbone, self).__init__()
self.num_channels = 3
self.setup_net()
def setup_net(self):
self.co... |
1685366 | import tensorflow as tf
import collections
class TrainModel(
collections.namedtuple("TrainModel",
("graph", "model"))):
pass
def create_train_model(
model_creator,
hparams):
graph = tf.Graph()
with graph.as_default(), tf.container("train"):
model = ... |
1685415 | import tkinter as tk
from tkinter import Menu, Tk, Text, DISABLED, RAISED,Frame, FLAT, Button, Scrollbar, Canvas, END
from tkinter import messagebox as MessageBox
from tkinter import ttk
import tkinter.simpledialog
from tkinter import *
from tkinter import font as tkFont
#Metodo para enumerar las lineas
class TextLineN... |
1685453 | import numpy as np
import plotly.express as px
import umap
def d3_umap(X, y_km, heat=None):
"""
Args:
X:
y_km:
heat:
"""
reducer = umap.UMAP(random_state=1234, n_components=3)
X_embedded = reducer.fit_transform(X)
node_colors = get_node_colormap(y_km)
x, y, z = X_em... |
1685456 | from __future__ import unicode_literals
from .common import InfoExtractor
class FreespeechIE(InfoExtractor):
IE_NAME = 'freespeech.org'
_VALID_URL = r'https?://(?:www\.)?freespeech\.org/stories/(?P<id>.+)'
_TEST = {
'add_ie': ['Youtube'],
'url': 'http://www.freespeech.org/stories/fcc-anno... |
1685478 | from typing import Any, Sequence
from tango import Format, JsonFormat, Step
from tango.common import DatasetDict
from tango.common.testing import run_experiment
@Step.register("train_data")
class TrainData(Step):
DETERMINISTIC = True
CACHEABLE = False
def run(self) -> Sequence[int]: # type: ignore
... |
1685484 | from gym import Env
class ProxyEnv(Env):
def __init__(self, wrapped_env):
self._wrapped_env = wrapped_env
self.action_space = self._wrapped_env.action_space
self.observation_space = self._wrapped_env.observation_space
@property
def wrapped_env(self):
return self._wrapped_e... |
1685522 | from eclcli.common import command
from eclcli.common import utils
from ..networkclient.common import utils as to_obj
class ListVPNService(command.Lister):
def get_parser(self, prog_name):
parser = super(ListVPNService, self).get_parser(prog_name)
return parser
def take_action(self, parsed_arg... |
1685558 | from flask import Flask, request, url_for
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer, SignatureExpired
app = Flask(__name__)
app.config.from_pyfile('config.cfg')
mail = Mail(app)
s = URLSafeTimedSerializer('Thisisasecret!')
@app.route('/', methods=['GET', 'POST']... |
1685620 | import tensorflow as tf
import universal_transformer_modified
class UGformerV1(object):
def __init__(self, feature_dim_size, hparams_batch_size, ff_hidden_size, seq_length, num_classes, num_self_att_layers, num_GNN_layers=1):
# Placeholders for input, output
self.input_x = tf.compat.v1.placeholder(... |
1685633 | import cv2
import sys
import numpy as np
import depthai as dai
from time import sleep
'''
This example attaches a NeuralNetwork node directly to the SPI output. The corresponding ESP32 example shows how to decode it.
Make sure you have something to handle the SPI protocol on the other end! See the included ESP32 exam... |
1685689 | from core.advbase import *
from slot.d import *
from slot.a import *
def module():
return Gala_Elisanne
class Gala_Elisanne(Adv):
a3 = ('primed_att',0.10)
conf = {}
conf['slots.a'] = BB()+FWHC()
conf['slots.frostbite.a'] = conf['slots.a']
conf['slots.d'] = Gaibhne_and_Creidhne()
conf['acl... |
1685729 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import time
import misc.utils as utils
from collections import OrderedDict
import torch
import sys
sys.path.append("cider")
from pyciderevalcap.ciderD.ciderD import CiderD
sys.path.append("c... |
1685746 | class FindObject:
"""An object represented a find(1) command"""
def __init__(self, cmd):
self.exec_cmd = ''
self.path = ''
self.opts = ''
if cmd.startswith('find'):
# find ./find -type f -exec rm -rf {} ;
# 012345 012 0123456
#
... |
1685765 | class Error(Exception):
pass
class UnknownObjectException(Error):
pass
class ObjectDisabledException(Error):
pass
class ObjectReadOnlyException(Error):
pass
class NoValueFoundException(Error):
pass
class NoMatchingWindowFoundException(Error):
pass
class UnknownFrameException(Error):
... |
1685779 | import unittest
from vaporwavely import vaporize
class VaporwavelyTestCase(unittest.TestCase):
def test_lower(self):
self.assertEqual('Tassoni, patrimonio italiano',
vaporize('Tassoni, patrimonio italiano'))
def test_mixed(self):
self.assertEqual('aesthetic nintendo'... |
1685792 | from app.utils import filters
def test_md_to_html():
assert '<h1>' in filters.md_to_html('# Hello World')
|
1685802 | from __future__ import unicode_literals
import logging
from django.db import migrations
from osf.utils.migrations import ensure_schemas
logger = logging.getLogger(__file__)
class Migration(migrations.Migration):
dependencies = [
('osf', '0141_merge_20181023_1526'),
]
operations = [
#... |
1685829 | import fnmatch
import os
import subprocess
from airflow import configuration
from airflow.models import DagModel, DagRun, TaskInstance
from airflow.settings import Session, engine
from airflow.utils.state import State
from airflow.www.app import csrf
from flask import Blueprint, make_response
from prometheus_client i... |
1685877 | import time
import datetime
import glob,os, fnmatch, urllib, math
from osgeo import gdal
import numpy
import argparse
import config
import json
force = 0
verbose = 0
BASE_DIR = config.EF5_DIR
def execute( cmd ):
if verbose:
print cmd
os.system(cmd)
def CreateLevel(l, geojsonDir, fileName, src_ds):
project... |
1685912 | from {{appname}}.models.elastic.testelastic import Testelastic
from datetime import datetime
# create the mappings in elasticsearch
Testelastic.init()
# create and save and article
article = Testelastic(meta={'id': 42}, title='Hello world!', tags=['test'])
article.body = ''' looong text '''
article.published_from = d... |
1685914 | import distro
import logging
from lxml import etree
import pkg_resources
log = logging.getLogger(__name__)
emulator_path = None
def parse_rbd_monitor(monitorlist):
monitors = dict()
for monitor in monitorlist.split(','):
port = '6789'
if ':' in monitor:
port = monitor.split(':')[... |
1685917 | import sys
import glob
import unittest
def create_test_suite():
test_file_strings = glob.glob('tests/test_*.py')
module_strings = ['tests.'+str[6:len(str)-3] for str in test_file_strings]
suites = [unittest.defaultTestLoader.loadTestsFromName(name) \
for name in module_strings]
testSuite = unittest.TestSuite(su... |
1685953 | import json
import click
from textwrap import dedent
from pathlib import Path
import os
from tabulate import tabulate
from PIL import Image, ImageOps
from math import ceil, floor
from ih import palette, helpers
DEFAULT = {
"palette": palette.PALETTE_DEFAULT,
"scale": 1,
"colors": 256,
"render": Fals... |
1685964 | import html
import json
import logging
import re
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from .utils import *
from .upload import uploadFile
from . import auth
CALL_INTERVAL = 0.35
MAX_CALLS_IN_EXECUTE = 25
def retOrCall(s, *p):
return s(*p) if callable(s) else... |
1685990 | import sys
import os
import math
import random
import numpy as np
import matplotlib.pyplot as plt
# our implementations
import run_ridge
import ridge
import theory
import covar
import output_pert
import naive_covar
#MIN_EPS = 0.00001
#MAX_EPS_CAP = 20.0
#MAX_NAIVE_EPS = 1000.0 # this one can be larger due to doubli... |
1686010 | from scout.build.hpo import build_hpo_term
import pytest
def test_build_hpo_term(adapter, test_hpo_info):
## GIVEN a hpo term
## WHEN building the hpo term
hpo_obj = build_hpo_term(test_hpo_info)
## THEN assert that the term has the correct information
assert hpo_obj["_id"] == hpo_obj["hpo_id"] ==... |
1686108 | import brownie
def test_set_royalties_receiver(token, owner, alice, royalty_wallet):
previous_royalties_receiver = token.royaltiesReceiver().return_value
token.setRoyaltiesReceiver(alice, {"from": owner})
new_royalties_receiver = token.royaltiesReceiver().return_value
assert previous_royalties_receive... |
1686130 | from __future__ import division
import matplotlib
# matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
import numpy as np
from solution import general_secondorder_ode_fd, poisson_square
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm
imp... |
1686162 | import numpy as np
import os
import pickle
import re
import sys
import argparse
class Preprocess():
def __init__(self, path_to_babi):
# path_to_babi example: '././babi_original'
self.path_to_babi = os.path.join(path_to_babi, "tasks_1-20_v1-2/en-valid-10k")
self.train_paths = None
... |
1686166 | import typer
import subprocess
from clumper import Clumper
from crontab import CronTab
def clean_cron(user):
cron = CronTab(user=user)
cron.remove_all()
cron.write()
def parse_job_from_settings(settings, name):
if len(settings) == 0:
print(f"The name `{name}` doesn't appear in supplied sched... |
1686184 | import argparse
import torch
from model.wide_res_net import WideResNet
from model.smooth_cross_entropy import smooth_crossentropy
from data.cifar import Cifar
from utility.log import Log
from utility.initialize import initialize
from utility.step_lr import StepLR
from utility.bypass_bn import enable_running_stats, dis... |
1686206 | from unittest import TestCase
import numpy as np
from skfem import BilinearForm, LinearForm, Functional, asm, condense, solve
from skfem.helpers import dd, ddot
from skfem.mesh import MeshQuad, MeshTri, MeshLine
from skfem.element import (ElementQuadBFS, ElementTriArgyris,
ElementTriMorley, ... |
1686251 | from pgdrive.component.map.base_map import BaseMap, MapGenerateMethod
from pgdrive.envs.pgdrive_env import PGDriveEnv
if __name__ == "__main__":
def get_image(env):
env.vehicle.image_sensors[env.vehicle.config["image_source"]].save_image()
env.engine.screenshot()
env = PGDriveEnv(
{
... |
1686271 | import os
from tqdm import tqdm
from persia.embedding.data import PersiaBatch
from persia.logger import get_logger
from persia.ctx import DataCtx
from data_generator import make_dataloader
logger = get_logger("data_loader")
train_filepath = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "data/train... |
1686275 | from __future__ import annotations
from result import Err, Ok, Result
def test_pattern_matching_on_ok_type() -> None:
"""
Pattern matching on ``Ok()`` matches the contained value.
"""
o: Result[str, int] = Ok("yay")
match o:
case Ok(value):
reached = True
assert value == ... |
1686285 | import unittest
from matbench.constants import CLF_KEY, REG_KEY
from matbench.metadata import mbv01_metadata, mbv01_validation
class TestMetadata(unittest.TestCase):
def test_mbv01_metadata(self):
# for matbench v0.1
for ds, metadata in mbv01_metadata.items():
for key in ["task_type"... |
1686306 | class DataModelRenderer:
def __init__(self):
self.lines = []
def add(self, template, value=None, **kwargs):
if isinstance(value, bool) and value:
self.lines.append(template.format(**kwargs))
elif isinstance(value, (list, set)):
for elem in value:
... |
1686326 | from keras.models import Model
from keras.layers import Input, Convolution1D, Activation, Merge, Lambda
from keras.layers.advanced_activations import PReLU
from keras.optimizers import Nadam
from eva.layers.causal_atrous_convolution1d import CausalAtrousConvolution1D
from eva.layers.wavenet_block import WavenetBlock, ... |
1686350 | from __future__ import division
from matplotlib import pyplot as plt
import numpy as np
import math as m
import matplotlib as mlp
pgf_with_rc_fonts = {
"font.family": "serif",
"font.size": 16,
"legend.fontsize": 16,
"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font
}
mlp.rcParams.up... |
1686368 | import asyncio
import logging
import typing
from ib_async.errors import UnsupportedFeature
from ib_async.instrument import Instrument
from ib_async.messages import Outgoing
from ib_async.protocol import RequestId, ProtocolInterface, OutgoingMessage
from ib_async.protocol_versions import ProtocolVersion
from ib_async.t... |
1686410 | from setuptools import setup, find_packages
setup(
name='corpus2graph', # Required
version='0.0.1', # Required
description='tools to generate graph from corpus', # Required
url='https://github.com/zzcoolj/corpus2graph', # Optional
author='<NAME> and <NAME>', # Optional
author_email='<EMAIL... |
1686415 | from selenium import webdriver
import os
import time
def save_and_submit():
driver.find_element_by_xpath(
"//button[@class='btn btn-icon btn-primary glyphicons circle_ok center']").click()
# save and submit
USERNAME = os.environ['STUDENT_USERNAME']
PASSWORD = os.environ['STUDENT_PASSWORD']
driver =... |
1686439 | from Core.App import App
from Core.Ui import *
import sys
import gc
class TwitchLink:
def run(self):
app = QtWidgets.QApplication(sys.argv)
Translator.load()
while True:
exitCode = App.start(Ui.MainWindow())
DB.save()
gc.collect()
if exitCod... |
1686492 | import unittest
from katas.kyu_7.sentence_to_words import splitSentence
class SplitSentenceTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(splitSentence('This string is splitsville'),
['This', 'string', 'is', 'splitsville'])
def test_equal_2(self):
... |
1686508 | import sys
import logging
from optparse import OptionParser
from flvlib import __versionstr__
from flvlib import tags
from flvlib import helpers
from flvlib.astypes import MalformedFLV
log = logging.getLogger('flvlib.debug-flv')
log.setLevel(logging.ERROR)
def debug_file(filename, quiet=False, metadata=False):
... |
1686526 | def up(cursor, bot):
cursor.execute("DROP TABLE hsbet_game, hsbet_bet")
cursor.execute("DROP TYPE hsbet_outcome")
|
1686542 | import sqlite3
import sys
import time
import traceback
sys.path.append('..\\SubredditBirthdays')
import sb
sys.path.append('..\\Usernames')
import un4
newnames_sql = sqlite3.connect('..\\Usernames\\newnames.db')
newnames_cur = newnames_sql.cursor()
def migrate():
resume_from = int(open('latest.txt', 'r').read()... |
1686578 | import sys
import pickle
import utils
from scribe.scribe import Scribe
if len(sys.argv) < 2:
print('Usage:'
'\n python3 {} <output_file_name> [configurations]'
'Generates data based on the configuration files.'.format(sys.argv[0]))
sys.exit(-1)
out_file_name = sys.argv[1]
if not out_file_n... |
1686580 | from __future__ import division
import numpy as np
model = None
labels_list = None
def _get_sampled_labels(idx):
model.add_data(model.labels_list[idx].data,initialize_from_prior=False)
l = model.labels_list.pop()
return l.z, l._normalizer
def _get_sampled_component_params(idx):
model.components[idx].... |
1686628 | import json
import operator
import os
import pickle
import subprocess
from django.contrib.auth import logout, authenticate, login
from django.shortcuts import render, render_to_response
from django.utils.datastructures import MultiValueDictKeyError
from django.contrib.auth.models import User
from carnivora.instabot.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.