content stringlengths 5 1.05M |
|---|
from piquery.piq_hash64 import download_to_hash
from piquery.piq_error import DownloadError, ImageFormatError
from piquery.piq_config import config as db_cfg
from piquery.piq_response import Response
class PIQueryHash64:
def __init__(self, db):
self.db = db
def queryRepeat(self, url):
try:
... |
import datetime
from core.state import State, StateTime
N_TESTS = 100000
state_avg = 0
state_time_avg = 0
for i in range(N_TESTS):
if i % (N_TESTS / 10) == 0:
print(i / N_TESTS * 100, "%")
t1 = datetime.datetime.now()
s1 = State()
t2 = datetime.datetime.now()
st = StateTime(s1, 0.0)
t... |
__author__ = 'flier'
|
#!/usr/bin/env python
# coding=utf-8
import dominate
from dominate.tags import *
from newspaper import Article
from textblob import TextBlob
from qutescript import userscript
polarity_map = {
8: 'green',
5: 'olive',
2: '#333',
0: '#777',
-2: 'orange',
-5: 'red',
-8: 'brown',
}
def get_po... |
#!/usr/bin/env python
import argparse
from HAPpy import genome_fork as genome
import re, os, subprocess, tempfile, shlex, sys
def orf_finder(sequence,startphase,stopphase,strand,expected_aa_len,length_variance,
search_coords = None, is_start = False, is_stop = False,
hmm_profile = None,... |
# Preppin' Data 2021 Week 16
import pandas as pd
import numpy as np
# remove warnings
pd.set_option('mode.chained_assignment', None)
# Input the files
fixtures = pd.read_csv('unprepped_data\\PD 2021 Wk 16 Input - PL Fixtures.csv')
# Filter out matches which haven't been played yet
played_matches = fixtures[fixtures[... |
matrix1 = [[1, 2, 3], [4, 6, 3], [2, 5, 5]]
matrix2 = [[1, 4, 2], [6, 2, 2], [6, 2, 7]]
resultMatrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
if len(matrix1) == len(matrix2) :
for i in range(len(matrix1)) :
for j in range(len(matrix2)) :
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j]
print('S... |
# Copyright 2021 Google LLC
#
# 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, ... |
import pytest
from fbotics.models.quick_reply import QuickReply
from schematics.exceptions import DataError
def test_validation_when_content_type_is_text_and_title_does_not_exist(client):
"""
GIVEN a QuickReply object with a text content type and not title
WHEN validating the object
THEN is throws a ... |
MeshLoop.tangent = None
|
import json
import pytest
import torch.distributed as dist
from tango.common.logging import initialize_logging, teardown_logging
from tango.common.testing import TangoTestCase
class TestTrainStep(TangoTestCase):
def setup_method(self):
super().setup_method()
initialize_logging(enable_cli_logs=Tr... |
from ._quantum import Quantum
from ._position import Position
|
# Copyright 2021 The FastEstimator 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 appl... |
#
# -*- coding: utf-8 -*-#
# Copyright (C) 2016 AllSeeingEyeTolledEweSew <allseeingeyetolledewesew@protonmail.com>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
# Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2009 Damien Churchill <damoxc... |
# Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
#
# 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... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import shutil
from contextlib import contextmanager
from os.path import (lexists, expanduser, isfile, islink, ismount,
realpath)
from stat import S_ISDIR, S_ISLNK, S_ISREG
import psutil
import send2trash
import xxhash
fro... |
#!/usr/bin/env python
# Authors: Chongzhi Zang, Weiqun Peng
#
# Disclaimer
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.... |
def notes(self, node):
pass
def properties(self, node):
pass
def property(self, node):
pass
def tag(self, node):
pass
def value(self, node):
pass
|
import seaborn as sns
import numpy as np
from pprint import pprint
from script.util.JobPool import JobPool
from script.util.PlotTools import PlotTools
import pandas
DF = pandas.DataFrame
def test_plot_tools_pair_plot():
iris = sns.load_dataset("iris")
plt_tools = PlotTools()
plt_tools.pair... |
from random import choice
class RandomWalk():
def __init__(self, num_points=5000):
"""Initalize attributes of a walk."""
self.num_points = num_points
# All walks start at (0, 0).
self.x_values = [0]
self.y_values = [0]
def get_step(self):
dire... |
import pygame
from world_map.camp import Camp
from fuzy_prob.prob import Prob
from fuzy_prob import prob
class Wmap():
preprint = None
__map_x_size = 10
__map_y_size = 10
__is_generated = False
__matrix = [] #world mape matriz
def __init__(self):
pass
def init(self):
print(self.preprint + 'wmap from wor... |
"""
This module is starting point for task 4.1 from Coding Campus 2018 Python course
(Dungeon Game)
"""
import logging
import threading
from .dungeon_map import DungeonMap
from .player import Player
import dungeon_game.utils as utils
import dungeon_game.log as log
from dungeon_game.decorators import log_dec... |
import indexTricks as iT
import numpy
from pylens import *
from imageSim import profiles,convolve,SBModels, models
import distances as D
import cPickle
import indexTricks as iT
import numpy,pylab
#from imageSim import profiles,convolve,models
import pylab as plt
from Surveys import Survey
from StochasticObserving impor... |
# -*- coding: utf-8 -*-
"""
Azure Resource Manager (ARM) Container Instance Group Execution Module
.. versionadded:: 3.0.0
:maintainer: <devops@eitr.tech>
:configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments
to every function or via acct in order to work proper... |
from alexandria.settings.commands import remove_activation
from alexandria.settings.extensions import db
from datetime import datetime,timedelta
def test_remove_activation_expired(client):
from alexandria.modules.security.models import User,AccountRegistration
days_to_expire6,days_to_expire8 = timedelta(days=6... |
symbols = []
exports = [{'type': 'function', 'name': 'AssocCreateForClasses', 'address': '0x7ffb39c36d10'}, {'type': 'function', 'name': 'AssocGetDetailsOfPropKey', 'address': '0x7ffb3a093050'}, {'type': 'function', 'name': 'AssocShouldProcessUseAppToAppLaunching', 'address': '0x7ffb39eb2a20'}, {'type': 'function', 'na... |
import requests
import numpy as np
from pandas import DataFrame, Series
import pandas as pd
from utilities import LICENSE_KEY, generate_token, master_player_lookup
import json
pd.options.mode.chained_assignment = None
LEAGUE_ID = 316893
TEAM_ID = 1605156
##############################################################... |
# -*- coding: utf-8 -*-
"""Generate the Resilient customizations required for fn_palo_alto_wildfire"""
from __future__ import print_function
from resilient_circuits.util import *
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_palo_alto_wildfire package"""
reload_params = {"packag... |
#!/usr/bin/env python
import numpy as np
import mirheo as mir
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--axes', type=float, nargs=3)
parser.add_argument('--coords', type=str)
parser.add_argument('--vis', action='store_true', default=False)
parser.add_argument('--drag', type=float... |
from src.shared.config.configuration import configuration
from src.layers.infrastructure.providers.temporary.queries import queryMfcTagsAndTitles, queryMfcTotal
import requests
import json
class ChapiProvider:
def __init__(self):
self.config = configuration.layers.infrastructure.providers.chapi_provider
... |
# Generated by Django 3.0.7 on 2020-09-23 05:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('preorders', '0004_auto_20200923_0710'),
]
operations = [
migrations.AlterField(
model_name='shoppingcartline',
name=... |
########################################################################
#
# Functions for calculating Total Return, Annualized Returns, etc.
#
########################################################################
#
# This file is part of FinanceOps:
#
# https://github.com/Hvass-Labs/FinanceOps
#
# Published under t... |
#!/usr/bin/env python
"""
Cleavage prediction src tool
usage: cleavageprediction.py [-h] [-m {proteasmm_i,netchop,proteasmm_c,pcm}]
[-v VERSION] -i INPUT [-l LENGTH] [-op OPTIONS]
-o OUTPUT
Commandline tool for cleavage site prediction
optional arguments:
-... |
# terrascript/resource/hashicorp/azurestack.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:13:15 UTC)
import terrascript
class azurestack_availability_set(terrascript.Resource):
pass
class azurestack_dns_a_record(terrascript.Resource):
pass
class azurestack_dns_zone(terrascript.Resource... |
"""Code for low-memory processing of tabular data.
This code works with IDotDatas, which are immutable streams of records. An IDotData has a fixed number of named columns,
and lets you take out iterators to iterate sequentially over the records (table rows). Unlike DotData, it does not provide
efficient random acce... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from collections import Counter
from matplotlib import rc
import pickle, sys, pdb, gzip
if sys.version_info[0]<3:
import cPickle
import numpy as np
from sklearn.metrics import log_loss, confusion_matrix
from sklearn.manifold import TSNE as tsn... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import pmagpy.pmag as pmag
def main():
"""
NAME
sort_specimens.py
DESCRIPTION
Reads in a pmag_specimen formatted file and separates it into different components (A,B...etc.)
SYNTAX
sort_specimens.py [-h] [... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: zlikun
import asyncio
import logging
import aiohttp
default_headers = {
"Host": "www.biquge5200.cc",
"Referer": "https://www.biquge5200.cc"
}
async def download(session, url, headers={}, error_url_queue=None):
"""
HTTP下载函数,下载失败后会重试三次(重试间隔1秒)
... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"#Importing relevant libraries\n",
"import numpy as np\n",
"import pandas as pd\n",
"import datetime\n",
"from datetime import datetime,timedelta, date, time\n",
"import matplo... |
import logging
import tempfile
import os
import re
import sys
import tweepy
import requests
from google.cloud import texttospeech
from requests_oauthlib import OAuth1Session
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
TEXTEMALL_BASE_DOMAIN = "staging-rest.call-em-all.com"
SUBSCRIPTIONS_API_BA... |
#!/usr/bin/env python3
import os
import random
import torch
import numpy as np
from faker import Faker
from loguru import logger
from transformers import GPT2LMHeadModel, GPT2Tokenizer
MODEL_NAME = os.environ.get('MODEL_NAME', 'gpt2')
if MODEL_NAME.lower() == 'gpt2':
logger.debug('***** Running basic GPT2 pret... |
# This file is part of the ISIS IBEX application.
# Copyright (C) 2012-2020 Science & Technology Facilities Council.
# All rights reserved.
#
# This program is distributed in the hope that it will be useful.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License... |
"""file to deal with batch operations"""
import sys
import json
import xlwt
import extract_info
from fit_sheet_wrapper import FitSheetWrapper
from xlwt import Workbook
import random
# from desk import *
import requests
import pandas as pd
import numpy as np
import nltk
import json
import csv
from nltk.corpus import st... |
import bpy
from bpy.props import *
from ... events import executionCodeChanged
from ... sockets.info import isBase, toBaseDataType
from ... base_types import AnimationNode, ListTypeSelectorSocket
class GetListElementNode(bpy.types.Node, AnimationNode):
bl_idname = "an_GetListElementNode"
bl_label = "Get List E... |
# Generated by Django 3.0 on 2019-12-06 23:39
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20191207_0015'),
]
operations = [
migrations.RemoveField(
model_name='post',
... |
import os
from flask import Flask, session, render_template, redirect, abort, url_for, request, jsonify
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from . import auth_tool
app = Flask(__name__)
app.config.from_pyfile('../config.py')
c... |
from sqlalchemy import func as sql_func, Date
from cebulany.models import db
def get_year_month_col(column: Date):
database_type = db.engine.dialect.name
if database_type == 'postgresql':
return sql_func.to_char(column, 'YYYY-MM')
if database_type == 'sqlite':
return sql_func.strftime('%Y... |
from numpy import *
# Download datafile
import urllib
urllib.urlretrieve('http://www.ai-geostats.org/fileadmin/Documents/Data/walker_01.dat',filename='walker_01.dat')
# Whhether to thin dataset; definitely thin it if you're running this example on your laptop!
thin = False
l = file('walker_01.dat').read().splitline... |
"""A setup script to demonstrate build using bcrypt"""
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the script without Python
from cx_Freeze import setup, Executable... |
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from ...utils import update_sentry_404s
class Command(BaseCommand):
def handle(self, *args, **kwargs):
update_sentry_404s()
|
def arithmatic_mean(list):
length_of_list = len(list)
summation = sum(list)
return summation / length_of_list
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
mean = arithmatic_mean(x)
print('Mean of', x,'is',mean) |
"""Cycles"""
from .rankinebasic import RankineBasic
|
# Title: 전깃줄
# Link: https://www.acmicpc.net/problem/2565
import sys
from bisect import bisect_left
sys.setrecursionlimit(10 ** 6)
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
read_single_int = lambda: int(sys.stdin.readline().strip())
def solution(n: int, lines: list):
line... |
#============================================
__author__ = "Sachin Mehta"
__maintainer__ = "Sachin Mehta"
#============================================
import torch
from torch import nn
from nn_layers.cnn_utils import CBR, CB
class Shuffle(nn.Module):
'''
This class implements Channel Shuffling
'''
def... |
class Phase(object):
"""The Phase class represents a phase a task may be in.
It has no function other than to act as an anchor in the task graph.
All phases are instantiated in common.phases
"""
def __init__(self, name, description):
# The name of the phase
self.name = name
# The description of the phase ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class TargetPool(pulumi.CustomResourc... |
import datetime
from django.test import Client, TestCase
from streamer.factories import AnimeRoomFactory, AnimeUserFactory
import pytest
from http import HTTPStatus
class TestIndexView(TestCase):
def setUp(self) -> None:
self.client = Client()
self.endpoint = "/"
@pytest.mark.django_db
de... |
# Copyright (c) 2015 Cloudbase Solutions Srl
#
# 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 applicab... |
from stackformation.aws.stacks import BaseStack
from stackformation.aws.stacks import TemplateComponent
from stackformation.aws import Ami
import logging
from colorama import Fore, Style, Back # noqa
from troposphere import apigateway, awslambda
from troposphere import ( # noqa
FindInMap, GetAtt, Join,
Parame... |
# Script to replace text in a designated field in a resource and post the resource back to API.
# Requirements:
# - ASFunctions.py
# - A csv of format repo,asid
# - sheetFeeder (optional, for reporting purposes)
import ASFunctions as asf
import json
from pprint import pprint
import re
import csv
from sheetFeeder impor... |
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
def find_packages(exclude=None):
"""
Just stub this. If you're packaging, you need setuptools. If
you're installing, not so much.
"""
return
required = [
'emds'... |
"""
In-memory treq returns stubbed responses.
"""
from functools import partial
from inspect import getmembers, isfunction
from mock import ANY
from six import text_type, binary_type
from twisted.trial.unittest import TestCase
from twisted.web.client import ResponseFailed
from twisted.web.error import SchemeNotSuppo... |
from bs4 import Comment, NavigableString, Tag
from prismriver.plugin.common import Plugin
from prismriver.struct import Song
class UtaTenPlugin(Plugin):
ID = 'utaten'
RANK = 9
def __init__(self, config):
super(UtaTenPlugin, self).__init__('UtaTen', config)
def search_song(self, artist, titl... |
#
# (c) Copyright 2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# 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
#... |
import matplotlib.pyplot as plt
import argparse
import pathlib
import numpy as np
import typing
colors = ["blue", "green", "cyan", "red", "yellow", "magenta", "peru", "azure", "slateblue", "plum"]
def plot_bbox(bbox_XYXY, label):
xmin, ymin, xmax, ymax = bbox_XYXY
plt.plot(
[xmin, xmin, xmax, xmax, x... |
feira = ('Pão', 2, 'Sorda', 4, 'Queijo', 12.75)
print('_' * 40)
print(' '*10, 'FEIRA NA PADARIA', ' '*10)
print('-' * 40)
for pos in range(0, len(feira)):
if pos % 2 == 0:
print(f'{feira[pos]:.<30}', end='')
else:
print(f'R${feira[pos]}')
print('_' * 40)
|
# Copyright 2020 Google LLC
#
# 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 random import sample
WORD_FILE_NAME = "/usr/share/dict/words"
def city_names(number=None):
with open(WORD_FILE_NAME, 'r') as word_file:
words = word_file.read().splitlines()
cities = [word[:-4] for word in words if (
len(word) > 4
and word.endswith('city')
an... |
'''
Dictionary store
=================
Use a Python dictionary as a store.
'''
__all__ = ('DictStore', )
try:
import cPickle as pickle
except ImportError:
import pickle
from os.path import exists
from kivy.compat import iteritems
from kivy.storage import AbstractStore
class DictStore(AbstractStore):
'... |
"""Well-known (and otherwise) constants used by JupyterLite"""
import shutil
from pathlib import Path
#: a locale for reproducible file sorting
C_LOCALE = "C"
#: the encoding for pretty much every file written and read by jupyterlite
UTF8 = dict(encoding="utf-8")
JSON_FMT = dict(sort_keys=True, indent=2)
ROOT = Path(... |
# Mainly copied from NeoPixel strandtest example. Author: Tony DiCola (tony@tonydicola.com)
# See: https://github.com/jgarff/rpi_ws281x
import threading
import time
from neopixel import *
# Led Driver for Pawn Shy to animate / set the Pawn LED states.
class LedDriver():
def __init__(self):
# LED strip configurat... |
import json
import time
import hashlib
from random import randrange
from flask import Flask, request, make_response, render_template
from flask_restful import Resource, Api
from sort_db import database
app = Flask(__name__)
api = Api(app)
class SortAPIHelp(Resource):
def get(self):
return {
"Hello... |
## INFOS ##
name = 'brs_utils'
descr = 'Basic utilities'
url = f'https://github.com/brsynth/{name}'
authors = 'Joan Hérisson'
corr_author = 'joan.herisson@univ-evry.fr'
###########
###########
from setuptools import (
setup,
find_packages
)
from os import path as os_path
here = os_pat... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Donny You(youansheng@gmail.com)
# Visualize the log files.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import visdom
import time
import numpy as np
import torchvision as tv
from utils.tools.logger ... |
import time
from timebudget import timebudget
with timebudget('load-file'):
readme = open('README.md','rt').read()
timebudget.report()
|
# Generated by Django 2.2.4 on 2019-08-05 04:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('globinq', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='globin',
... |
import sys
print(sys.version)
name = "jc"
print("my name is " + name)
|
from trpg.data_classes import *
def hook(obj):
# TODO: Hook all types
if '__type__' in obj:
obj_type = obj.pop('__type__')
if obj_type == 'scenario':
return Scenario(**obj)
elif obj_type == 'player':
return Player(**obj)
elif obj_type == 'item':
... |
from functools import partial
from math import sqrt
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import string
import timeit
import torch
from torch import nn
import torch.functional as F
import torch.nn.functional as F
import statistics
import re
import warnings
from math import floor
im... |
class Simple1Exception(Exception):
pass
class Simple2Exception(Exception):
pass
def abc():
try:
raise Simple1Exception
except Simple1Exception as e:
raise Simple2Exception from e
abc()
|
import os
import requests
class ApiCore(object):
def __init__(self):
self.api_key = {"appid":os.environ["API_KEY"]}
self.base_url = os.environ["BASE_URL"]
self.weather_url = os.environ["WEATHER_URL"]
self.several_cities = os.environ["SERVAL_CITIES"]
self.cities_in_cycle = ... |
import logging
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.views.generic.edit import FormView
from ipware.ip import get_ip
from knownly import plans
from knownly.billing.errors import PaymentProviderError
from knownly.... |
def l():print('\n'+'=-'*30 + '=')
ns = [[], []]
n = 0
for i in range(0, 7):
n = int(input('digite um numero: '))
if n % 2 == 0:
ns[0].append(n)
else:
ns[1].append(n)
l()
ns[0].sort()
ns[1].sort()
l():
print('valores pares:\n')
for i in ns[0]:
print(' ', i, end='')
l()
print('\nvalores i... |
# coding=utf-8
import codecs
import os
import scrapy
import datetime
import csv
from scrapy import Request
from selenium import webdriver
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class IdeaSpider(scrapy.Spider):
name = "idea"
allowed_domains = ["www.writepop.com"]
def __init__(self, *args, ... |
"""
Models for interfacing asynchronous programs with pretty CLI output.
"""
|
import unittest
from basketball_reference_scraper.drafts import get_draft_class
class TestDraft(unittest.TestCase):
def test_should_get_class(self):
df = get_draft_class(2003)
self.assertEqual(len(df), 58)
row = df.iloc[0]
self.assertEqual('LeBron James', row['PLAYER'])
def test_should_get_old_c... |
#!/usr/bin/env python
import os
from cli import parser
from __init__ import MusicFile
ACOUSTID_API_KEY = 'cSpUJKpD'
def main():
args = parser.parse_args()
if args.current_dir:
files = [x for x in os.listdir(os.getcwd()) if x.endswith('.mp3')]
else:
files = args.files
for file in fi... |
import re
import six
from lxml import etree
from sbedecoder.message import SBEMessage, TypeMessageField, EnumMessageField, SetMessageField, CompositeMessageField, \
SBERepeatingGroupContainer
def convert_to_underscore(name):
name = name.strip('@').strip('#')
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)... |
import numpy as np
from eval_instance_segmentation_coco import eval_instance_segmentation_coco
# with open('data/fake.pkl', 'rb') as f:
# bboxes, masks, labels, scores, keys = pickle.load(f)
#
# with open('data/fake_gt.pkl', 'rb') as f:
# sizes, gt_bboxes, gt_masks, gt_labels, gt_crowdeds, gt_areas = pickle.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lck.django.common import nested_commit_on_success
from ralph.util import plugin
from ralph.discovery.models import IPAddress
from ralph.discovery.http import get_http_family
@nested_commit_on_success
def run_http(ip):
family = get_http_family(ip)
ip_addres... |
import logging
from qcodes.instrument.base import Instrument
from qcodes.utils import validators as vals
class IQ_mixer(Instrument):
'''
Passive object designed to hold paramters for the mixer.
'''
def __init__(self, name, **kw):
logging.info(__name__ + ': Initializing instrument')
su... |
import rename
import rss
import transfer
urls = rss.part_a()
rss.part_b(urls)
rename.main()
transfer.main() |
import pytest
from lumido import Cronjob
@pytest.mark.parametrize('mins, hours, result', [(30, 1, (130, 'tomorrow')), (45, '*', (1645, 'today')),
('*', '*', (1610, 'today')), ('*', 19, (1900, 'today'))])
def test_next(mins, hours, result):
cron = Cronjob(mins, hour... |
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from pxtrade.assets import Stock
def test_stock_str():
stock = Stock("QQQ AU", 2.55, currency_code="AUD")
stock_str = str(stock)
assert stock_str == "Stock('QQQ AU', 2.55, currency_code='AUD')"
|
"""AoC 2018 Day 20: A Regular Map"""
import re
from collections import OrderedDict
import numpy as np
# Part 1
def reduce_path(path):
new_path = ''
# Find the innermost parenthesis group
innermost = re.compile(r'(\([NSEW|]*?\))')
previous_start = 0
for m in innermost.finditer(path):
new... |
from datetime import datetime
from lights.base.history import History
from time import time
import numpy as np
class Learner:
"""The base class for a Solver.
Not intended for end-users, but for development only.
It should be sklearn-learn compliant
Parameters
----------
verbose : `bool`, defa... |
#!/usr/bin/python
#Description: Download media items from an rss feed using youtube-dl
import feedparser
import sys
import subprocess
url = sys.argv[1]
tag = sys.argv[2]
#number = 10000
request = "%s%s" % (url, tag)
feed = feedparser.parse(request)
for entry in feed['entries']:
dl_link = entry.get('link', '')
dl... |
#!/usr/bin/env python
"""
Usage: testPartMesh.py infile
"""
import fvm
import fvm.fvmparallel as fvmparallel
import sys, time
from numpy import *
from mpi4py import MPI
from FluentCase import FluentCase
numIterations = 10
def usage():
print __doc__
sys.exit(1)
if len(sys.argv) < 2:
usage()
casfile = sys... |
from helpers import customs_exception
from utils.number_vehicles.stops.manager import stops_manager_cvrp
from utils.number_vehicles.stops.objects import stops_cvrptw
from utils.number_vehicles.stops import classDepot
import numpy as np
class StopsManagerCVRPTW(stops_manager_cvrp.StopsManagerCRVP):
"""
Class o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.