text string | size int64 | token_count int64 |
|---|---|---|
"""SDC properties mixins module."""
"""
Copyright 2021 Deutsche Telekom AG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless r... | 6,714 | 1,769 |
import re
import math
import codecs
import random
import numpy as np
def is_not_chinese(uchar:str):
"""
判断一个unicode是否是汉字
:param uchar: (str) 待判断的字符
"""
if uchar.isalpha() is True:
return False
elif uchar >= u'\u4e00' and uchar <= u'\u9fa5':
return False
else:
retur... | 3,193 | 1,282 |
import kivy
from kivy.app import App
from kivy.uix.pagelayout import PageLayout
class PageLayoutApp(App):
def build(self):
return PageLayout()
if __name__ == '__main__':
PageLayoutApp().run() | 197 | 72 |
__author__ = ["Francisco Clavero"]
__description__ = "Click groups for different optimizers."
__email__ = ["fcoclavero32@gmail.com"]
__status__ = "Prototype"
import click
from vscvs.cli.decorators import pass_kwargs_to_context
from vscvs.trainers.mixins import (
AdaBoundOptimizerMixin,
AdamOptimizerMixin,
... | 5,988 | 2,051 |
import torch
from torch.utils.data import Dataset, DataLoader
from pre_ast_path import ASTParser
from tqdm import tqdm, trange
import multiprocessing
from multiprocessing import Process, freeze_support
import pickle
import config
import os
import re
from gen_graph import get_adj, gen_feature
from unified_vocab import u... | 5,323 | 2,028 |
# coding=utf-8
# *** WARNING: this file was generated by Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
import pul... | 1,708 | 550 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from benedict.serializers.abstract import AbstractSerializer
from benedict.utils import type_util
from six import text_type
import json
class JSONSerializer(AbstractSerializer):
def __init__(self):
super(JSONSerializer, self).__init__()
... | 847 | 256 |
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers impo... | 5,148 | 1,726 |
# -*- coding: utf-8 -*-
#
# HPX - dashboard
#
# Copyright (c) 2020 - ETH Zurich
# All rights reserved
#
# SPDX-License-Identifier: BSD-3-Clause
"""
"""
import copy
from datetime import datetime
import json
from bokeh.layouts import column, row
from bokeh.models.widgets import Button, Div, Toggle, TextAreaInput
from... | 11,625 | 3,291 |
# Generated by Django 3.2.6 on 2021-08-29 18:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('thanos', '0002_auto_2021... | 2,063 | 609 |
from .base import *
import array
class UVPrimitivePart:
def __init__(self, picking_color_id, owner, data_row_range, start_positions,
default_positions, geom_prim, pos):
self.picking_color_id = picking_color_id
self.id = picking_color_id
self.owner = owner
self.da... | 15,379 | 5,293 |
import codecs
import json
import os
from pathlib import Path
import shutil
from packaging import version
from lyrebird.mock.logger_helper import get_logger
from .version import IVERSION
from typing import List
from flask import Response, abort
from lyrebird.mock.console_helper import warning_msg, err_msg
import subpro... | 5,185 | 1,652 |
# Write a program to find the nth super ugly number.
# Super ugly numbers are positive numbers
# whose all prime factors are in the given prime list primes of size k.
# Example:
# Input: n = 12, primes = [2,7,13,19]
# Output: 32
# Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12
# ... | 1,279 | 447 |
#!/usr/bin/env python
from livereload import Server
import bitwrap_io.server
from bitwrap_io.api import Config
from bitwrap_io.server import app, pnml_editor
from flask_restful import Resource, Api
class VetChain(Resource):
""" save new Petri-Net XML definition """
def post(self, vetid):
machine_de... | 1,118 | 364 |
# $Id$
#
# Copyright (C)2003-2010 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" Hybrid EState-VSA de... | 3,368 | 1,474 |
# Punto 1
def multiplicar(a, b):
m = 0
for i in range(0, b):
m = m + a
return m
# Punto 2
def potencia(a, b):
p = 1
for i in range(0, b):
p = multiplicar(p, a)
return p
# Punto 3
a = input()
b = input()
print potencia(a, b)
| 266 | 120 |
import time
import numpy as np
from goprocam import GoProCamera, constants
gpCam = GoProCamera.GoPro()
# Extracts clips from latest video
latestVideo = gpCam.getVideoInfo()
print("Tag count %s" % latestVideo.get(constants.Info.TagCount))
arrayLength = latestVideo[constants.Info.TagCount]
if arrayLength % 2 == 0:
... | 2,019 | 651 |
from django.core.management import BaseCommand
from django_gamification.models import BadgeDefinition, Category, UnlockableDefinition, GamificationInterface
from gogoedu.models import myUser
class Command(BaseCommand):
help = 'Generates fake data for the app'
def handle(self, *args, **options):
cate... | 1,647 | 437 |
import numpy as np
import scipy
import scipy.io
import pickle
from scipy.special import lpmv, spherical_jn, spherical_yn
class Directivity:
def __init__(self, data_path, rho0, c0, freq_vec, simulated_ir_duration, measurement_radius, sh_order, type, sample_rate=44100, **kwargs):
''... | 16,675 | 5,652 |
#!/usr/bin/env python
import sys
import rospy
from nav_msgs.srv import GetMap
from comp313p_reactive_planner_controller.occupancy_grid import OccupancyGrid
from comp313p_reactive_planner_controller.search_grid import SearchGrid
from comp313p_reactive_planner_controller.grid_drawer import GridDrawer
# This class pings... | 1,326 | 413 |
###########################################################
# ORM Initialization
###########################################################
import json
from sqlalchemy import (
Column,
ForeignKey,
Integer,
String,
DateTime,
Text,
Enum,
)
from sqlalchemy.orm import relationship
from sqlalche... | 2,808 | 896 |
# TOKEN
PAD_token = 0
GO_token = 1
EOS_token = 2
| 49 | 29 |
#!/usr/bin/env python
'''
@author Nicolas Berberich
@date 07.09.2017
ROS node for converting joint sensor encoder values to degrees and radians.
'''
import rospy
from std_msgs.msg import Int64
from spinn_ros_msgs.msg import Myo_Joint_Angle
import numpy as np
def convert_angle():
'''
#topic: /to_spinnaker
... | 1,151 | 433 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | 10,098 | 2,824 |
"""Create brief responses table
Revision ID: 570
Revises: 560
Create Date: 2016-02-10 12:19:22.888832
"""
# revision identifiers, used by Alembic.
revision = '570'
down_revision = '560'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.create_table('br... | 1,048 | 388 |
import numpy
import pandas
from sklearn.decomposition import PCA
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from pdpcli.stages.sklearn_stages import SklearnPredictor, SklearnTransformer
def test_sklearn_predictor() -> None:
df = pandas.DataFram... | 2,224 | 784 |
from drain3.template_miner import TemplateMiner
| 49 | 16 |
"""A collection of scripts that can be used to plot the various quantities that CLMM models."""
import matplotlib.pyplot as plt
from .galaxycluster import GalaxyCluster
def plot_profiles(cluster=None, rbins=None, tangential_component=None, tangential_component_error=None,
cross_component=None, cross... | 5,043 | 1,350 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import astropy.units as u
import numpy as np
from astropy.io import ascii
from astropy.tests.helper import pytest
from astropy.utils.data import get_pkg_data_filename
from ..analysis import read_run, save_run
from ..model_fitter import Interact... | 3,823 | 1,458 |
from twccli.twcc.services.compute import GpuSite, VcsSite, VcsSecurityGroup, VcsServerNet
from twccli.twcc.util import isNone, mk_names
from twccli.twcc.services.compute import getServerId, getSecGroupList
from twccli.twcc.services.compute_util import list_vcs
from twccli.twccli import pass_environment, logger
from twc... | 7,513 | 2,424 |
from django.conf import settings
from django.core import mail
from django.forms import Form
from mock import patch
from nose.tools import eq_, ok_
from test_utils import TestCase
from users import forms
class EditProfileFormTests(TestCase):
def _form(self, **kwargs):
"""Default profile edit form."""
... | 4,154 | 1,334 |
#!/usr/bin/env python
import warnings
import os
import sys
import os.path as op
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
import nibabel as nb
import numpy as np
from qsiprep.niworkflows.viz.utils import slices_from_bbox
from qsiprep.interfaces.converters import fib2amps, mif2amps
fr... | 16,609 | 5,810 |
from django.conf import settings
from django.test import TestCase
from django.db.models import Count, Max
from regressiontests.aggregation_regress.models import *
class AggregationTests(TestCase):
def test_aggregates_in_where_clause(self):
"""
Regression test for #12822: DatabaseError: aggregate... | 2,740 | 797 |
class Node () :
def __init__ (self , table , index = None) :
self.__table = table
self.__index = index
self.__weight = self.__calculateWeight ()
self.__left_child = None
self.__forward_child = None
self.__right_child = None
self.__parent = None
def getTab... | 3,884 | 1,117 |
from jsonschema import validate
# A sample schema, like what we'd get from json.load()
schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number", "minimum": 0, "maximum": 39},
"name" : {"type" : "string"},
},
}
# If no exception is raised by validate(), the instance is valid.
validate(instanc... | 732 | 258 |
print(len(str(input()))) | 24 | 10 |
# -*- coding: utf-8 -*-
"""
Test for text writer.
"""
from __future__ import print_function
import tempfile
import textwrap
from docutils.core import publish_string
import rst2txt
def assert_serialized(source, expected_output, settings=None):
source = textwrap.dedent(source)
expected_output = textwrap.dede... | 7,262 | 2,133 |
# The goal: Extract the first four columns from serial_log.txt and place them in output1.csv
#
# Hint: to join a list of strings into one string, use the .join() function:
# ','.join(['256', '24.525', '103.70'])
# yields
# '256,24.525,103.70'
| 247 | 102 |
# Generated by Django 3.1.7 on 2022-01-24 16:28
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateM... | 998 | 294 |
# Time: O(n)
# Space: O(1)
# 746
# On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
#
# Once you pay the cost, you can either climb one or two steps.
# You need to find minimum cost to reach the top of the floor,
# and you can either start from the step with index 0, or the step ... | 1,789 | 707 |
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Test an individual filename with a pattern.
"""
#end_pymotw_header
import fnmatch
import os
pattern = 'fnmatch_*.py'
print('Pattern :', pattern)
print()
files = os.listdir('.')
for name in sorted(files):
print... | 398 | 142 |
import numpy as np
from anchor import compute_iou
import torch
def AP(prediction, gt, iou_threshold):
"""compute average precision of detection, all the coordinate should be
(top left bottom right)
Args:
predict_bboxes (ndarray): should be a N * (4 + 1 + 1) ndarray
N is number of boxe... | 3,767 | 1,198 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-19 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('heroes', '0008_change_places_history_format'),
]
operations = [
migrations.RemoveField(
model_name='hero'... | 541 | 185 |
import random
import pickle
import pathlib
import numpy as np
import pandas as pd
from json import loads
from os.path import exists
from typing import Any, Dict, List, Tuple
from metrics import Category, Feature
def unpickle_file(file: pathlib.Path) -> Any:
abs_path = str(file)
if not abs_path.endswith(".pick... | 4,151 | 1,325 |
"""
Created on Dec 05, 2013
@author: StarlitGhost
"""
import random
from twisted.plugin import IPlugin
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import IModule
from desertbot.modules.commandinterface import BotCommand
from desertbot.response import... | 1,564 | 456 |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... | 9,457 | 2,638 |
import argparse
import sys
import os
import urllib
import requests
import json
import random
commands = []
path = sys.path[0]
dpath = sys.path[0]
autocreate = False
netease_api = {
'music_url': 'http://music.163.com/song/media/outer/url?id=',
'playlist': 'https://api.surmon.me/music/list/',
... | 13,552 | 4,896 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lic... | 4,604 | 1,356 |
from haps import base
@base
class IHeater:
def heat(self) -> None:
raise NotImplementedError
@base
class IPump:
pass
| 137 | 49 |
from __future__ import print_function, absolute_import
import time
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
#from .evaluation_metrics import accuracy
from .utils.meters import AverageMeter
def MIL(element_logits, seq_len, batch_size, labels):
''' elemen... | 6,258 | 2,277 |
import logging
from copy import deepcopy
import os.path as osp
from tqdm import tqdm
import torch
from torch.nn.parallel import DistributedDataParallel
from basicsr.models.video_base_model import VideoBaseModel
from basicsr.utils import imwrite, tensor2img
from basicsr.utils.dist_util import get_dist_info
from basicsr.... | 6,618 | 1,941 |
import struct
from mesh.generic.radio import Radio
from mesh.generic.slipMsg import SLIP_END
from mesh.generic.cmds import FPGACmds
import crcmod.predefined
class FPGARadio(Radio):
def __init__(self, serial, config):
Radio.__init__(self, serial, config)
self.crc16 = crcmod.predefined.mkCr... | 733 | 261 |
# -*- coding:utf-8 -*-
import re, sys
import time, logging
from collections import OrderedDict
from util.MRZ import MRZ, MRZOCRCleaner
from util.ctc2hanzi import ctc_code
from util.name2pinyin import ChineseName
from util.CHN_ID_Verify import CHNIdNumber
from util.log import logging_elapsed_time
class doc_etl(object)... | 28,100 | 9,002 |
import ConsecutivePieces as Cp
import math
import copy
def mid_control_streaks(board, turn):
"""
Uses the 'calculate_streaks' method to work out the heuristic values. Then the heuristic values of the pieces that
are in the middle 5x5 area of the board is doubled. This will bump up the final score as well.... | 4,238 | 1,299 |
#! /usr/bin/env python
# -*- coding:UTF-8
# 基于SocketServer的服务器
import socket
import threading
import SocketServer
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
response = "{}:{... | 1,259 | 426 |
from mpi4py import MPI
import common
def main():
comm = MPI.COMM_WORLD
print_mpi = common.create_print_mpi(comm)
print_mpi('Hello World!')
if comm.rank == 0 or comm.rank == 1:
intracomm = comm.Split(color=0, key=comm.rank)
else:
intracomm = comm.Split(color=1, key=comm.rank)
... | 1,237 | 446 |
''' This script reverse engineers the protocols defined in pilight.
It converts them to voloptuous schemes to allow protocol validation
before sending data to the pilight daemon.
'git' python package has to be installed.
TODO: use regex for numbers
'''
import re
import glob
import voluptuous as vo... | 3,151 | 905 |
from .nnf import NNFTransformation, to_negation_normal_form
from .cnf import CNFTransformation, to_conjunctive_normal_form
from .prenex import PrenexTransformation, to_prenex_negation_normal_form
from .quantifier_elimination import QuantifierElimination, QuantifierEliminationMode, remove_quantifiers
from .neg_builtin ... | 352 | 112 |
del_items(0x80137C50)
SetType(0x80137C50, "struct THEME_LOC themeLoc[50]")
del_items(0x80138398)
SetType(0x80138398, "int OldBlock[4]")
del_items(0x801383A8)
SetType(0x801383A8, "unsigned char L5dungeon[80][80]")
del_items(0x80138038)
SetType(0x80138038, "struct ShadowStruct SPATS[37]")
del_items(0x8013813C)
SetType(0x... | 10,665 | 6,518 |
"""
682. Baseball Game
Easy
You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith o... | 6,255 | 2,064 |
from typing import Any, Callable, Dict, List
from openslides.utils.cache_providers import Cachable, MemoryCacheProvider
def restrict_elements(elements: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Adds the prefix 'restricted_' to all values except id.
"""
out = []
for element in elements:
... | 2,823 | 909 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ESOPSynthesis.ui'
#
# Created: Wed May 11 17:29:16 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except A... | 4,780 | 1,668 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
import sys
import torch
import numpy as np
import scipy.misc as m
import matplotlib.pyplot as plt
import matplotlib.image as imgs
from PIL import Image
import random
import scipy.io as io
from tqdm import tqdm
from scipy import stats
... | 6,970 | 2,735 |
import tensorflow as tf
import random as rand
import numpy as np
import pickle
import random
import argparse
import pprint
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib.animation import Fu... | 14,857 | 5,489 |
import os
import unittest
import torch
import torch.distributed as c10d
import bagua.torch_api as bagua
from tests.internal.common_utils import find_free_port
from tests.internal.multi_process import MultiProcessTestCase, setup_bagua_env
from tests import skip_if_cuda_not_available
class Result(object):
def __i... | 4,175 | 1,555 |
"""
This module generates predictions using a pre-trained ensemble neural network for unlabeled SVM regression test data and alignment images. The ensemble model is a combination of two neural networks: a MultiLayerPerceptron (for regression test data) and a 3D Image Convolutional Neural Network (CNN). The script inclu... | 9,292 | 2,967 |
class Kassapaate:
def __init__(self):
self.kassassa_rahaa = 100000
self.edulliset = 0
self.maukkaat = 0
def syo_edullisesti_kateisella(self, maksu):
if maksu >= 240:
self.kassassa_rahaa = self.kassassa_rahaa + 240
self.edulliset += 1
return ma... | 1,209 | 466 |
import os
import time
import urllib
import logging
import mimetypes
from hashlib import sha1
from random import choice
from wsgiref.util import FileWrapper
from django.conf import settings
from django.core.files import File
from django.http import HttpResponse, StreamingHttpResponse
from django.utils.tim... | 4,135 | 1,346 |
import socket
sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
print(conn)
while True:
data = conn.recv(1024)
data = str(data.decode())
print(data)
if not data=='pifagor':
conn.send('Такой задачи нет'.encode())
break
else:
conn.send('вве... | 672 | 255 |
from expects import expect
from icdiff_expects import equal
from unittest import mock
import striemann.metrics
import json
class Test:
def test_gauges(self):
transport = striemann.metrics.InMemoryTransport()
metrics = striemann.metrics.Metrics(transport, source="test")
metrics.recordGauge(... | 12,025 | 3,314 |
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from ipywidgets import Layout
import starry
from ylm_rot import get_ylm_coeffs
import matplotlib.pyplot as pl
import numpy as np
vslider = \
widgets.FloatSlider(
value=0.1,
min=0.1,
max=10.0,
step=0.01,
... | 5,128 | 2,202 |
"""Tests for mousebender.simple."""
import warnings
import importlib_resources
import packaging.version
import pytest
from mousebender import simple
from .data import simple as simple_data
class TestProjectURLConstruction:
"""Tests for mousebender.simple.create_project_url()."""
@pytest.mark.parametrize(... | 14,101 | 5,409 |
from django import forms
from django.utils.translation import gettext_lazy as _
from django.db.models import F
from dal import autocomplete
from danceschool.core.models import Customer
class CustomerGuestAutocompleteForm(forms.Form):
'''
This form can be used to search for customers and names on the guest
... | 1,743 | 439 |
from .base import APP
from utils.config import apps
if 'pixiv' in apps:
from .pixiv import pixiv_router
APP.include_router(pixiv_router)
if 'shorturl' in apps:
from .shorturl import shorturl_router
APP.include_router(shorturl_router)
| 252 | 89 |
from scipy.integrate import solve_ivp
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from hyperopt import hp, fmin, tpe
from typing import Tuple
def SIR(t, y, N, kappa, tau, nu):
"""
Expresses SIR model in initial value ODE format, including time,
... | 3,093 | 1,068 |
#!/usr/bin/env python
"""
Example Script to show LCM serialized data transported
on by very simple ZeroMQ pub/sub message server/client
"""
import zmq
from example_lcm import image_t
import time
#
# Set up a simple ZMQ publisher
# - socket type is zmq.PUB, meaning fire and forget publisher
# - socket connection... | 854 | 315 |
import logging
import time
import pandas as pd
from pandas.errors import EmptyDataError
import sqlalchemy
from typing import Union, List
class DataFrameToDatabase:
def __init__(self, df:Union[pd.DataFrame, pd.io.parsers.TextFileReader],
dbTableName:str,
driver:str,
... | 6,799 | 1,688 |
"""The analysis server. Process raw image to PDF."""
import typing as tp
import databroker
from bluesky.callbacks.zmq import Publisher
from databroker.v2 import Broker
from event_model import RunRouter
from ophyd.sim import NumpySeqHandler
from pdfstream.callbacks.analysis import AnalysisConfig, VisConfig, ExportConf... | 5,508 | 1,604 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Title '''
__author__ = 'Hiroshi Kajino <KAJINO@jp.ibm.com>'
__copyright__ = 'Copyright IBM Corp. 2020, 2021'
from copy import deepcopy
import unittest
import torch
from diffsnn.pp.snn import FullyObsSigmoidSNN
from .base import (TestBase,
GenFullyOb... | 2,965 | 1,000 |
import json
filename = 'tmp/favorite-number.json'
with open(filename) as f_obj:
favorite = json.load(f_obj)
print('I know your favorite number! It\'s ' + str(favorite) + '.')
| 184 | 70 |
import unittest
from app.models import News
class MewsTest(unittest.TestCase):
"""
Test Class to test the behaviour of the News class
"""
def setUp(self):
"""
Set up method that will run before every Test
"""
self.new_news = News(1234,'bbc','www.you.com','business')
... | 406 | 125 |
# Copyright (C) 2021 Nippon Telegraph and Telephone Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICE... | 12,940 | 3,680 |
"""Module for fetching code coverage info from Codecov."""
from agithub import base as agithub_base
from flask_api import status
import logging
from typing import Any, Dict, Optional, Text
import env
class CodecovApiError(Exception):
"""Errors encountered while querying the Codecov API."""
def __init__(self, s... | 2,059 | 637 |
# Calibrates camera using chessboard video
import numpy as np
import cv2
import glob
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgr... | 2,564 | 1,159 |
'''This module provides a class for VANs calls to the CC API'''
from currencycloud.http import Http
from currencycloud.resources import PaginatedCollection, Van
import deprecation
class Vans(Http):
'''This class provides an interface to the VANs endpoints of the CC API'''
def find(self, **kwargs):
'... | 1,788 | 502 |
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 5,703 | 1,695 |
import json
from collections import defaultdict
import random
def transform_to_json(data):
a_json = {}
cluster_id=1
for pid, separate_ids in data.items():
for spid in separate_ids:
a_json[spid]=cluster_id
cluster_id+=1
return a_json
def create_keys_per_name(data):
"""
... | 4,799 | 1,427 |
import logging
import importlib
import asyncio
import aiohttp
logger = logging.getLogger('hypotonic')
class Hypotonic:
def __init__(self, url=None):
self.commands = []
self.results = []
self.errors = []
if url:
self.commands.append(('get', (url,), {}))
async def worker(self, i, session, ... | 2,151 | 670 |
class Alumno:
def declarar(self,nombre,dato):
self.nombre=nombre
self.puntuacion=dato
def visualizar(self):
print("Nombre:",self.nombre)
print("Puntuacion:",self.puntuacion)
def estadistica(self):
if self.puntuacion<=4:
print("insuficiente")... | 714 | 276 |
from bert_serving.client import BertClient
import pandas as pd
import numpy as np
import json
import sagas.tracker_fn as tc
from sagas.conf.conf import cf
def search_in(text, lang):
with open(f'{cf.conf_dir}/stack/crawlers/langcrs/all_{lang}.json') as json_file:
sents=json.load(json_file)
return [s... | 5,487 | 1,848 |
import unittest
import numpy as np
from bsm_stream_vector import LinkIdentifier
"""Test LinkIndentifier class in bsm_stream_vector to ensure the BSMs are being assigned to the correct Measures Estimation link
"""
class LinkIdentifierTest(unittest.TestCase):
#This test only works if findLink in LinkIndentifier retur... | 882 | 323 |
import sys, os
import tensorflow as tf
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from graphnn_free import GraphNN
from mlp import Mlp
def build_network(d):
# Define hyperparameters
d = d
learning_rate = 2e-5
l2norm_scaling = 1e-10
global_norm_gradient_clipping_ratio = 0.65
# Defin... | 8,350 | 2,921 |
"""Tests to verify the async=True functionality of operations
"""
import pytest
from ixnetwork_restpy import TestPlatform, BadRequestError
def test_async_operation(ixnetwork):
# uncomment the following to see the full request and response
# from ixnetwork_restpy import TestPlatform
# ixnetwork.parent.pare... | 1,593 | 464 |
#!/usr/bin/env python
# coding: utf-8
# Created on: 24.02.2016
# Author: Roman Miroshnychenko aka Roman V.M. (romanvm@yandex.ua)
from __future__ import print_function
import os
from subprocess import call
gh_token = os.environ['GH_TOKEN']
repo_slug= os.environ['TRAVIS_REPO_SLUG']
gh_repo_url = 'https://{gh_token}@git... | 1,452 | 522 |
import warnings
warnings.filterwarnings('ignore')
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow.python.util.deprecation as deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
import json
import argparse
import multiprocessing
import random
import shutil
import time
import tempfile
from... | 12,861 | 4,498 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : run_eval.py
# Author : Mohamed Alzayat <alzayat@mpi-sws.org>
# Date : 21.10.2020
# Last Modified Date: 21.10.2020
# Last Modified By : Mohamed Alzayat <alzayat@mpi-sws.org>
import argparse
from bcns import sim
from evaluation... | 16,611 | 5,597 |
#D:\Python\Python35\python.exe
# -*- coding:utf-8 -*-
'淘宝商品价格定向爬虫'
import requests,csv,re,os,time
i=1 #全局计数变量
def getHTMLtext(url):
try:
r=requests.get(url)
r.encoding=r.apparent_encoding
return r.text
except:
print('获取页面异常')
def parsePage(ilt,html):
# info=re.findall(r'... | 1,618 | 704 |
from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response, render, get_object_or_404, redirect
from django.views.decorators.cache import cache_page
from django.views.generic.list import ListView
from django.contrib import messages
from replica import se... | 2,359 | 684 |
# -*- coding: utf-8 -*-
import discord
from discord.ext import commands
class Commands:
def __init__(self, bot):
self.bot = bot
# you can use events here too
async def on_message(self, msg):
print(msg.content)
# or commands like this
@commands.command()
async d... | 1,844 | 676 |
from django.apps import AppConfig
class NgappConfig(AppConfig):
name = 'ngapp'
| 85 | 28 |