content stringlengths 5 1.05M |
|---|
"""
key_krumhansl.py
Key analysis: Basic Krumhansl
"""
import music21
from leadreader.analyses.base import BaseAnalysis
class KeyKrumhansl(BaseAnalysis):
"""
http://web.mit.edu/music21/doc/moduleReference/moduleAnalysisDiscrete.html
"""
def name(self):
return 'key_krumhansl'
def descript... |
#!/usr/bin/env python
#-------------------------------------------------------
# Translates between lat/long and the slippy-map tile
# numbering scheme
#
# http://wiki.openstreetmap.org/index.php/Slippy_map_tilenames
#
# Written by Oliver White, 2007
# This file is public-domain
#-------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# test_unique_id.py
"""Tests the unique_id function of mop_tinyDB."""
def test_return_unique_id(db_with_3_mops):
"""Test unique_id() returns correct id.""" # noqa
db = db_with_3_mops
new_id = db.unique_id()
assert new_id == 4 # nosec
|
import numpy as np
from lib.explainers import (
get_n_best_features
)
def test_get_n_best_features():
global_shaps = np.array([0.1, 0.5, 1, 7, 8])
n = 5
assert get_n_best_features(n, global_shaps) == [4, 3, 2, 1, 0]
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os, time, datetime, re, argparse, textwrap, subprocess
from datetime import date, timedelta
from time import mktime
from os.path import expanduser
import shutil
from distutils.dir_util import copy_tree
import json
import glob
import codecs
import fnmatch
impo... |
#!/usr/bin/python
import socket
import fcntl
import struct
import os
def hosts():
"slcli"
slcli = "slcli vs list | awk '{ print $3 }' > ./ip-hosts.txt"
os.system(slcli)
return
hosts()
with open( "./ip-hosts.txt", 'r') as fin:
print fin.read()
|
from django.conf import settings
from social_django.models import UserSocialAuth
def append_social_info_to_context(request):
return_content = {}
try:
user = request.user
except:
user = None
try:
return_content["GITHUB_LOGIN"] = user.social_auth.get(provider="github")
exce... |
import os
import numpy as np
import subprocess
from deepethogram import utils
from setup_data import get_testing_directory
testing_directory = get_testing_directory()
config_path = os.path.join(testing_directory, 'project_config.yaml')
BATCH_SIZE = 4 # small but not too small
# if less than 10, might have bugs with ... |
# coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team and Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... |
"""
Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).
Note: is considered to be an even index.
"""
import sys
if __name__=="__main__":
string_list=[]
T=int(raw_input())
... |
# coding: utf-8
"""
IOInterfaceTypeData.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are m... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import hashlib
import json
import datetime
import pandas as pd
import os
import numpy as np
from CountingGridsPy.models import CountingGridModel
import traceback
from browseCloudServiceAuthorizer import BrowseCloudServiceAuth... |
# encoding: utf-8
r"""
A full summary of all nodes.
+---------------------+--------------------+----------------+------------------------------+
| Name | Children | Example | Description |
+=====================+====================+================+===================... |
"""
These test cases can be used to test-drive a solution to the diamond kata, in an incremental manner.
to run the tests, use 'py.test' - see http://pytest.org
Instructions:
1. Make the first test case for Diamond A pass
2. change the 'ignore_' to 'test_' for the next test case. Make it pass.
3. Uncomment the next l... |
import numpy as np
import os
import sys
import time
import platform
import pyvisa.errors as VisaError
from visa import constants
path = os.path.realpath('../')
if not path in sys.path:
sys.path.insert(0, path)
from pyDecorators import InOut, ChangeState, Catch
try:
import visa
except Exception as e:
prin... |
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
if 0 <= x < 10:
return True
if x%10 == 0:
return False
recv = 0
while recv < x:
p = x % 10
x = int(x / 10)
recv = recv * 10 + p
... |
from collections import OrderedDict
from math import log2, ceil
def get_data_types(data):
"""
returns a dictionary with column names and their respective data types
:param pandas.DataFrame data: a dataframe
:rtype: dict[str,str]
"""
dtypes = data.dtypes
return OrderedDict(zip(dtypes.index, dtypes.astype(str)))
... |
import scripts.clausecat.clausecat_component
import scripts.clausecat.clause_segmentation
import scripts.clausecat.clausecat_reader
import scripts.clausecat.clausecat_model
import scripts.clausecat.clause_aggregation
import benepar
|
from pathlib import Path
def read(filename='in'):
file_path = Path(__file__).parent / filename
with file_path.open('r') as file:
return read_lines(file.readlines())
def read_lines(lines):
passports = []
passport = {}
for line in lines:
if not line.strip():
passports.a... |
#coding=utf-8
from dirbot.items import User
from user import UserSpider
from scrapy import Request, Selector
from urlparse import urlparse, parse_qs
import logging
import json
class UserFanSpider(UserSpider):
"""Docstring for UserSpider. """
name = 'user_fan'# 命名规则 user_{从哪种渠道获得的用户名称}
def query_some_re... |
'''Test warnings replacement w PyShell.py oraz run.py.
This file could be expanded to include traceback overrides
(in same two modules). If so, change name.
Revise jeżeli output destination changes (http://bugs.python.org/issue18318).
Make sure warnings module jest left unaltered (http://bugs.python.org/issue18081).
'... |
from typing import Tuple
import os
def validate_update_todo(todo_path: str, todo_name: str, todo_file_name: str) -> Tuple[bool, str]:
"""
TODOファイルの名前を更新する際に実行するチェック関数
Parameters
----------
todo_path: str
todo_name: str
todo_file_name: str
Returns
-------
is_validate, error_m... |
import clipboard
from twisted.internet import task
class Clipboard(object):
def __init__(self, clipboard, clipboard_polling_interval=1.0):
self._clipboard = clipboard
self._clipboard_callbacks = []
self._last_clipboard_value_on_poll = self.value
self._polling_is_active = False
... |
from __future__ import absolute_import
from widgy.contrib.review_queue.site import ReviewedWidgySite
class DemoWidgySite(ReviewedWidgySite):
pass
widgy_site = DemoWidgySite()
|
import logging
from typing import Dict, List, Any
from mlflow import pyfunc
class PyFuncEnsemblerRunner:
"""
PyFunc ensembler runner used for real-time outputs
"""
def __init__(self, artifact_dir: str):
self.artifact_dir = artifact_dir
self._ensembler = None
def load(self):
... |
import os
from a_d.ny_AD import detect as nyImDetect
from a_d.absZ_AD_1 import detect as absZDetect
from a_d.phase_AD_1 import detect as phaseDetect
from data_processor.GOA_preprocessor.goa_data_wrapper import load_Lai_EIS_data
from IS.IS import IS_0
from goa.integration.goa_intergration import goa_fitter_1
from playg... |
from pygarl.data_readers import SerialDataReader
from pygarl.mocks import VerboseTestSampleManager
# This example uses a SerialDataReader to read data from a serial port
# and uses a VerboseTestSampleManager to print the received data and signals
def run_example(*args, **kwargs):
# Create the SerialDataReader
... |
#! /usr/bin/env python3
import argparse
from contextlib import contextmanager, closing
import os
import sys
import tempfile
import pysam
import pbio.misc.parallel as parallel
import pbio.misc.shell_utils as shell_utils
import pbio.misc.slurm as slurm
import logging
import pbio.misc.logging_utils as logging_utils
l... |
#!/usr/bin/env python
import codecs
import fnmatch
import os
import subprocess
import sys
import tarfile
import unicodedata
import pandas
import progressbar
from sox import Transformer
from tensorflow.python.platform import gfile
from deepspeech_training.util.downloader import maybe_download
SAMPLE_RATE = 16000
de... |
#!/usr/bin/env python
# coding: utf-8
OR_train_data = [[0,0,0], [0,1,1], [1,0,1], [1,1,1]]
AND_train_data = [[0,0,0], [0,1,0], [1,0,0], [1,1,1]]
NOR_train_data = [[0,0,1], [0,1,0], [1,0,0], [1,1,0]]
NAND_train_data = [[0,0,1], [0,1,1], [1,0,1], [1,1,0]]
w1 = 0.5
w2 = 0.2
b = -2
eta = 0.7
for epoch in range(1, 10):
... |
#!/usr/bin/python3
r'''Tests special-case projection functions
Simple things like project_lonlat(), project_stereographic(), etc.
I do 3 things:
Here I make sure the projection functions return the correct values. This is a
regression test, so the "right" values were recorded at some point, and any
deviation is fla... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^create/$', views.MediaCreateAPIView.as_view(), name='create'),
url(r'^$', views.MediaListAPIView.as_view(), name='list'),
# url(r'^(?P<pk>\d+)$', views.WitnessRetrieveAPIView.as_view(), name='detail'),
]
|
def matcher(text, term, label):
# Find occurences of a string pattern in a larger string.
index = 0
matches = []
while True:
index = text.find(term, index + 1)
matches.append((index, index + len(term), label))
if index == -1:
break
return matches[:-1]
def updat... |
# Generated by Django 4.0 on 2021-12-22 15:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0007_remove_posts_file_remove_posts_user_post_and_more'),
('comments', '0004_alter_comments_post'),
]
operations = [
migrations.Delet... |
__author__ = 'yue'
import unittest
import frequency_map as fmap
class TestFrequencyMap(unittest.TestCase):
def test_ctor(self):
fm = fmap.FrequencyMap('aaabbc')
self.assertEqual(3, fm.dictionary['a'])
self.assertEqual(2, fm.dictionary['b'])
self.assertEqual(1, fm.dictionary['c']... |
import torch.nn as nn
import torch.nn.functional as F
from models.modules.super_resolution_modules.FSR_modules import res_block
class Bottleneck(nn.Module):
expansion = 2
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchN... |
import os
from itertools import combinations
from IPython import embed
import doanet_parameters
params = doanet_parameters.get_params()
final_data_size_multiplier = 4
fold_list = [3, 4, 5, 6]
wav_path = os.path.join(params['dataset_dir'], '{}_{}'.format(params['dataset'], params['mode']))
meta_path = os.path.join(pa... |
import numpy as np
__all__ = ["AFMSegment"]
class AFMSegment(object):
"""Simple wrapper around dict-like `data` to expose a single segment
This class also caches the segment indices.
"""
def __init__(self, raw_data, data, segment):
"""New Segment data
Parameters
----------
... |
from copy import deepcopy
from django.forms import ChoiceField, ValidationError
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as DjangoBaseUserAdmin
from django.contrib.auth.forms import UserChangeForm as DjangoBase... |
# this file is required to get the pytest working with relative imports
|
import pyutilib.workflow
# @class:
class TaskA(pyutilib.workflow.Task):
def __init__(self, *args, **kwds):
"""Constructor."""
pyutilib.workflow.Task.__init__(self, *args, **kwds)
self.inputs.declare('z')
self.outputs.declare('z')
def execute(self):
"""Compute the sum o... |
import numpy as np
from utils import ms2smp, compute_stride, win_taper, build_linear_interp_table
import sounddevice as sd
"""
Real-time pitch shifting with granular synthesis for shift factors <=1.0
"""
""" User selected parameters """
grain_len = 30
grain_over = 0.2
shift_factor = 0.7
data_type = np.int16
# deriv... |
import SortTestHelper
def __merge(arr , l, mid, r):
#归并操作,arr为原数组, lr 为带排序的部分索引值
#k为在原数组上的待排序位置
#ij用于标记在辅助数组中左右两部分相比较的索引值
assist = arr[l:r+1]
k = l
i = l
j = mid+1
for k in range(l, r+1):
#先检查索引范围,当排序未结束时,及k未在lr之间遍历完时
#如果i j超过了各自的部分,则将另一部分的剩余部分一次填入原数组
if(i > ... |
"""Basic gate-constraint encoders
This module contains constraint encoders for gate constraints with a single
output literal (e.g. `o <-> AND(i_1, i_2, ..., i_N)`).
"""
from cscl.interfaces import ClauseConsumer, CNFLiteralFactory
from cscl.utils import ensure_tuple_or_list
# TODO: support Plaisted-Greenbaum encoder... |
name: Testing
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [ '3.7' ]
name: Python ${{ matrix.python-version }} sample
steps:
- uses: actions/checkout@v2
- name: Setup python
uses: actions/setup-python... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize
from os.path import join
import os.path
import numpy
ext_modules = [Extension("saxstools.libsaxstools",
[join('src', 'libsaxstools.pyx')],
include_dirs = ... |
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import splrep,splev
import sys
import os
class rb_fit_interactive_continuum(object):
def __init__(self,wave,flux,error):
self.wave=wave
self.flux=flux
self.error=error
... |
from pytest import raises
from unittest import mock
from sqlalchemy import Table, Column, MetaData
from fhirpipe.extract.extractor import Extractor
from fhirpipe.analyze.sql_column import SqlColumn
from fhirpipe.analyze.sql_join import SqlJoin
from test.unit.conftest import mock_config
meta = MetaData()
tables = {
... |
"""
The question is to group all same integers together - Sort colors in place
The challenge is: - They can give a pivot index
They can also to do this in-place
Generic version of the problem:
- Given an I/P array - rearrange the elements such that all elements less than pivot appear first,
... |
# 보석 쇼핑
def solution(gems):
answer = []
counts = {}
maximum_value = 987654321
kinds = len(set(gems))
left, right = 0, 0
while right < len(gems):
gem = gems[right]
counts[gem] = counts.get(gem, 0) + 1
right += 1
if len(counts) == kinds:
while left < rig... |
# coding: utf-8
import os
import re
from mitmproxy import io
from mitmproxy.exceptions import FlowReadException
from mitmproxy import http
import urllib
import sys
import typing
import matplotlib
matplotlib.use('agg')
class Reader:
"""
运行mitmproxy,并筛选cookie和appmsg_token, 这里的编码是二进制编码,所以需要dec... |
import logging
import boto3
import json
from botocore.exceptions import ClientError
from pathlib import Path
def status_cnf( cf_client, stack_name ):
stacks_cnf = cf_client.describe_stacks(StackName=stack_name)["Stacks"]
print("Current status of stack " + stacks_cnf[0]["StackName"] + ": " + stacks_cnf[0]["Stac... |
import io
from typing import List
from fastapi import UploadFile
from PyPDF2 import PdfFileMerger
def merge_files(files: List[UploadFile]) -> bytes:
output_stream = io.BytesIO()
merger = PdfFileMerger()
for file in files:
merger.append(file.file)
merger.write(output_stream)
output = outpu... |
#!/usr/bin/env python
# 参考 https://github.com/schedutron/CPAP/blob/master/Chap2/sleep_clnt.py
from socket import *
from time import sleep
HOST = input('Enter host: ')
if not HOST:
HOST = 'localhost'
PORT = input('Enter port: ')
if not PORT:
PORT = 1145
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST,... |
import subprocess
import os
from hurry.filesize import size, alternative
import psutil
import utils.plugins as plugins
import utils.hook as hook
import utils.misc as misc
import utils.time as time
class Misc(plugins.Plugin):
@hook.command(command='list')
def listcmd(self, bot, event, args):
'''[<pl... |
from raiden.tests.integration.fixtures.blockchain import * # noqa: F401,F403
from raiden.tests.integration.fixtures.raiden_network import * # noqa: F401,F403
from raiden.tests.integration.fixtures.smartcontracts import * # noqa: F401,F403
from raiden.tests.integration.fixtures.transport import * # noqa: F401,F403
f... |
import math
try:
tests=int(input())
z=[]
for _ in range(tests):
n=int(input())
w=list(map(int,input().rstrip().split()))
l=list(map(int,input().rstrip().split()))
ind={}
s=0
for i in range(1,n+1):
ind[i]=w.index(i)
for i in rang... |
import sys
import argparse
import pandas as pd
def func(args):
"""detect csv data
Examples:
toad evaluate -i xxx.csv
"""
from .evaluate import evaluate
sys.stdout.write('reading data....\n')
test_data = pd.read_csv(args.input)
if args.base is not None:
self_data = pd.re... |
def welcome_again_again_again(start):
print(f"""
{start},HA Ha hA
""")
def fourth_choose(first_step):
print("""
""")
def a(animal):
print("""
""")
def b(fruit):
print("""
""")
def end(endfirstpart)... |
#!/bash/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'Jeffrey'
import random
import time
def doing(activity, use_time):
print activity , int(use_time) * 5 + 1, "minutes"
class PythonProgrammer(object):
real_English_name = "Jeffrey Chu"
nick_name = "魔术师Jeffrey Chu"
occupation = "Server developm... |
from typing import Any, Dict
import pytest
from statham.schema.constants import NotPassed
from statham.schema.elements import Element, Null
from statham.schema.helpers import Args
from tests.schema.elements.helpers import assert_validation
from tests.helpers import no_raise
class TestNullInstantiation:
@staticm... |
from sublime import CLASS_WORD_START
from sublime import CLASS_WORD_END
from sublime import CLASS_PUNCTUATION_START
from sublime import CLASS_PUNCTUATION_END
from sublime import CLASS_EMPTY_LINE
from sublime import CLASS_LINE_END
from sublime import CLASS_LINE_START
from Vintageous.vi.utils import next_non_white_spac... |
'''Test it all'''
from __future__ import print_function
import numpy as np
import sparse_dot
from sparse_dot.testing_utils import (
generate_test_set,
generate_test_saf_list,
sparse_dot_full_validate_pass,
dot_equal_basic,
is_naive_same,
run_timing_test_v1,
run_timing_test,
run_timing_t... |
import os
from os import path
from typing import Any, Dict, Optional, Union
import torch
from torch import nn
from torchvision.datasets.utils import check_md5
import pystiche
from pystiche.misc import download_file
from ..license import License, UnknownLicense
from ._core import _Image, _ImageCollection
class Down... |
"""Module that contains tests to check that xml file has been written"""
import os
from pathlib import Path
from conftest import get_jarvis4se, remove_xml_file
from xml_adapter import XmlParser3SE
jarvis4se = get_jarvis4se()
xml_parser = XmlParser3SE()
def test_generate_xml_file_template():
"""Notebook equivale... |
"""DNS Authenticator for OVH DNS."""
import logging
from typing import Any
from typing import Callable
from typing import Optional
from lexicon.providers import ovh
from requests import HTTPError
from certbot import errors
from certbot.plugins import dns_common
from certbot.plugins import dns_common_lexicon
from cert... |
# Copyright (C) 2015-2018 Regents of the University of California
#
# 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 app... |
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from cStringIO import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
def pdf_to_text(s):
infile = StringIO(s)
output = StringIO()
manager = PDFResourceManager()
con... |
from django.urls import reverse_lazy
from django.http import HttpResponseRedirect
def index_dashboard(request):
return HttpResponseRedirect(reverse_lazy("budget:dashboard"))
|
from __future__ import annotations
import sys
import numpy as np
import numpy.ma as ma
def iterate(drawn: list[int], boards: ma.core.MaskedArray, need_to_win: int):
_, _, board_size = boards.shape
idx_won = []
for num in drawn:
# mark current number
boards.mask[boards.data == num] = Tr... |
import asyncio
import aiohttp
from time import perf_counter
import timeit
import string
import random
sample = 10_000
errors = dict()
measure = list()
result = list()
def id_generator(size=2, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
async def test... |
#-------------------------------------------------------------------------------
# Name: Single Band Gap Filler For Landsat 7
# Purpose: To use cloud masks for three seperate scenes to fill gaps in data
# due to SLC-induced gaps and clouds
# Author: Quinten Geddes Quinten.A.Geddes@nasa.... |
__source__ = 'https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/find-minimum-in-rotated-sorted-array.py
# Time: O(logn)
# Space: O(1)
# Binary Search
#
# Description: Leetcode # 153. Find Minimum in Rotated Sorted Array
#
# Suppose a sorted a... |
# Copyright 2021 code-injection-example contributors.
#
# 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 ... |
# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
from dnnsvg.svgeables.variables.tensor_3d import Tensor3D
from dnnsvg.svgeables.variables.tensor_2d import Tensor2D
from dnnsvg.svgeables.shapes.line import Line
from dnnsvg.svgeables.shapes.text import Text
from dnnsvg.svgeables.shapes.arc_arrow import ArcArrow
from dnnsvg.svgeables.shapes.arrow import Arrow |
from RedWebhook import RedWebhook
webhook = RedWebhook(url="", content="Webhook Message")
response = webhook.execute() |
import json
from flask import Flask, jsonify, request
from flask_cors import CORS
from datetime import datetime
import pytz
app = Flask(__name__)
cors = CORS(app)
@app.route("/positions")
def positions():
f = open('positions.json', "r")
r = f.read()
r = json.loads(r)
return jsonify(r)
@app.route("... |
from . import (
cmdline_parser,
manga_to_json,
bakaupdates
)
def _get_id(args: cmdline_parser.Args) -> str:
if args.id_url:
if args.id_url.isdigit():
id_ = args.id_url
else:
try:
id_ = bakaupdates.utils.get_id_from_url(args.id_url)
ex... |
def fib(n):
sequence_list = []
current_number = 0
next_number = 1
for i in range(n + 1):
sequence_list.append(current_number)
current_number = next_number
if i > 0:
# next = sequence_list[i] + current
next_number = sequence_list[i] + current_number
... |
import numpy as np
class DataProcessor():
def __init__(self, means=(), stds=()):
self.means = means
self.stds = stds
def format_x(self, x, size=-1):
_x = x
if isinstance(x, (tuple, list)):
_x = np.array([x])
if size > 0 and _x.shape[1] != size... |
# %%
import shortuuid
from ctrace import PROJECT_ROOT
from ctrace.exec.param import GraphParam, SIRParam, FileParam, ParamBase
from pathlib import Path, PurePath
import multiprocessing as mp
import concurrent.futures
from typing import List, Tuple, Dict, Any, Callable
from zipfile import ZipFile
import itertools
import... |
# Author: Abhishek Sharma
# Reference: Element of Programming Interview in Python
def count_bits(num):
bit_count = 0
while num:
bit_count += num & 1
num >>= 1
return bit_count
|
import datetime
from typing import List
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.event import listens_for
from sqlalchemy import Column, ForeignKey, String, Integer, BLOB, JSON, DateTime
from sqlalchemy.dialects.postgresql import BYTEA, JSONB
from sqlalchemy.ext.hybrid import hybrid_prop... |
import csv
from datetime import datetime
from decimal import Decimal
from pathlib import Path
from typing import List, Optional, Tuple
from exceptions import ParsingError, UnexpectedColumnCountError
from model import ActionType, BrokerTransaction
columns = [
"Action",
"Time",
"ISIN",
"Ticker",
"Na... |
import os
import re
import azure.batch.batch_auth as batchauth
import azure.batch.batch_service_client as batch
import azure.storage.blob as blob
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.batch import BatchManagementClient
from azure.mgmt.storage import StorageManagementClient
fr... |
import os, subprocess, shutil
class kh2fmtoolkit:
def __init__(self, workdir='.', binary_name='KH2FM_Toolkit.exe'):
self.workdir = workdir
self.author = 'kh2lib'
self.binary_name = binary_name
self.version = '1'
def _check_binary(self):
if not os.path.isfile(os.path.join... |
import numpy as np
def circular(diameter):
"""
Calculates the equivalent diameter and projected capture area of a
circular turbine
Parameters
------------
diameter : int/float
Turbine diameter [m]
Returns
---------
equivalent_diameter : float
Equivalent... |
#!/bin/python
import math
import numpy
import simple_error_distribution
import somewhat_homomorphic_keygen
import rvg
class BootstrappableKeygen(object):
def __init__(self, short_dimension, long_dimension, multiplicative_depth, short_odd_modulus, long_odd_modulus, matrix_rows, short_seed=1, long_seed=1):
... |
import logging
import logging.config
import time
import traceback
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
from pathlib import Path
from typing import Any, Dict, List
import ruamel.yaml
import HABApp
from HABApp import __version__
from . import CONFIG
from .default_logfile import get... |
#!/usr/bin/env python3
import copy
# Funcao: print_sudoku
# Essa funcao ja esta implementada no arquivo lab20_main.py
# A funcao imprime o tabuleiro atual do sudoku de forma animada, isto e,
# imprime o tabuleiro e espera 0.1s antes de fazer outra modificacao.
# Voce deve chamar essa funcao a cada modificacao na matr... |
import unittest
import frappe
from frappe.desk.reportview import get_stats
from frappe.desk.doctype.tag.tag import add_tag
class TestTag(unittest.TestCase):
def setUp(self) -> None:
frappe.db.delete("Tag")
frappe.db.sql("UPDATE `tabDocType` set _user_tags=''")
def test_tag_count_query(self):
self.assertDictE... |
"""
Minimum jerk trajectory for 6DOF robot
Latest update: 14.12.2020
Written by Daniel Stankowski
"""
import numpy as np
import robosuite.utils.angle_transformation as at
class PathPlan(object):
"""
IMPORTANT: When the pose is passed [x,y,z,Rx,Ry,Rz] one has to convert the orientation
part from axis-angle ... |
T = int(input())
N = int(input())
L1 = list(map(int,input().split()))
M = int(input())
L2 = list(map(int,input().split()))
d1 = dict()
d2 = dict()
D1 = [0,L1[0]]
D2 = [0,L2[0]]
for i in range(1,N):
D1.append(D1[-1]+L1[i])
for i in range(1,M):
D2.append(D2[-1]+L2[i])
for i in range(N+1):
for j in range(i... |
from airflow.hooks.postgres_hook import PostgresHook
from sqlalchemy.orm.session import sessionmaker
def get_db_session():
engine = PostgresHook(postgres_conn_id='huey_dev').get_sqlalchemy_engine()
Session = sessionmaker()
Session.configure(bind=engine)
db_session = Session()
return db_session
|
from pathlib import Path
from typing import Dict, List, Optional, cast
import pytest
from darwin.datatypes import (
Annotation,
AnnotationClass,
AnnotationFile,
EllipseData,
Point,
SubAnnotation,
)
from darwin.importer.formats.superannotate import parse_path
from jsonschema import ValidationErr... |
# Generated by Django 3.0.2 on 2020-01-24 15:24
import common.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [('shop', '0001_initial'), ('shop', '0002_auto_20200120_1458'), ('shop', '0003_productcategory_main_photo'), ('shop', '... |
from pythonforandroid.recipe import CythonRecipe
from os.path import join
#import sh
"""
Note for future recipe creation.
The best way to structure a project is to push add-on modules to github,
and place setup.py in the very top directory. Setup.py should have build
instructions for different architectures.
"""
... |
# Databricks notebook source
import boto3
import yaml
import os
import re
# COMMAND ----------
def parse_source_location(arg_source_location):
pattern = 's3:\/\/([^\/]*)\/(.*)'
# this regex expression with split source llocation into two parts:
# (1) bucket name - s3://<all characters until the next fo... |
# define a large classification dataset
from sklearn.datasets import make_classification
# define dataset
X, y = make_classification(n_samples=10000, n_features=500, n_informative=10, n_redundant=490, random_state=1)
# summarize the shape of the dataset
print(X.shape, y.shape)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.