id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1677035 | import json
from hamcrest import assert_that, is_, equal_to
from lxd_image_server.simplestreams.index import Index
class TestIndex(object):
def test_generate_json(self):
INDEX = {
'format': 'index:1.0',
'index': {
'images': {
'datatype': 'image-... |
1677044 | from magma import array, wire, compile, EndCircuit
from loam.boards.icestick import IceStick
from mantle.lattice.ice40.RAMB import RAMB
icestick = IceStick()
icestick.Clock.on()
icestick.J1[0].rename('I0').input().on()
icestick.J1[1].rename('I1').input().on()
icestick.J1[2].rename('I2').input().on()
icestick.J1[3].ren... |
1677048 | import asyncio
import json
import flask
import pytest
from flask import request
from mitmproxy.addons import asgiapp
from mitmproxy.addons import next_layer
from mitmproxy.addons.proxyserver import Proxyserver
from mitmproxy.test import taddons
tapp = flask.Flask(__name__)
@tapp.route("/")
def hello():
print("... |
1677064 | from .dual_primal_edge_unpool import DualPrimalEdgeUnpooling
__all__ = ['DualPrimalEdgeUnpooling']
|
1677168 | import time
import numpy as np
import torch as T
import torch.nn.functional as F
from torch.optim.adam import Adam
from ..utils.networks_mlp import Actor, Critic
from ..agent_base import Agent
from ..utils.exploration_strategy import GaussianNoise
class TD3(Agent):
def __init__(self, algo_params, env, transition_... |
1677182 | import pyb
import stm
# This script sets up a timer to do quadrature decoding
#
# It was tested using a switch similar to https://www.sparkfun.com/products/9117
# with some debounce wired up like this: https://hifiduino.files.wordpress.com/2010/10/analogdeb.jpg
# Note: the debounce is only really required for mechanic... |
1677212 | from __future__ import unicode_literals
from flask import Flask, render_template_string, Markup
from unittest import TestCase
from textwrap import dedent
try:
from unittest import mock
except ImportError:
import mock
import misaka
from misaka import (EXT_AUTOLINK, EXT_FENCED_CODE, # pyflakes.ignore
... |
1677218 | from __future__ import division
import numpy as np
from numpy import linalg as la
import pdb, copy
import utils.utils
class LMPC(object):
"""Learning Model Predictive Controller (LMPC)
Inputs:
- ftocp: Finite Time Optimal Control Prolem object used to compute the predicted trajectory
Methods:
- addTrajectory:... |
1677226 | class TaxJarError(Exception):
"""Base class for TaxJar-related errors"""
class TaxJarResponseError(TaxJarError):
"""Response errors (400, 500)"""
class TaxJarConnectionError(TaxJarError):
"""Connection errors"""
class TaxJarTypeError(TaxJarError):
"""Factory errors"""
|
1677232 | import logging
import pathlib
import joblib
from tqdm import tqdm
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from util import INDEX_COLUMNS, init, reduce_mem_usage
def dump(df, name):
df = reduce_mem_usage(df)
save_dir = pathlib.Path('../data/01_readcsv')
if not ... |
1677275 | from OpenSSL import crypto, SSL
def generate_certificate(
organization="PrivacyFilter",
common_name="https://www.url.com",
country="NL",
duration=(365 * 24 * 60 * 60),
keyfilename="key.pem",
certfilename="cert.pem"):
k = crypto.PKey()
k.generate_key(crypto.TYPE... |
1677285 | import maya.cmds as cmds
import sys
import maya.mel as mel
from . import stereoCameraErrors
import os
import imp
def __call(language, method, rigName, kwords={}, cmd_args=[]):
"""
Private method to call a MEL or Python callback. Return 'Error' in
case of error. We avoid None, [], '' because those are more ... |
1677294 | import pytest
from mendeley.exception import MendeleyApiException
from test import cassette
from test.resources.documents import *
def test_should_trash_document():
session = get_user_session()
delete_all_documents()
with cassette('fixtures/resources/trash/move_to_trash/trash_document.yaml'), \
... |
1677306 | import logging
from typing import List
from hydra.utils import instantiate
from omegaconf import DictConfig
from nuplan.planning.script.builders.utils.utils_type import validate_type
from nuplan.planning.training.modeling.metrics.abstract_training_metric import AbstractTrainingMetric
logger = logging.getLogger(__nam... |
1677333 | from collections import namedtuple
Config = namedtuple("Config", [
"dataset_path",
"models_dir",
"folder",
"img_rows",
"img_cols",
"target_rows",
"target_cols",
"num_channels",
"network",
"loss",
"lr",
"optimizer",
"batch_size",
"epoch_size",
"use_clahe",
... |
1677341 | from ...vendor import click
@click.command(
help='Exit with a successful status code',
)
@click.help_option('-h', '--help')
def subcommand():
pass
|
1677354 | import pandas as pd
import matplotlib.pyplot as plt
import textwrap
import yaml
# draw histograms
def draw_hists(columns, test_vectors, width=20, height=5):
n = len(columns)
fig, axes = plt.subplots(1, n)
fig.set_figwidth(width)
fig.set_figheight(height)
i = 0
for column in columns:
te... |
1677373 | import os
import sys
import time
def progbar(i, iter_per_epoch, message='', bar_length=50, display=True):
j = (i % iter_per_epoch) + 1
end_epoch = j == iter_per_epoch
if display:
perc = int(100. * j / iter_per_epoch)
prog = ''.join(['='] * (bar_length * perc // 100))
template = "\r[... |
1677388 | from taichi._lib import core as _ti_core
from taichi.lang.enums import Layout
from taichi.lang.expr import Expr, make_expr_group
from taichi.lang.util import taichi_scope
class AnyArray:
"""Class for arbitrary arrays in Python AST.
Args:
ptr (taichi_core.Expr): A taichi_core.Expr wrapping a taichi_co... |
1677389 | import os
from flask import Flask, Response
from hanako.server.player_api import player_api
from hanako.server.room_api import room_api
api = Flask(__name__)
api.register_blueprint(player_api)
api.register_blueprint(room_api)
@api.route('/health')
def health_check():
return 'Health OK for: ' + str(Response(os.un... |
1677397 | import time
import RPi.GPIO as GPIO
switch1 = 17
switch2 = 26
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
GPIO.setup(switch1, GPIO.IN)
GPIO.setup(switch2, GPIO.IN)
print "start"
while True:
if not GPIO.input(switch1):
print "Button 1 pressed"
time.sleep(0.5)
elif not GPIO.inp... |
1677448 | import re
from telethon import TelegramClient
def test_all_methods_present(docs_dir):
"""
Determine if all methods existance of the given documentation.
Args:
docs_dir: (str): write your description
"""
with (docs_dir / 'quick-references/client-reference.rst').open(encoding='utf-8') as f... |
1677457 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np # type: ignore
import onnx
from ..base import Base
from . import expect
class Hardmax(Base):
@staticmethod
def export(): # type: () -> No... |
1677458 | from quicksort import partition
from animate import Plot
def heapify(unsorted, index, start, end):
heap_size = end + 1 - start
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[start + left_index] > unsorted[start + largest]:
larg... |
1677464 | from rover import rover
import datetime
import numpy as np
import rospy
def thread_log():
print('LOG: thread starting ..')
freq = 50.0
t0 = datetime.datetime.now()
t = datetime.datetime.now()
t_pre = datetime.datetime.now()
avg_number = 100
header_written = False
file_open = False
... |
1677479 | from flask_restplus import Resource
from flask import request, current_app
from sqlalchemy import desc, func, or_
from marshmallow.exceptions import MarshmallowError
from werkzeug.exceptions import BadRequest
from app.extensions import api
from app.api.now_submissions.models.application_start_stop import ApplicationSt... |
1677565 | from __future__ import print_function
__authors__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["<NAME>", "<NAME>"]
__license__ = "3-clause BSD"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
from pylearn2.testing.skip import skip_if_no_gpu
skip_if_no_gpu()
import n... |
1677572 | import distrax
import jax.numpy as jnp
from shinrl import Pendulum
def test_step_reset():
env = Pendulum()
env.reset()
for _ in range(env.config.horizon - 1):
a = env.action_space.sample()
obs, rew, done, info = env.step(a)
assert not done
obs, rew, done, info = env.step(a)
... |
1677574 | from itertools import chain
from django.contrib.staticfiles.finders import find
import pytest
from codemirror2.widgets import CodeMirrorEditor
@pytest.fixture
def w():
"""
construct a CodeMirrorEditor widget with default settings
"""
return CodeMirrorEditor()
def test_dont_share_options(settings):
... |
1677582 | import os
import time
from data_util.log import logger
import torch as T
import rouge
from model import Model
from data_util import config, data
from data_util.batcher import Batcher, Example, Batch
from data_util.data import Vocab
from beam_search import beam_search
from train_util import get_enc_data
from rouge impor... |
1677603 | from monday.resources.base import BaseResource
from monday.query_joins import create_update_query, get_update_query, get_updates_for_item_query
class UpdateResource(BaseResource):
def __init__(self, token):
super().__init__(token)
def create_update(self, item_id, update_value):
query = create... |
1677607 | import numpy as np
from attention_utils import get_activations, get_data
np.random.seed(1337) # for reproducibility
from keras.models import *
from keras.layers import Input, Dense, merge
input_dim = 32
def build_model():
inputs = Input(shape=(input_dim,))
# ATTENTION PART STARTS HERE
attention_probs... |
1677612 | import numpy as np
from tqdm import trange, tqdm
import tensorflow as tf
from .fedbase import BaseFedarated
from flearn.utils.tf_utils import process_grad, cosine_sim, softmax, norm_grad
from flearn.utils.model_utils import batch_data, gen_batch, gen_epoch
class Server(BaseFedarated):
def __init__(self, params,... |
1677631 | import sys
import re
import traceback
import os
from opsbro.util import lower_dict
from opsbro.collector import Collector
if os.name == 'nt':
import opsbro.misc.wmi as wmi
class Memory(Collector):
def launch(self):
logger = self.logger
# logger.debug('getMemoryUsage: start')
if os.na... |
1677632 | import PySimpleGUI as sg
import os, re, subprocess
from flask import Flask, render_template, flash, redirect, url_for, request, session
from classes.forms import RegistrationForm
from classes.functions import Main
import datetime, textwrap
from configparser import ConfigParser
from multiprocessing import Process
import... |
1677694 | from pywavefront import *
from PyVMF import *
def obj_to_solids(filename: str, material_path: str = "", scale=64):
"""
Turns an .obj file to VMF solids, **BETA** it's very finicky and remember to invert normals
:param filename: The name of the .obj file with path (ex: "test/wall.obj")
:param material... |
1677698 | from distutils.core import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='ipython_pytest',
version='0.0.1',
author='<NAME>',
author_email='<EMAIL>',
py_modules=['ipython_pytest'],
url='https://github.com/akaihola/ipython_pytest',
classifiers=['Developmen... |
1677734 | from jinja2 import Template
import os
from optparse import OptionParser
import logging
import csv
import time
import re
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, FileSystemEventHandler
from itertools import zip_longest
from livereload import Server
VERSION = '0.1.0'
REN... |
1677749 | from os.path import join
from os import listdir
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
visual = True
color_bar = np.random.randint(0, 255, (90, 3))
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
img_base_path = join(VID_base_path, 'Da... |
1677771 | import demistomock as demisto
import json
import pytest
from CommonServerPython import entryTypes
entryTypes['warning'] = 11
bot_id: str = '9bi5353b-md6a-4458-8321-e924af433amb'
tenant_id: str = 'pbae9ao6-01ql-249o-5me3-4738p3e1m941'
team_id: str = '19:<EMAIL>'
team_aad_id: str = '7d8efdf8-0c5a-42e3-a489-5ef5c3fc7... |
1677774 | import os
from flask import Flask, Response, jsonify, abort
from flask_restplus import Api, Resource, fields, reqparse
from flask_cors import CORS, cross_origin
import json
import pandas as pd
from dotenv import load_dotenv
import time
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
impo... |
1677809 | import torch
import torch.nn as nn
def ConvBNReLU(in_channels,out_channels,kernel_size,stride,padding=1):
return nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size//2),
nn.BatchNorm2d(out_channels),
... |
1677872 | set_name(0x80121A34, "PreGameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x80123AF8, "DRLG_PlaceDoor__Fii", SN_NOWARN)
set_name(0x80123FCC, "DRLG_L1Shadows__Fv", SN_NOWARN)
set_name(0x801243E4, "DRLG_PlaceMiniSet__FPCUciiiiiii", SN_NOWARN)
set_name(0x80124850, "DRLG_L1Floor__Fv", SN_NOWARN)
set_name(0x8012493C, "StoreBlo... |
1677873 | from planemo.engine import (
engine_context,
)
from planemo.galaxy import galaxy_config
from planemo.galaxy.config import _find_test_data
from planemo.galaxy.test import (
handle_reports_and_summary,
run_in_config,
)
from planemo.runnable import (
for_paths,
RunnableType,
)
def test_runnables(ctx,... |
1677891 | import numpy as np
import pandas as pd
import holoviews as hv
import colorcet as cc
from ..backend_transforms import _transfer_opts_cur_backend
from ..util import with_hv_extension
@with_hv_extension
def andrews_curves(data, class_column, samples=200, alpha=0.5,
width=600, height=300, cmap=None, ... |
1677897 | def iteminfo:
def__init__(self):
self.icode=0
self.item=null
self.price=0
self.qty=0
self.discount=0
self.netprice=0
def cal(self):
if self.qty<=10:
self.discount=0
if self.qty>=11 and self.qty<=20:
self.discount=15
if self.qty>=20:
self.discount=20
def buy(self,ic,in,pr,q):... |
1677917 | from requests import get
import json
class Paginator:
"""
Paginator for moving through Partial collections.
It can move forwards, backwards or can jump to specific page
"""
def __init__(self, response, base_url='http://localhost:8080'):
self.response = response
self.base_url = ba... |
1677925 | import torch
import torch.nn as nn
from torch.autograd import Variable
import math
from rlpytorch import ArgsProvider, add_err
from rlpytorch.trainer import topk_accuracy
class MultiplePrediction:
def __init__(self):
self.args = ArgsProvider(
call_from = self,
define_args = [
... |
1677937 | import unittest
import numpy as np
import pandas as pd
import os
import sys
from mastml.datasets import LocalDatasets
sys.path.insert(0, os.path.abspath('../../../'))
from mastml.feature_selectors import NoSelect, EnsembleModelFeatureSelector, PearsonSelector, MASTMLFeatureSelector
from sklearn.ensemble import RandomF... |
1677945 | import unittest
from unittest import mock
from flumine.order.order import OrderStatus, OrderTypes
from betfairlightweight.resources.bettingresources import PriceSize
from flumine import config
from flumine.markets.market import Market
from flumine.markets.markets import Markets
from flumine.order.order import (
... |
1677971 | import sleuth_backend.views.views_utils as utils
from django.test import TestCase
class TestViewsUtils(TestCase):
'''
Test views utility functions
'''
def test_build_core_request(self):
'''
Test building list of requested cores
'''
solr_cores = ['genericPage', 'redditPo... |
1678050 | from xv_leak_tools import tools_root
from xv_leak_tools.log import L
from xv_leak_tools.process import check_subprocess
from xv_leak_tools.test_components.local_component import LocalComponent
from xv_leak_tools.test_device.connector_helper import ConnectorHelper
class Git(LocalComponent):
@staticmethod
def _... |
1678141 | import time
import simpleaudio as sa
import asyncio
import threading
import random
import os
from simpleaudio._simpleaudio import SimpleaudioError
dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'music')
class Player():
def __init__(self):
self.audio_files = [{
'path': o... |
1678154 | from typing import Dict
from ruamel.yaml import YAML
import constants
from constants import (
NORMALIZED_INTERFACES,
INTERFACE_NAME_RE,
NEIGHBOR_SPLIT_RE,
CDP_NEIGHBOR_RE,
HOSTS_FILE,
DEVICE_USERNAME,
DEVICE_PASSWORD,
DEVICE_TYPE,
CONNECTION_TIMEOUT,
)
def normalize_interface_typ... |
1678198 | import asyncio
import datetime
import json
import asyncpg
import discord
from discord.ext import commands, tasks
from discord.ext.commands.cooldowns import BucketType
class Stats(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Track command count
self.command_count = 0
s... |
1678213 | from django.contrib import admin
from .models import (IP)
# Register your models here.
admin.site.register(IP)
|
1678242 | from vega.search_space.networks.pytorch.network import Network
from .backbones import *
from .heads import *
from .blocks import *
from .customs import *
from .super_network import *
from .esrbodys import *
from .detectors import *
from .roi_extractors import *
from .shared_heads import *
from .utils import *
from .nec... |
1678272 | import networkx as nx
import matplotlib.pyplot as plt
from pyvis.network import Network
import pandas as pd
import streamlit as st
def got_func(physics):
got_net = Network(height="600px", width="100%", font_color="black",heading='Game of Thrones Graph')
# set the physics layout of the network
got_net.barnes_hut(... |
1678284 | import requests
from requests_oauthlib import OAuth1
consumer_key = '확인한 consumer_key'
consumer_secret = '확인한 onsumer_secret'
access_token = '확인한 access_token'
access_token_secret = '확인한 access_token_secret'
oauth = OAuth1(client_key=consumer_key, client_secret=consumer_secret,
resource_owner_key=acces... |
1678297 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
from indra.util import read_unicode_csv
logger = logging.getLogger(__name__)
from protmapper.uniprot_client import *
def _build_uniprot_subcell_loc():
fname = os.path.dirname(os.path... |
1678311 | import torch
import torch.nn as nn
from torch.nn import functional as F
from dassl.optim import build_optimizer, build_lr_scheduler
from dassl.utils import count_num_param
from dassl.engine import TRAINER_REGISTRY, TrainerXU
from dassl.engine.trainer_tmp import SimpleNet
@TRAINER_REGISTRY.register()
class MCD(Traine... |
1678319 | import requests
import os
from pathlib import Path
import pickle
from shutil import unpack_archive
urls = dict()
urls['ecg']=['http://www.cs.ucr.edu/~eamonn/discords/ECG_data.zip',
'http://www.cs.ucr.edu/~eamonn/discords/mitdbx_mitdbx_108.txt',
'http://www.cs.ucr.edu/~eamonn/discords/qtdbsele... |
1678364 | import requests
from scrapy.selector import Selector
import pymysql
import time
conn = pymysql.connect(host="127.0.0.1", user="feson", passwd="<PASSWORD>", db="Spider", charset="utf8")
cursor = conn.cursor()
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chro... |
1678382 | from polyphony import testbench
def f(l1:list, l2:list):
return l1[0] + l2[0]
def func11(a:list, b:list):
t1 = f(a, b)
t2 = f(b, a)
return t1 + t2
@testbench
def test():
a = [1]
b = [2]
assert 6 == func11(a, b)
test()
|
1678398 | from django.contrib import admin
# Register your models here.
from .models import Company, Flight, Comment
admin.site.register(Company)
admin.site.register(Flight)
admin.site.register(Comment)
|
1678417 | import numpy as np
import pytest
from mirdata.datasets import mtg_jamendo_autotagging_moodtheme
from tests.test_utils import run_track_tests
def test_track():
default_trackid = "track_0000948"
data_home = "tests/resources/mir_datasets/mtg_jamendo_autotagging_moodtheme"
dataset = mtg_jamendo_autotagging_m... |
1678421 | from app.models import *
from app.services.steps import Step_VR_7
def test_step_vr7_is_complete_false(app, db_session, client):
form_payload = {}
step = Step_VR_7(form_payload)
assert step.run() == False
assert step.is_complete == False
assert step.next_step == None
def test_step_vr7_is_complete_... |
1678444 | import pytest
from django_test_migrations.exceptions import MigrationNotInPlan
from django_test_migrations.plan import truncate_plan
@pytest.mark.parametrize(('targets', 'index'), [
([], 9), # full plan for empty targets
([('app1', None)], 0),
([('app1', None), ('app3', None)], 7),
([('app2', '0002_... |
1678478 | from rdr_service.api import check_ppi_data_api
from rdr_service.code_constants import FIRST_NAME_QUESTION_CODE
from rdr_service.dao.code_dao import CodeDao
from rdr_service.dao.participant_dao import ParticipantDao
from rdr_service.dao.participant_summary_dao import ParticipantSummaryDao
from rdr_service.model.particip... |
1678479 | import tensorflow as tf
class Resnet_152_feature(tf.keras.Model):
def __init__(self, class_resnet_152):
super(Resnet_152_feature, self).__init__(name='Resnet_152_feature')
self.resnet_152 = class_resnet_152
self.resnet_152_preprocess = tf.keras.applications.resnet.preprocess_input
def ... |
1678491 | from pydantic import BaseModel
from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Documentation, PortDoc, Form, FormGroup, \
FormField, FormComponent
from tracardi.service.plugin.runner import ActionRunner
from tracardi.service.plugin.domain.result import Result
from tracardi.service.notat... |
1678498 | dict={}
dict_all = {}
list = []
with open('rm_overlap_des-jan25.txt','r') as f:
lines = f.readlines()
for i in xrange(len(lines)):
try:
mid = lines[i].split('\t')[0]
if dict.has_key(mid):
# print 'Overlap!'
pass
else:
di... |
1678501 | import os
from .common_config import ffmpeg_bin_dir
# 为 .ts 文件的(1.ts,2.ts,3.ts,...,101.ts,...)这样的文件列表进行从小到大排序
def bubbleSortTsFile(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if int(str(arr[j]).replace('.ts','... |
1678504 | import os
import xml.etree.ElementTree as ET
import numpy as np
import cv2
import sys
from tqdm import tqdm
from albumentations import *
from multiprocessing import Process
classes = ["0","1","0head","1head"]
imageFolder = "images"
annotationFolder = "annotations"
if len(sys.argv) < 2:
quit()
wd = sys.argv[1]
... |
1678564 | import pytest
from iocage_lib.ioc_common import validate_plugin_manifest
VALID_MANIFEST = {
"name": "test_plugin",
"release": "12.2-RELEASE",
"pkgs": [],
"packagesite": "http://pkg.FreeBSD.org/${ABI}/latest",
"fingerprints": {
"iocage-plugins": [
{
"function": "... |
1678616 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.performance_curves import CurveFanPressureRise
log = logging.getLogger(__name__)
class TestCurveFanPressureRise(unittest.TestCase):
def setUp(self):
self.fd, self.p... |
1678621 | import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.pardir, os.pardir)))
from TaskKit.Scheduler import Scheduler
class TaskKitTest(unittest.TestCase):
def setUp(self):
self._scheduler = Scheduler()
def checkBasics(self):
sched = self._scheduler
s... |
1678623 | import pytest
@pytest.fixture
def default_internal_request():
return dict(
concepto_pago='PRUEBA',
institucion_ordenante='646',
cuenta_beneficiario='072691004495711499',
institucion_beneficiaria='072',
monto=1020,
nombre_beneficiario='<NAME>',
nombre_ordenan... |
1678635 | lsd_and_math.loc[7] = [6, 70]
x, y = lsd_and_math.T.values
b0, b1 = fmin(sum_of_squares, [0,1], args=(x,y))
b0_abs, b1_abs = fmin(sum_of_absval, [0,0], args=(x,y))
print('\nintercept: {0:.2}, slope: {1:.2}'.format(b0,b1))
ax = lsd_and_math.plot(x='Drugs', y='Score', style='ro', legend=False, xlim=(0,8))
ax.plot([0,10... |
1678674 | import numpy as np
def get_src_indices_by_row(row_idxs, shape, flat=True):
"""
Provide the src_indices when connecting a vectorized variable from an output to an input.
Indices are selected by choosing the first indices to be passed, corresponding to node
index in Dymos.
Parameters
---------... |
1678691 | from .common import *
def process_get_test(options):
if not load_session_with_options(options):
fatal('No session known. Use init first.')
for i in options.numbers:
global_vars.problem.download_test(i)
save_session()
def process_get_all_tests(options):
if not load_session_with_option... |
1678715 | import argparse
import os
import sys
# for linux env.
sys.path.insert(0,'..')
from distutils.util import strtobool
import pickle
import torch
import numpy as np
from data.data_loader import NumpyTupleDataset
import pandas as pd
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem, Draw
import torch
imp... |
1678758 | import torch
import torch.nn as nn
import torch.nn.functional as F
affine_par = True
class Separable_transpose_convolution(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=2,
padding=1, output_padding=0, bias=False, dilation=1):
super(Separable_transpose_conv... |
1678908 | import LibCall
from .module import Module
from .. import functional as F
class Linear(Module):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = LibCall.torch.callTen... |
1678920 | import os
import time
from fds.analyticsapi.engines import ApiException
from fds.analyticsapi.engines.api_client import ApiClient
from fds.analyticsapi.engines.api.pub_calculations_api import PubCalculationsApi
from fds.analyticsapi.engines.configuration import Configuration
from fds.analyticsapi.engines.model.pub_cal... |
1678941 | import tensorflow as tf
import numpy as np
def linear(input_, output_size, scope_name="linear"):
with tf.variable_scope(scope_name):
input_ = tf.reshape(
input_,
[-1, np.prod(input_.get_shape().as_list()[1:])])
output = tf.layers.dense(
input_,
outpu... |
1678945 | import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
training_data_df = pd.read_csv("dataset/sales_data_training_scaled.csv")
X = training_data_df.drop('销售总额', axis=1).values
Y = training_data_df[['销售总额']].values
# 定义模型:全连接网络
model = Sequential()
model.add(Dense(50... |
1679001 | import numpy as np
def dbMoriWen(z, us, umf, d_bed, l_or, dist_type):
"""
Calculates the equivalent diameter of the gas bubble in the bed, assuming
that all of the volume in bubbles in the bed were combined into a single
spherical bubble. This uses the Mori/Wen correlation as given in
Fluidization... |
1679028 | import ee
import geemap
# Create a map centered at (lat, lon).
Map = geemap.Map(center=[40, -100], zoom=4)
# Composite 6 months of Landsat 8.
# Note that the input to simpleComposite is raw data.
l8 = ee.ImageCollection('LANDSAT/LC08/C01/T1')
# The asFloat parameter gives floating-point TOA output instead of
# the... |
1679053 | from typing import Any, Dict
# Even though it is not imported, it is actually required, it downlaods some stuff.
import allennlp_models # noqa: F401
from allennlp.predictors.predictor import Predictor
from app.pipelines import Pipeline
class QuestionAnsweringPipeline(Pipeline):
def __init__(
self,
... |
1679070 | import unittest
from pathlib import Path
from bridgebots.board_record import BidMetadata
from bridgebots.deal_enums import Direction, Rank, Suit
from bridgebots.pbn import _build_record_dict, _parse_bidding_record, _sort_play_record, parse_pbn
class TestParsePbnFile(unittest.TestCase):
def test_parse_file(self):... |
1679082 | import os
from unittest.case import TestCase
from checkov.cloudformation.graph_builder.graph_components.block_types import BlockType
from checkov.cloudformation.graph_manager import CloudformationGraphManager
from checkov.common.graph.db_connectors.networkx.networkx_db_connector import NetworkxConnector
TEST_DIRNAME ... |
1679092 | from manimlib.scene.scene import Scene
class ThreeDScene(Scene):
CONFIG = {
"camera_config": {
"samples": 4,
"anti_alias_width": 0,
}
}
def begin_ambient_camera_rotation(self, rate=0.02):
pass # TODO
def stop_ambient_camera_rotation(self):
pas... |
1679145 | import os
import yaml
import pkg_resources
class _ConfigurationItem(object):
def __init__(self, val):
self._val = val
def __getitem__(self, key):
val = self._val[key]
if isinstance(val, dict):
return _ConfigurationItem(val)
else:
return val
def __setitem__(self, key, value):
self._val[key] = valu... |
1679171 | from insights.parsers.tmpfilesd import TmpFilesD
from insights.tests import context_wrap
SAP_CONF = """
# systemd tmpfiles exclude file for SAP
# SAP software stores some important files
# in /tmp which should not be deleted
# Exclude SAP socket and lock files
x /tmp/.sap*
# Exclude HANA lock file
x /tmp/.hdb*lock
"... |
1679178 | from __future__ import unicode_literals
import frappe
from frappe.model.db_query import DatabaseQuery
@frappe.whitelist()
def get_data(rfm=None, rfp=None, por=None,
start=0, sort_by='', sort_order='desc'):
'''Return data to render the item dashboard'''
filters_rfm = []
if rfm:
filters_rfm.append(['name', '=', r... |
1679185 | from nltk.stem.snowball import SnowballStemmer
from nltk.corpus import stopwords
from summariser.rouge.rouge import Rouge
import summariser.utils.data_helpers as util
import numpy as np
import operator as op
import functools
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text im... |
1679191 | import time
from collections import OrderedDict
import torch
import torch.nn as nn
import MinkowskiEngine as ME
__all__ = ['MinkUNet']
class BasicConvolutionBlock(nn.Module):
def __init__(self, inc, outc, ks=3, stride=1, dilation=1, D=3):
super().__init__()
self.net = nn.Sequential(
... |
1679212 | import json
import typing as t
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from uuid import UUID
from piccolo.columns.base import Column
from piccolo.table import Table
from piccolo.testing.random_builder import RandomBuilder
from piccolo.utils.sync import run_sync
class ModelBui... |
1679214 | import Exalt.view as vu
import Exalt.messages as messages
import Exalt.encodings as encodings
from lxml import etree
import Exalt.impl.parsetools as parsetools
from io import BytesIO
def format_markup(markup, view, **kwargs):
encoding = markup.docinfo.encoding
# lxml only indents HTML if method == "xml", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.