text string | size int64 | token_count int64 |
|---|---|---|
import os
import sys
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
from src.hw2 import csv_reader
def testCsvReader():
expectedResult = [['outlook', 'Temp', '?Humidity', 'windy', 'Wins+', 'Play-'],
['sunny', 85, 85, 'FALSE', 10, 20],
['sunny', 80, 90, ... | 1,192 | 493 |
from telnetlib import Telnet
from threading import Thread
class Hyperdeck:
def __init__(self, ip_address, id) -> None:
self.deck = Telnet(ip_address, 9993)
self.id = id
self.thread = Thread(target=self.listener)
self.thread.start()
def listener(self):
while True:
... | 2,462 | 754 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import threading
import time
import weakref
class RepeatedTimer:
class State:
Stopped=0
Paused=1
Running=2
def __init__(self, secs, callback, count=None):
self.secs = secs
self.callback = weakref.... | 2,215 | 631 |
import time
from pushpy_examples.client.ex_push_manager import ExamplePushManager
m = ExamplePushManager()
m.connect()
class ScheduleTask:
def apply(self, control):
import schedule
import time
def job():
print(f"I'm working...{time.time()}")
schedule.clear()
... | 1,037 | 363 |
'''
https://leetcode.com/contest/weekly-contest-154/problems/maximum-number-of-balloons/
'''
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
m = {}
for c in text:
if c not in m: m[c] = 0
m[c] += 1
ans = len(text)
for c in 'lo':
if ... | 453 | 168 |
# -*- coding: utf-8 -*-
import logging
import pickle
from abc import ABCMeta, abstractmethod
from app import redis
from app.cache import set_dict_if_key_expire, set_data_if_key_expire, set_redis_dict_with_timeout, \
set_redis_data_with_timeout
from task.asyncTask import refresh_cache
class CacheABC(object, meta... | 3,100 | 968 |
import discord
import sqlite3
import random
import requests
import pymorphy2
from itertools import product
# база, в которой будут храниться заработанные очки и статус отношений бота с пользователем - играет оно и во что,
# или просто общается
class Bnc:
def __init__(self):
random.seed(self.ge... | 38,343 | 11,059 |
"""Convert, load or write JSON."""
import json
import logging
import os
import re
import sys
from os import geteuid, path
from subprocess import CalledProcessError, PIPE, Popen, STDOUT, check_call
from iocage.lib.ioc_common import checkoutput, get_nested_key, open_atomic
def _get_pool_and_iocroot():
"""For inter... | 31,698 | 8,804 |
#!usr/bin/env python3
#coding:utf8
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from astropy.io import ascii
from uncertainties import ufloat
import uncertainties.unumpy as unp
from modules.table import textable
import scipy.constants as const
import math as math
from modules.... | 6,913 | 3,351 |
import os
import matplotlib.pyplot as plt
import numpy as np
import cv2
filedir = '/Users/gabrielfior/Dropbox/Hackzurich16/pupils_cutout/'
readbgr = filedir+'left_pupil232.bmp'
frame = plt.imread(readbgr)
white=plt.imread('/Users/gabrielfior/Dropbox/Hackzurich16/pupils_bw/right_pupil61.bmp')
black=plt.imread('/Users/... | 2,256 | 1,076 |
from django.shortcuts import render
from chat.models import *
# Create your views here.
def home(request):
chat = ChatMessage.objects.all()
return render(request,'common/home.html', {'chat':chat})
def video(request):
return render(request,'video.html')
def video3(request):
return render(request,'video3.html')
... | 496 | 158 |
#-------------------------------------------------------------------------------
# Name: GTFS_Arnold_Stops
#
# Purpose: Associate stops with the route shapes that have already been snapped to ARNOLD
#
# Author: Alex Oberg and Gary Baker
#
# Created: 10/17/2016
#
# Last updated 6/15/2017
#---------------------------... | 6,113 | 2,050 |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated Authors.
#
# 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 ... | 14,298 | 4,520 |
import csv
from iterdeciser import models
def data_loader(filename):
with open(filename, newline='') as fd:
reader = csv.reader(fd, delimiter=',', quotechar='"')
# remove all previous entries
models.Answer.objects.all().delete()
models.Question.objects.all().delete()
model... | 893 | 220 |
import torch
from torch import nn
from transformers.modeling_bert import BertIntermediate, BertOutput, BertLayer, BertEncoder, BertModel, BertForSequenceClassification
def get_nonlin_func(nonlin):
if nonlin == "tanh":
return torch.tanh
elif nonlin == "relu":
return torch.relu
elif nonlin =... | 6,146 | 1,878 |
""" This module is used for integration testing. """
# pylint: disable=locally-disabled,unused-import
import venv_exclusive
| 125 | 38 |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from .aspp import ASPP
from .decoders import SegmentHead
from .mobilenet_v2 import MobileNetV2
class DeepLab(nn.Module):
def __init__(self,
args,
backbone='mobilenet',
output_stride=16... | 3,837 | 1,289 |
"""
Generates a image of the top view of a chunk
Needs a textures folder with a block folder inside
"""
import sys
if len(sys.argv) == 1:
print('You must give a region file')
exit()
else:
region = sys.argv[1]
chx = int(sys.argv[2])
chz = int(sys.argv[3])
import os
from PIL import Image
import _path
... | 1,224 | 439 |
"""Celery worker application instantiation."""
import os
from celery import Celery
from django.conf import settings
from django_structlog.celery.steps import DjangoStructLogInitStep
def create_application():
"""Create a Celery application using Django settings."""
os.environ.setdefault(
'DJANGO_SET... | 2,468 | 669 |
file = open("./data.txt" , encoding = 'utf-8')
data = file.readlines()
liste=[]
for string in data:
string=string.replace('ü','ü')
string=string.replace('ÅŸ','ş')
string=string.replace('ÄŸ','ğ')
string=string.replace('ç','ç')
string=string.replace('ı','ı')
string=string.replace('ö','ö')
strin... | 876 | 364 |
import datetime
import os
from avro_models import avro_schema, AvroModelContainer
EXAMPLE_NAMES = AvroModelContainer(default_namespace="example.avro")
DIRNAME = os.path.dirname(os.path.realpath(__file__))
@avro_schema(
EXAMPLE_NAMES,
schema_file=os.path.join(DIRNAME, "Date.avsc"))
class Date(object):
d... | 1,485 | 502 |
import django
import sys
# Compatibility import
from Bcfg2.Bcfg2Py3k import ConfigParser
# Django settings for bcfg2 reports project.
c = ConfigParser.ConfigParser()
if len(c.read(['/etc/bcfg2.conf', '/etc/bcfg2-web.conf'])) == 0:
raise ImportError("Please check that bcfg2.conf or bcfg2-web.conf exists "
... | 5,401 | 1,825 |
from enum import Enum
import arachne.nouns as a
nouns = (
a.Container,
a.Item,
a.Door,
a.Room,
a.Key,
a.Door
)
class Verb(Enum):
# basic player actions
LOOK = 'im rotating it in my mind'
TAKE = 'the act of picking things up'
DROP = 'the act of putting things down'
PUT = '... | 2,851 | 1,140 |
from typing import List
from argo_workflows.models import HostAlias as ArgoHostAlias
from pydantic import BaseModel
class HostAlias(BaseModel):
"""mapping between IP and hostnames
Notes
-----
See https://github.com/argoproj/argo-workflows/blob/master/sdks/python/client/docs/HostAlias.md
"""
... | 488 | 165 |
from slpp import slpp as lua
import json
class LuaConverter:
def parse(self, luafile):
with open(luafile, 'r') as to_convert:
to_convert = str(to_convert.read())
to_convert = to_convert.replace('data:extend(\n{\n {', '').replace('})\n', '') # slpp가 알아먹을수 있는 형태로 가공
to_convert ... | 1,297 | 584 |
#!/usr/bin/env python
#==============================================================================
#author :Miryam de Lhoneux
#email :miryam.de_lhoneux@lingfil.uu.se
#date :2015/12/30
#version :1.0
#description :collect iso codes in UD directories
#usage :python scripts/collect_iso_codes.py
#Python version ... | 839 | 296 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
import socket
import traceback
from airtest import aircv
from airtest.utils.snippet import reg_cleanup, on_method_ready, ready_method
from airtest.core.ios.constant import ROTATION_MODE, DEFAULT_MJPEG_PORT
from airtest.utils.logger import get_logger
from airte... | 5,696 | 1,956 |
import time
import datetime
import os
import sys
import atexit
import signal
from multiprocessing import Pool
from threading import Thread
class HappyScrum:
def __init__(
self,
pid_path,
pool_size=4,
busy_wait=90,
idle_wait=300,
say_hi_wait=1800,
is_debug=Fa... | 3,342 | 1,098 |
from .base import *
class GalleryPageTests(SeleniumTestCase):
def test_gallery_items(self):
browser = self.browser
browser.get('http://127.0.0.1:8000/gallery/')
assert "we don't have any Galleries" not in browser.page_source
def test_gallery_images(self):
browser = self.b... | 526 | 177 |
import cadquery as cq # type: ignore
nd = 0.4 # Nozzle Diameter
length = 50
width = 20
gap = 5
p1 = (
cq.Workplane("XY", origin=(-(width + gap), 0, 0))
.rect(width, length)
.extrude(nd/2)
)
#show_object(p1)
p2 = (
cq.Workplane("XY", origin=(0, 0, 0))
.rect(width, length)
.extrude(nd)
)
#sho... | 784 | 339 |
import unittest
import logging
from tonalmodel.chromatic_scale import ChromaticScale
class TestChromaticScale(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_frequencies(self):
assert is_close(ChromaticScale.get_frequency((4, 9)), 440.0), \
... | 2,430 | 879 |
import numpy as np
import math
import polygon_sampler
nan_rgb = np.zeros((3,)) + np.NaN
# sampler session: texture, W_,H_,W,H
'''
Used by `sample_colors_squarepixels()`
Samples a single point.
Using square pixels.
[0, ... ,W-1] (incl.)
By mapping [0,1) -> [0,W) (int)
(mapping u,v)
'''
def sample1(um,vm, texture, W_... | 3,093 | 1,217 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'workspace_view.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObj... | 5,237 | 1,683 |
"""Custom celery task to capitalize text"""
import task_queuing.celery_app as app
class Capitalize(app.queue_broker.Task):
"""Custom task without the decorator"""
def run(self, text):
capitalized = text.upper()
return capitalized
@app.queue_broker.task(base=Capitalize)
def shit(x):
prin... | 389 | 133 |
"""add topics
Revision ID: d805931e1abd
Revises: 9430b6bc8d1a
Create Date: 2018-09-18 15:11:45.922659
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd805931e1abd'
down_revision = '9430b6bc8d1a'
branch_labels = None
depends_on = None
def upgrade():
# ###... | 654 | 268 |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-03-24
算法思想:下一个排列
"""
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for idx in range(len(nums)-1, ... | 726 | 286 |
from h1st.tuner.hyperparameter_tuner import HyperParameterTuner
| 64 | 23 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 5 00:17:06 2018
@author:
Dr. Maximilian N. Günther
European Space Agency (ESA)
European Space Research and Technology Centre (ESTEC)
Keplerlaan 1, 2201 AZ Noordwijk, The Netherlands
Email: maximilian.guenther@esa.int
GitHub: mnguenther
Twitter: m_n... | 78,296 | 24,254 |
#coding: utf-8
import re
import os
from lxml import etree as ET
from bs4 import BeautifulSoup
import csv
class schSSK:
def create_directory(self, directory):
"""Create a new directory.
:param directory: path to new directory
:type directory: string
"""
if not os.path.exis... | 3,334 | 970 |
import localmodule
import datetime
import h5py
import math
import music21 as m21
import numpy as np
import os
import scipy
import scipy.linalg
import sys
import time
# Parse arguments
args = sys.argv[1:]
composer_str = args[0]
track_str = args[1]
# Define constants.
J_tm = 8
N = 2**10
n_octaves = 8
midi_octave_off... | 14,798 | 5,906 |
import logging
from spaceone.core.manager import BaseManager
from spaceone.core.connector.space_connector import SpaceConnector
_LOGGER = logging.getLogger(__name__)
class PluginManager(BaseManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.plugin_connector: S... | 983 | 275 |
# -*- coding: utf-8 -*-
"""
# @file name : hist_label_portrait.py
# @author : JLChen
# @date : 2020-03-11
# @brief : 统计各类别数量
"""
import numpy as np
import os
import matplotlib.pyplot as plt
import pylab as pl
import cv2
def cal_cls_nums(path, t=0.78):
label_img = cv2.imread(path)
label_img = c... | 1,107 | 488 |
# -*- coding: utf-8 -*-
"""Client context module."""
import pytz
import time
from flask import current_app
from datetime import datetime, timedelta
from mongoengine import DoesNotExist
from .ab_test import get_enrolled_experiments
from .core import cache
from .errors import APIError
from .helpers import assert_vali... | 7,924 | 2,425 |
from configparser import ConfigParser
import json
import fnmatch
import os
__author__ = 'justin@shapeways.com'
TEST_RUN_SETTING_CONFIG = 'TEST_RUN_SETTING_CONFIG'
confg_dict = {}
class NullConfigAttribute(object):
def __init__(self, description, default_value=None):
self.description = description
... | 4,180 | 1,136 |
from enum import Enum
import tensorflow.compat.v1 as tf
from tensorflow.keras.layers import Layer, Conv3D, Conv3DTranspose, AveragePooling3D
from tensorflow_core.python.keras.utils import conv_utils
import tensorflow_compression as tfc
import tensorflow.keras as keras
def relu():
return keras.activations.relu
def... | 16,468 | 5,071 |
"""
Main module for running NetSpeedGraphs.
"""
##### IMPORTS #####
# Standard imports
from pathlib import Path
from datetime import datetime, timedelta
from argparse import ArgumentParser
# Third party imports
import speedtest
import numpy as np
import pandas as pd
from bokeh.plotting import figure, output_file,... | 6,485 | 1,832 |
from typing import Tuple
from ground.base import Relation
from hypothesis import given
from orient.hints import (Multiregion,
Region)
from orient.planar import (contour_in_multiregion,
region_in_multiregion,
region_in_region)
from tests.u... | 7,478 | 2,101 |
#!/usr/bin/env python
#---------------------------------------------------------
# Name: parse_qca.py
# Purpose: Parsing functions for QCADesigner files
# Author: Jacob Retallick
# Created: 2015.10.22
# Last Modified: 2015.10.22
#---------------------------------------------------------
# NOTE
# the origin... | 11,676 | 3,915 |
"""
=================
Linear Regression
=================
In this tutorial, we are going to demonstrate how to use the ``abess`` package to carry out best subset selection
in linear regression with both simulated data and real data.
"""
###############################################################################
#... | 7,391 | 2,390 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tracing module."""
import asyncio
from pathlib import Path
from typing import Any, Awaitable
from pyppeteer.connection import Session
class Tracing(object):
"""Tracing class."""
def __init__(self, client: Session) -> None:
"""Make new tracing objec... | 2,386 | 692 |
from typing import Optional, Dict
from wai.common.adams.imaging.locateobjects import LocatedObjects
from wai.common.cli.options import TypedOption
from ....core.component import ProcessorComponent
from ....core.stream import ThenFunction, DoneFunction
from ....core.stream.util import RequiresNoFinalisation
from ....c... | 2,627 | 690 |
#===========================================================================
#
# msgHub package
#
#===========================================================================
__doc__ = """Zero-MQ Message Hub
The msgHub is a pub/sub forwarder. All of the various data producers
send messages to the msgHub as a single ... | 793 | 163 |
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
Module for gramex exposure. This shouldn't be imported anywhere, only for use
with gramex.
"""
import glob
import json
import os
import os.path as op
import pandas as pd
from six.moves.urllib import parse
from tornado.template import Template
from gramex.apps.nlg import g... | 8,221 | 2,744 |
import plotly.graph_objects as go
import plotly as plt
import random
# Uncomment the names you want the diagram to show
# Names in english
# sta = "Statistical Office"
# si = "Emergency call admission" #"sprejem intervencij"
# pni = "Emergency intervention report" #"poročilo/protokol nujne intervencije"
# pnrv = "Em... | 3,682 | 1,417 |
from __future__ import print_function
from builtins import str
from builtins import range
# This script is not meant to provide a fully automated test, it's
# merely a hack/starting point for investigating memory consumption
# manually. The behavior also depends heavily on the version of meliae.
from meliae import scan... | 569 | 175 |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
__developer__ = 'Alex Pinheiro'
__version__ = 1.4
__build__ = 6
import sqlite3
from tkinter.ttk import *
from tkinter.filedialog import *
from threading import Thread
from utils import Utils
from login import Login
u = Utils
# Listas
estados = ['AC', 'AL', 'AP', 'AM'... | 8,468 | 3,153 |
from pricehist import beanprice
from pricehist.sources.alphavantage import AlphaVantage
Source = beanprice.source(AlphaVantage())
| 131 | 39 |
import math
import sys
from scipy.interpolate import interp2d
from scipy.ndimage import rotate, center_of_mass
from scipy.spatial import distance
from skimage.feature import canny
from skimage.filters import rank, gaussian
from skimage.measure import subdivide_polygon
from skimage.morphology import medial_axis, square... | 12,846 | 6,291 |
#!/usr/bin/env python
# coding: utf-8
from sacred.observers import TinyDbReader
import pdb
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def get_exclusion_metadata(
d,
ideal_rule = [['i0', 'not', ''], ['i1', 'not', '']],
w_lb=1e-8):
r = dict(d)
r['rule_avg_cov... | 3,749 | 1,425 |
# Copyright (C) 2005-2017 Splunk Inc. All Rights Reserved. Version 6.x
# Author: Andrew Quill
import sys,splunk.Intersplunk
import string
import getpass
import re
def replace_xns(field):
try:
punydecode = field.encode("idna").decode("idna")
except:
punydecode = field
return punydecode
def... | 9,282 | 2,937 |
# Write a function that takes a string as input and reverse only the vowels of a string.
# Example 1:
# Input: "hello"
# Output: "holle"
# Example 2:
# Input: "leetcode"
# Output: "leotcede"
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set(list("aeiouAEIOU"))
s = list(s)
... | 774 | 273 |
import argparse
from slackbot.basic.igfbasicslackbot import IgfBasicSlackBot
parser=argparse.ArgumentParser()
parser.add_argument('-s','--slack_config', required=True, help='Slack configuration json file')
parser.add_argument('-p','--project_data', required=True, help='Project data CSV file')
args=parser.parse_args()... | 574 | 195 |
def countDown(start,message):
import time
if start > 20:
raise OverflowError("Countdown can accept numbers bigger that 20.")
for i in range(start,0,-1):
time.sleep(1)
print(i)
print(message)
countDown(20,"Blastoff!🚀")
| 258 | 90 |
from glob import glob
import os
import shutil
from django.core.management.base import BaseCommand
from bgbl.pdf_utils import fix_glyphs, remove_watermark
class Command(BaseCommand):
help = 'Fix glyphs pdfs'
def add_arguments(self, parser):
parser.add_argument('doc_path', type=str)
def handle(s... | 1,170 | 347 |
from dataclasses import dataclass, field
from typing import List
from bindings.csw.abstract_time_complex_type import AbstractTimeComplexType
from bindings.csw.time_topology_primitive_property_type import (
TimeTopologyPrimitivePropertyType,
)
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class TimeTopo... | 657 | 199 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from flask import Blueprint, abort, request
from ...utils.docker_controller import DockerController
from ...utils.exception import CommandExecutionError
# Flask related.
blueprint = Blueprint(name="container", import_name=__name__)
URL_PREFIX... | 1,534 | 457 |
# print to log file, not shown on screen (to stderr which ev3dev os puts in logfile)
from ev3devlogger import log
#from ev3devlogger import timedlog as log
log("starwars song(log)")
from ev3devlogger import timedlog
timedlog("starwars song(timedlog)")
print("starwars (print)")
log("starwars song")
from ev3devlogg... | 384 | 128 |
# Copyright (C) 2021 Google Inc.
#
# 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, ... | 5,305 | 1,656 |
#
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... | 6,521 | 2,166 |
#
# Copyright 2021-2022 konawasabi
#
# 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 o... | 14,383 | 5,223 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import tempfile
def is_in(line: str, dest: str) -> bool:
if os.path.isfile(dest):
with open(dest) as file:
for content in filter(None, map(lambda s: s.strip(), file)):
if line == content:
r... | 1,011 | 334 |
"""
Script that runs all tests written
"""
import os
import pathlib
import pytest
cwd = pathlib.Path.cwd
os.chdir(cwd() / "tests")
def subfolders(dir):
return [x[0] for x in os.walk(dir)][1:] # without current directory
for subf in subfolders(cwd()):
if not subf.endswith("__pycache__"):
os.chd... | 353 | 138 |
# -*- coding: utf-8 -*-
# Copyright 2017-2018 Orbital Insight Inc., all rights reserved.
# Contains confidential and trade secret information.
# Government Users: Commercial Computer Software - Use governed by
# terms of Orbital Insight commercial license agreement.
"""
Created on Tue Oct 22 21:22:36 2019
@author: fe... | 7,933 | 2,437 |
import sys
import traceback
import cPickle as pickle
if len(sys.argv) != 3:
print 'Usage: script.py input output'
sys.exit()
in_path, out_path = sys.argv[1:]
benchmarks = pickle.load(open(in_path))
results = {}
for bmk in benchmarks:
try:
res = bmk.run()
results[bmk.checksum] = res
ex... | 508 | 179 |
import sys
import random
MAX_R = 1000
MAX_D = 25
MAX_K = 20
MAX_C = 2000
MAX_B = 100
case_no = 1
def next_file(suffix=None, desc=None):
global case_no
basename = '%02d' % case_no if suffix is None else '%02d-%s' % (case_no, suffix)
f = open(basename + '.in', 'w')
if desc is not None:
with ope... | 6,445 | 2,963 |
#!/usr/bin/env python
import os
import sys
sys.path.append(os.getcwd())
import abinitio_driver as driver
from abinitio_driver import AUtoEV
import scipy.optimize as opt
from scipy.interpolate import interp1d
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
except:
pass
# This i... | 8,797 | 3,310 |
import unittest
from basketball_reference_scraper.pbp import get_pbp
class TestPbp(unittest.TestCase):
def test_pbp(self):
df = get_pbp('2020-01-06', 'DEN', 'ATL')
expected_columns = ['QUARTER', 'TIME_REMAINING', 'DENVER_ACTION', 'ATLANTA_ACTION', 'DENVER_SCORE', 'ATLANTA_SCORE']
self.asser... | 415 | 162 |
import re
import os
from sys import argv
def grep(match):
def _do_grep_wrapper(match):
def _do_grep(lines):
if match(lines):
yield lines
return _do_grep
return _do_grep_wrapper(match)
def find(what, where, depth=True):
"""
:param what: str String to search ... | 978 | 311 |
import csv
def inner(cell, spreadsheet):
try:
parts = cell.split()
if len(parts) == 0:
return 0.0
stack = []
for part in parts:
if part[0].isalpha():
col = ord(part[0]) - ord('a')
row = int(part[1:]) - 1
cell ... | 2,023 | 581 |
'''
Created on Sep 19, 2020
@author: esdev
'''
class SlacmException(Exception):
'''
Base class for all SLAcM expressions
'''
def __init__(self, message):
super().__init__(message)
class NotYetImplemented(SlacmException):
def __init__(self, message):
super().__ini... | 1,147 | 333 |
from buycoins_client import Auth
import unittest
class TestAuthMethods(unittest.TestCase):
def test_invalid_secret_key_setup(self):
"""
Should throw an exception for invalid secret key
"""
try:
Auth.setup("name",3)
except Exception as e:
self.ass... | 959 | 262 |
# from ui import UI
# from ui import UI_Element
import sys
import time
import threading
import socket
from plcrpcservice import PLCRPCClient
import pyndn
from pyndn import Name
from pyndn import Face
from pyndn import Interest
from pyndn.security import KeyChain
from pyndn.security.identity import IdentityManager
fr... | 6,328 | 2,001 |
from typing import Union
import discord
from discord.ext import commands
import cogs.gamertags
from ansura.ansurabot import AnsuraBot
from ansura.ansuracontext import AnsuraContext
class Administration(commands.Cog):
def error(self, title, message={}, color=0xff0000):
e = discord.Embed()
e.colou... | 2,876 | 945 |
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
app = Celery('jobboard')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print(... | 357 | 128 |
def rotatelist(l,k):
(i,t) = (1,l)
while i<=k:
(l,i) = (l[len(l)-1:len(l)] + l[0:len(l)-1],i+1)
(rot,l) = (l,t)
return rot | 128 | 84 |
#-*- coding: utf-8 -*-
from .mixins import *
from .filemodels import *
from .clipboardmodels import *
from .imagemodels import *
from .foldermodels import *
from .virtualitems import *
from .archivemodels import *
| 214 | 68 |
from time import time
from datetime import datetime
from twisted.internet.defer import inlineCallbacks
from EGGS_labrad.clients import GUIClient
from EGGS_labrad.clients.cryovac_clients.fma1700a_gui import fma1700a_gui
class fma1700a_client(GUIClient):
name = 'FMA1700A Client'
FLOWID = 877920
servers = ... | 2,388 | 806 |
import sys
import unittest
sys.path.append('../')
from app import db # NOQA
from app.models import User # NOQA
from tests.base import BaseTestCase # NOQA
class UserModelCase(BaseTestCase):
def test_model_password_hashing(self):
"""Test the password hashing."""
... | 1,653 | 545 |
# coding=utf-8
"""Examples demonstrating usage of PyPinT
.. moduleauthor:: Torbjörn Klatt <t.klatt@fz-juelich.de>
"""
| 119 | 51 |
from flask import Flask, render_template, request
import cd4ml.app_utils as utils
from cd4ml.fluentd_logging import FluentdLogger
app = Flask(__name__, template_folder='webapp/templates',
static_folder='webapp/static')
fluentd_logger = FluentdLogger()
@app.route('/')
def index():
return render_templ... | 1,440 | 488 |
from fastapi import HTTPException
from tortoise.exceptions import DoesNotExist
from db.models import Events
from schemas.events import EventsOutSchema
async def get_events():
return await EventsOutSchema.from_queryset(Events.all())
async def get_event(event_id) -> EventsOutSchema:
return await EventsOutSch... | 1,456 | 467 |
import asyncio
import os
import unicodedata
import aiohttp
import discord
import lavalink
import unidecode
from redbot.core import Config, checks, commands
from redbot.core.utils.chat_formatting import pagify
from redbot.core.utils.predicates import MessagePredicate
from .api import generate_urls
try:
from redb... | 29,428 | 8,531 |
"""
Normalizes contents for all data files.
- Converts column names to uppercase
- Converts data values to uppercase
- Converts to Unix line endings
- Removes trailing whitespace from all lines
"""
import os
csvs = ['data/' + f for f in os.listdir('data') if f.endswith('.csv')]
for f in csvs:
lf = f.lower()
o... | 581 | 222 |
from NERDA.models import NERDA
from NERDA.datasets import get_conll_data, get_dane_data
from transformers import AutoTokenizer
trans = 'bert-base-multilingual-uncased'
tokenizer = AutoTokenizer.from_pretrained(trans, do_lower_case = True)
data = get_dane_data('train')
sents = data.get('sentences')
out = []
for sent ... | 2,929 | 1,146 |
# Copyright 2014 Cisco Systems, Inc.
# 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 requi... | 2,099 | 668 |
"""
Quantiphyse - Analysis widgets
Copyright (c) 2013-2020 University of Oxford
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 a... | 1,368 | 410 |
import click
from rlpy.domains import ChainMDP
from rlpy.tools.cli import run_experiment
import methods
def select_domain(chain_size):
return ChainMDP(chain_size=chain_size)
def select_agent(name, domain, max_steps, seed, **kwargs):
if name is None or name == "lspi":
return methods.tabular_lspi(dom... | 1,042 | 352 |
"""empty message
Revision ID: 6e2656ef034b
Revises: f8f949ce4522
Create Date: 2019-11-26 11:05:54.376467
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '6e2656ef034b'
down_revision = 'f8f949ce4522'
branch_labels = None
depends_on = None
def upgrade():
# ... | 694 | 274 |
from contextvars import ContextVar
from hcl_mlir.dialects import hcl as hcl_d
from hcl_mlir.ir import *
ImperativeLoopNestCount = ContextVar("ImperativeLoopNestCount", default=1)
ImperativeLoopDepth = ContextVar("ImperativeLoopDepth", default=0)
StageName = ContextVar("StageName", default="")
NestedCompute = ContextV... | 1,940 | 628 |
from typing import List
import heapq
# 排序
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
res = sorted(sum(matrix,[]))
return res[k-1]
# 最小堆维护归并排序
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
hpq = ... | 1,216 | 439 |