content
stringlengths
5
1.05M
import os import sys import argparse from roblib import read_fasta from random import randint, shuffle __author__ = 'Rob Edwards' parser = argparse.ArgumentParser(description='Convert a fasta file to fastq, faking the qual scores. Either -f or -n is required') parser.add_argument('-f', help='fasta file') parser.add_a...
from unittest import mock import pytest from behave_django.runner import SimpleTestRunner from behave.runner import Context, Runner from django.test.testcases import TestCase from .util import DjangoSetupMixin class TestSimpleTestCase(DjangoSetupMixin): @mock.patch('behave_django.management.commands.behave.be...
from countdown.parser.Parser import Parser def test_lex_duration_string(): test_input = 'ashdf 40m afsda 60hours asdf 5 second 20 hour 5day 2minute' test_parser = Parser({ 'duration': object(), 'printer': object(), 'alarm': object() }) expected_output = ['40m', '60hours', '5...
import pandas as pd import os #import sed_eval import gzip import glob import pickle import librosa import soundfile as sf import numpy as np import random import math from scipy.signal import hanning from sklearn.preprocessing import StandardScaler class DataGenerator(): 'Generates data for the experiments'...
""" Collection of Numpy general functions, wrapped to fit Ivy syntax and signature. """ # global import logging import numpy as np import math as _math from operator import mul as _mul from functools import reduce as _reduce import multiprocessing as _multiprocessing # local import ivy from ivy.functional.ivy import ...
# # Contributed by Rodrigo Tobar <rtobar@icrar.org> # # ICRAR - International Centre for Radio Astronomy Research # (c) UWA - The University of Western Australia, 2019 # Copyright by UWA (in the framework of the ICRAR) # ''' Benchmarking utility for ijson ''' import argparse import collections import io import os impor...
import os import yaml def read_config(): with open(os.path.join(os.path.dirname(__file__), "../config.yml")) as ymlfile: return yaml.load(ymlfile, Loader=yaml.BaseLoader) def chromedriver_path(): os.environ["webdriver.chrome.driver"] = read_config()["paths"]["webdriver"]["chromedriver"] return ...
from .base import ObjectModel from .event_log import EventLog from .handler_log import HandlerLog from .sync_task import SyncTask
class Solution: def maxProfit(self, prices: List[int]) -> int: maxCur = 0 maxFar = 0 for i in range(1,len(prices)): maxCur += prices[i] - prices[i-1] print(maxCur,maxFar) maxCur = max(0,maxCur) maxFar = max(maxCur,maxFar) ...
#-------------------------# #Author: Albert Bagdasarov #Date 16.08.20 #-------------------------# import os import time import pyttsx3 as x3 import speech_recognition as sr from Commands import * import random import re import webbrowser import wikipedia import json import request from datetime import da...
from sns_boomerang.api.resources.jobs import Jobs from sns_boomerang.common.items import Job import pytest from werkzeug.exceptions import NotFound def test_get_job(monkeypatch): test_id = 'test-id' def mock_get(id): assert id == test_id return Job('topic', 'payload', 123, id=test_id) mo...
""" Just a simple sample """ import sys import time from twitter_requests.generator import TwitterBearerGenerator from twitter_requests.twitter import Twitter, TwitterQueryBuilder QUERY = sys.argv[1] EPOCH = 0 KEYS = { 'api_key': 'YOUR_API_KEY', 'api_secret_key': 'YOUR_API_SECRET_KEY' } TWITTER_BEARER_GEBERA...
# -*- coding: utf-8 -*- # Copyright (2017) Hewlett Packard Enterprise Development LP # # 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...
import tkinter as tk from browserHandler import browserHandler from GUI import MainMenu from GUI import helper class Application: def __init__(self): """ Combines the created modules and create the main application :return: None """ web_handler = browserHandler.WebHandler()...
#!/usr/bin/env python3 import argparse import asyncio import math import os import sys import traceback as tb import warnings from pathlib import Path import aiohttp from aiohttp.web import Application, HTTPBadGateway, Response, WebSocketResponse, WSMsgType, hdrs, json_response from devtools import VERSION WITH_UJS...
import serial from datetime import datetime, timedelta from random import uniform from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Float, DateTime, String Base = declarative_base() class Data(Base): __tablename__ = 'data' id = Column(Integer, primary_key=True) ...
from flask import Flask from flask import render_template from flask import session app = Flask(__name__) app.config['SECRET_KEY'] = 'top secret' @app.route('/') def index(): if 'count' not in session: session['count'] = 1 else: session['count'] += 1 return render_template('index12.html', count=session['count'...
# Generated by Django 2.2.2 on 2019-07-31 09:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0064_auto_20190731_0950'), ] operations = [ migrations.AlterField( model_name='organization', name='logo', ...
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ a, b = None, None for i, n in enumerate(nums): if a and n == a[0]: a = (n, a[1]+1) elif b and n == b[0]: b ...
import plotly.plotly as py import plotly.graph_objs as go # plotly # import plotly # plotly.tools.set_credentials_file( # username='houterm', api_key='putYaOwnKey') def plot(sphero, step_count): if step_count == 40000: # if step_count == 1000: x_error_behaviour = go.Scatter( x=sphero.p...
import shutil import errno import os import time import codecs from django.http import HttpResponse from django.utils.encoding import smart_str from katana.wui.core.core_utils.app_info_class import AppInformation from katana.utils import date_time_stamp_utils as dtutils def readlines_from_file(path, start=None, end...
"""Constants for Mosoblgaz module""" CONF_CONTRACTS = "contracts" CONF_METER_NAME = "meter_name" CONF_CONTRACT_NAME = "contract_name" CONF_METERS = "meters" CONF_INVOICES = "invoices" CONF_INVOICE_NAME = "invoice_name" CONF_INVERT_INVOICES = "invert_invoices" CONF_PRIVACY_LOGGING = "privacy_logging" DOMAIN = "mosoblga...
import numpy as np import torch def record(t, X, S, record_times, dt): sims = X.shape[0] M = X.shape[1] num_t = X.shape[2] N = X.shape[3] # recorded data containers X_record = [] S_record = [] # find recorded values for m in range(M): X_temp = torch.z...
# -*- coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lic...
# -*- encoding: utf-8 -*- from openerp.report import report_sxw import datetime import logging class diario_reporte(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(diario_reporte, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'dateti...
"""General utilites.""" from . import marshmallow, specs, sqla def get_all_subclasses(cls): """Recursively return all subclasses.""" all_subclasses = [] for subclass in cls.__subclasses__(): all_subclasses.append(subclass) all_subclasses.extend(get_all_subclasses(subclass)) return ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import requests import xml2ass import os import io import shutil def Danmuku(cid): path = 'D:/ass' if os.path.exists(path): shutil.rmtree(path) os.makedirs(path) else: os.makedirs(path) # 链接格式:https://www.bilibili.com/video/BV*******...
""" WSGI config for project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import logging import os import platform from django.core.wsgi import get_wsgi_application from d...
import os import click from dehinter.font import dehint from fontTools.ttLib import TTCollection from fontTools.ttLib import TTFont from fontTools.ttLib.removeOverlaps import removeOverlaps from ftcli.Lib.Font import Font from ftcli.Lib.utils import getFontsList, makeOutputFileName, getSourceString # add-dsig @click...
import logging import random import threading import time from counters import Counters from filter.filter import Filter from filter.profanity import Profanity from match import Match from rate_limiters import RateLimiters from replies import Replies from sleep_wake import SleepWake import telegram from telegram.ex...
from sklearn.base import BaseEstimator, TransformerMixin from pyyawt.denoising import wden import numpy as np from sklearn.utils.validation import check_is_fitted class WaveletDenoiser(BaseEstimator, TransformerMixin): def __init__(self, threshold_rule='sqtwolog', threshold_type='s', scale='one', level=1, wavelet...
from threading import Thread from config import mismatch_cron_interval_sec, mismatch_email_service_url import logging from src.db import ModelRepo import requests from logging.config import dictConfig log = logging.getLogger('file') from logging.config import dictConfig repo = ModelRepo() class AlertCronProc...
from tailow.operators.base import Operator class SizeOperator(Operator): """ operator to query for arrays by number of elements """ def to_query(self, field_name, value): return {"$size": value} def get_value(self, field, value): return field.to_son(value)
import pandas as pd import torch from PIL import Image, ImageFile from torch.utils.data import Dataset import os device = torch.device("cuda:0") ImageFile.LOAD_TRUNCATED_IMAGES = True class CollectionsDataset(Dataset): def __init__(self, csv_file, root_dir, num_classes, image_size, folds=None, transform=None): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.MemberRule import MemberRule class ZhimaCreditPeZmgoTemplateCreateModel(object): def __init__(self): self._benefit_url = None self._biz_no = None self...
# Copyright 2019 Megagon Labs, Inc. and the University of Edinburgh. 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 # ...
from random import randint from collections import OrderedDict # from collections module my_dict = OrderedDict() # provide ordered dictionary my_dict['isim'] = 'ali' my_dict['cinsiyet'] = 'erkek' my_dict['yas'] = 123 print(my_dict) # from random module x = randint(1, 19) # random number generator print(x)
from tensorflow_asr.featurizers.text_featurizers import CharFeaturizer txf = CharFeaturizer(None, blank_at_zero=True) a = txf.extract("fkaff aksfbfnak kcjhoiu") print(a)
from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig ws = Workspace.from_config() experiment = Experiment(workspace=ws, name='pre-process') config = ScriptRunConfig(source_directory='src/azure_pipeline/src/', script='preprocess.py', compute_target='cpu-cluster') # set up environment env = En...
# farm_animals = {"sheep","cow","hen"} # # print(farm_animals) # # for animal in farm_animals: # print(animal) # # print("="*40) # # wild_animals = set(["lion","tiger","panther","elephant","fox"]) # # print(wild_animals) # for animal in wild_animals: # print(animal) # # farm_animals.add("horse") ...
import numpy as np import _pickle as pickle import os from Sliding_Block import * from LQR import dlqr import sys sys.path.insert(0,'./../') from Housekeeping import * def generate_demonstrator_logs(): if not os.path.exists(LOGS_DIRECTORY): os.makedirs(LOGS_DIRECTORY) file_to_save_logs = LOGS_DIREC...
from datetime import datetime import json import decimal from server.models.associations import Associations from datetime import datetime from pytz import timezone import pytz def comma_num(num): return "{:,}".format(int(num)) def pst_time(date): utc_dt = pytz.utc.localize(date) pst_tz = timezone('US/Pac...
from rest_framework import routers from app.apiviews import ( EntryViewSet, NotificationViewSet, PrivateMessageViewSet, TagViewSet, ) router = routers.DefaultRouter() router.register(r"entries", EntryViewSet) router.register(r"notifications", NotificationViewSet, basename="notifications") router.regis...
def main(): matching_names = [] name_data = {'Mick': {2010: 2, 2000: 1, 1910: 10}, 'Sam': 2021, 'Tim': 2022} target = 'Mick' y = name_data[target].get(1910) if y is None: print('**') else: x = name_data[target][1910] print(x) if __name__ == "__main__": ...
import base64 import json import logging import time import traceback import sys from apiclient import errors from docopt import docopt from googleapiclient import discovery from google.cloud import pubsub_v1 logger = logging.getLogger('resurrect.prere') PROJECT_ID = ' YOUR PROJECTID ' class GoogleCloud: """Help...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import asyncio import logging from typing import Any, Callable, List, NoReturn, Optional, Sequence, Uni...
import requests with open('lifx_token.txt', 'r') as myfile: token=myfile.read().replace('\n', '') headers = { "Authorization": "Bearer %s" % token, } #response = requests.get('https://api.lifx.com/v1/lights/all', headers=headers) #print(response.text) data = { "period": 2, "cycles": 6, "color":...
import pytest from discovery import api def sample_payload(): return { "Name": "my-query", "Session": "adf4238a-882b-9ddc-4a9d-5b6758e4159e", "Token": "", "Service": { "Service": "redis", "Failover": {"NearestN": 3, "Datacenters": ["dc1", "dc2"]}, ...
import pandas as pd from sklearn.svm import SVC import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix # Import data df = pd.read_csv("train.csv") # Inspect data scatter_matrix(df, alpha=0.2, figsize=(12, 12), diagonal='kde') plt.show()
from .containers import Dynamics, Cost from .controller import iLQR, MPC from .utils import GetSyms, Constrain, SoftConstrain, Bounded
#!/usr/bin/env python # -*- coding: utf-8 -*- # Data Processing for Journal Entries # Author: Gordon Blake """ Import command mongoimport --db vitaDB --collection entries --jsonArray < C:\Users\gblak\OneDrive\CodePractice\webdev\vita-app\data\parsed_entries.json Fixing the date db.getCollection('entries').find().fo...
# -- coding: utf-8 -- import tensorflow as tf import numpy as np import argparse from model.hyparameter import parameter import os import pandas as pd train_path=r'data/train.csv' class DataIterator(): #切记这里的训练时段和测试时段的所用的对象不变,否则需要重复加载数据 def __init__(self, site_id=0, ...
#!/usr/bin/env python # coding=utf-8 from unittest import TestCase from onepiece.example import hello_world class HelloWordTestCase(TestCase): def test_hello_world(self): self.assertEqual('One Piece', hello_world())
from fbs.fbs import FBSType class FBSJavaType(FBSType): _VALUES_TO_JAVA_TYPES = { FBSType.BOOL: "boolean", FBSType.BYTE: "char", FBSType.UBYTE: "char", FBSType.SHORT: "short", FBSType.USHORT: "short", FBSType.INT: "int", FBSType.UINT: "int", FBSType....
#!/usr/bin/python #-*- coding: utf-8 -*- #encoding=utf-8 import urllib2 import os import re from bs4 import BeautifulSoup import time # 下载文件 def downloadBook(bookLink): req = urllib2.Request(bookLink) req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML,...
""" ------------------------------------------------------------------------------- Name: dataPreprocessing Purpose: Pre-processing of the local test data Author: Christian Buchholz, Marcus Vogt Created: 01.12.2021 Copyright: Chair of Sustainable Manufacturing and Life Cycle Engineering, Institu...
# 取消协程 import asyncio from asyncio import Task def method_one(): async def cancellable(delay=10): loop = asyncio.get_running_loop() now = loop.time() try: print(f'sleeping from {now} for {delay} seconds...') await asyncio.sleep(delay) print(f'sleep {dela...
from __future__ import print_function, absolute_import from six import iteritems, itervalues from six.moves import range from ._file_reader import FileReader from ._table_data import PunchTableData def _default_callback(table_data): print(table_data.header) class OP2Reader(object): def __init__(self, filen...
def find_max(l): if len(l) == 1: # base case return l[0] else: n = len(l) left = l[:n//2] right = l[n//2:] l_start = left[0] l_end = left[-1] r_start = right[0] r_end = right[-1] if l_end == r_start: r...
import cv2 import numpy as np from utils.opencv_util import OpenCVUtil # def test_match(): # OpenCVUtil.init_load() # # img1 = cv2.imread("../data/small/aaweapon_type_1.png", cv2.COLOR_BGR2GRAY) # img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) # img2 = cv2.imread("../data/test.png", cv2.COLOR_BGR...
""" Given A Series Of N Positive Integers a1,a2,a3........an. , Find The Minimum And Maximum Values That Can Be Calculated By Summing Exactly N-1 Of The N Integers. Then Print The Respective Minimum And Maximum Values As A Single Line Of Two Space-Separated Long Integers. Input Format First Line Take Input Value Of ...
#!/usr/bin/env python3 # import logging import time import requests from telnetlib import Telnet from camdoris.camdoris_cfg import * from izquierbot.izquierbot import sendMessageToAdmin class Camdoris(object): def __init__(self, host, user, password, port, timeout, check_interval): self.host = host ...
# https://edabit.com/challenge/q4bBcq5NET4CH5Rcb # Jay and Silent Bob have been given a fraction of an ounce but they only understand grams. # Convert a fraction passed as a string to grams with up to two decimal places. An ounce weighs 28 grams. def jay_and_bob(weight: str) -> str: try: weight_dict...
import numpy as np import tensorflow as tf from baselines.common.runners import AbstractEnvRunner import copy class Runner(AbstractEnvRunner): """ We use this object to make a mini batch of experiences __init__: - Initialize the runner run(): - Make a mini batch """ def __init__(self,...
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Reference Release: STU3 Version: 3.0.2 Revision: 11917 Last updated: 2019-10-24T11:53:00+11:00 """ from pydantic import Field from . import element, fhirtypes class Reference(element.Element): """Disclaimer: Any field name ends with ``_...
import cv2 import cvzone from cvzone.HandTrackingModule import HandDetector import pyautogui import numpy as np import time wCam, hCam = 640, 480 frameR = 100 # Frame reduction smoothening = 10 INDEX_FINGER_TIP = 8 MIDDLE_FINGER_TIP = 12 INDEX_FINGER = 1 MIDDLE_FINGER = 2 pTime = 0 plocX, plocY = 0,0 clocX, clocY =...
import json import sys import os from tqdm import tqdm from mdf_refinery.parsers.tab_parser import parse_tab from mdf_refinery.validator import Validator # VERSION 0.3.0 # This is the converter for: Dataset for "Canopy uptake dominates nighttime carbonyl sulfide fluxes in a boreal forest" # Arguments: # input_path ...
import logging import logging.config def init_logging(file=None, file_level=logging.DEBUG, stdout=True): config = { 'version': 1, 'formatters': { 'consoleFormatter': { 'format': '%(levelname)s %(message)s' }, 'fileFormatter': { 'f...
import pandas as pd from tqdm.notebook import tqdm from .get_patient_protein_to_mutations_dict import get_patient_protein_to_mutations_dict from .is_core import is_core from .is_in_elaspic import is_in_elaspic from collections import defaultdict def counts_baseline_vs_our_method_personalized( proteins: list...
import shlex from subprocess import PIPE, STDOUT, Popen def get_simple_cmd_output(cmd, stderr=STDOUT): args = shlex.split(cmd) return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0].decode("utf8") def get_simple_cmd_output_lines(cmd, stderr=STDOUT): return get_simple_cmd_output(cmd, stderr).spl...
from uwsgiconf.config import Section def test_applications_basics(assert_lines): assert_lines([ 'need-app = true', ], Section().applications.set_basic_params(exit_if_none=True)) assert_lines([ 'mount = /articles=app.py', ], Section().applications.mount('/articles', 'app.py')) as...
from abc import ABC, abstractmethod from data_generators.basic_generator import * from data_generators.standard_generator import StandardDataGenerator class Environment(ABC): """Environment abstract base class. Constructor method uploads all the basic data from the given json source in the given mode""" ...
import random import re import numpy as np from utils import get_segments, get_ids, create_padding_mask def preprocess(file, BATCH_SIZE, max_length, tokenizer): train_dataset = [] input_vocab_size = len(tokenizer.vocab) f = open(file, 'r') words = f.read() words = words.replace('\n\n', '.') words...
from nginxauthdaemon import app
# App 8 file searcher
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache ...
from pyspark import SparkContext from pyspark.streaming import StreamingContext import pickle def averdd(x): global dict,counts,i i += 1 print(i) ts, mo, da, ho, mi, te, pr, hu, ws, wd, cl, wc = x.split(',') if mi=='0': init_dict() dict['hour'] = ho dict['temp'] += float(te)/counts ...
#!/usr/bin/env python # pylint:disable=E0401, E0611, C0103, W0621, W0612 # pylint:disable=R0912, R0914, R0915 '''Margarita - An Flask Application for managing Reposado Catalogs''' # This Flask application will only work with # Python 3 - Tested with Python 3.6.8 on CentOS 8 # Original Project by jessepeterson # https:/...
# Generated by Django 2.2.2 on 2019-06-23 15:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tracemap', '0006_species_mdd_id'), ] operations = [ migrations.RenameField( model_name='audiorecording', old_name='is_noise'...
# python3 asteroids.py # by Etienne Pitout import math import time import random import turtle import engine WIDTH = 640 HEIGHT = 480 MAXY = HEIGHT // 2 MINY = -HEIGHT // 2 MAXX = WIDTH // 2 MINX = -WIDTH // 2 MYX = 0 MYY = 0 MYDELTA = 0 MYCOLOR = 'white' MYSHAPE = 'triangle' THETA = 10 BGCOLOR = 'black' TEXTCOLOR ...
from greenlet import greenlet def consumer(): last = '' while True: receival = pro.switch(last) if receival is not None: print 'Consume %s' % receival last = receival def producer(n): con.switch() x = 0 while x < n: x += 1 print 'Produce %s' ...
from keystone.manage2 import base from keystone.manage2 import common from keystone.manage2 import mixins from keystone.backends import models @common.arg('--user-id', required=True, help='identifies the user who can authenticate with this credential') @common.arg('--tenant-id', required=False, help='...
#!/usr/bin/env python3 import sys import numpy as np from example import AmiciExample class ExampleDirac(AmiciExample): def __init__(self): AmiciExample.__init__( self ) self.numX = 2 self.numP = 4 self.numK = 0 self.modelOptions['theta'] = np.log10([1, 0.5, 2, 3]) ...
# coding: utf-8 """ qTest Manager API Version 8.6 - 9.1 qTest Manager API Version 8.6 - 9.1 OpenAPI spec version: 8.6 - 9.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class ManualTestLo...
# This module contains the shaders used to render snap point coordinates. # The shaders for snapping to a vertex. VERT_SHADER_V = """ #version 330 uniform mat4 p3d_ModelMatrix; in vec4 p3d_Vertex; void main() { gl_Position = p3d_ModelMatrix * p3d_Vertex; } """ GEOM_SHADER_V = """ #...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' The MIT License (MIT) Copyright (c) 2012-2013 Karsten Jeschkies <jeskar@web.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restrict...
from apps.terreno.models import Medida from django import forms class MedidaForm(forms.ModelForm): class Meta: model = Medida fields = ['largomedida', 'anchomedida', 'superficietotal'] labels = {'Largo':"Ingrese el Largo", 'Ancho': "Ingr...
from modeflip.utils.config import get_configuration from modeflip.utils.mongo import MongoManager from modeflip.models.statistics import * local_config = get_configuration('production') get_database = MongoManager(local_config, force_load=True) config_db = get_database('mf_config') sc = StatisticsConfig(config_db) d...
#!/usr/bin/env python3 """Quickly identify repos that are active and inactive from a user's personal... repos, starred and watching Note that this is the REST version and is less optimised than the Graph version This has been kept so a comparison can be made """ from __future__ import annotations from typing import ...
''' Created on Feb 5, 2013 @author: Brad ''' from solver import Solver, has_count, has_size, SolvedSet class JellyFishSolver(Solver): NAME = "JellyFish" TYPES = {1:"Row",2:"Col"} def find(self, board, do_all = False): solved_sets = [] possible = [has_count(has_size(board.get_row(i),2,...
# -*- coding: utf-8 -*- # Copyright (c) 2018 Sergey Bogatyrets # See LICENSE.md for details. import functools from copy import deepcopy from OPi.constants import BOARD, BCM, SUNXI, CUSTOM class _sunXi(object): def __getitem__(self, value): offset = ord(value[1]) - 65 pin = int(value[2:]) ...
import requests import json import xmltodict import datetime import calendar import os.path import os from pathlib import Path import pandas as pd from openpyxl import Workbook class Dolar(object): def __init__(self): self._url = 'https://www3.bcb.gov.br/bc_moeda/rest/converter/1/1/790/220/' def get_...
from django import template register = template.Library() @register.filter def richtext_isempty(value): """ Returns True if a value is None, an empty string, or empty paragraph tags Working around known issue https://github.com/wagtail/wagtail/issues/3111 with modification of workaround suggested i...
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- __author__ = 'lycheng' __email__ = "lycheng997@gmail.com" from public import ListNode, TreeNode from public import list_to_linked, linked_to_list import unittest class Solution(unittest.TestCase): def search(self, A, target): l, r = 0, len(A) - 1 whi...
import pytest from dbks.util import * @pytest.mark.parametrize( "src_dict, tgt_dict, result", [ ({"a": "A", "num": 0}, {"a": "A", "num": 0}, True), ({"a": "B", "num": 0}, {"a": "A", "num": 0}, False), ({"a": "A", "b": "B", "num": 0}, {"a": "A", "num": 0}, False), ({"a": "A", "n...
""" Create climate stripes version 1 Reference : https://matplotlib.org/matplotblog/posts/warming-stripes/ Author : Zachary M. Labe Date : 18 January 2021 """ ### Import modules import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from matplotlib.collections import Patch...
from forecastiowrap.api import ForecastioWrapper
#!/usr/bin/env python # Gant-chart style build time visualization tool for bam event logs. Usefull to find things preventing # good parallelization. Not very done, not very nice. # # build: # bam --debug-eventlog evlog.txt # Run: # vistime.py evlog.txt # # Written by Markus Alind (markus.alind at gmail.com) import ...
import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import weight_reduce_loss def _expand_onehot_labels(labels, label_weights, target_shape, ignore_index): """Expand onehot labels to match the size of prediction.""" bin_labels = labels.new_zeros(target_...
""" Type and packaing and unpacking of data values """ # pylint: disable=redefined-builtin,too-many-return-statements,too-many-branches,no-member import base64 import json from io import BytesIO from collections import OrderedDict import inspect import glob import re import sphinxcontrib.napoleon import sphinxcontri...