text string | size int64 | token_count int64 |
|---|---|---|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
from database import db
class User(object):
def __init__(self, name, avatar, email, password):
self.name = name
self.email = email
self.password = password
sel... | 686 | 187 |
from pyformlang.regular_expression import Regex
from pyformlang.regular_expression.regex_objects import Symbol
from project.interpreter_gql.memory import MemBox
from project.interpreter_gql.interpreter_utils.type_utils import get_target_type
from project.interpreter_gql.interpreter_utils.interpreter_except import Inter... | 4,807 | 1,679 |
from __future__ import annotations
from argparse import ArgumentParser
from collections import deque
import numpy as np
def count_lte(mat: np.ndarray) -> np.ndarray:
"""
lte[i,j] = count (neighbours <= mat[i,j])
. t .
l . r
. b .
"""
aug = np.pad(mat.astype(float), (1, 1), mode="constant... | 2,757 | 1,099 |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import tensorflow as tf
from tensorflow.python.ops import math_ops
import logging
from . import imagenet_processing
from custom_exceptions import UnsupportedFormat, DimensionError
class DataTransformer:
logger = logging.getLogger('data_transformer')
... | 5,997 | 1,902 |
from django.urls import path
from social import apis
urlpatterns=[
path('recommend',apis.recommend),
path('like',apis.like),
path('dislike',apis.dislike),
path('superlike',apis.superlike),
path('rewind',apis.rewind),
path('like-me',apis.like_me),
] | 273 | 95 |
#MIT License
#
#Copyright (c) 2019 TheHWcave
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish,... | 3,657 | 1,409 |
import os.path
import subprocess
import sys
import json
import yaml
import shlex
def test_spec():
executable = sys.argv[1]
specs_file = sys.argv[2]
if specs_file.endswith('.json'):
with open(specs_file) as f:
try:
specs = json.load(f)
except json.decoder.JSON... | 3,224 | 955 |
import numpy as np
import tensorflow as tf
def split_reim(array):
"""Split a complex valued matrix into its real and imaginary parts.
Args:
array(complex): An array of shape (batch_size, N, N) or (batch_size, N, N, 1)
Returns:
split_array(float): An array of shape (batch_size, N, N, 2) conta... | 4,874 | 1,600 |
#!/usr/bin/env python
'''
modify camera parameters using v4l
'''
import os
# change /dev/video6 resolution
#os.system('v4l2-ctl -d /dev/video6 -v width=640,height=480')
os.system('v4l2-ctl -d /dev/video6 -v width=160,height=120')
| 233 | 102 |
# /bin/env python
# coding: utf-8
from __future__ import print_function
import sys
import argparse
import logging
import os
import math
import cv2
import numpy as np
class GenerateSyntheticData:
import PythonMagick as Magick
def __init__(self, logger=None):
if logger == None:
logging.b... | 24,611 | 8,179 |
from service_objects import services
import numpy as np
import pandas as pd
from django.db import connection
import datetime
from front.models import Match, Match_Stats, Player, Tourney, Tourney_Level, Surface
class IngestMatchesService(services.Service):
def process(self):
cursor = connection.cursor()
... | 10,065 | 2,931 |
# Copyright 2019, Luke Macken, Kim Bui, and the binance-chain-python contributors
# SPDX-License-Identifier: MIT
"""
Binance DEX WebSocket Test Suite
"""
import asyncio
import pytest
from binancechain import HTTPClient, WebSocket
def on_error(msg):
print(f'Error: {msg}')
@pytest.fixture
async def client():
... | 5,583 | 1,864 |
import os
from collections import defaultdict
import yaml
from libtaxii.constants import ST_TYPES_10, ST_TYPES_11
current_dir = os.path.dirname(os.path.realpath(__file__))
ENV_VAR_PREFIX = 'OPENTAXII_'
CONFIG_ENV_VAR = 'OPENTAXII_CONFIG'
DEFAULT_CONFIG_NAME = 'defaults.yml'
DEFAULT_CONFIG = os.path.join(current_dir... | 2,590 | 757 |
def tree_16b(features):
if features[12] <= 0.0026689696301218646:
if features[2] <= 0.00825153129312639:
if features[19] <= 0.005966400067336508:
if features[19] <= 0.0029812112336458085:
if features[17] <= 0.001915214421615019:
return 0
else: # if features[17] > 0.0... | 56,108 | 29,559 |
class Employee:
def __init__(self, name, emp_id, email_id):
self.__name=name
self.__emp_id=emp_id
self.__email_id=email_id
def get_name(self):
return self.__name
def get_emp_id(self):
return self.__emp_id
def get_email_id(self):
return self.__email_id
... | 1,193 | 418 |
import subprocess
import secrets
import getpass
import os
import requests
import urllib.parse
import time
from google.colab import files, drive, auth
from google.cloud import storage
import glob
def connect(LOG_DIR = '/log/fit'):
print('It may take a few seconds for processing. Please wait.')
root_password = s... | 11,290 | 3,949 |
# -*- coding: utf-8 -*-
import pymysql
import json
def countNum(table):
# 打开数据库连接
db = pymysql.connect("cd-cdb-6sbfm2hw.sql.tencentcdb.com", "root", "Mrsnow@0", "spider")
# 使用cursor()方法创建一个可以执行SQL语句的游标对象cursor
cursor = db.cursor()
sql = "SELECT COUNT(*) FROM" + table + "WHERE text like '%川大%'"
... | 763 | 391 |
import pytest
import sys
import ray
from ray._private.test_utils import wait_for_condition
def test_list_named_actors_basic(ray_start_regular):
@ray.remote
class A:
pass
a = A.remote()
assert not ray.util.list_named_actors()
a = A.options(name="hi").remote()
assert len(ray.util.list... | 1,683 | 626 |
class tablecloumninfo:
col_name=""
data_type=""
comment=""
def __init__(self,col_name,data_type,comment):
self.col_name=col_name
self.data_type=data_type
self.comment=comment
| 218 | 74 |
"""Main/example start-up script for the pyjobserver
Use this as a guide if importing pyjobserver into another app instead
"""
# Built-Ins:
import asyncio
from logging import getLogger, Logger
import os
from pathlib import Path
# External Dependencies:
from aiohttp import web
import click
from dotenv import load_dote... | 2,620 | 755 |
class GraphLearner:
"""Base class for causal discovery methods.
Subclasses implement different discovery methods. All discovery methods are in the package "dowhy.causal_discoverers"
"""
def __init__(self, data, library_class, *args, **kwargs):
self._data = data
self._labels = list(self._data.columns)
self... | 492 | 168 |
""" Provide function to load a wasm module into the current process.
Note that for this to work, we require compiled wasm code and a runtime.
The wasm runtime contains the following:
- Implement function like sqrt, floor, bit rotations etc..
"""
import os
import abc
import shelve
import io
import struct
import logg... | 16,227 | 4,674 |
# coding:utf-8
import datetime
import json
import random
import requests
def get_stock_type(stock_code):
"""判断股票ID对应的证券市场
匹配规则
['50', '51', '60', '90', '110'] 为 sh
['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz
:param stock_code:股票ID, 若以 'sz... | 2,823 | 1,282 |
import numpy as np
import cv2
import os
from matplotlib import pyplot as plt
#### INPUT ####
# folder that contains datapoints
folderName = '2dIR'
#### SETTINGS ####
# settings listed below are suitable for 2D data
# intensity of noise filtering; higher values mean more blurring
medianKernel = 5
# bl... | 13,370 | 4,612 |
"""
aiida_crystal_dft
AiiDA plugin for running the CRYSTAL code
"""
__version__ = "0.8"
| 90 | 41 |
from rest_framework import serializers
| 42 | 12 |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import pytest
from pants.backend.terraform import target_gen
from pants.backend.terraform.target_types import (
TerraformModulesGeneratorTarget,
... | 2,938 | 880 |
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import matplotlib.pyplot as plt
plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')
class MyApp(App):
def build(self):
box = BoxLayout()
box.add_widget(FigureCan... | 377 | 144 |
import os
import random
from tqdm import tqdm
from collections import defaultdict
from data_genie.data_genie_config import *
from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj
from data_genie.data_genie_utils import count_performance_retained, get_best_results
from... | 5,240 | 2,178 |
import numpy as np
from matplotlib import pyplot as plt
from env import DrivingEnv
from solvers import GridSolver, SampleGraphSolver
def time_compare(seed=1234, min_sample=10, max_sample=50, count=10):
sample_count = np.linspace(min_sample, max_sample, count).astype(int)
grid_times = []
graph_times = []
... | 3,934 | 1,421 |
"""
Imported calendars from the exchange_calendars project
GitHub: https://github.com/gerrymanoim/exchange_calendars
"""
from datetime import time
from .market_calendar import MarketCalendar
import exchange_calendars
class TradingCalendar(MarketCalendar):
def __init__(self, open_time=None, close_time=None):
... | 1,912 | 618 |
from .enum import EnumBase
def is_builtin_type(obj) -> bool:
"""
检查 obj 是否基础类型
"""
return isinstance(obj, (int, str, float, bool)) or obj is None
| 164 | 68 |
import cherrypy, cherrypy_cors, os
import tca_ng.example_maps
import tca_ng.models
import random
class TCAServer(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def start(self):
self.automaton = tca_ng.models.Automaton()
self.automaton.topology = tca_ng.example_maps.simple_map(10... | 1,647 | 542 |
from rest_framework import viewsets
from api.serializers import LabelSerializer, ItemSerializer
from api.models import Label, Item
class LabelViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows labels to be viewed or edited.
"""
queryset = Label.objects.all().order_by('name')
serializer_... | 553 | 151 |
import string
import random
class User:
def __init__(self,username,password):
self.username = username
self.password = password
userList = []
def addUser(self):
'''
method saves a new user object to credentials list
'''
User.userList.append(self)
def ... | 802 | 221 |
from typing import List
def public_gcr_images(project: str) -> List[str]:
# the worker cannot import batch_configuration because it does not have all the environment
# variables
return [f'gcr.io/{project}/{name}' for name in ('query', 'hail', 'python-dill', 'batch-worker')]
| 289 | 86 |
from django.conf import settings
from django.forms.utils import flatatt
from django_cradmin import renderable
class NotBootsrappedError(Exception):
"""
Raised when trying to use features of
:class:`.AbstractContainerRenderable`
that requires is to have been bootstrapped.
"""
class AlreadyBootsra... | 24,972 | 6,877 |
class attributes_de:
def __init__(self,threshold_list,range_for_r):
self.country_name = 'Germany'
self.population = 83190556
self.url = 'https://opendata.arcgis.com/datasets/dd4580c810204019a7b8eb3e0b329dd6_0.geojson'
self.contains_tests=False
self.csv=False # if the resource... | 5,982 | 2,056 |
# Generated by Django 3.2.5 on 2021-11-09 18:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0008_auto_20211108_1633'),
]
operations = [
migrations.AlterField(
model_name='protection',
name='descri... | 408 | 148 |
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
elif sys.platform == "win64":
base = "Win64GUI"
excludes = ['PyQt5', 'colorama', 'pandas', 'sqlalchemy', 'numpy', 'notebook', 'Django', 'schedule']
packages = ["idna", "_cffi_backend", "bcrypt", "rsa"... | 899 | 316 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('cms', '0013_auto_20151121_1602'),
]
operations = [
migrations.AddField(
model_name=... | 2,200 | 641 |
'''
Tree-Matching implementation
Based on BURS (Bottom-Up Rewrite System)
Similar to tree-match-burs1 project
Inspired from:
- Instruction Selection via Tree-Pattern Matching - Enginner a Compiler p610
- An Improvement to Bottom-up Tree Pattern Matching - David R. Chase
- Simple and Efficient BURS Table Generation - T... | 5,674 | 1,807 |
import numpy as np
import math
from scipy.stats import truncnorm
class ElectricMotor:
"""
Base class for all technical electrical motor models.
A motor consists of the ode-state. These are the dynamic quantities of its ODE.
For example:
ODE-State of a DC-shunt motor... | 95,650 | 29,227 |
from pyrem.task import Task, TaskStatus
class DummyTask(Task):
def _start(self):
pass
def _wait(self):
pass
def _stop(self):
pass
class TestDummyTask(object):
@classmethod
def setup_class(klass):
"""This method is run once for each class before any tests are run"... | 1,004 | 302 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Resolve the Keyword referenced in the Document."""
import jsonresolver
from werkzeug.routing import Rule
from... | 1,302 | 391 |
"""Planning (Chapters 11-12)
"""
from __future__ import generators
| 68 | 29 |
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# At... | 15,025 | 3,946 |
"""
Oracle implementation of GetLocationFile
"""
from WMCore.WMBS.MySQL.Files.GetLocation import GetLocation \
as GetLocationFileMySQL
class GetLocation(GetLocationFileMySQL):
"""
_GetLocation_
Oracle specific: file is reserved word
"""
pass
| 270 | 80 |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Voting system core service
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 1.1.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance ... | 5,471 | 1,464 |
# Copyright (C) 2018 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... | 4,665 | 1,315 |
import socket
from ast import literal_eval
import Yetiborg.Drive as Yetiborg
HEADERSIZE = 2
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 12345)) # 192.168.0.11 / localhost / 192.168.0.108
# car always looks up at the beginning
car = Yetiborg.Yetiborg((0, 1))
"""
fs: finished
"... | 1,046 | 395 |
# Copyright 2020 Aaron Barany
#
# 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 law or agreed to in writing,... | 9,785 | 3,856 |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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 require... | 8,500 | 2,898 |
'''
Venn diagram plotting routines.
Two-circle venn plotter.
Copyright 2012, Konstantin Tretyakov.
http://kt.era.ee/
Licensed under MIT license.
'''
# Make sure we don't try to do GUI stuff when running tests
import sys, os
if 'py.test' in os.path.basename(sys.argv[0]): # (XXX: Ugly hack)
import matplotlib
ma... | 10,769 | 4,006 |
import pdfkit
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
pdfkit.from_url('http://google.com', '/tmp/out.pdf')
with open('/tmp/out.pdf', 'rb') as f:
response = s3.put_object(
Bucket='temp-awseabsgddev',
Key='juni/google.pdf',
Body=f.re... | 370 | 132 |
import pytest
import torch
from packaging.version import parse as V
from torch_complex import ComplexTensor
from espnet2.enh.layers.complex_utils import is_complex
from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator
is_torch_1_9_plus = V(torch.__version__) >= V("1.9.0")
@pytest.mark.parametrize("inpu... | 4,997 | 2,050 |
version = "1.1.5rc1"
__version__ = version
project_name = "datarobot-drum"
| 75 | 33 |
from django.conf.urls import url
from usaspending_api.download.v2 import views
urlpatterns = [
url(r'^awards', views.RowLimitedAwardDownloadViewSet.as_view()),
url(r'^accounts', views.AccountDownloadViewSet.as_view()),
# url(r'^columns', views.DownloadColumnsViewSet.as_view()),
url(r'^status', views.... | 661 | 218 |
"""
Common bazel version requirements for tests
"""
CURRENT_BAZEL_VERSION = "5.0.0"
OTHER_BAZEL_VERSIONS = [
"4.2.2",
]
SUPPORTED_BAZEL_VERSIONS = [
CURRENT_BAZEL_VERSION,
] + OTHER_BAZEL_VERSIONS
| 208 | 96 |
# See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='dansbecker',
course_name='Machine Learning',
course_url='https://www.kaggle.com/learn/intro-to-machine-learning'
)
lessons = [
dict(
topic='Your First BiqQuery ML Model',
... | 600 | 208 |
# ---------------------------------------------------------------------
# Initialize SubInterface.managed_object
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# -----------------------------------------------------------------... | 859 | 236 |
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
# Since all the three parts are equal, if we sum all element of arrary it should be a multiplication of 3
# so the sum of each part must be equal to sum of all element divided by 3
quotient, remainder = divmod(sum(A), 3)
... | 651 | 174 |
# ===============================================================================
# Copyright 2019 Jan Hendrickx and Gabriel Parrish
#
# 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:/... | 14,224 | 5,746 |
import os
import sys
sys.path.append('.')
import argparse
import numpy as np
import os.path as osp
from multiprocessing import Process, Pool
from glob import glob
from tqdm import tqdm
import tensorflow as tf
from PIL import Image
from lib.core.config import INSTA_DIR, INSTA_IMG_DIR
def process_single_record(fname,... | 2,076 | 724 |
# Generated by Django 3.1.5 on 2021-03-22 17:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movies', '0010_actors_moved'),
('person', '0003_refactoring_movie_person_m2m_rels'),
]
operations = [
migrations.AddField(
... | 672 | 223 |
import os
import pytest
from edalize_common import make_edalize_test
def run_oxide_test(tf):
tf.backend.configure()
tf.compare_files(
["Makefile", "edalize_yosys_procs.tcl", "edalize_yosys_template.tcl"]
)
tf.backend.build()
tf.compare_files(["yosys.cmd", "nextpnr-nexus.cmd", "prjoxide.c... | 1,653 | 653 |
# time.py
import gc
import os
import sys
from arm_ds.debugger_v1 import Debugger
from arm_ds.debugger_v1 import DebugException
import config
import memory
import mmu
# obtain current execution state
debugger = Debugger()
execution_state = debugger.getCurrentExecutionContext()
def cleanup():
if... | 4,265 | 1,894 |
from pathlib import Path
import sys
path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)
from mnist_utils.util import _x, _y_int
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import accuracy_score, adjusted_rand_score
import numpy as np
from fast_pytorch_kmean... | 3,134 | 1,141 |
import os
import json
import random
random.seed(32767)
import shutil
import numpy as np
np.random.seed(32767)
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
from torch.optim import Adam, SGD, lr_scheduler
import torch.backends.cudnn as cudnn
from tensorboardX import Su... | 6,224 | 1,950 |
STATE_CITY = "fluids_state_city"
OBS_QLIDAR = "fluids_obs_qlidar"
OBS_GRID = "fluids_obs_grid"
OBS_BIRDSEYE = "fluids_obs_birdseye"
OBS_NONE = "fluids_obs_none"
BACKGROUND_CSP = "fluids_background_csp"
BACKGROUND_NULL = "fluids_background_null"
REWARD_PATH = "fluids_reward_path"
REWARD_NONE = "fluids_rew... | 462 | 248 |
from .app import app
application = app.server
| 47 | 14 |
class Solution:
def generate(self, num_rows):
if num_rows == 0:
return []
ans = [1]
result = [ans]
for _ in range(num_rows - 1):
ans = [1] + [ans[i] + ans[i + 1] for i in range(len(ans[:-1]))] + [1]
result.append(ans)
return result
| 312 | 108 |
"""
Constants and constant generators
"""
import os
INPUTS_FOLDER_NAME = "inputData"
def getInputsFolder():
"""
:return str: the absolute path on the file system to the inputData folder, which should be relative to this package
"""
# figure out where we are
utilsFolder = os.path.dirname(os.path... | 472 | 152 |
################################################################################
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your op... | 4,738 | 1,942 |
"""
MIT License
Copyright (c) 2020-2021 ilovetocode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publi... | 11,683 | 3,301 |
import graphene
import os
from promise import Promise
from datetime import datetime
from promise.dataloader import DataLoader
import requests
from core.graphql.types import CountryType
from core.models import Country
class Natura2000FeatureType(graphene.ObjectType):
id = graphene.String()
site_code = graphene... | 3,011 | 815 |
#! /usr/bin/env python
""" Simple test script for cmathmodule.c
Roger E. Masse
"""
import cmath
import unittest
from test import test_support
from test.test_support import verbose
p = cmath.pi
e = cmath.e
if verbose:
print 'PI = ', abs(p)
print 'E = ', abs(e)
class CmathTestCase(unittest.TestCase):
d... | 3,548 | 1,322 |
from _satoshitx import *
import struct
#https://bitcoincore.org/en/segwit_wallet_dev/
class SWitnessTransaction(STransaction):
def __init__(version,flag,ins,outs,witness,locktime):
super(SWitnessTransaction,self).__init__(version,ins,outs,locktime)
self.flag=flag
self.witness=witness
def serialize(self):
tx... | 6,633 | 2,800 |
from __future__ import print_function
import datetime
from awsme.metric import Metric
from awsme.buffered_recorder import BufferedRecorder
from typing import List, Dict, Any # noqa
class StdoutRecorder:
def put_metric_data(self, metric_data: List[Dict[str, Any]]) -> None:
print(metric_data)
recorder =... | 506 | 162 |
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from... | 11,309 | 3,074 |
for testcase in range(int(input())):
n = int(input())
dict = {}
comb = 1
m = (10**9)+7
for x in input().split():
no = int(x)
try:
dict[no] = dict[no] + 1
except:
dict[no] = 1
dict = list(dict.items())
dict.sort(key=lambda x: x[0], reverse=Tru... | 729 | 267 |
from tarfile import open as tarfile_open
from pandas import read_csv
def read_correlate_copynumber_vs_mrnaseq(tar_gz_file_path, genes):
with tarfile_open(tar_gz_file_path) as tar_gz_file:
n = read_csv(
tar_gz_file.extractfile(
tuple(file for file in tar_gz_file if file.name.... | 709 | 242 |
#module import
import urllib.request
from bs4 import BeautifulSoup
from datetime import datetime
def get_ships(imo_list):
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,applica... | 2,525 | 826 |
#!/usr/bin/env python3
# Copyright (c) 2020 Jeffrey A. Webb
import sys
f = open(sys.argv[1])
for line in f:
s = line.strip()
if s.startswith("source:"):
id = s.split(":")[-1].strip()
indent = ' '*line.index("source")
sys.stdout.write(f"{indent}source:\n")
sys.stdout.write(f"{i... | 715 | 272 |
#!/usr/bin/env python3
# coding: utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec
import datetime, time
from scipy.signal import savgol_filter
from scipy.interpolate import interp1d, Akima1DInterpolator, PchipInterpolator
from sys import platform
import warn... | 10,093 | 4,368 |
#!/usr/bin/env python3
import sys
if sys.version_info >= (3, 3):
import importlib
def import_file(module_path='', module=''):
importlib.invalidate_caches()
if module in sys.modules:
del sys.modules[module]
sys.path.insert(0, module_path)
loader = importlib.find_lo... | 1,067 | 345 |
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from cadastro.models import tipocacamba
from solicitacao.models import ordemServico
from .forms import pedidosForm,opcoesForm,textoForm,statusForm
import time
from django.utils import timezone
from datetime i... | 3,411 | 1,132 |
import math
import types
import numpy as np
import scipy as sp
import scipy.linalg
import torch
import torch.nn as nn
import torch.nn.functional as F
# The following code is adapted from the following repository
# https://github.com/ikostrikov/pytorch-flows/blob/master/flows.py
def get_mask(in_features, out_feature... | 8,879 | 2,857 |
import uuid
from PIL import Image
import graphviz as gv
styles = {
'graph': {
'label': 'Discreta - Representación de AST',
'fontsize': '16',
'fontcolor': 'white',
'bgcolor': '#333333',
},
'nodes': {
'fontname': 'Helvetica',
'shape': 'hexagon',
'font... | 1,477 | 509 |
import os
from pathlib import Path
from flask import Flask, current_app, jsonify, request
from flask_cors import CORS
from mongoengine import connect, MongoEngineConnectionError
import namesgenerator
from model import Doc
from app_logic import random_df, call_r
def create_app(config=None):
app = Flask(__name__)
... | 1,557 | 508 |
class Timer:
def __init__(self, duration, ticks):
self.duration = duration
self.ticks = ticks
self.thread = None
def start(self):
pass
# start Thread here
| 200 | 58 |
import os
from configurations.importer import install
from mypy.version import __version__ # noqa: F401
from mypy_django_plugin import main
def plugin(version):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development')
install()
ret... | 345 | 113 |
import numpy as np
from JacobiPolynomials import *
import math
# 1D - LINE
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
#---------... | 9,866 | 3,995 |
#Exercises of the Problem 1 (77/91)
#Say "Hello, World!" With Python
print ("Hello, World!")
#Python If-Else
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(raw_input().strip())
if n%2==1:
print("Weird")
else:
if n>2 and n<5 :
... | 24,849 | 10,700 |
import logging
import helpers.hunit_test as hunitest
import oms.order as omorder
import oms.order_example as oordexam
_LOG = logging.getLogger(__name__)
class TestOrder1(hunitest.TestCase):
def test1(self) -> None:
"""
Test building and serializing an Order.
"""
order = oordexam.... | 2,046 | 858 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import calendar
import frappe
from datetime import datetime
from frappe.utils import today
from frappe import _
from frappe.model.document import Docum... | 1,147 | 406 |
#MAIN PROGRAM STARTS HERE:
num = int(input('Enter the number of rows and columns for the square: '))
for x in range(1, num + 1):
for y in range(1, num - 2 + 1):
print ('{} {} '.format(x, y), end='')
print() | 223 | 83 |
import os
import torch
import librosa
import pickle
import soundfile as sf
from synthesis import build_model
from synthesis import wavegen
spect_vc = pickle.load(open('results.pkl', 'rb'))
device = torch.device("cuda")
model = build_model().to(device)
checkpoint = torch.load("checkpoint_step001000000_ema.pth")
model.l... | 628 | 242 |
"""
File: bouncing_ball.py
Name: Jonathan Ma
-------------------------
TODO:
"""
from campy.graphics.gobjects import GOval
from campy.graphics.gwindow import GWindow
from campy.gui.events.timer import pause
from campy.gui.events.mouse import onmouseclicked
VX = 3
DELAY = 10
GRAVITY = 1
SIZE = 20
REDUC... | 2,067 | 747 |
#!/usr/bin/env python
import subprocess
import sys
import os
import signal
serverproc = subprocess.Popen([sys.executable, "TestServer.py"])
try:
ret = subprocess.call([sys.executable, "TestClient.py"])
if ret != 0:
raise Exception("subprocess failed")
finally:
# fixme: should check that server di... | 373 | 122 |