content stringlengths 7 928k | avg_line_length float64 3.5 33.8k | max_line_length int64 6 139k | alphanum_fraction float64 0.08 0.96 | licenses list | repository_name stringlengths 7 104 | path stringlengths 4 230 | size int64 7 928k | lang stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|
#!/usr/bin/env python3
# Print out all the codons for the sequence below in reading frame 1
# Use a 'for' loop
dna = 'ATAGCGAATATCTCTCATGAGAGGGAA'
for nt in range(0, len(dna) - 2, 3):
print(dna[nt:nt+3])
"""
ATA
GCG
AAT
ATC
TCT
CAT
GAG
AGG
GAA
"""
| 11.636364 | 68 | 0.671875 | [
"MIT"
] | tmbolt/learning_python | codons.py | 256 | Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\design.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWin... | 58.832168 | 138 | 0.730893 | [
"Apache-2.0"
] | AlgieParvin/openpose-gui | design.py | 8,521 | Python |
from Cocoa import NSDocument
class CurrencyConvBindingDocument(NSDocument):
def windowNibName(self):
return "CurrencyConvBindingDocument"
| 21.714286 | 46 | 0.789474 | [
"MIT"
] | linuxfood/pyobjc-framework-Cocoa-test | Examples/AppKit/CocoaBindings/CurrencyConvBinding/CurrencyConvBindingDocument.py | 152 | Python |
import json
import pathlib
import airflow
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from kubernetes.client import models as k8s
from airflow.contrib.operators import kubernetes_pod_operator
import datetime
from airf... | 21.678571 | 67 | 0.747117 | [
"Apache-2.0"
] | skhatri/airflow-by-example | airflow-example-dags/dags/k8s-pod-operator-cluster.py | 1,214 | Python |
from django.contrib import admin
from django.contrib.auth.models import User
from django.test.testcases import TestCase
from django.urls import reverse
from pagetools.menus.admin import MenuAdmin, make_entrieable_admin
from pagetools.menus.apps import MenusConfig
from pagetools.menus.models import Link, Menu, MenuEntr... | 36.185393 | 96 | 0.575221 | [
"MIT"
] | theithec/django-pagetools | pagetools/menus/tests/test_admin.py | 6,441 | Python |
# coding: utf8
from __future__ import absolute_import
import datetime
from celery import shared_task
from celery.utils.log import get_task_logger
from django.utils.translation import ugettext as _
from django.core.mail import send_mail
from django.contrib.auth import get_user_model
from django.conf import settings
f... | 26.185185 | 66 | 0.720651 | [
"MIT"
] | Socialsquare/RunningCause | challenges/tasks.py | 1,414 | Python |
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.goal.task_registrar import TaskRegistrar as task
from pants.contrib.codeanalysis.tasks.bundle_entries import BundleEntries
from pants.contrib.codeanalysis.tasks.extract_java im... | 42.666667 | 73 | 0.798438 | [
"Apache-2.0"
] | odisseus/pants | contrib/codeanalysis/src/python/pants/contrib/codeanalysis/register.py | 640 | Python |
import os
import glob
import json
import argparse
from tokenizers import ByteLevelBPETokenizer
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--train_path', type=str)
parser.add_argument('--n_files', type=int)
parser.add_argument('--save_path', type=str)
parser... | 25.625 | 80 | 0.654634 | [
"MIT"
] | bilal2vec/lm-finetuning | train_tokenizer.py | 1,025 | Python |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class OslusiadasextractItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
| 21 | 53 | 0.725275 | [
"MIT"
] | Guilherme-Valle/os-lusiadas-api | root_package/oslusiadasextract/items.py | 273 | Python |
import torch
from torch.autograd import Variable
def train(epoch, dataloader, net, criterion, optimizer, opt):
net.train()
for i, (adj_matrix, annotation, target) in enumerate(dataloader, 0):
net.zero_grad()
padding = torch.zeros(len(annotation),
opt.state_dim - ... | 31.764706 | 72 | 0.585185 | [
"MIT"
] | RanganThaya/ggnn.pytorch.sparse | utils/train.py | 1,080 | Python |
import numpy as np
import math
# number will be decreased by a small amount when some deletions happen
number_of_vertices = 5_000
# probability of an arc between any two instances
probability_of_an_arc = 0.001
# number of reads in the read-heavy test
read_test_operations = 20_000
# probability of removing a ran... | 45.053191 | 106 | 0.661393 | [
"Apache-2.0"
] | ArendJan/TUD-DistributedSystems | Conflict-free_Replicated_Data_Types/experiments/benchmarking/OperationTestsGenerator.py | 4,235 | Python |
flag = b'HSCTF{1d9cb42f-3302-46f3-a3a7-0ca30d631cc9}'
| 27 | 53 | 0.777778 | [
"MIT"
] | scnu-sloth/hsctf-2021-freshmen | Crypto-babyFibo/ans/secret.py | 54 | Python |
"""Tests related to inheritance from interface."""
from datetime import datetime
import pytest
from generics import defended
from generics import delegated
from generics import private
pytestmark = pytest.mark.parametrize("f", [private, delegated, defended])
def test_allow_inheritance_from_interface(f, s):
""... | 24.947368 | 73 | 0.757384 | [
"BSD-2-Clause"
] | proofit404/generics | tests/test_subtyping.py | 474 | Python |
import math
import collections
import numpy as np
def __CheckEvaluationInput(y, yPredicted):
# Check sizes
if(len(y) != len(yPredicted)):
raise UserWarning("Attempting to evaluate between the true labels and predictions.\n Arrays contained different numbers of samples. Check your work and try again."... | 30.781022 | 174 | 0.641688 | [
"MIT"
] | isibord/LogisticRegression | Code/EvaluationsStub.py | 4,217 | Python |
import os
import json
import logging
logger = logging.getLogger(__name__)
from aiohttp import web, ClientSession
async def index(request):
logger.debug('Accessing index')
client = request.app['arango']
sys_db = client.db('_system', username='root', password=os.environ['MULTINET_ROOT_PASSWORD'])
dbs = ... | 37.684932 | 125 | 0.683206 | [
"MIT"
] | multinet-app/multinet-server-poc | multinet-server/views.py | 5,502 | Python |
"""
module housing core library functionality
"""
import numpy as np
from typing import Optional, Tuple
import humba.jits as jits
def histogram(
x: np.ndarray,
bins: int = 10,
range: Tuple[float, float] = (0, 10),
weights: Optional[np.ndarray] = None,
flow: bool = False,
) -> Tuple[np.ndarray, O... | 32.421053 | 88 | 0.603432 | [
"BSD-3-Clause"
] | douglasdavis/humba | humba/core.py | 4,312 | Python |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | 24.228571 | 77 | 0.646226 | [
"Apache-2.0"
] | AustinGilliam/qiskit-terra | qiskit/circuit/library/template_circuits/toffoli/template_2a_1.py | 896 | Python |
import os
import csv
import logging
import itertools
import pandas as pd
import psutil as ps
from _pytest.monkeypatch import MonkeyPatch
from dataactcore.interfaces.db import GlobalDB
from dataactcore.config import CONFIG_SERVICES
from dataactcore.models.domainModels import concat_tas_dict
from dataactcore.models.look... | 61.134111 | 120 | 0.599774 | [
"CC0-1.0"
] | RonSherfey/data-act-broker-backend | tests/integration/error_warning_file_tests.py | 62,907 | Python |
import os
import PyQt5.QtCore as qc
DATA_DIR = 'MiptCisDocs'
WRITABLE_LOCATION = qc.QStandardPaths.writableLocation(
qc.QStandardPaths.StandardLocation.AppDataLocation
)
def get_data_dir() -> str:
data_dir = os.path.abspath(os.path.join(WRITABLE_LOCATION, DATA_DIR))
if not os.path.exists(data_dir):
... | 22.6875 | 73 | 0.749311 | [
"MIT"
] | ivigns/mipt-cis-docs | client/data_manage/data_dir.py | 363 | Python |
# -*- coding: utf-8 -*-
import os
import sys
import csv
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')
import ccxt # noqa: E402
# --------------------------------... | 39.578947 | 133 | 0.628657 | [
"MIT"
] | yinfeng2016/Bitcoin-Trader-RL | binance-fetch-ohlcv-to-csv.py | 3,008 | Python |
##########################################
# File: refine_multiple_shards_joint.py #
# Copyright Richard Stebbing 2014. #
# Distributed under the MIT License. #
# (See accompany file LICENSE or copy at #
# http://opensource.org/licenses/MIT) #
##########################################
# Imports
... | 33.831683 | 78 | 0.609599 | [
"MIT"
] | rstebbing/shards | refine_multiple_shards_joint.py | 3,417 | Python |
import numpy as np
import math
from arena import Arena
from agent import HAgent, AAgent
import random
# np.random.seed(1234)
# place the humans on the arena
def place_soldiers(n, arena, agents):
x = 0
y = 0
for i in range(n):
agents[i + 1] = HAgent([x, y])
arena.arena[x, y] = 1
y ... | 29.344633 | 86 | 0.555641 | [
"MIT"
] | ryflect/CS683-xcom | helper.py | 5,194 | Python |
# -*- coding: utf-8 -*-
# This file was generated
import ctypes
import nidigital.errors as errors
import threading
from nidigital._visatype import * # noqa: F403,H303
import nidigital.history_ram_cycle_information as history_ram_cycle_information # noqa: F401
class Library(object):
'''Library
Wrapper ar... | 76.338766 | 278 | 0.743591 | [
"MIT"
] | SukruthGrandhiNI/nimi-python | generated/nidigital/nidigital/_library.py | 65,575 | Python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from chirpstack_api.as_pb.external.api import organization_pb2 as chirpstack__api_dot_as__pb_dot_external_dot_api_dot_organization__pb2
from google.protobuf impo... | 51.046196 | 158 | 0.704764 | [
"MIT"
] | GaiaFL/chirpstack-api | python/src/chirpstack_api/as_pb/external/api/organization_pb2_grpc.py | 18,785 | Python |
import sys
import base64
import platform
import functools
from keyring.util import properties
from keyring.backend import KeyringBackend
from keyring.errors import PasswordDeleteError, ExceptionRaisedContext
from . import file_base
try:
# prefer pywin32-ctypes
from win32ctypes import pywintypes
from win32... | 30.06701 | 78 | 0.642208 | [
"MIT"
] | nficano/alexa-find-my-iphone | src/site-packages/keyrings/alt/Windows.py | 5,833 | Python |
def multiple(first,second):
return first * second
def add(x,y):
return x+y
| 16.6 | 27 | 0.662651 | [
"MIT"
] | tavleensasan/Tav | maths2.py | 83 | Python |
"""
This module is used to manage rules.
## Base format
A context and rule is written in JSON.
A context contains an identifier, AND one or three rules.
One of rules must specify the SCHC Compression/Decompression (CD).
Two specify SCHC Fragmentation/Reassembly (FR) if needed.
Therefore, a context has to be formed ... | 32.285417 | 120 | 0.545589 | [
"MIT"
] | n44hernandezp/openschc | rulemanager.py | 15,497 | Python |
"""
This module is to support *bbox_inches* option in savefig command.
"""
import warnings
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
def adjust_bbox(fig, format, bbox_inches):
"""
Temporarily adjust the figure so that only the specified area
(bbox_inches) is saved.
It modifi... | 29.602941 | 69 | 0.594883 | [
"Unlicense"
] | mattl1598/Project-Mochachino | editing files/Portable Python 3.2.5.1/App/Lib/site-packages/matplotlib/tight_bbox.py | 4,026 | Python |
import logging
from authlib.common.urls import add_params_to_uri
from .base import BaseGrant, AuthorizationEndpointMixin
from ..errors import (
OAuth2Error,
UnauthorizedClientError,
AccessDeniedError,
)
log = logging.getLogger(__name__)
class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin):
"""T... | 40.478448 | 79 | 0.589607 | [
"BSD-3-Clause"
] | 2tunnels/authlib | authlib/oauth2/rfc6749/grants/implicit.py | 9,391 | Python |
import pandas as pd
import numpy as np
def load_from_tsfile_to_dataframe(full_file_path_and_name, replace_missing_vals_with='NaN'):
data_started = False
instance_list = []
class_val_list = []
has_time_stamps = False
has_class_labels = False
uses_tuples = False
is_first_case = True
w... | 44.825243 | 119 | 0.509638 | [
"BSD-3-Clause"
] | TonyBagnall/boss_fork | sktime/utils/load_data.py | 4,617 | Python |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 17:14:19 2020
@author: Mitchell
model_training.py
~~~~~~~~~~~~~~~~~
This file serves as a script for building and training our VAE model. To do
so we used the VAE and DataSequence classes defined in the file `VAE.py`, as
well as helper functions from the file `dataset... | 31.748299 | 79 | 0.611099 | [
"MIT"
] | youngmg1995/NES-Music-Maker | VAE/full_model/model_training.py | 4,667 | Python |
from rlpyt.utils.launching.affinity import encode_affinity
from rlpyt.utils.launching.exp_launcher import run_experiments
from rlpyt.utils.launching.variant import make_variants, VariantLevel
script = "rlpyt/experiments/scripts/atari/pg/train/atari_ff_a2c_gpu_multi.py"
affinity_code = encode_affinity(
n_cpu_cores... | 27.447368 | 77 | 0.760307 | [
"MIT"
] | DilipA/rlpyt | rlpyt/experiments/scripts/atari/pg/launch/pabti/launch_atari_ff_a2c_gpu_multi.py | 1,043 | Python |
# Copyright 2014 OpenStack Foundation
# 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 requ... | 33.742424 | 78 | 0.643018 | [
"Apache-2.0"
] | Juniper/nova-docker | novadocker/virt/docker/network.py | 2,227 | Python |
import unittest
from tests.test_utils import get_sample_pdf_with_labels, get_sample_pdf, get_sample_sdf, get_sample_pdf_with_extra_cols, get_sample_pdf_with_no_text_col ,get_sample_spark_dataframe
from nlu import *
class TestSarcasm(unittest.TestCase):
def test_sarcasm_model(self):
pipe = nlu.load('sarc... | 45.980392 | 180 | 0.658422 | [
"Apache-2.0"
] | UPbook-innovations/nlu | tests/nlu_core_tests/component_tests/classifier_tests/sarcasm_tests.py | 2,345 | Python |
# Generated by Django 2.2.6 on 2019-10-22 15:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | 40.302326 | 240 | 0.668782 | [
"MIT"
] | Swiss-Polar-Institute/project-application | ProjectApplication/project_core/migrations/0051_createmodify_country.py | 1,733 | Python |
def combination(n, r):
"""
:param n: the count of different items
:param r: the number of select
:return: combination
n! / (r! * (n - r)!)
"""
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return ... | 19.25 | 42 | 0.503896 | [
"MIT"
] | ta7uw/atcoder | lib/python-lib/combination.py | 385 | Python |
#!/usr/bin/env python
import sys
import numpy as np
from pandas import *
from sklearn.metrics import mean_absolute_error
from djeval import *
n_estimators = 200
n_jobs = -1
msg("Hi, reading yy_df.")
yy_df = read_pickle(sys.argv[1])
msg("Getting subset ready.")
train = yy_df[yy_df.elo.notnull()]
for blend in np.ar... | 23.826087 | 102 | 0.722628 | [
"MIT"
] | Keesiu/meta-kaggle | data/external/repositories/137656/blundercheck-master/combine/20150301a/modeling/blend_models.py | 548 | Python |
import os
import json
import time
import datetime
import manageMonitoredUsersDB
pathToJSON = os.getcwd() + '/generatedJSON'
def get_local_json_timestamp_epoch(username, filename):
monitoredJSON = None
try:
monitoredJSON = json.load(open(pathToJSON + os.sep + filename, "r+"))
except:
with o... | 43.676056 | 135 | 0.659787 | [
"Apache-2.0"
] | lmagellanic-cloud/phishers-monitor | TFG/checkEpochAndUpdateJSON.py | 3,104 | Python |
import torch
import torch.nn as nn
import torch.nn.functional as F
from starter_code.modules.networks import MLP, MinigridCNN
from mnist.embedded_mnist import MNIST_CNN
class SimpleValueFn(nn.Module):
def __init__(self, state_dim, hdim):
super(SimpleValueFn, self).__init__()
self.value_net = MLP(d... | 32.5625 | 74 | 0.650672 | [
"MIT"
] | mbchang/decentralized-rl | starter_code/modules/value_function.py | 1,042 | Python |
"""CD SEM structures."""
from functools import partial
from typing import Optional, Tuple
from gdsfactory.cell import cell
from gdsfactory.component import Component
from gdsfactory.components.straight import straight as straight_function
from gdsfactory.components.text_rectangular import text_rectangular
from gdsfact... | 28.773585 | 76 | 0.685902 | [
"MIT"
] | gdsfactory/gdsfactory | gdsfactory/components/cdsem_straight.py | 1,525 | Python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from ....unittest import TestCase
from oauthlib.oauth2.rfc6749 import BaseEndpoint, catch_errors_and_unavailability
from oauthlib.oauth2 import Server, RequestValidator, FatalClientError, OAuth2Error
class BaseEndpointTest(TestCase):
... | 34.676056 | 83 | 0.668156 | [
"BSD-3-Clause"
] | Blitzen/oauthlib | tests/oauth2/rfc6749/endpoints/test_base_endpoint.py | 2,462 | Python |
from .protocol import *
import serial
import time
from threading import Lock
from PIL import Image, ImageDraw, ImageOps, ImageFont
class Device:
ser = None
inbuffer = ""
awaitingResponseLock = Lock()
testmode = False
nLeds = 0
dispW = 0
dispH = 0
rotFactor = 0
rotCircleSteps = 0
... | 38.753906 | 224 | 0.535934 | [
"MIT"
] | lubeda/Inkkey-SW-for-Macro-Keypad-Pro | inkkeys/device.py | 9,921 | Python |
# -*- coding: utf-8 -*-
# Copyright 2018 Joshua Bronson. All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""Provides bidict duplication policies... | 27.054054 | 84 | 0.736264 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | gaborbernat/bidict | bidict/_dup.py | 1,001 | Python |
#!/usr/bin/env python3
# Day 13: Transparent Origami
# https://adventofcode.com/2021/day/13
import sys
data = open("input.txt" if len(sys.argv) == 1 else sys.argv[1]).read().splitlines()
n = 2000
grid = [["." for _ in range(n)] for _ in range(n)]
for line in data:
if not line:
break
x, y = map(int,... | 23.849057 | 83 | 0.505538 | [
"Unlicense"
] | rene-d/advent-of-rust | 2021/day13/day13.py | 1,264 | Python |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
from typing import Callable, Dict, List, Sequence
from reggen.field import Field
from reggen.register import Register
from reggen.reg_block import RegBlock
from shared.ot... | 32.958333 | 79 | 0.591761 | [
"Apache-2.0"
] | Daasin/FOSS-fTPM | hw/ip/otbn/dv/otbnsim/sim/ext_regs.py | 9,492 | Python |
import json
import os
import sys
import numpy as np
import random
import math
import time
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
from env import R2RBatch
from utils import padding_idx, add_idx, Tokenizer
imp... | 44.722934 | 145 | 0.532655 | [
"MIT-0",
"MIT"
] | rcorona/R2R-EnvDrop | r2r_src/agent.py | 38,417 | Python |
from dataclasses import dataclass
from beebole.interfaces.entities import IdEntity, CountEntity
@dataclass
class Group(IdEntity):
name: str
groups: CountEntity
@dataclass
class ParentedGroup(IdEntity):
name: str
parent: IdEntity
| 15.625 | 61 | 0.764 | [
"MIT"
] | Dogeek/beebole | beebole/interfaces/entities/group.py | 250 | Python |
import math
n=int(input())
c=list(map(int, input().split()))
print(sum([abs(i) for i in c]))
print(math.sqrt(sum([i*i for i in c])))
print(max([abs(i) for i in c])) | 27.333333 | 39 | 0.628049 | [
"MIT"
] | consommee/AtCoder | ABC180/ABC180_B.py | 164 | Python |
import xarray as xr
import pandas as pd
import numpy as np
import xgboost as xgb
import time
import pickle
import sys
from xgboost import XGBRegressor
# load dataframe with maximal temp
def load_df_max_TREFHT(member, start_date, end_date):
path = "/glade/scratch/zhonghua/CESM-LE-members-csv/"
print("*********... | 37.388235 | 109 | 0.602895 | [
"MIT"
] | zzheng93/code_uhws | 3_model_valid/pred/apply_model_members.py | 3,178 | Python |
'''
This is to fetch the tip table data for a telegram_id
Error Handling
==============
- /withdrawmemo tipuser11111 0.0001 TLOS pay_bill
- /withdrawmemo tipuser11111 0.00001 EOS pay_bill
{"code": 3050003, "name": "eosio_assert_message_exception", "what": "eosio_assert_message assertion failure"
, "details... | 51.223684 | 121 | 0.642949 | [
"MIT"
] | abhi3700/tipuser_bot | app/chain_table.py | 3,893 | Python |
#!/usr/bin/env python
#Copyright (c) 2008 Erik Tollerud (erik.tollerud@gmail.com)
from __future__ import division,with_statement
from glob import glob
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup,find_packages
from distutils.command.build_py import build_py as du_build_py
... | 35.52381 | 120 | 0.635389 | [
"Apache-2.0"
] | bezthomas/astropysics | setup.py | 5,968 | Python |
#!/usr/bin/env python
import argparse, re, os
from StringIO import StringIO
import language
#* Build instruction
#*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*#
def roundup(x, to=8):
return x if x % to == 0 else x + to - x % to
def build_form(ins):
form = ["%i"]... | 25.694737 | 100 | 0.566776 | [
"MIT"
] | brgmnn/uob-cpu-simulator | assembler.py | 4,882 | Python |
import time
import serial
print "Iniciando Comunicao Serial com Arduino"
# Iniciando conexao serial
comport = serial.Serial('/dev/ttyACM0', 115200)
#comport = serial.Serial('/dev/ttyUSB0', 115200)
LED_ON='l'
LED_OFF='d'
# Time entre a conexao serial e o tempo para escrever (enviar algo)
time.sleep(1.8) # Entre 1.5s ... | 19.821429 | 67 | 0.691892 | [
"MIT"
] | cleitonbueno/arduinoday | comunicacao_serial.py | 555 | Python |
#!/usr/bin/env python
# Copyright 2016 The Kubernetes 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 by appli... | 43.913462 | 98 | 0.657105 | [
"Apache-2.0"
] | justaugustus/test-infra | gubernator/main_test.py | 9,134 | Python |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (9, 9, 9):
def swig_im... | 36.4375 | 92 | 0.799528 | [
"MIT"
] | Jackintoshh/Web-Mapping | venv/Lib/site-packages/osgeo/gdalconst.py | 9,328 | Python |
import pandas as pd
from math import exp, log,sqrt
from numpy import cumsum,std,sum, mean
def outData(ts,actionHist,indx,startIndex=0):
out=pd.DataFrame(ts,index=indx,columns=['ts']).applymap(lambda x: x/100)
out=out[startIndex:]
out['cum_log_ts']=cumsum([log(1+i) for i in out['ts']])
out['Action_Hist'... | 33.333333 | 93 | 0.670526 | [
"BSD-3-Clause"
] | samstern/MSc-Project | pybrain/rl/environments/timeseries/performanceEvaluation.py | 1,900 | Python |
from enum import IntFlag, IntEnum
import numpy as np
from . import Base
from . import ByteIO
from .axis_interp_rule import AxisInterpRule
from .jiggle_bone import JiggleRule
from .quat_interp_bone import QuatInterpRule
from ....utils.math_utilities import quat_to_matrix
class BoneFlags(IntFlag):
# BONE_CALCULA... | 37.496241 | 88 | 0.6538 | [
"MIT"
] | anderlli0053/SourceIO | library/source1/mdl/structs/bone.py | 9,974 | Python |
"""
Core OpenBCI object for handling connections and samples from the WiFi Shield
Note that the LIB will take care on its own to print incoming ASCII messages if any (FIXME, BTW).
EXAMPLE USE:
def handle_sample(sample):
print(sample.channels_data)
wifi = OpenBCIWifi()
wifi.start(handle_sample)
TODO: Cyton/Gangli... | 39.516691 | 189 | 0.551585 | [
"MIT"
] | daniellasry/OpenBCI_Python | openbci/wifi.py | 27,227 | Python |
"""
Code for understanding type annotations.
This file contains functions that turn various representations of
Python type annotations into :class:`pyanalyze.value.Value` objects.
There are three major functions:
- :func:`type_from_runtime` takes a runtime Python object, for example
``type_from_value(int)`` -> ``... | 38.000818 | 88 | 0.636988 | [
"Apache-2.0"
] | nbdaaron/pyanalyze | pyanalyze/annotations.py | 46,475 | Python |
"""
Unittests for gpsdio load
"""
from click.testing import CliRunner
import gpsdio
import gpsdio.cli.main
def test_load(types_json_path, types_msg_gz_path, tmpdir, compare_msg):
pth = str(tmpdir.mkdir('test').join('test_load'))
with open(types_json_path) as f:
stdin_input = f.read()
result =... | 23.0625 | 81 | 0.639566 | [
"Apache-2.0"
] | GlobalFishingWatch/gpsdio | tests/test_cli_load.py | 738 | Python |
# -*- coding: utf-8 -*-
'''
Pillar data from vCenter or an ESXi host
.. versionadded:: 2017.7.0
:depends: - pyVmomi
This external pillar can pull attributes from objects in vCenter or an ESXi host and provide those attributes
as pillar data to minions. This can allow for pillar based targeting of minions on ESXi ho... | 36.734463 | 121 | 0.463396 | [
"Apache-2.0"
] | aaannz/salt-1 | salt/pillar/vmware_pillar.py | 19,506 | Python |
from .step import Step
from .step_0 import Step_0
from .step_1 import Step_1
from .step_vr_1 import Step_VR_1
from .step_vr_2 import Step_VR_2
from .step_vr_3 import Step_VR_3
from .step_vr_4 import Step_VR_4
from .step_vr_5 import Step_VR_5
from .step_vr_6 import Step_VR_6
from .step_vr_7 import Step_VR_7
from .step_v... | 29.944444 | 32 | 0.842301 | [
"MIT"
] | 8by8-org/usvotes | app/services/steps/__init__.py | 539 | Python |
import datetime
x = datetime.datetime.now()
print(x.strftime("%j"))
# Author: Bryan G
| 12.714286 | 27 | 0.685393 | [
"MIT"
] | Web-Dev-Collaborative/PYTHON_PRAC | mini-scripts/Python_Datetime_day_number_of_year.txt.py | 89 | Python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
from pyes.tests import ESTestCase
class IndexStatsTestCase(ESTestCase):
def setUp(self):
super(IndexStatsTestCase, self).setUp()
self.conn.indices.create_index(self.index_name)
self.conn.indices.put_mapping(self... | 46.55 | 120 | 0.664876 | [
"BSD-3-Clause"
] | aparo/pyes | tests/test_index_stats.py | 1,862 | Python |
from allennlp_models.generation.dataset_readers.copynet_seq2seq import CopyNetDatasetReader
from allennlp_models.generation.dataset_readers.seq2seq import Seq2SeqDatasetReader
from allennlp_models.generation.dataset_readers.cnn_dm import CNNDailyMailDatasetReader
| 66 | 91 | 0.920455 | [
"Apache-2.0"
] | DendiHust/allennlp-models | allennlp_models/generation/dataset_readers/__init__.py | 264 | Python |
import logging
logger = logging.getLogger(__name__)
from mykrobe.species_data import DataDir
def describe(parser, args):
args = parser.parse_args()
ddir = DataDir(args.panels_dir)
print(f"Gathering data from {ddir.root_dir}")
ddir.print_panels_summary()
def update_metadata(parser, args):
args = p... | 29.090909 | 75 | 0.683333 | [
"MIT"
] | Zhicheng-Liu/mykrobe | src/mykrobe/cmds/panels.py | 960 | Python |
from __future__ import unicode_literals, division, absolute_import
import logging
from flexget import plugin
from flexget.event import event
from flexget.entry import Entry
from flexget.utils.tools import group_entries
log = logging.getLogger('best_quality')
entry_actions = {
'accept': Entry.accept,
'reject'... | 33.933333 | 111 | 0.629175 | [
"MIT"
] | Daeymien/Flexget | flexget/plugins/filter/best_quality.py | 2,036 | Python |
import doctest
import pytest
from insights.parsers import lscpu, SkipException
from insights.tests import context_wrap
LSCPU_1 = """
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 2
On-line CPU(s) list: 0,1
Thread(s) per core: 2
Cor... | 27.206186 | 61 | 0.57105 | [
"Apache-2.0"
] | CodeHeeler/insights-core | insights/parsers/tests/test_lscpu.py | 2,639 | Python |
from mpp.models import SQLTestCase
from mpp.models import SQLConcurrencyTestCase
class HcatalogPrimitiveTypes(SQLConcurrencyTestCase):
"""
@product_version gpdb: [2.0-]
@db_name pxfautomation
@concurrency 1
@gpdiff True
"""
sql_dir = 'sql'
ans_dir = 'expected'
out_dir = 'output'
| 22.714286 | 53 | 0.694969 | [
"Apache-2.0"
] | ashuka24/pxf | automation/tincrepo/main/pxf/features/hcatalog/primitive_types/runTest.py | 318 | Python |
'''
Given one or more regular expressions on the command line, searches
the PATH for all files that match.
Copyright (C) 2002 GDS Software
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either vers... | 30.408163 | 78 | 0.624832 | [
"CC0-1.0"
] | raychorn/chrome_gui | vyperlogix/gds/where.py | 2,980 | Python |
import numpy as np
import pandas as pd
from shapely import prepared
from geopandas import GeoDataFrame
from geopandas import _compat as compat
from geopandas.array import _check_crs, _crs_mismatch_warn
def sjoin(
left_df, right_df, how="inner", op="intersects", lsuffix="left", rsuffix="right"
):
"""Spatial ... | 36.140625 | 84 | 0.590899 | [
"BSD-3-Clause"
] | anathnathphy67/geopandas | geopandas/tools/sjoin.py | 9,252 | Python |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | 44.825137 | 80 | 0.665464 | [
"Apache-2.0"
] | muarachmann/oppia | scripts/build_test.py | 41,015 | Python |
# 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 acc... | 40.143885 | 118 | 0.757706 | [
"Apache-2.0"
] | Chen188/aws-parallelcluster | tests/integration-tests/tests/dns/test_dns.py | 5,580 | Python |
import csv
import os
import numpy as np
dir_path = os.path.dirname(os.path.realpath(__file__))
survey_path = os.path.join(dir_path, '../data/test_two_entries.csv')
NUM_QUESTIONS = 8
RESPONSE_PERSON = ['pat', 'jeremy', 'zach']
TASTE_PROFILE_TYPES = ['deliciousness', 'heaviness', 'reliability', 'frequency', 'between']
... | 33.147059 | 95 | 0.658829 | [
"MIT"
] | zchuruk/sandwichbot | sandwichbot/survey_processor.py | 2,254 | Python |
# Copyright 2018 The TensorFlow 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 applica... | 35.579655 | 125 | 0.710579 | [
"MIT"
] | boristown/tpu | models/official/amoeba_net/amoeba_net.py | 18,537 | Python |
# Copyright (C) 2020-2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import csv
import os
import os.path as osp
from datumaro.components.annotation import (
AnnotationType, Bbox, Label, LabelCategories, Points,
)
from datumaro.components.converter import Converter
from datumaro.components.extractor import... | 43.41 | 86 | 0.522 | [
"MIT"
] | openvinotoolkit/datumaro | datumaro/plugins/vgg_face2_format.py | 13,023 | Python |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import argparse
from mo.graph.graph import Graph
from mo.pipeline.common import get_ir_version
from mo.utils import class_registration
def unified_pipeline(argv: argparse.Namespace):
graph = Graph(cmd_params=argv, name=argv.model_... | 31.85 | 89 | 0.78022 | [
"Apache-2.0"
] | AkillesAILimited/openvino | model-optimizer/mo/pipeline/unified.py | 637 | Python |
from pyFilter.py_filter import PyFilter
if __name__ == "__main__":
p = PyFilter()
try:
p.run()
except KeyboardInterrupt:
print("\nClosing PyFilter")
finally:
p.make_persistent(loop=False) # Save any outstanding bans without the constant loop
if p.settings["database"] ==... | 31.214286 | 92 | 0.647597 | [
"MIT"
] | Jason2605/PyFilter | run.py | 437 | Python |
import codecs
import json
from tqdm import tqdm
import copy
submit_result2 = []
with codecs.open('dialog_chinese-macbert.txt', mode='r', encoding='utf8') as f:
reader = f.readlines(f)
data_list = []
for dialogue_idx_, dialogue_ in enumerate(tqdm(reader)):
dialogue_ = json.loads(dialogue_)
submit_re... | 51.537815 | 268 | 0.612098 | [
"Apache-2.0"
] | DataArk/CHIP2021-Task1-Top1 | predict/ensemble.py | 6,187 | Python |
"""hvac init."""
| 8.5 | 16 | 0.470588 | [
"Apache-2.0"
] | jokajak/infinity_tracker | hvac/__init__.py | 17 | Python |
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10,3),columns=['a','b','c'],index=list('abcdefghij'))
print(df)
df.ix[::2,0] = np.nan; df.ix[::4,1] = np.nan; df.ix[::3,2] = np.nan;
df = df.dropna(subset=['a','b']) #mid delete rows where df['htm3']==na
bins = np.arange(-3,3,0.1)
bins = [-10... | 26.25 | 87 | 0.631746 | [
"MIT"
] | UpSea/midProjects | BasicOperations/05_Pandas/05_Pandas_02_groupby.py | 726 | Python |
"""All functions return a Component so you can easily pipe or compose them.
There are two types of functions:
- decorators: return the original component
- containers: return a new component
"""
from functools import lru_cache
import numpy as np
from omegaconf import OmegaConf
from pydantic import validate_argument... | 26.166667 | 88 | 0.676069 | [
"MIT"
] | jorgepadilla19/gdsfactory | gdsfactory/functions.py | 6,594 | Python |
#!/usr/bin/python3 -B
exec(open("../index.py").read())
from waitress import serve
serve(application, host='0.0.0.0', port=8080, threads=1, channel_timeout=1)
| 26.833333 | 76 | 0.695652 | [
"MIT"
] | shark555/websnake_demo | scripts/serve.py | 161 | Python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019/2/19 11:06
# @User : zhunishengrikuaile
# @File : TrainTicket.py
# @Email : binary@shujian.org
# @MyBlog : WWW.SHUJIAN.ORG
# @NetName : 書劍
# @Software: 百度识图Api封装
# 火车票识别
import os
import base64
import requests
from bin.AccessToken.AccessToken imp... | 28.019231 | 89 | 0.621139 | [
"Apache-2.0"
] | haodaohong/zimt8 | utils/BaiduTextApi/BaiduTextApi/bin/TrainTicket/TrainTicket.py | 1,509 | Python |
# Authors: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
# Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
from warnings import warn
from copy import deepcopy
import os.path as op
import numpy as np
from scipy import linalg
from ..externals.six import BytesIO
from datetime import da... | 34.535714 | 79 | 0.58414 | [
"BSD-3-Clause"
] | Anevar/mne-python | mne/fiff/meas_info.py | 21,274 | Python |
import ctypes
import pytest
c_lib = ctypes.CDLL('../solutions/0709-to-lower/to-lower.so')
@pytest.mark.parametrize('string, ans',
[(b"Hello", b"hello"),
(b"here", b"here"),
(b"LOVELY", b"lovely")])
def test_to_lower(string, ans):
c_lib.toLo... | 27.769231 | 61 | 0.542936 | [
"MIT"
] | msztylko/2020ify-leetcoding | tests/test_0709.py | 361 | Python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import numpy as np
import tensorflow as tf
from niftynet.layer.activation import ActiLayer
from niftynet.layer.convolution import ConvolutionalLayer
from niftynet.layer.deconvolution import DeconvolutionalLayer
from niftynet.laye... | 40.671937 | 81 | 0.558212 | [
"Apache-2.0"
] | LucasFidon/NiftyNet-RobustOptim | niftynet/network/simulator_gan.py | 10,290 | Python |
# Desafio 42 - Aula 12 : Refazer Desasfio 35 e mostrar qual o tipo do triangulo.
# A/ Equilatero.
# B/ Isósceles.
# C/ Escaleno.
print('\033[32mATENÇÃO! VAMOS MONTAR UM TRIÂNGULO!!!\033[m')
a = int(input('Digite a primeira medida: '))
b = int(input('Digite a segunda medida: '))
c = int(input('Digite a terceira medid... | 39.47619 | 104 | 0.659831 | [
"MIT"
] | duartecgustavo/Python---Estudos- | desafios/Mundo 2/Ex042.py | 842 | Python |
"""
pyAutoSpec
Spectral learning for WFA/MPS
"""
from .wfa import Wfa, SpectralLearning
from .mps import Mps
from .plots import parallel_plot
from .function_wfa import FunctionWfa
from .function_mps import FunctionMps
from .dataset_mps import DatasetMps
from .image_wfa import ImageWfa
__all__ = ["Wfa", "Mps", "paral... | 25.4375 | 117 | 0.77887 | [
"MIT"
] | lucamarx/pyAutoSpec | pyautospec/__init__.py | 407 | Python |
# -*- coding: utf-8 -*-
import sys
from os.path import dirname, abspath, normpath, join, realpath
from os import listdir, remove, system
import json
from datetime import datetime
begin = len(normpath(abspath(join(dirname(__file__), "../.."))))
end = len(normpath(abspath(join(dirname(__file__), ".."))))
MAIN_DIR = dir... | 34.888889 | 109 | 0.626654 | [
"Apache-2.0"
] | IrakozeFD/pyleecan | pyleecan/Generator/run_generate_classes.py | 4,082 | Python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Single NN
@author: xuping
"""
import numpy as np
import scipy.io
#from threeNN import sigmoid
def layer_sizes(X, Y):
n_in = X.shape[0]
n_out = Y.shape[0]
return(n_in, n_out)
def initialize_parameters(dim):
np.random.seed(3)
W = np.random.ran... | 24.260504 | 101 | 0.553516 | [
"MIT"
] | xupingxie/deep-learning-models | NN_buildingblock/SingleNN.py | 2,887 | Python |
import os
import math
import numpy as np
root_path = '/home/project/I3D/data/Kinetics/train_256'
num_frames = 16
data_list = []
id_list = []
label_list = []
erro_data = []
label = 0
id = 0
for file_path in sorted(os.listdir(root_path)):
for video_path in sorted(os.listdir(os.path.join(root_path, file_path))):
... | 28.111111 | 86 | 0.666996 | [
"Apache-2.0"
] | LossNAN/3D-Resnet-tensorflow | experiments/kinetics-400/data_list/gen_train_list.py | 1,012 | Python |
# the TestEnv environment is used to simply simulate the network
from flow.envs import TestEnv
# the Experiment class is used for running simulations
from flow.core.experiment import Experiment
# the base network class
from flow.networks import Network
from flow.envs.base import Env
# all other imports are standard
... | 37.053312 | 125 | 0.588158 | [
"Apache-2.0"
] | KarlRong/Safe-RL-for-Driving | traci_pedestrian_crossing/movexy_ped.py | 22,992 | Python |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 14:52:03 2020
@author: DELL
"""
import pandas as pd
data = pd.read_csv('http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip', encoding = 'ANSI')
res = data[data['ENTIDAD_RES'] == 31]
res.to_csv('data_yuc_actualizado.csv', index = False) | 19.8125 | 116 | 0.690852 | [
"MIT"
] | Luisbaduy97/COVID-YUCATAN | datos_yuc_actualizado.py | 317 | Python |
#!/usr/bin/env python
import unittest
from ct.proto import client_pb2
from ct.proto import test_message_pb2
from ct.serialization import tls_message
valid_test_message = test_message_pb2.TestMessage()
valid_test_message.uint_8 = 0
valid_test_message.uint_16 = 258
valid_test_message.uint_24 = 197637
valid_test_messa... | 39.521583 | 80 | 0.70638 | [
"Apache-2.0"
] | DavadDi/archon | vendor/github.com/google/certificate-transparency/python/ct/serialization/tls_message_test.py | 10,987 | Python |
class Solution:
def intToRoman(self, num: int) -> str:
romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
res = ''
for i in range(len(romans)):
while (num - values[i] >... | 31.615385 | 88 | 0.403893 | [
"MIT"
] | geemaple/algorithm | leetcode/12.integer-to-roman.py | 411 | Python |
__author__ = 'Eduardo Mendes'
__email__ = 'mendesxeduardo@gmail.com'
__version__ = '0'
| 21.75 | 38 | 0.758621 | [
"MIT"
] | dunossauro/qaninja-liveclass | qaclass-bdd/__init__.py | 87 | Python |
# coding: utf-8
import codecs
import re
import json
from budget2013_common import *
class Budget2013_37_SubTable1Item(object):
def __init__(self):
self._no = None
self._purpose = None
self._principal = None
self._value = None
self._regress = None
self._check = None
self._other = []
@property
def n... | 25.50591 | 137 | 0.700806 | [
"MIT"
] | capocannoniere/budget | federal/2013/code/budget2013_37.py | 10,833 | Python |
"""
Baseline CNN, losss function and metrics
Also customizes knowledge distillation (KD) loss function here
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
"""
This is t... | 40.058442 | 119 | 0.625385 | [
"MIT"
] | eungbean/knowledge-distillation-cifar10 | model/studentB.py | 6,169 | Python |
from typing import TypedDict
from cff.models.cloudfront_event import CloudFrontEvent
class Record(TypedDict):
"""Record of an event that raised a Lambda event."""
cf: CloudFrontEvent
"""The CloudFront event that raised this Lambda event."""
| 23.363636 | 61 | 0.747082 | [
"MIT"
] | cariad/cff | cff/models/record.py | 257 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.