text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python3
#
# Copyright (c) 2019 Miklos Vajna and contributors.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The test_webframe module covers the webframe module."""
from typing import List
from typing import TYPE_CHECKING
from typing import Tupl... | 3,909 | 1,184 |
from __future__ import unicode_literals
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import requests
from youtube_search import YoutubeSearch
import youtube_dl
import eyed3.id3
import eyed3
import lyricsgenius
import telepot
spotifyy = spotipy.Spotify(
client_credentials_manager=SpotifyClient... | 6,533 | 2,284 |
#------------------------------------------------------------------------------
# Copyright (c) 2018-2019, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------... | 5,512 | 2,050 |
from datetime import datetime
class Timestamp(float):
def __new__(cls, value=None):
return super().__new__(
cls, datetime.utcnow().timestamp() if value is None else value
)
def to_date(self) -> datetime:
return datetime.utcfromtimestamp(self)
def __repr__(self):
... | 433 | 133 |
from django.contrib import admin
from bible.models import Bible, VerseOfTheDay
@admin.register(Bible)
class BibleAdmin(admin.ModelAdmin):
list_display = ['__str__', 'text']
readonly_fields = ['book', 'chapter', 'verse', 'text', 'category']
search_fields = ['text', 'book', 'chapter']
list_filter = ['ca... | 701 | 216 |
"""
Our own implementation of an abstract syntax tree (AST).
The convert function recursively converts a Python AST (from the module `ast`)
to our own AST (of the class `Node`).
"""
import ast
from logging import debug
from typy.builtin import data_types
from typy.exceptions import NotYetSupported, NoSuchAttribute, ... | 15,158 | 4,785 |
"""
Testing:
- uploading over existing files
- using deleted credentials
- using expired credentials
"""
import io
import minio
from minio import Minio
import pytest
from minio.credentials import AssumeRoleProvider, Credentials
from entityservice.object_store import connect_to_object_store, connect_to_upload_obje... | 2,310 | 709 |
# Copyright 2020 Soil, Inc.
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); yo... | 1,731 | 543 |
import calendar
import datetime
from unittest import TestCase
import pytz
from dateutil.parser import parse as date_parse
from tests import BaseTestCase
from redash import models, redis_connection
from redash.models import db, types
from redash.utils import gen_query_hash, utcnow
class DashboardTest(BaseTestCase):
... | 26,237 | 8,793 |
'''
Fibonacci Sequence
'''
import HeaderOfFiles
def fibonacciSeq(number):
'''
Generate Fibonacci Sequence to the given number.
'''
a = 1
b = 1
for i in range(number):
yield a
a,b = b,a+b
while True:
try:
f = int(input("Enter a number for Fibonacci: "... | 407 | 146 |
# Copyright 2021 MosaicML. All Rights Reserved.
from composer.algorithms.mixup.mixup import MixUp as MixUp
from composer.algorithms.mixup.mixup import MixUpHparams as MixUpHparams
from composer.algorithms.mixup.mixup import mixup_batch as mixup_batch
_name = 'MixUp'
_class_name = 'MixUp'
_functional = 'mixup_batch'
_... | 463 | 180 |
from __future__ import absolute_import, print_function
import unittest
import os
import tensorflow as tf
from tensorflow.keras import regularizers
from niftynet.network.simple_gan import SimpleGAN
from tests.niftynet_testcase import NiftyNetTestCase
class SimpleGANTest(NiftyNetTestCase):
def test_3d_reg_shape(s... | 1,503 | 527 |
import time
import thingspeak_wrapper as tsw
# Initiate the class ThingWrapper with (CHANNEL_ID, WRITE_API__KEY, READ_API_KEY)
# if is a public channel just pass the CHANNEL_ID argument, api_key defaults are None
my_channel = tsw.wrapper.ThingWrapper(501309, '6TQDNWJQ44FA0GAQ', '10EVD2N6YIHI5O7Z')
# all set of func... | 2,537 | 890 |
#
# Copyright (c) 2019, Neptune Labs Sp. z o.o.
#
# 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 agr... | 6,798 | 2,139 |
#!/usr/bin/python
#
# This might be horrible code...
# ...but it works
# Feel free to re-write in a better way
# And if you want to - send it to us, we'll update ;)
# maltego@paterva.com (2010/10/18)
#
import sys
from xml.dom import minidom
class MaltegoEntity(object):
value = "";
weight = 100;
displayInformation ... | 5,771 | 2,112 |
# Generated by Django 2.1.5 on 2019-02-12 21:18
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("api", "0049_add_all_other_translations")]
operations = [
migrations.CreateModel(
name="ClickThroughAgreement... | 1,017 | 280 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""IIIF API for Invenio."""
IIIF_API_PREFIX = '/iiif/'
"""URL prefix to IIIF API."""
III... | 813 | 329 |
#!/user/bin/env/python
"""
pub_ingest.py -- Read a bibtex file and make VIVO RDF
The following objects will be made as needed:
-- publisher
-- journal
-- information resource
-- timestamp for the information resource
-- people
-- authorships
-- concepts
The result... | 14,306 | 4,224 |
#!/usr/bin/env python
'''Generally useful bits and bobs.'''
import queue # For PrintThread and exe_run
from time import sleep, time, gmtime, strftime # For lock timeout, exe_run timeout and logging
from multiprocessing import RLock
from copy import copy
import threading # For Print... | 63,527 | 16,646 |
import numpy as np
import astropy.modeling.blackbody as bb
import astropy.constants as const
from astropy.io import fits
from scipy.interpolate import interp2d
class FaiglerMazehFit():
def __init__(self, P_orb, inc, R_star, M_star, T_star, A_ellip=False, A_beam=False,
R_p=False, a=False, u=False, g=0.65, logg=... | 8,765 | 3,884 |
import torch.nn.utils.prune as prune
import torch
from src.vanilla_pytorch.utils import count_rem_weights
from src.vanilla_pytorch.models.linearnets import LeNet, init_weights
from src.vanilla_pytorch.models.resnets import Resnets
def remove_pruning(model):
for i, (name, module) in enumerate(model.named_modules()... | 2,986 | 1,045 |
"""
read_instance_BH-cyclic.py
"""
'''
[seed graph]
V_C : "V_C"
E_C : "E_C"
[core specification]
ell_LB : "\ell_{\rm LB}"
ell_UB : "\ell_{\rm UB}"
cs_LB : "\textsc{cs}_{\rm LB}"
cs_UB : "\textsc{cs}_{\rm UB}"
'''
import sys
def read_pmax_file(filename):
with ope... | 13,681 | 5,960 |
from .system import *
from .colours import *
class InputSystem(System):
def init(self):
self.key = 'input'
def setRequirements(self):
self.requiredComponents = ['input']
def updateEntity(self, entity, scene):
# don't allow input during a cutscene
if scene.cutscene is... | 527 | 142 |
# 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 ... | 3,484 | 1,207 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import peewee
from flask import current_app,abort
from flask.ext.login import AnonymousUserMixin, UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from peewee import Model, IntegerField, CharField,PrimaryKeyField
from website.app import db_wr... | 2,923 | 943 |
# application
import application | 32 | 6 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2012 Michal Kalewski <mkalewski at cs.put.poznan.pl>
#
# This file is a part of the Simple Network Simulator (sim2net) project.
# USE, MODIFICATION, COPYING AND DISTRIBUTION OF THIS SOFTWARE IS SUBJECT TO
# THE TERMS AND CONDITIONS OF THE MIT LICENSE. YOU SHOULD H... | 2,039 | 640 |
from nexula.nexula_utility.utility_import_var import import_class
class NexusFunctionModuleExtractor():
"""
Used for constructing pipeline data preporcessing and feature representer
"""
def __init__(self, module_class_list, args_dict, **kwargs):
"""
Instantiate class(es) object in pip... | 2,088 | 620 |
import os
from configparser import ConfigParser
cfg = ConfigParser()
#PATH_CUR = os.getcwd() + '/pynori'
PATH_CUR = os.path.dirname(__file__)
cfg.read(PATH_CUR+'/config.ini')
# PREPROCESSING
ENG_LOWER = cfg.getboolean('PREPROCESSING', 'ENG_LOWER')
class Preprocessing(object):
"""Preprocessing modules before tokeniz... | 717 | 279 |
#
# THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS
# FOR A PARTICULAR PURPOSE. THIS CODE AND INFORMATION ARE NOT SUPPORTED BY XEBIALABS.
#
import com.xhaus.jyson.JysonCodec... | 2,106 | 720 |
# Generated by Django 2.2.10 on 2020-03-31 15:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("recruitment", "0021_merge_20200331_1503"),
("recruitment", "0013_button_block"),
]
operations = []
| 272 | 115 |
"""
The Depth First Search (DFS)
The goal of a dfs is to search as deeply as possible, connecting as many nodes in the graph as possible and
branching where necessary. Think of the BFS that builds a search tree one level at a time, whereas the DFS
creates a search tree by exploring one branch of the tree a... | 1,580 | 461 |
def sysrc(value):
"""Call sysrc.
CLI Example:
.. code-block:: bash
salt '*' freebsd_common.sysrc sshd_enable=YES
salt '*' freebsd_common.sysrc static_routes
"""
return __salt__['cmd.run_all']("sysrc %s" % value)
| 250 | 93 |
from .rest import RestClient
class Blacklists(object):
"""Auth0 blacklists endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
token (str): Management API v2 Token
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
"""
... | 1,429 | 445 |
# coding=utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# 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 th... | 2,886 | 1,233 |
"""
field.py
Class instance used for modifying field via Display window.
"""
# Load the needed packages
from functools import partial
from ..core import Variable, Component, QtGui, QtCore
class FieldButtonWindow(Component):
'''Class to display a Window with Field name radio buttons.'''
Vradar = None #: s... | 4,010 | 1,077 |
from bson.errors import InvalidId
from django.core.exceptions import ValidationError
from django.utils.encoding import smart_str
from mongoengine import dereference
from mongoengine.base.document import BaseDocument
from mongoengine.document import Document
from rest_framework import serializers
from mongoengine.fields... | 4,101 | 1,143 |
import pytest
from fuzz_lightyear.datastore import _ALL_POST_FUZZ_HOOKS_BY_OPERATION
from fuzz_lightyear.datastore import _ALL_POST_FUZZ_HOOKS_BY_TAG
from fuzz_lightyear.datastore import _RERUN_POST_FUZZ_HOOKS_BY_OPERATION
from fuzz_lightyear.datastore import _RERUN_POST_FUZZ_HOOKS_BY_TAG
from fuzz_lightyear.datastore... | 1,657 | 598 |
"""Module for a Data Vault field."""
from typing import Optional
from . import (
FIELD_PREFIX,
FIELD_SUFFIX,
METADATA_FIELDS,
TABLE_PREFIXES,
UNKNOWN,
FieldDataType,
FieldRole,
TableType,
)
class Field:
"""A field in a Data Vault model."""
def __init__(
self,
... | 8,375 | 2,433 |
"""DEEPSCORESV2
Provides access to the DEEPSCORESV2 database with a COCO-like interface. The
only changes made compared to the coco.py file are the class labels.
Author:
Lukas Tuggener <tugg@zhaw.ch>
Yvan Satyawan <y_satyawan@hotmail.com>
Created on:
November 23, 2019
"""
from .coco import *
import os
im... | 5,702 | 1,810 |
#!/usr/bin/env python
import unittest
from xml.dom.minidom import parseString
import xml.etree.ElementTree as ET
from decimal import Decimal
from gomatic import GoCdConfigurator, FetchArtifactDir, RakeTask, ExecTask, ScriptExecutorTask, FetchArtifactTask, \
FetchArtifactFile, Tab, GitMaterial, PipelineMaterial,... | 81,840 | 25,575 |
import logging
from qrutilities.imageutils import ImageUtils
from PyQt4.QtGui import QColor
logger = logging.getLogger('console')
class WellPlotStyleHandler(object):
'''
classdocs
'''
def saveDataState(self, wellPlotData, wellPlotStyleWidget):
if wellPlotStyleWidget.plotTitleOnCheckBox.isC... | 1,628 | 470 |
from django.conf.urls import url
from . import views
app_name = "messages"
urlpatterns = [
url(r'^$', views.InboxListView.as_view(), name='inbox'),
url(r'^sent/$', views.SentMessagesListView.as_view(), name='sent'),
url(r'^compose/$', views.MessagesCreateView.as_view(), name='compo... | 599 | 218 |
import datetime
import json
import dateutil.parser
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from django.utils import timezone
from apps.devicelocation.models import DeviceLocation
from apps.physicaldevice.models import Device
from apps.property.models import GenericProp... | 24,159 | 7,380 |
# 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, software
# d... | 12,221 | 3,467 |
# !/usr/bin python
"""
#
# set-env - a small python program to setup the configuration environment for data-push.py
# data-push.py contains the python program to push attribute values to vROps
# Author Sajal Debnath <sdebnath@vmware.com>
#
"""
# Importing the required modules
import json
import base64
i... | 1,577 | 517 |
import unittest
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
m = self.c(root)
r=0
for n in ... | 1,504 | 500 |
TOKEN = "1876415562:AAEsX_c9k3Fot2IT0BYRqkCCQ5vFEHQDLDQ"
CHAT_ID = [957539786] # e.g. [1234567, 2233445, 3466123...]
| 118 | 96 |
"""entry point"""
from . import main
start = main.app.launch
| 63 | 22 |
from tests import run_main_and_assert
FAST_LOCAL_TEST_ARGS = "--exp-name local_test --datasets mnist" \
" --network LeNet --num-tasks 5 --seed 1 --batch-size 32" \
" --nepochs 2 --num-workers 0 --stop-at-task 3"
def test_finetuning_stop_at_task():
args_line = FAST_LO... | 411 | 153 |
# Autor: Anuj Sharma (@optider)
# Github Profile: https://github.com/Optider/
# Problem Link: https://leetcode.com/problems/contains-duplicate/
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
count = {}
for n in nums :
if count.get(n) != None :
ret... | 375 | 117 |
#!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import logging
import optparse
import os
import sys
import tempfile
import zipfile
from util import build_utils
def _C... | 8,824 | 2,829 |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.hashers import check_password, make_password
from django.views import View
from utils.response_code import RET, error_map
from rest_framework.views import APIView
from rest_framework.response import Response
from apps.ser... | 11,199 | 3,919 |
import numpy as np;
from .covariance_target import CovarianceTarget;
class AMaLGaMCovariance(CovarianceTarget):
_API=2.
def __init__(self,
theta_SDR = 1.,
eta_DEC = 0.9,
alpha_Sigma = [-1.1,1.2,1.6],
NIS_MAX = 25,
tau = 0.35,
epsilon = 1e-30,
condition_n... | 4,283 | 1,527 |
{
'target_defaults': {
'win_delay_load_hook': 'false',
'conditions': [
['OS=="win"', {
'msvs_disabled_warnings': [
4530, # C++ exception handler used, but unwind semantics are not enabled
4506, # no definition for inline function
],
}],
],
},
'targets'... | 1,487 | 528 |
"""Django settings for botwtracker project.
Copyright (c) 2017, Evan Moritz.
botw-tracker is an open source software project released under the MIT License.
See the accompanying LICENSE file for terms.
"""
import os
from .config_local import *
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... | 2,917 | 987 |
from flask import Blueprint, request, jsonify
from app.domains.users.actions import get_all_users, insert_user, get_user_by_id, update_user, delete_user
app_users = Blueprint('app.users', __name__)
@app_users.route('/users', methods=['GET'])
def get_users():
return jsonify([user.serialize() for user in get_all_... | 1,013 | 370 |
import legacy_code.tf_cnn_siamese.configurations as conf
import tensorflow as tf
import numpy as np
def construct_cnn(x, conv_weights, conv_biases, fc_weights, fc_biases,
dropout = False):
"""
constructs the convolution graph for one image
:param x: input node
:param conv_weights: convolutio... | 8,513 | 2,989 |
import sys
import logging
import unittest
from testfixtures import LogCapture
from twisted.python.failure import Failure
from scrapy.utils.log import (failure_to_exc_info, TopLevelFormatter,
LogCounterHandler, StreamLogger)
from scrapy.utils.test import get_crawler
from scrapy.extensions... | 3,591 | 1,113 |
import heapq
from typing import List
from definitions import RoomPosition, Position
import random
import sys
class PriorityQueue:
def __init__(self):
self.elements: Array = []
def empty(self) -> bool:
return len(self.elements) == 0
def put(self, item, priority: float):
hea... | 2,329 | 732 |
from pypeflow.common import *
from pypeflow.data import PypeLocalFile, makePypeLocalFile, fn
from pypeflow.task import PypeTask, PypeThreadTaskBase, PypeTaskBase
from pypeflow.controller import PypeWorkflow, PypeThreadWorkflow
from falcon_kit.FastaReader import FastaReader
import subprocess, shlex
import os, re
cigar... | 19,152 | 6,831 |
from keras.datasets import mnist
from keras.layers.merge import _Merge
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv... | 8,490 | 2,632 |
from Core.IFactory import IFactory
from Regs.Block_C import RC480
class RC480Factory(IFactory):
def create_block_object(self, line):
self.rc480 = _rc480 = RC480()
_rc480.reg_list = line
return _rc480
| 231 | 91 |
###############################################################################
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
###############################################################################
imp... | 1,594 | 470 |
'''Test package.'''
import xroms
from glob import glob
import os
def test_open_netcdf():
'''Test xroms.open_netcdf().'''
base = os.path.join(xroms.__path__[0],'..','tests','input')
files = glob('%s/ocean_his_000?.nc' % base)
ds = xroms.open_netcdf(files)
assert ds
def test_open_zar... | 554 | 229 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^piechart/', views.demo_piechart, name='demo_piechart'),
url(r'^linechart/', views.demo_linechart, name='demo_linechart'),
url(r'^linechart_without_date/', views.demo_linechart_without_date,... | 1,381 | 500 |
import time
import mido
from pinaps.piNapsController import PiNapsController
from NeuroParser import NeuroParser
"""
Equation of motion used to modify virbato.
"""
def positionStep(pos, vel, acc):
return pos + vel * 2 + (1/2) * acc * 4
def velocityStep(vel, acc):
return acc * 2 + vel
CTRL_LF... | 2,557 | 914 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 11:47:47 2019
@author: yanyanyu
"""
"""
Tab1-plot1: candlestick
"""
import json
import datetime
import pandas as pd
from math import pi
from random import choice
from pytz import timezone
from bokeh.plotting import figure,show
from bokeh.p... | 15,109 | 4,461 |
# -*- coding:utf-8 -*-
import tensorflow as tf
class CNN:
def __init__(self, save_or_load_path=None, trainable=True, learning_rate = 0.00002,timestep=9,road=189,predstep=1):
self.trainable = trainable
self.learning_rate = learning_rate
self.road = road
self.input_size = timestep *... | 7,499 | 3,043 |
import cv2
import mediapipe as mp
from time import sleep
import numpy as np
import autopy
import pynput
wCam, hCam = 1280, 720
wScr, hScr = autopy.screen.size()
cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
mouse = pynput.mouse.Cont... | 2,755 | 1,008 |
import glob
import logging
import os
import shutil
import sys
"""script to divide a folder with generated/training data into a train and val folder
- val folder contains 500 Samples if not changed in source code
- DOES NOT work if images structured in subfolders, see below
- if there is no dir in the given... | 2,804 | 891 |
import threading
from queue import Queue
from multiprocessing.pool import ApplyResult
import tabular_logger as tlogger
class AsyncWorker(object):
@property
def concurrent_tasks(self):
raise NotImplementedError()
def run_async(self, task_id, task, callback):
raise NotImplementedError()
... | 4,793 | 1,300 |
import os
registry = {}
class RegisterPlatform(object):
'''
classdocs
'''
def __init__(self, platform):
'''
Constructor
'''
self.platform = platform
def __call__(self, clazz):
registry[self.platform] = clazz
def platform():
# Decide on whi... | 557 | 163 |
"""Django Admin Panels for App"""
from django.contrib import admin
from mailer import models
@admin.register(models.SendingAddress)
class SendingAddressAdmin(admin.ModelAdmin):
"""Admin View for SendingAddress"""
list_display = ('address', 'organization')
list_filter = ('organization__name',)
actions ... | 553 | 151 |
DEBUG = True
USE_TZ = True
SECRET_KEY = "dummy"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"rest_framework",
"django_filters",
"belt",
"tests.app",
]... | 492 | 201 |
import sys
import json
import transformation
class StopPointGrid:
def __init__( self, nm, layer, direction, width, pitch, offset=0):
self.nm = nm
self.layer = layer
self.direction = direction
assert direction in ['v','h']
self.width = width
self.pitch = pitch
... | 26,482 | 10,506 |
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import os
import time
import csv
from webdriver_manager.chrome import ChromeDriverManager
import math
from basic_function import ... | 13,457 | 4,413 |
from pydantic import BaseSettings
class Settings(BaseSettings):
deta_project_key: str
settings = Settings()
| 116 | 35 |
#!/usr/bin/env python
''' This module provides configuration options for OS project. No more magic numbers! '''
BLOCK_SIZE = 16 # words
WORD_SIZE = 4 # bytes
# length od RS in blocks
RESTRICTED_LENGTH = 1
# length of DS in blocks
DS_LENGTH = 6
# timer value
TIMER_VALUE = 10
# buffer size
BUFFER_SIZE = 16
# num... | 819 | 338 |
#!/usr/bin/env python
import numpy as np
from roboticstoolbox.robot.ERobot import ERobot
from math import pi
class Puma560(ERobot):
"""
Class that imports a Puma 560 URDF model
``Puma560()`` is a class which imports a Unimation Puma560 robot definition
from a URDF file. The model describes its kine... | 3,022 | 1,135 |
#!/usr/bin/env python
# Copyright (c) 2016 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
"""Define t... | 26,052 | 8,426 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ntptrace - trace peers of an NTP server
Usage: ntptrace [-n | --numeric] [-m number | --max-hosts=number]
[-r hostname | --host=hostname] [--help | --more-help]
hostname
See the manual page for details.
"""
# SPDX-License-Identifier: BS... | 5,059 | 1,761 |
import struct
import msgpack
from lbrynet.wallet.transaction import Transaction, Output
from torba.server.hash import hash_to_hex_str
from torba.server.block_processor import BlockProcessor
from lbrynet.schema.claim import Claim
from lbrynet.wallet.server.model import ClaimInfo
class LBRYBlockProcessor(BlockProce... | 7,529 | 2,411 |
from ProjectEulerCommons.Base import *
numbers_list = """37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
8926167... | 5,450 | 5,226 |
"""Endpoint for the manipulation of datasets
"""
import hashlib
from flask import Response
from flask_restx import Namespace, Resource, abort
from app.common import client
from app.common import datasets as datasets_fcts
from app.common import path
api = Namespace("datasets", description="Datasets related endpoints... | 4,584 | 1,412 |
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [float('inf')] * n
dp[0] = 0
tail = 1
for i in range(n):
limit = min(n, i + nums[i] + 1)
for j in range(tail, limit):
dp[j] = min(dp[j], dp[i] + 1)
... | 360 | 140 |
from .knn import KNNClassifier
__all__ = ['KNNClassifier'] | 59 | 22 |
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.rem... | 571 | 173 |
import sys
import time
import uasyncio as asyncio
from ahttpserver import sendfile, Server
app = Server()
@app.route("GET", "/")
async def root(reader, writer, request):
writer.write(b"HTTP/1.1 200 OK\r\n")
writer.write(b"Connection: close\r\n")
writer.write(b"Content-Type: text/html\r\n")
... | 2,575 | 961 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Unet(nn.Module):
def __init__(self, fc_dim=64, num_downs=5, ngf=64, use_dropout=False):
super(Unet, self).__init__()
# construct unet structure
unet_block = UnetBlock(
ngf * 8, ngf * 8, input_n... | 3,851 | 1,352 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Path hack
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
try:
import unittest2 as unittest
except ImportError:
import unittest
from kgtool.core import * # noqa
class CoreTestCase(unittest.TestCase):
def setUp(self):
pass
def t... | 6,117 | 2,279 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import scriptcontext as sc
import compas_rhino
from compas_ags.rhino import SettingsForm
from compas_ags.rhino import FormObject
from compas_ags.rhino import ForceObject
__commandname__ = "AGS_toolbar_displa... | 903 | 256 |
from typing import (
Any,
cast,
List,
Optional,
Type
)
import lpp.ast as ast
from lpp.builtins import BUILTINS
from lpp.object import(
Boolean,
Builtin,
Environment,
Error,
Function,
Integer,
Null,
Object,
ObjectType,
String,
Return
)
TRUE = Boolean(True... | 10,312 | 3,066 |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accom... | 121,132 | 39,042 |
from flask import Flask
from flask import request
from flask import Response
from resources import resourcePing, resourceResolution
from message_protocol.resolution_input import parseResolutionInput
import json
app = Flask(__name__)
@app.route('/ping', methods=['GET'])
def ping():
output = resourcePing.main()
... | 652 | 186 |
"""
WSGI config for server project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTIN... | 996 | 297 |
import os
from functools import reduce
import boto3
import yaml
from copy import deepcopy
from cryptography.fernet import Fernet
from pycbc import json
from pycbc.utils import AttrDict as d
s3 = boto3.client('s3')
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
_DEFAULTS = d({
'users': [],
'enc... | 2,583 | 879 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Module Name
Description...
"""
__author__ = "Vinícius Pereira"
__copyright__ = "Copyright 2021, Vinícius Pereira"
__credits__ = ["Vinícius Pereira","etc."]
__date__ = "2021/04/12"
__license__ = "GPL"
__version__ = "1.0.0"
__pythonversion__ = "3.9.1"
__maintaine... | 1,881 | 661 |
def us_choropleth(t):
import matplotlib.cm
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.colors import Normalize
import shapefile
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
im... | 2,893 | 1,010 |
import time
import os
#parameters
sunset_hr=8
dawn_hr=7
daytime_period_min=60
nighttime_period_min=1
time.localtime()
print("program starts at ",time.localtime());
while(1):
#Is it day or night?
time.localtime()
hour = time.localtime()[3]
minute = time.localtime()[4]
hour_float = 1.0*hour+minute... | 2,348 | 824 |