id
stringlengths
3
8
content
stringlengths
100
981k
1691476
from __future__ import division, with_statement from ...._common import block_to_format, get_label_length from ._helpers import prune_nones_dict, prune_nones_list, read_record __all__ = [ "read", ] def read(filename, label_length=None): """ Read TOUGH input file. Parameters ---------- filen...
1691478
class Solution: def beautifulArray(self, N: int) -> List[int]: result = [1] while len(result) < N: result = [i * 2 - 1 for i in result] + [i * 2 for i in result] return [i for i in result if i <= N]
1691493
import copy import random from configuration import config from src.genotype.cdn.nodes.blueprint_node import BlueprintNode from src.genotype.cdn.nodes.module_node import ModuleNode from src.genotype.neat.connection import Connection from src.genotype.neat.genome import Genome from src.genotype.neat.mutation_record imp...
1691537
import importlib from . import config import atexit import os HEAP_DEFAULT = 0 HEAP_UPLOAD = 1 HEAP_READBACK = 2 SHADER_BINARY_TYPE_DXIL = 0 SHADER_BINARY_TYPE_SPIRV = 1 SHADER_BINARY_TYPE_DXBC = 2 SHADER_BINARY_TYPE_MSL = 3 SHADER_BINARY_TYPE_GLSL = 4 class UnknownBackend(Exception): pass class BufferExcepti...
1691546
import ast import pathlib import yaml from typing import Any, Dict, Set from viewflow.adapters.python.python_adapter import DependantDataFrame class NoDocstringError(Exception): pass class UnparseableDocstringError(Exception): pass def get_dependencies_from_function_def(node: ast.FunctionDef) -> Set[str]...
1691549
import os try: os.makedirs("./temp") except OSError: #faz o que acha que deve se não for possível criar #https://pt.stackoverflow.com/q/170615/101
1691576
from os import listdir, mkdir from os.path import join, split, isfile, isdir conversions = [ ('./track2-gallery-query-metadata-v2m100/test-prob-v2m100.log', './track2-gallery-query-metadata-v2m100/prob_v2m100.txt', './track2-gallery-query-metadata-v2m100/imglist_v2m100.txt'), ] img_gline = {} with open...
1691583
import os import unittest import subprocess from fuc.api.common import FUC_PATH from fuc import pyvcf, pybed, pyfq, pygff vcf_file1 = f'{FUC_PATH}/data/vcf/1.vcf' vcf_file2 = f'{FUC_PATH}/data/vcf/2.vcf' vcf_file3 = f'{FUC_PATH}/data/vcf/3.vcf' bed_file1 = f'{FUC_PATH}/data/bed/1.bed' bed_file2 = f'{FUC_PATH}/data/be...
1691602
import argparse import sys import time from multiprocessing import Pool import numpy as np import pandas as pd from terminaltables import * from dataset import VideoDataSet from ops.utils import temporal_nms sys.path.append('./anet_toolkit/Evaluation') import os import pdb import pickle from anet_toolkit.Evaluation...
1691606
from api.event import Event class TaskCreatedEvent(Event): """ A `task-created` event that replaces the celery's `task-sent` event. Sent by TaskResponse for every PENDING/STARTED task. """ _type_ = _name_ = 'task-created'
1691613
import unittest import comma.cpp_bindings class test(unittest.TestCase): def test_size(self): self.assertEqual(comma.cpp_bindings.csv.format('d,2ub,s[5]').size(), 15) if __name__ == '__main__': unittest.main()
1691615
from ekphrasis.classes.preprocessor import TextPreProcessor from ekphrasis.classes.tokenizer import SocialTokenizer from ekphrasis.dicts.emoticons import emoticons def ws_tokenizer(text): return text.split() text_processor = TextPreProcessor( normalize=['url', 'email', 'percent', 'money', 'phone', 'user', '...
1691629
import logging import time from src.tasks.celery_app import celery from src.queries.get_trending_playlists import ( make_trending_cache_key, make_get_unpopulated_playlists, ) from src.utils.redis_cache import pickle_and_set from src.utils.redis_constants import trending_playlists_last_completion_redis_key from ...
1691641
import os import pickle import tensorflow as tf from six.moves import cPickle from moon.models.lstm_gen.char_rnn.model import Model def get_sample(base_save_dir, sample_length, seed_str): with open("sample_args.pickle", "rb") as handle: args = pickle.load(handle) args.save_dir = base_save_dir ar...
1691655
from smart_grasping_sandbox.smart_grasper import SmartGrasper from tf.transformations import quaternion_from_euler from math import pi import time import rospy from math import sqrt, pow import random from sys import argv sgs = SmartGrasper() MIN_LIFT_STEPS = 5 MAX_BALL_DISTANCE = 0.6 CLOSED_HAND = {} CLOSED_HAND["...
1691658
import pandas as pd import numpy as np import plotly.graph_objs as go import plotly.colors from collections import OrderedDict import requests # default list of all countries of interest country_default = OrderedDict([('Canada', 'CAN'), ('United States', 'USA'), ('Brazil', 'BRA'), ('France', 'FRA'), ('India', 'IND...
1691660
from django.db import models from django.contrib.contenttypes.models import ContentType from django.utils.encoding import force_text class CommentManager(models.Manager): def for_model(self, model): """ QuerySet for all comments for a particular model (either an instance or a class). ...
1691661
from django.contrib import admin from reversion.admin import VersionAdmin from symposion.teams.models import Team, Membership admin.site.register(Team, prepopulated_fields={"slug": ("name",)}) class MembershipAdmin(VersionAdmin): list_display = ["team", "user", "state"] list_filter = ["...
1691676
import json import pytest from verity_sdk.utils import unpack_forward_message from verity_sdk.utils.Context import Context from verity_sdk.protocols.Protocol import Protocol from ..test_utils import get_test_config, cleanup @pytest.mark.asyncio async def test_get_message(): message = {'hello': 'world'} conte...
1691684
import cv2 import numpy as np cap = cv2.VideoCapture(0) while (1): _, frame = cap.read() # intialize the object detector = cv2.CascadeClassifier("haarcascade_smile.xml") # read the image and convert to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # perform the the face...
1691716
from ps1_argonaut.files.DATFile import DATFile class BINFile(DATFile): suffix = 'BIN' def __str__(self): return 'Translated text'
1691725
import asyncio import logging from public_plugins.trickcord_patches import trickcord_patches logger = logging.getLogger('gradiusbot') logger.info("[Message Event Plugin] <trickcord_patches.py>: Trickcord Edit Event patches.") TRICKCORD_ID = 755580145078632508 async def action(**kwargs): event_type = kwargs['ev...
1691735
import string import unittest class BrailleTest(unittest.TestCase): def testLowercase(self): self.assertEqual( answer("code"), "100100101010100110100010") def testMixedcase(self): self.assertEqual( answer("Braille"), "000001110000111010100000010100111000111...
1691758
import pyspark.sql.functions as F import pyspark.sql.types as T from typing import Callable from pyspark.sql import SparkSession, DataFrame # helper function for looping def loop(op: Callable[[DataFrame], DataFrame], df: DataFrame = None) -> DataFrame: for _ in range(10): df = op(df) return df class ...
1691814
import os,sys from tkinter import * import tkinter.font as font from tkinter import filedialog class Final(Frame): def __init__(self, parent=None, pid=0,side=LEFT, anchor=N,wt=600,ht=400,is_next=True,is_back=True,next_frame=None,back_frame=None,info_txt="",path_frm=None,path_frm2=None,frames=[],fdict=[],prefix_v...
1691836
import argparse import os import subprocess import sys from datetime import datetime from config.Config import Config from enums.Architectures import Arch from utils.console import Console from utils.utils import detect_arch class ExportViewer: def __init__(self, arch=Arch.x64): self.path = str(Config()....
1691895
import os from LAUG.aug.Word_Perturbation.multiwoz.multiwoz_eda import MultiwozEDA from LAUG.aug.Word_Perturbation.multiwoz.db.slot_value_replace import MultiSourceDBLoader, MultiSourceDBLoaderArgs from LAUG.aug.Word_Perturbation.multiwoz.util import load_json, dump_json from LAUG import DATA_ROOT,REPO_ROOT import json...
1691930
from pybricks.parameters import Port class AnalogSensor: """ Generic or custom analog sensor. Args: port (Port): Port to which the sensor is connected. """ def __init__(self, port: Port): if port == Port.A or port == Port.B or port == Port.C or port == Port.D: raise V...
1691964
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.path import numexpr as ne import scipy as sp import scipy.sparse plt.ion() import pybie2d """ Demonstrate how to use the pybie2d package to solve an interior/exterior Laplace problem on a complicated domain using a global qua...
1691967
import pytest from protoactor.actor import PID from protoactor.remote.messages import JsonMessage from protoactor.remote.serialization import Serialization from tests.remote.messages.protos_pb2 import DESCRIPTOR @pytest.fixture(scope="session", autouse=True) def register_file_descriptor(): Serialization().regis...
1692057
from django.contrib import admin #from .models import Article, Category, BlogComment, Tag #from .models import Image # Register your models here. #admin.site.register([Article, Category, BlogComment, Tag]) #admin.site.register([Image])
1692064
import numpy as np from tgym.utils import calc_spread def test_calc_spread(): spread_coefficients = [1, -0.1] prices = np.array([1, 2, 10, 20]) spread_price = (-1, 1) assert calc_spread(prices, spread_coefficients) == spread_price
1692083
import numpy as np from mmcv.parallel import DataContainer as DC from mmdet.datasets.builder import PIPELINES from mmdet.datasets.pipelines import to_tensor @PIPELINES.register_module() class ConcatVideoReferences(object): """Concat video references. If the input list contains at least two dicts, concat the ...
1692096
import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) import argparse import datetime import json import contextlib from func_timeout import func_timeout, FunctionTimedOut import multiprocessing import numpy as np import os import sys from job_id_pair import Job...
1692185
from nose.tools import eq_ import openxc.version def test_get_version(): version = openxc.version.get_version() eq_(type(version), str)
1692219
import math import numpy as np class Robot: def __init__(self, wheel_base, track_width, wheel_radius, max_v, max_w): # w1<--track width--> w2 # ^ | # | | # wb | # | | # v | ...
1692228
from bentoml.yatai.grpc_interceptor.prom_server_interceptor import ( PromServerInterceptor, ServiceLatencyInterceptor, ) __all__ = [ "ServiceLatencyInterceptor", "PromServerInterceptor", ]
1692251
import requests import json import datetime import azure.functions as func import base64 import hmac import hashlib import os import logging import re from .state_manager import StateManager customer_id = os.environ['WorkspaceID'] shared_key = os.environ['WorkspaceKey'] slack_api_bearer_token = os.envir...
1692282
import pytest from sitri import Sitri from sitri.providers.contrib.system import SystemConfigProvider @pytest.fixture(scope="module") def test_sitri(): return Sitri(config_provider=SystemConfigProvider(prefix="test"))
1692294
class Stack(object): def __init__(self): """ initialize your data structure here. """ self.q1 = [] self.q2 = [] def push(self, x): """ :type x: int :rtype: nothing """ self.q1.append(x) def pop(self): """ :rtyp...
1692325
from functools import wraps from flask_login import login_required from werkzeug.exceptions import abort from sarna.model.enums import UserType valid_auditors = {UserType.manager, UserType.trusted_auditor, UserType.auditor} valid_trusted = {UserType.manager, UserType.trusted_auditor} valid_managers = {UserType.manag...
1692362
import zipfile import sys import os import ase.io from datetime import datetime def extract_file(zipname, file_to_unzip, extract_to): with zipfile.ZipFile(zipname, 'r') as traj_zip: traj_zip.extract(file_to_unzip, extract_to) def main(): """ Given a directory containing adsorbate subdirectories, ...
1692366
import numpy as np import cv2 segmentation_colors = np.array([[0, 0, 0], [255, 191, 0], [192, 67, 251]], dtype=np.uint8) detection_color = (191, 255, 0) label = "car" ORIGINAL_HORIZON_POINTS = np.float32([[571, 337], [652, 337]]) num_horizon_points = 0 new_horizon_points = [] def util_d...
1692404
import io import glob import os import pytest from readme_renderer.markdown import render, variants MD_FIXTURES = [ (fn, os.path.splitext(fn)[0] + ".html", variant) for variant in variants for fn in glob.iglob( os.path.join( os.path.dirname(__file__), "fixtures", ...
1692407
import unittest from katas.kyu_7.rule_of_divisibility_by_7 import seven class SevenTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(seven(483), (42, 1)) def test_equals_2(self): self.assertEqual(seven(371), (35, 1)) def test_equals_3(self): self.assertEqual(s...
1692415
import os import sys import pytest from sonic_platform_base.sonic_sfp import sfputilhelper @pytest.fixture(scope="class") def setup_class(request): # Configure the setup test_dir = os.path.dirname(os.path.realpath(__file__)) request.cls.port_config_file = os.path.join(test_dir, 'port_config.ini') @pyt...
1692432
from tqdm import tqdm class DLProgress(tqdm): """ Class to show progress on dataset download """ # Progress bar code adapted from a Udacity machine learning project. last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_n...
1692458
from kafka.structs import TopicPartition from typing import Dict from typing import List from typing import Optional class KafkaConsumer: def __init__( self, bootstrap_servers: List[str], enable_auto_commit: Optional[bool] = True, group_id: Optional[str] = None, ): ... ...
1692459
from db import connect from db.model import Basic, Decision from sqlalchemy import and_ class DecisionFactory: @staticmethod def get_by_user(user_id): """ Get by user id :param int user_id: user id :return: decisions :rtype: list[Decision] """ session =...
1692469
import scipy.ndimage as scnd import scipy.optimize as sio import numpy as np import stemtool as st import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib_scalebar.scalebar as mpss import matplotlib.offsetbox as mploff import matplotlib.gridspec as mpgs import matplotlib as mpl class atomic...
1692470
import time from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.text import get_valid_filename, slugify from django.utils.encoding import python_2_unicode_compatible EXTENSION_CHOICES = ( ('.ini', _('INI file')), ('.yml', _('YAML file')), ('.xml', _('XML ...
1692499
from abc import ABCMeta, abstractmethod class AbstractDataHandler(object): """Abstract Data Handler Class The data handler is an abstract base class providing an interface for all subsequent (inherited) data handlers (both live and historic). The goal of a (derived) data handler object is to output ...
1692528
import ast import csv import datetime import pytz from sqlalchemy import Column, Integer, Numeric, String, Boolean, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Device(Base): __tablename__ = 'devices' id = Column(Integer, primary_key=True, autoincrement=True...
1692530
import os import datetime import requests, json from django.contrib.auth.models import User from django.core.mail import send_mail ## Global var to be used any time we need to use the range or min/max # of ## Google's category scoring scale. Names changed for more global usage. ## Ex: An accessibility score isn...
1692548
import cmath if __name__ == '__main__': s = input() #input a complex number print(abs(complex(s))) #output the distance in polar coordinate print(cmath.phase(complex(s))) #output the angle in polar coordinate
1692605
load( "//reason/private:extensions.bzl", "CMXA_EXT", "CMI_EXT", "CMO_EXT", "CMX_EXT", "C_EXT", "H_EXT", "MLI_EXT", "ML_EXT", "O_EXT", ) load( "//reason/private:providers.bzl", "MlCompiledModule", ) load( ":utils.bzl", "TARGET_BYTECODE", "TARGET_NATIVE", ...
1692633
import sublime from os import path import urllib import json import subprocess import re from .settings import get_setting server_addr = "http://127.0.0.1:15155" cli = 'padawan' server_command = 'padawan-server' class Server: def start(self): subprocess.Popen( server_command, sh...
1692658
import unittest import numpy as np import pandas as pd import os import sys sys.path.insert(0, os.path.abspath('../../../')) from mastml.plots import Scatter, Histogram class TestPlots(unittest.TestCase): def test_scatter(self): X = pd.Series(np.random.uniform(low=0.0, high=100, size=(50,))) y = ...
1692673
import pytest from sentinelhub import SentinelHubSession @pytest.mark.sh_integration def test_session(): session = SentinelHubSession() token = session.token headers = session.session_headers for item in [token, headers]: assert isinstance(item, dict) for key in ['access_token', 'expir...
1692710
self.description = "Sysupgrade with sync packages having absurd epochs" versions = ( "1234327518932650063289125782697890:1.0-1", "1234327518932650063289125782697891:0.9-1", "1234327518932650063289125782697891:1.0-1", "1234327518932650063289125782697891:1.1-1", "1234327518932650063289125782697892:1.0-1", ) pkgver...
1692728
import unittest from mock import MagicMock from src.domain.input_text.input_text_processor import InputTextProcessor from src.domain.interaction.information_phase import InformationPhase from src.domain.interaction.transition_to_question_answering_phase import TransitionToQuestionAnsweringPhase class TestInformatio...
1692779
import torch from tqdm import tqdm # MLP + Positional Encoding class Decoder(torch.nn.Module): def __init__(self, input_dims = 3, internal_dims = 128, output_dims = 4, hidden = 5, multires = 2): super().__init__() self.embed_fn = None if multires > 0: embed_fn, input_ch = get_em...
1692783
import argparse import os import torch import yaml from train.train import train os.environ['NCCL_LL_THRESHOLD'] = '0' parser = argparse.ArgumentParser(description='Train model on multiple cards') parser.add_argument('--config', help='path to yaml config file') parser.add_argument('--local_rank', type=i...
1692791
from unittest import TestCase from torch.nn import BCELoss from tqdm import tqdm from experiments import Experiment from experiments.environment import get_env from experiments.utils import flatten from models.transformers import JointBERT from wiki.data_helpers import JointBERTWikiDataHelper class ExperimentTest(T...
1692837
from .AutomatonGenerators import generate_random_dfa, generate_random_mealy_machine, generate_random_moore_machine, generate_random_markov_chain from .AutomatonGenerators import generate_random_mdp, generate_random_ONFSM from .FileHandler import save_automaton_to_file, load_automaton_from_file, visualize_automaton from...
1692838
from enum import Enum class CriminalCase: pass class CriminalOffence(Enum): # List from https://www.cps.gov.uk/sites/default/files/ # documents/publications/annex_1a_table_of_offences_scheme_c.pdf DANGEROUS_DRIVING = "Dangerous driving" ENDANGERING_AN_AIRCRAFT = "Endangering an aircraft" FAL...
1692844
def create_dictionary_from_lexicon(path, punctuation_marks): words = ["<unk>", "</s>"] with open(path, 'r') as f: for line in f: word = line.strip() if word not in punctuation_marks: words.append(word) return dict(zip(words, range(len(words)))) def create_p...
1692849
import os import copy from continual_rl.policies.policy_base import PolicyBase from continual_rl.policies.impala.impala_policy_config import ImpalaPolicyConfig from continual_rl.policies.impala.impala_environment_runner import ImpalaEnvironmentRunner from continual_rl.policies.impala.nets import ImpalaNet from continua...
1692873
try: from rgbmatrix import graphics except ImportError: from RGBMatrixEmulator import graphics from data.config.color import Color from data.config.layout import Layout from data.standings import Division, League from utils import center_text_position def render_standings(canvas, layout: Layout, c...
1692925
import torch from typing import List from yacs.config import CfgNode from torch.nn import functional as F from .jenson_shannon_divergence import jensen_shannon_divergence from .build import LOSS_REGISTRY @LOSS_REGISTRY.register('weighted_focal_loss') class WeightedFocalLoss(torch.nn.Module): """ If dysfunctio...
1692947
from polyphony import testbench def ifexp01(x, y): return True if x == y else False @testbench def test(): assert False == ifexp01(0, 1) assert True == ifexp01(1, 1) assert False == ifexp01(True, False) test()
1692956
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .utils import * from .affine_net import * from .momentum_net import * import mermaid.module_parameters as pars import mermaid.model_factory as py_mf import mermaid.utils as py_utils from functools import p...
1692964
from direct.directnotify import DirectNotifyGlobal from pandac.PandaModules import ModelNode, LODNode, NodePath from pandac.PandaModules import TextureStage from pandac.PandaModules import AnimControlCollection, Character, PartSubset from pirates.ship import ShipGlobals from pirates.ship import ShipBlueprints MastSubse...
1692996
from relogic.logickit.scorer.scorer import Scorer from relogic.logickit.utils.utils import softmax, sigmoid import torch.nn.functional as F import torch from tqdm import tqdm import os import subprocess import json class RecallScorer(Scorer): def __init__(self, label_mapping, topk, correct_label='1', dump_to_file=No...
1693001
from common.diagrams import Diagram from common.definitions import G_PROTEIN_SEGMENTS from residue.models import Residue from residue.models import ResidueGenericNumber from residue.models import ResidueNumberingScheme from django.utils.safestring import mark_safe from math import cos, sin, pi, floor,sqrt from datet...
1693007
from django.urls import path from .views import show_foilaw urlpatterns = [ path("<slug:slug>/", show_foilaw, name="publicbody-foilaw-show"), ]
1693027
from CvPythonExtensions import * import CvUtil gc = CyGlobalContext() class CvPediaProject: def __init__(self, main): self.iProject = -1 self.top = main self.X_INFO_PANE = self.top.X_PEDIA_PAGE self.Y_INFO_PANE = self.top.Y_PEDIA_PAGE self.W_INFO_PANE = 380 #290 self.H_INFO_PANE = 120 self.W_ICON =...
1693029
import torch import torch.nn as nn from uninas.modules.heads.abstract import AbstractHead from uninas.utils.args import Argument from uninas.utils.shape import Shape from uninas.register import Register @Register.network_head() class PwClassificationHead(AbstractHead): """ Network output, pixel-wise act f...
1693043
import os import pickle as pkl import numpy as np import scipy.io as scio import SimpleITK as sitk from sklearn.preprocessing import normalize from hyperg.utils import minmax_scale from hyperg.utils import print_log DATA_DIR = os.path.join(os.path.dirname(__file__), 'datasets') def load_myocardium(test_idx=[4]): ...
1693070
from app import db from app.models.base_model import BaseEntity class Contact(db.Model, BaseEntity): __tablename__ = 'contact' name = db.Column(db.String(256)) email = db.Column(db.String(200), unique=True) phone_nr = db.Column(db.String(64)) location_id = db.Column(db.Integer, db.ForeignKey('loc...
1693157
import pytest from torch.nn import Embedding as _Embedding from neuralpy.layers.sparse import Embedding def test_embedding_should_throw_type_error(): with pytest.raises(TypeError): Embedding() @pytest.mark.parametrize( "num_embeddings, embedding_dim, padding_idx, \ max_norm, norm_type, scale_gra...
1693169
import tensorflow as tf import math def fully_connected(input_, output_nodes, name, stddev=0.02): with tf.variable_scope(name): input_shape = input_.get_shape() input_nodes = input_shape[-1] w = tf.get_variable('w', [input_nodes, output_nodes], initializer=tf.truncated_normal_i...
1693171
import cv2 import os from hdn.core.config import cfg '''This script is using for transform POT dataset from video to img frames.''' if __name__ == "__main__": import os, shutil result_path = cfg.BASE.PROJ_PATH + 'experiments/tracker_homo_config/results/POT/HDN' for i in os.listdir(result_path): or...
1693173
import re import pytest from django.core.exceptions import ImproperlyConfigured from precise_bbcode.bbcode import BBCodeParserLoader from precise_bbcode.bbcode import get_parser from precise_bbcode.bbcode.defaults.placeholder import _color_re from precise_bbcode.bbcode.defaults.placeholder import _email_re from preci...
1693203
from __future__ import division import pickle import numpy import time def run_tti_sim(model, T, max_dt=None, intervention_start_pct_infected=0, average_introductions_per_day=0, testing_cadence='everyday', pct_tested_per_day=1.0, test_falseneg_rate='temporal', testin...
1693230
import requests import json import time import os import sys from contextlib import contextmanager from subprocess import Popen, check_output, CalledProcessError import shlex class Droplet: def __init__(self, session, id, i_know_what_im_doing=False): if not i_know_what_im_doing: raise Except...
1693334
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: int """ from collections import Counter out=even=sum(v for k,v in Counter(s).items() if v%2==0) odd_big=[v for k,v in Counter(s).items() if v%2!=0 and v>1] odd_small=[v for k,v in...
1693336
import time import mock from datetime import datetime, timedelta from chalice import logs from chalice.awsclient import TypedAWSClient from six import StringIO NO_OPTIONS = logs.LogRetrieveOptions() def message(log_message, log_stream_name='logStreamName'): return { 'logStreamName': log_stream_name, ...
1693357
import warnings import numpy as np import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams import treeano import treeano.nodes as tn fX = theano.config.floatX @treeano.register_node("normal_sample") class NormalSampleNode(treeano.NodeImpl): input_keys = ("mu", "sigma") ...
1693383
class Person: def __init__(self, name, age): self.name = name self.age = age def print_name(self): pass print("Hello my name is " + self.name) class Dog: def __init__(self, name): self.name = name self.tricks = [] def add_trick(self, trick): se...
1693385
from ..utils import TranspileTestCase class SetComprehensionTests(TranspileTestCase): def test_syntax(self): self.assertCodeExecution(""" x = [1, 2, 3, 4, 5] s = {v**2 for v in x} print(len(s)) print(1 in s) print(4 in s) print(9 in s...
1693416
import hugectr from mpi4py import MPI solver = hugectr.CreateSolver(max_eval_batches = 70, batchsize_eval = 65536, batchsize = 65536, lr = 0.5, warmup_steps = 300, vvgpu ...
1693418
import pandas_flavor as pf import pandas as pd @pf.register_dataframe_method def sort_column_value_order( df: pd.DataFrame, column: str, column_value_order: dict, columns=None ) -> pd.DataFrame: """ This function adds precedence to certain values in a specified column, then sorts based on that column ...
1693440
import json import os import platform import sys import threading import traceback from copy import deepcopy from datetime import datetime from string import lower class AbstractLog(object): # AbstractLog provides an ABC for the creation of a concrete Log class def __init__(self, ToolProjectName, ToolProject...
1693484
from modeltranslation.translator import translator, TranslationOptions from .models import Language, Keyword, KeywordSet, Place, Event, Offer, License class LanguageTranslationOptions(TranslationOptions): fields = ('name',) translator.register(Language, LanguageTranslationOptions) class KeywordTranslationOpti...
1693512
from decouple import config DATAPORTEN = { "STUDY": { "ENABLED": config("OW4_DP_STUDY_ENABLED", cast=bool, default=False), "TESTING": config("OW4_DP_STUDY_TESTING", cast=bool, default=True), "CLIENT_ID": config("OW4_DP_STUDY_CLIENT_ID", default=""), "CLIENT_SECRET": config("OW4_DP_S...
1693517
def test(): assert ( "patterns = list(nlp.pipe(people))" in __solution__ ), "你有用list将nlp.pipe的结果变为列表吗?" __msg__.good( "干得漂亮!接下来我们看一个实际例子,用nlp.pipe来处理文档生成更多的元数据。" )
1693548
from orator.migrations import Migration class CreateSubredditsTable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('subreddits') as table: table.increments('id') table.timestamps() table.text('subreddit').unique() ...
1693576
import os import config import models import gamestats import message import addgamestats import basehandler from wrap import PropWrap from wrap import DictWrap from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db class GameDetail(basehandler.Ba...
1693582
from nose.tools import with_setup import pandas as pd from ..widget import utils as utils from ..widget.encoding import Encoding df = None encoding = None def _setup(): global df, encoding records = [{u'buildingID': 0, u'date': u'6/1/13', u'temp_diff': 12, "mystr": "alejandro", "mystr2": "1"}, ...