text string | size int64 | token_count int64 |
|---|---|---|
import argparse
import pickle
import os
import numpy as np
#from parse_contig_realign import mark_edit_region, variant_link_graph, haplotyping_link_graph, output_contig_correction
from parse_contig_realign import variant_link_graph, output_contig_correction, parse_CIGAR, parse_MD, trim_dict, find_double_pos, get_farthe... | 20,359 | 6,431 |
import time
from contextlib import suppress, contextmanager
from astropy import units as u
from panoptes.utils import error
from panoptes.utils.utils import get_quantity_value
from panoptes.utils.time import current_time, wait_for_events, CountdownTimer
from panoptes.pocs.observatory import Observatory
from panoptes.... | 30,257 | 8,184 |
from django.conf.urls import url
from dist import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^add$', views.AddCategoryView.as_view(), name='add_category'),
url(r'^(?P<cat_id>\d+)/$', views.CategoryView.as_view(), name='category'),
]
| 285 | 105 |
# Copyright 2018 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 3,980 | 1,224 |
import cv2
import numpy
import time
import iir_filter
from scipy import signal
import math
import matplotlib.pylab as pl
# This program detects and measures the frequency of strobe lights
def main():
capture = cv2.VideoCapture(0)
prev_frame = None
point_light_threshold = 200
time_now = time.time()
... | 1,981 | 673 |
# Generated by Django 3.1.5 on 2021-01-10 04:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='descripton',
new... | 358 | 122 |
import numpy
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
INTMAX32 = 2147483647
if abs(x) > INTMAX32:
return 0
negative = False
if x < 0:
negative = True
x = abs(x)
str_x... | 687 | 241 |
"""A collection of performance-enhancing functions that have to know just a
little bit too much to go anywhere else.
"""
from dbt.adapters.factory import get_adapter
from dbt.parser.manifest import load_manifest
from dbt.contracts.graph.manifest import Manifest
from dbt.config import RuntimeConfig
def get_full_manife... | 917 | 252 |
import tensorflow as tf
from tensorflow.contrib import slim
from scipy import misc
import os, random
import numpy as np
from glob import glob
from keras.utils import np_utils
try:
import xml.etree.cElementTree as ET #解析xml的c语言版的模块
except ImportError:
import xml.etree.ElementTree as ET
class ImageData:
de... | 7,576 | 2,764 |
class PrivilegeNotHeldException(UnauthorizedAccessException):
"""
The exception that is thrown when a method in the System.Security.AccessControl namespace attempts to enable a privilege that it does not have.
PrivilegeNotHeldException()
PrivilegeNotHeldException(privilege: str)
PrivilegeNotHeldExcepti... | 1,812 | 560 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 11:30:05 2019
@author: Jongmin Sung
"""
# config.py
import os
from pathlib import Path
from inspect import currentframe, getframeinfo
fname = getframeinfo(currentframe()).filename # current file name
current_dir = Path(fname).resolve().parent
data_dir = Path(fna... | 367 | 135 |
from conans import ConanFile, tools
class HapplyConan(ConanFile):
name = "happly"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/nmwsharp/happly"
topics = ("conan", "happly", "ply", "3D")
license = "MIT"
description = "A C++ header-only parser for the PLY... | 968 | 324 |
api_key = "1be3b57d0592f2096543bc46ebf302f0"
| 48 | 39 |
import os,sys,logging,multiprocessing,Queue,traceback
logger = logging.getLogger(__name__)
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from balsam import models,BalsamJobReceiver,QueueMessage
from common import DirCleaner,log_uncaught_exceptions,TransitionJob
fro... | 8,798 | 2,357 |
from djitellopy import Tello
from time import sleep
# Initialize and Connect
tello = Tello()
tello.connect()
# Takeoff and move up to 6 feet (183cm)
tello.takeoff()
tello.move_up(101)
# Move forward (east) 5 feet (152cm)
tello.move_forward(152)
sleep(.5)
# rotate 90 degrees CCW
tello.rotate_counter_clockwise(90)
#... | 857 | 381 |
import cv2
import numpy as np
import math
# img = cv2.imread('/home/geesara/Pictures/bp8OO.jpg', 0)
# img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary
# ret, labels = cv2.connectedComponents(img)
#
# print("Number of labels" , len(labels))
#
# def imshow_components(labels):
# # Map componen... | 882 | 401 |
# Generated by Django 2.2 on 2019-10-11 17:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('review', '0002_auto_20191009_1119'),
]
operations = [
migrations.RenameField(
model_name='review',
old_name='is_deleted',
... | 369 | 139 |
# We can easily verify that none of the entries in the first seven
# rows of Pascal's triangle are divisible by 7:
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
# 1 5 10 10 5 1
# 1 6 15 20 15 6 1
# Howeve... | 556 | 185 |
from random import shuffle
__author__ = 'Junior Teudjio'
def quick_select(l, k, find_largest=True):
"""
return the k_th largest/smallest element of list l
Parameters
----------
l : list
k : int
find_largest : Boolean
True if return the k_th largest element False if return the k-t... | 2,056 | 674 |
# -*- coding: utf-8 -*-
'''
这个来源于 udacity 的讲座
验证基础的概念和算法
'''
from grid_world import *
import sys
#from PyQt5.QtCore import QPoint, QRect, QSize, Qt
#from PyQt5.QtGui import (QBrush, QPainter, QColor, QPen )
#from PyQt5.QtWidgets import (QApplication, QPushButton, QCheckBox, QGridLayout,QLabel, QWidg... | 6,895 | 2,585 |
# -*- coding: utf-8 -*-
import os
import pytest
from simmate.conftest import copy_test_files
from simmate.calculators.vasp.inputs import Incar
from simmate.calculators.vasp.error_handlers import LargeSigma
def test_large_sigma(tmpdir):
copy_test_files(
tmpdir,
test_directory=__file__,
t... | 1,711 | 607 |
import math
import random
from PIL import Image
import cairo
from wyggles import Dna
PI = math.pi
RADIUS = 32
WIDTH = RADIUS
HEIGHT = RADIUS
class WyggleDna(Dna):
def __init__(self, klass):
super().__init__(klass)
name = self.name
r = random.uniform(0, .75)
r1 = r + .20
r... | 3,043 | 1,299 |
#!/usr/bin/python3
from tools import *
from sys import argv
from os.path import join
import h5py
import matplotlib.pylab as plt
from matplotlib.patches import Wedge
import numpy as np
if len(argv) > 1:
pathToSimFolder = argv[1]
else:
pathToSimFolder = "../data/"
parameters, electrodes = readParameters(pathT... | 17,847 | 5,126 |
"""Views for Django Rest Framework Session Endpoint extension."""
from django.contrib.auth import login, logout
from rest_framework import parsers, renderers
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
cla... | 1,187 | 313 |
import os
import time
from concurrent.futures import ThreadPoolExecutor
from enum import Enum
from hashlib import sha256
from typing import List, Type
import genshinstats as gs
from cachetools import TTLCache
from fastapi import Depends, FastAPI, HTTPException, Path, Query, Request
from fastapi.responses import JSONRe... | 4,348 | 1,519 |
import pytest
import stweet as st
from tests.test_util import get_temp_test_file_name, get_tweets_to_tweet_output_test, \
two_lists_assert_equal
def test_csv_serialization():
csv_filename = get_temp_test_file_name('csv')
tweets_collector = st.CollectorTweetOutput()
get_tweets_to_tweet_output_test([
... | 940 | 349 |
#
from mypy.physics import constants
def averageVelocity(positionEquation, startTime, endTime):
"""
The position equation is in the form of a one variable lambda and the
averagevelocity=(changeinposition)/(timeelapsed)
"""
startTime=float(startTime)
endTime=float(endTime)
vAvg=(positionEquation(star... | 391 | 125 |
def segmented_sieve(n):
# Create an boolean array with all values True
primes = [True]*n
for p in range(2,n):
#If prime[p] is True,it is a prime and its multiples are not prime
if primes[p]:
for i in range(2*p,n,p):
# Mark every multiple of a prime as not prim... | 690 | 215 |
# coding=utf-8
"""
Setup for scikit-surgerytf
"""
from setuptools import setup, find_packages
import versioneer
# Get the long description
with open('README.rst') as f:
long_description = f.read()
setup(
name='scikit-surgerytf',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
... | 2,003 | 653 |
# Fonte: https://leetcode.com/problems/string-to-integer-atoi/
# Autor: Bruno Harlis
# Data: 03/08/2021
"""
Implemente a função myAtoi(string s), que converte uma string em um
inteiro assinado de 32 bits (semelhante à função C / C ++ atoi).
O algoritmo para myAtoi(string s) é o seguinte:
Leia e ignore qualquer espaç... | 2,155 | 811 |
# coding: utf-8
"""
2018-03-19.
Maximum screenshots in 1 second by computing BGRA raw values to RGB.
GNU/Linux
pil_frombytes 139
mss_rgb 119
pil_frombytes_rgb 51
numpy_flip 31
numpy_slice 29
macOS
pil_frombytes 209
mss_rgb 174
pil_frombytes_rgb 113
numpy_fl... | 1,547 | 573 |
# Generated by Django 3.2.7 on 2021-09-25 05:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app1', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='author',
name='date_of_birth',
),
... | 431 | 145 |
# Copyright 2017 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.
# pylint: disable=no-member,relative-import
"""Unit tests for blink_idl_parser.py."""
import unittest
from blink_idl_parser import BlinkIDLParser
class B... | 672 | 210 |
import calc
def caesar_cipher(word, base):
up_alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
low_alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x... | 1,705 | 627 |
from dataclasses import dataclass
from typing import Any, Generic, TypeVar
from typing_extensions import Protocol
TComparable = TypeVar("TComparable", contravariant=True)
class Comparable(Protocol[TComparable]):
"""
Defines the protocol for comparable objects. Objects that satisfy this
protocol are ass... | 2,142 | 591 |
import neural_renderer as nr
from ..math.unitvec import *
class Renderer(nr.Renderer):
"""
A class extending the Neural Renderer
Attributes
----------
device : str or torch.device (optional)
the tensor the renderer will be stored to (default is 'cuda:0')
culling : str (optional)
... | 2,725 | 788 |
import copy
from datetime import datetime
from typing import List, Tuple
from .store2db import createTabels, store_data_2_db
from .GameUr import GameUr
from .GameSettings import GameSettings
import multiprocessing as mp
import tqdm
def getThreadCount()->int:
return mp.cpu_count()
def runGameNTimes(n: int, gs: ... | 6,241 | 2,223 |
import setuptools
setuptools.setup(
name="aioregex",
version="0.1",
author="Wirtos_new",
author_email="Wirtos.new@gmail.com",
description="regex to allow both sync and async callables in the sub as repl",
url="https://wirtos.github.io/aioregex/",
packages=setuptools.find_packages(),
pro... | 641 | 213 |
"""
Allows easy loading of pixmaps used in UI elements.
Provides support for frozen environments as well.
"""
import os, sys, pickle
from ..functions import makeQImage
from ..Qt import QtGui
from ..python2_3 import basestring
if sys.version_info[0] == 2:
from . import pixmapData_2 as pixmapData
else:
... | 830 | 296 |
from statistics import mean
from typing import Dict, List, Optional, Set
from collections import defaultdict
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.nn.util import get_lengths_from_binary_sequence_mask
from allennlp.data.vocabulary import Vocabulary
from allennlp.training.metr... | 7,920 | 2,271 |
def test_test():
"""A generic test
:return:
"""
assert True
| 78 | 27 |
# -*- encoding: utf-8 -*-
# Importação das bibliotecas necessárias.
import mysql.connector
import datetime
# Configuração da conexão.
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="teste"
)
# Variável que executará as operações.
cursor = connection.cursor(... | 833 | 293 |
# Unit Tests for the Enum Combo Box
import pytest
from logging import ERROR
from qtpy.QtCore import Slot, Qt
from ...widgets.enum_combo_box import PyDMEnumComboBox
from ... import data_plugins
# --------------------
# POSITIVE TEST CASES
# --------------------
def test_construct(qtbot):
"""
Test the const... | 10,814 | 3,329 |
import os
import random
import argparse
import multiprocessing
import numpy as np
import torch
from torchvision import models, transforms
from torch.utils.data import DataLoader, Dataset
from pathlib import Path
from PIL import Image
from utils import Bar, config, mkdir_p, AverageMeter
from datetime import datetime
fro... | 7,421 | 2,322 |
class AuxPowMixin(object):
AUXPOW_START_HEIGHT = 0
AUXPOW_CHAIN_ID = 0x0001
BLOCK_VERSION_AUXPOW_BIT = 0
@classmethod
def is_auxpow_active(cls, header) -> bool:
height_allows_auxpow = header['block_height'] >= cls.AUXPOW_START_HEIGHT
version_allows_auxpow = header['version'] & cls.B... | 406 | 164 |
from sys import stdin
a,b = [int(x) for x in stdin.readline().split(' ')]
diff = abs(a-b) +1
a = min(a,b) +1
print(a)
for x in range(1,diff):
print(a+x)
| 159 | 77 |
import os
class Cajero:
def __init__(self):
self.continuar = True
self.monto = 5000
self.menu()
def contraseña(self):
contador = 1
while contador <= 3:
x = int(input("ingrese su contraseña:" ))
if x == 5467:
print("Contraseña ... | 2,338 | 697 |
from threading import Thread, enumerate
from random import choice
from time import sleep as slp
from time import time as tiime
from os import mkdir, getcwd, path as pth
from subprocess import run as run_
from math import ceil
from traceback import format_exc
from sys import exit
import logging, json, ctypes
from ppadb... | 77,732 | 22,353 |
#!/usr/bin/env python3
#filter sensitive words in user's input
def replace_sensitive_words(input_word):
s_words = []
with open('filtered_words','r') as f:
line = f.readline()
while line != '':
s_words.append(line.strip())
line = f.readline()
for word in s_words:
... | 548 | 176 |
from builtins import super
from moceansdk.modules.command.mc_object import AbstractMc
class TgRequestContact(AbstractMc):
def __init__(self, param=None):
super().__init__(param)
self.set_button_text('Share button')
def action(self):
return 'send-telegram'
def required_key(self):... | 1,172 | 362 |
"""Test the execute method of the synchronous backend."""
import os
import shutil
import time
import unittest
from vizier.datastore.fs.factory import FileSystemDatastoreFactory
from vizier.engine.backend.multiprocess import MultiProcessBackend
from vizier.engine.controller import WorkflowController
from vizier.engine... | 5,418 | 1,566 |
from time import sleep
from random import random, uniform
from OMDM import Evolution
"""
Run the model optimization program we're creating from this script.
"""
hyper_parameters = {
"number_of_generations": 10,
"genome_length": 6,
"mutation_probability": 0.2,
... | 1,496 | 467 |
#-----
# Description : Import classes/functions from subfolders
# Date : February 2021
# Author : Berkan Lafci
# E-mail : lafciberkan@gmail.com
#-----
# package version
__version__ = "1.0.0"
# oa recon codes
from pyoat.reconstruction import cpuBP, cpuMB, modelOA
# data readers
from pyoat.rea... | 688 | 220 |
from game.globals import *
from game.lib import load_sprite_sheet
import pygame, random
class Cactus(pygame.sprite.Sprite):
def __init__(self, speed = 5, sizeX = -1, sizeY = -1):
pygame.sprite.Sprite.__init__(self, self.containers)
self.images, self.rect = load_sprite_sheet('cacti-small.png', 3, 1, sizeX, si... | 680 | 266 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... | 15,624 | 5,164 |
"""
contains microservice KeyValueStorage
"""
import uuid as _uuid
from fdrtd.server.microservice import Microservice
class KeyValueStorage(Microservice):
"""stores and retrieves values by key"""
def __init__(self, bus, endpoint):
super().__init__(bus, endpoint)
self.storages = {'default': ... | 1,396 | 386 |
import pytest
from requisitor.session import Session
def test_client_cert_auth(mocker):
conn = mocker.patch('http.client.HTTPSConnection',
side_effect=RuntimeError)
s = Session()
with pytest.raises(RuntimeError):
s.request('GET', 'https://foo.bar', cert=('cert', 'key'))
... | 739 | 239 |
class Solution:
def XXX(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)-1
# 找到第一个大于或等于target的位置
while l<r:
m = (l+r) // 2
if nums[m] >= target:
r = m
else:
l = m + 1
if nums[r] >= target:
... | 370 | 137 |
#!/usr/bin/python
import elasticsearch
from elasticsearch_dsl import Search, A, Q
#import logging
import sys
import os
#logging.basicConfig(level=logging.WARN)
#es = elasticsearch.Elasticsearch(
# ['https://gracc.opensciencegrid.org/q'],
# timeout=300, use_ssl=True, verify_certs=False)
es = elasticsea... | 1,773 | 681 |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/create_folds.ipynb (unless otherwise specified).
__all__ = ['df', 'df', 'y', 'kf', 'df', 'y']
# Cell
import os
import pandas as pd
from sklearn.model_selection import StratifiedKFold
# Cell
df = pd.read_csv(os.path.join('../data', 'en_task_a', 'hasoc_2020_en_train_new... | 849 | 373 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | 6,976 | 1,910 |
"""pycstruct definitions
Copyright 2021 by Joel Midstjärna.
All rights reserved.
This file is part of the pycstruct python library and is
released under the "MIT License Agreement". Please see the LICENSE
file that should have been included as part of this package.
"""
# pylint: disable=too-many-lines, protected-acce... | 55,075 | 14,408 |
import huckelpy
from huckelpy import file_io
class ExtendedHuckel:
def __init__(self, geometry, charge=0):
self._EH = huckelpy.ExtendedHuckel(geometry.get_positions(), geometry.get_symbols(), charge=charge)
self._alpha_electrons = None
self._beta_electrons = None
self._total_elect... | 1,103 | 380 |
#Faça um algoritimo que leia o preço de um produto e mostre o seu novo preço com 5% de desconto.
price = float(input("Digite o preço do produto: "))
sale = price - (price * 0.05)
print("O valor bruto do produto é: {:.2f}R$.".format(price))
print("Com o desconto de 5%: {:.2f}R$".format(sale)) | 293 | 122 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.bcdeter import bcdeter
def test_bcdeter():
"""Test module bcdeter.py by downloading
bcdeter.csv and testing shape of
extracted data has 95... | 514 | 173 |
from .request import *
from .response import *
| 47 | 13 |
import logging
import math
import os.path
import re
import annoy
import numpy as np
from gensim.models import KeyedVectors
from gensim.utils import to_unicode
from smart_open import smart_open
from .utils import NP_FLOAT
def from_mikolov(lang, inpath, outpath):
if not os.path.isdir(outpath): os.makedirs(outpath)... | 4,900 | 1,635 |
import math
import torch
import unittest
import gpytorch
import numpy as np
from torch.autograd import Variable
from gpytorch.utils import approx_equal, function_factory
from gpytorch.lazy import NonLazyVariable
_exact_gp_mll_class = function_factory.exact_gp_mll_factory()
class TestFunctionFactory(unittest.TestCas... | 13,819 | 5,507 |
# SPDX-License-Identifier: BSD-2-Clause-Patent
# SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md)
# This code is subject to the terms of the BSD+Patent license.
# See LICENSE file for more details.
from .prplmesh_base_test import PrplMeshBaseTest
from boardfarm.exceptions import SkipTest
from ca... | 5,016 | 1,692 |
#Calcular el salario neto de un tnrabajador en fucion del numero de horas trabajadas, el precio de la hora
#y el descuento fijo al sueldo base por concepto de impuestos del 20%
horas = float(input("Ingrese el numero de horas trabajadas: "))
precio_hora = float(input("Ingrese el precio por hora trabajada: "))
sueldo_ba... | 709 | 266 |
__source__ = 'https://github.com/kamyu104/LeetCode/blob/master/Python/battleships-in-a-board.py'
# Time: O(m * n)
# Space: O(1)
#
#
# Description: 419. Battleships in a Board
#
# Given an 2D board, count how many different battleships are in it.
# The battleships are represented with 'X's, empty slots are represented ... | 3,189 | 1,068 |
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import message_filters
import cv2
import torch
import torchvision.transforms as transforms
from exps.stage3_root2.config import cfg
# from demo import process_video
from model.main_model.smap import SMAP
from model.refine_model.refinenet imp... | 8,823 | 3,283 |
from typing import Dict
import correct_spellings
import epub_handling
import xml_handling
import argparse
import string
import re
# ---------------------------------------------------------------------------------------------------
def correct_file_contents(corrections : Dict[str, str], file_contents : str):
file... | 3,176 | 962 |
import cv2
import pickle
import numpy as np
from flag import Flag
flag = Flag()
with open('assets/colors.h5', 'rb') as f:
colors = pickle.loads(f.read())
with open('label.txt', 'r') as f:
classes = f.readlines()
def detector(image, label):
image = np.asarray(image * 255., np.uint8)
image = cv2.cvtCo... | 2,119 | 849 |
import retrieve
import validation
from time_functions import time_delay
from selenium.webdriver import ActionChains
def like_pic(browser):
heart = retrieve.like_button(browser)
time_delay()
if validation.already_liked(heart):
heart.click()
def like_pic_in_feed(browser, number = 1):
loop = 1
wh... | 760 | 239 |
#! /usr/bin/env python
import matplotlib.colors as mc
import numpy as np
import re
class Palette(object):
black = "#000000"
white = "#ffffff"
blue = "#73cef4"
green = "#bdffbf"
orange = "#ffa500"
purple = "#af00ff"
red = "#ff6666"
yellow = "#ffffa0"
@staticmethod
def _is_hex... | 1,261 | 489 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":synopsis: Implements :mod:`itertools` for older versions of Python.
:module: mom.itertools
:copyright: 2010-2011 by Daniel Neuhäuser
:license: BSD, PSF
Borrowed from brownie.itools.
"""
from __future__ import absolute_import
import itertools
from mom import builtins... | 8,941 | 2,710 |
# this is the three dimensional configuration space for rrt
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yue qi
"""
import numpy as np
# from utils3D import OBB2AABB
def R_matrix(z_angle,y_angle,x_angle):
# s angle: row; y angle: pitch; z angle: yaw
# generate rotation matrix in SO3
... | 6,377 | 2,892 |
from context import ascii_magic
try:
output = ascii_magic.from_url('https://wow.zamimg.com/uploads/blog/images/20516-afterlives-ardenweald-4k-desktop-wallpapers.jpg')
ascii_magic.to_terminal(output)
except OSError as e:
print(f'Could not load the image, server said: {e.code} {e.msg}') | 289 | 118 |
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import time
class Film(object):
"""docstring for film"""
def __init__(self):
self.title = ""
self.rank = ""
self.year_of_production = ""
self.link = ""
def create_phantom_driver():
driver = webdriver.PhantomJS(executable_path = ... | 2,706 | 1,123 |
"""
MCP3008 analog to digital converter
"""
import logging
from typing import cast
from mqtt_io.types import ConfigType, SensorValueType
from . import GenericSensor
REQUIREMENTS = ("adafruit-mcp3008",)
CONFIG_SCHEMA = {
"spi_port": dict(type="integer", required=False, empty=False, default=0),
"spi_device":... | 1,409 | 489 |
"""
Worklist model classes
"""
# AristaFlow REST Libraries
from af_worklist_manager.models.qualified_agent import QualifiedAgent
from af_worklist_manager.models.worklist_revision import WorklistRevision
from af_worklist_manager.models.worklist_update_configuration import WorklistUpdateConfiguration
class Worklist(obj... | 1,031 | 298 |
# NLP written by GAMS Convert at 04/21/18 13:51:02
#
# Equation counts
# Total E G L N X C B
# 3 2 0 1 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | 163,982 | 114,192 |
#!/usr/bin/env python3
from glob import glob
import pandas as pd
import os
import gzip
import sys
path_to_vcf_files = sys.argv[1]
true_variants = sys.argv[2]
vcf_files = glob(path_to_vcf_files + "/*tp-base.vcf")
print(vcf_files)
all_variants = []
summary = {}
## Build master list of True Variants
with gzip.open(true... | 1,304 | 418 |
#!/usr/bin/env python3
"""
Apple EFI Package
Apple EFI Package Extractor
Copyright (C) 2019-2021 Plato Mavropoulos
"""
print('Apple EFI Package Extractor v2.0_Linux_a1')
import os
import sys
import zlib
import shutil
import subprocess
if len(sys.argv) >= 2 :
pkg = sys.argv[1:]
else :
pkg = []
in_path = input('\n... | 3,448 | 1,482 |
# -*- coding: utf-8 -*-
# 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 version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | 3,344 | 1,238 |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 4,264 | 1,257 |
import numpy as np
def group_stats(y, w, groups):
uts = list()
nts = list()
nc = (w == 0).sum()
if nc == 0:
yc = 0
else:
yc = y[w == 0].mean()
for group in groups:
ng = (w == group).sum()
if ng == 0:
uts.append(-yc)
else:
uts.ap... | 414 | 166 |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00c_annotation_types.ipynb (unless otherwise specified).
__all__ = []
# Internal Cell
from pathlib import Path
from collections.abc import MutableMapping
from typing import Dict, Optional, Iterable, Any, Union
from ipywidgets import Layout
from ..mltypes import OutputIm... | 3,958 | 1,137 |
import optapy
import optapy.score
import optapy.config
import optapy.constraint
@optapy.planning_entity
class InverseRelationEntity:
def __init__(self, code, value=None):
self.code = code
self.value = value
@optapy.planning_variable(object, ['value_range'])
def get_value(self):
re... | 3,001 | 894 |
import datetime
import uuid
from pizza_store.enums.role import Role
from pydantic import BaseModel
class UserBase(BaseModel):
username: str
email: str
class UserCreate(UserBase):
"""User register model"""
password: str
class UserIn(BaseModel):
"""User login model."""
username: str
p... | 714 | 235 |
# Copyright (c) 2022 Tulir Asokan, Sumner Evans
#
# 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/.
from typing import Any
from attr import dataclass
import attr
from ..... | 874 | 261 |
class Runtime:
@staticmethod
def v3(major: str, feature: str, ml_type: str = None, scala_version: str = "2.12"):
if ml_type and ml_type.lower() not in ["cpu", "gpu"]:
raise ValueError('"ml_type" can only be "cpu" or "gpu"!')
return "".join(
[
f"{major}.",
... | 885 | 285 |
from dvc.scheme import Schemes
from .base import PathCloudBASE
class PathS3(PathCloudBASE):
scheme = Schemes.S3
| 118 | 40 |
#! /usr/bin/env/ python
# filter out CA distances with large minimum
# filter out CA distances with small standard deviations
# save to file for later use
# will plot distances used
import mdtraj as md
import pyemma.coordinates as coor
import numpy as np
import pickle
from util.plot_structure_util import plot_vmd_cyli... | 2,729 | 1,165 |
"""
Methods for the connector application to convert and sync content to the target endpoint
Start with this template to implement these methods for the connector application
"""
# Standard Library Imports
import json
import logging
import os
# Third party
import requests
# Global constants
DIR = os.path.dirname(os... | 4,206 | 1,258 |
# script for daily update
from bs4 import BeautifulSoup
# from urllib.request import urlopen
import requests
import csv
import time
from datetime import datetime, timedelta
import os
from pathlib import Path
from dashboard.models import Case, Country, District, State, Zone
def run():
scrapeStateStats()
def scrapeC... | 6,255 | 2,658 |
import numpy as np
from keras.layers import Concatenate, Input, Dense, Reshape, Flatten, Dropout, multiply, \
BatchNormalization, Activation, Embedding, ZeroPadding2D, Conv2DTranspose
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.mode... | 9,022 | 2,953 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 14 21:19:42 2017
@author: ubuntu
"""
import numpy as np
from numpy import cross,dot
from numpy.linalg import norm
import pandas as pd
import os
def read_ndi_data(mydir, file_name,sensors,subcolumns):
'''
Read data produced by NDI WaveFront ... | 9,704 | 3,132 |
from __future__ import print_function, absolute_import, division
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as UnitTest
import KratosMultiphysics.ConvectionDiffusionApplication as ConvectionDiffusionApplication
class ApplyThermalFaceProcessTest(UnitTest.TestCase):
def runTest(self):
... | 2,879 | 927 |