content stringlengths 5 1.05M |
|---|
from deep_translator import GoogleTranslator
import json
import yaml
import time
from tqdm import tqdm
from functools import partial
from datasets import load_dataset
import pickle as pk
failed = 'failed.jsonl'
dataset = load_dataset("covid_qa_deepset")
dataset_completo = dataset["train"]
def read_dataframe(dataset)... |
import pytest
from sam_spot_bot_create_job.job_dao import JobDao
from .my_ut_config import create_env
@pytest.fixture
def init_env():
create_env()
# TODO
def test_populate_file_meta_data(init_env):
pass
def test_create_index(init_env):
dao = JobDao()
dao.create_index()
def test_insert(init_env)... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.10.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import os
import pandas as pd
... |
from tree import *
from copy import deepcopy
n = 5
#
# given a tree (representing a vertex),
# yields the adjacent edges (pairs of trees)
#
def generate_adjacent_edges(t):
edges = []
# traverse tree to find pivot points
nodes = t.get_nodes()
for i in range(len(nodes)):
n = nodes[i]
if ... |
import argparse
import sys
import json
from typing import Optional, IO, Any
from dateutil.parser import parse as parse_date
from drillsrs.cmd.command_base import CommandBase
from drillsrs import db, util, scheduler
def _import(handle: IO[Any]) -> None:
with db.session_scope() as session:
deck_obj = json.l... |
from typing import List, Tuple
import numpy as np
from habitat.sims.habitat_simulator.actions import HabitatSimActions
from numpy import ndarray
class DiscretePathPlanner:
"""Runs a path planning algorithm that greedily minimizes the Euclidean
distance to a goal location as given in polar coordinates. The pa... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RRoc(RPackage):
"""utilities for ROC, with microarray focus.
Provide utilitie... |
from typing import Dict, List, Tuple
import numpy as np
from .util import Pigment
def confs_to_arrs(confs: List[Tuple[np.ndarray, List[Pigment]]]) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Convert the list of tuples of arrays into separate arrays."""
n_confs = len(confs)
n_pigs = len(confs[0][1])... |
import numpy as np
from matplotlib import pyplot as plt
import stat_tools as st
from datetime import datetime,timedelta
import ephem
from skimage.morphology import remove_small_objects
from scipy.ndimage import morphology,sobel
from scipy.ndimage.filters import maximum_filter,laplace
import mncc, geo
from scipy import ... |
import sys
from . import Archive
from . import Find
def get_input(v):
"""Get a REPL input."""
try:
if Archive.is_url(v):
return v
else:
print("[!]This input is invalid.", file=sys.stderr)
return ''
except(EOFError, KeyboardInterrupt):
print("\... |
"""Our decorator for web service methods"""
import json
import logging
from inspect import getargspec
from functools import update_wrapper
try:
from json import JSONDecodeError
except ImportError:
# Python 2
JSONDecodeError = ValueError
from circuits.core import handler
from circuits.web.wrappers import R... |
import requests
from bs4 import BeautifulSoup
import os
def get_config(config_str):
result = {}
for line in config_str.split("\\n"):
(key, val) = line.split(": ")
result[key.replace("'", "")] = val.replace("'", "")
return result
def request():
return requests.get(
os.environ[... |
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings("ignore")
def reverse_personality(nombre):
if nombre == 5:
nombre = 1
elif nombre == 4:
nombre = 2
elif nombre == 2:
nombre = 4
elif nombre == 1:
nombre = 5
return nombre
def reverse(nom... |
import matplotlib.pyplot as plt
import pandas as pd
from rich.progress import track
def plot_landscape(df, output_file = 'landscape.png'):
# Create a new figure
plt.figure()
# Convert ele to numeric
df['ele'] = pd.to_numeric(df['ele'])
# Create a list of activity names
activities = df['... |
"""The download config file consists of parameters required to download files
:param download_params['download_type']: Server name of the file location, currently supports Google Drive
:type download_params['download_type']: str (required)
:param download_params['base_url']: base URL of the server
:type downl... |
"""Tasks for TaxaTree Wrangler."""
from app.extensions import celery
from app.display_modules.utils import persist_result_helper
from app.tool_results.metaphlan2 import Metaphlan2ResultModule
from app.tool_results.kraken import KrakenResultModule
from app.tool_results.krakenhll import KrakenHLLResultModule
from .mode... |
import cv2
import imutils
import numpy as np
from datetime import datetime
from math import cos, sin, radians
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
# To capture video from webcam.
#cap = cv2.VideoCapture... |
from gensim.models.word2vec import Word2VecKeyedVectors
from gensim.models.word2vec import Word2Vec
import numpy as np
import util
print("Initializing word2vec")
w2v_fpath = "all.norm-sz100-w10-cb0-it1-min100.w2v" # small
# w2v_fpath = "tenth.norm-sz500-w7-cb0-it5-min5.w2v" # middle
# w2v_fpath = "all.norm-sz500-w10... |
import os
from database.settings.common import * # NOQA F401,F403
from database.settings.common import SITE_PACKAGE_NAME
from database.settings.common import BASE_DIR
from database.settings.common import INSTALLED_APPS
from database.settings.common import MIDDLEWARE
from database.settings.common import LOGGING
from d... |
numbers=[1,2,3,4,5]
sum_n=1
for i in numbers:
sum_n *= i
print(sum_n)
|
#!/usr/bin/python
# Copyright 2018, Red Hat, 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 a... |
import numpy as np
class Prey:
def __init__(self, initpos = [0, 0]) -> None:
self.pos = np.asarray(initpos, dtype = int)
def set_action(self, action):
action = int(action)
if action not in list(range(8)):
print('set_action传参错误!')
else:
cho... |
# Generated by Django 2.2.2 on 2019-08-19 12:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contents', '0007_auto_20190819_1210'),
]
operations = [
migrations.AddField(
model_name='focus',
name='color',
... |
import os
import sys
import re
import glob
import errno
files = glob.glob('output.txt')
for name in files:
print name
infile = open(name, "r")
outfile = open("hindi_nt_final.txt", "w")
lines = infile.readlines()
n = 23145
for line in lines:
n += 1
print line
findv = re.search(r"[0-9A-Z]{3... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 22:26:00 2020
@author: paulcalle
"""
# Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
# TensorFlow ≥2.0-preview is required
import tensor... |
import sys
def print_arr(arr, lo, hi):
for n in range(lo,hi+1):
print(arr[n], end=" ")
if hi != lo:
print()
def partition(arr, lo, hi, lo_list, hi_list):
lo_k, hi_k = 0,0
pivot = arr[lo]
for i in range(lo+1, hi+1):
if arr[i] < pivot:
lo_list[lo_k] = arr[i]
... |
import numpy as np
import scipy.ndimage as spim
import scipy.misc as spm
import skimage.transform as skit
import matplotlib.pyplot as plt
import sys, os
sys.path.append(os.getcwd())
from quadboost.datasets import MNISTDataset
from mnist.mnist_visualization import plot_images
from quadboost.utils import *
import json
... |
import pytest
import slack_responder
from mocks import SlackClient
config = {
'token': 'my-token',
'rules': {
'jira': {
# pattern: ABCD-1234 without any surrounding slashes / /
'pattern': r'(?<!/)\b([A-Z]{2,6}-\d{1,4})\b(?!/)',
'response': r'https://domain.jira.com/b... |
from flask import Flask
from config import config_options
from flask_bootstrap import Bootstrap
from flask_admin import Admin
from flask_sqlalchemy import SQLAlchemy
# from flask_login import LoginManager
# login_manager = LoginManager()
# login_manager.session_protection = 'strong'
# login_manager.login_view = 'auth... |
self.description = "Print replacements when using -Sup"
lp = pmpkg("a", "1-1")
self.addpkg2db("local", lp)
sp = pmpkg("b", "2-2")
sp.replaces = ["a"]
self.addpkg2db("sync", sp)
self.args = "-Sup"
self.addrule("PACMAN_RETCODE=0")
self.addrule("PACMAN_OUTPUT=%s-%s" % (sp.name, sp.version))
|
import gbp
import wave
import whgo
#import hog
import time
import cv2
import centrist
import numpy as np
import os
directory = "/media/neduchal/data2/datasety/miniplaces/images"
train_names = open("filelist.txt", "r").read().split("\n")
if len(train_names[-1]) == 0:
train_names = train_names[:-1]
test_names = tra... |
import glob
import os
import sys
import urllib.request
import django
sys.path.append("/var/projects/museum/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "z2.settings")
django.setup()
from z2_site.models import File
def main():
# Iterate over File objects
# Finds Files() that have no Zips
count = ... |
from django import template
from gpcharts import figure
from django.db import connection
from django.utils.safestring import mark_safe
import datetime
import time
register = template.Library()
@register.filter(name='split_valor')
def split_valor(num):
print 'valor q llego para corte es ',num
return ... |
# Add spaces to syntax in lines (for easier splitting by white-space)
FORT_TEXT_REPLACEMENTS = {
"DOUBLE PRECISION": "REAL ( KIND ( 0.0D0 ) )",
"END DO": "ENDDO",
"END IF": "ENDIF",
",":" , ",
"(":" ( ",
")":" ) ",
":":" : ",
"+":" + ",
"-":" - ",
"*":" * ",
"/":" / ",
"=... |
from django.db import models
from datetime import datetime
def expensive_calculation():
expensive_calculation.num_runs += 1
return datetime.now()
class Poll(models.Model):
question = models.CharField(max_length=200)
answer = models.CharField(max_length=200)
pub_date = models.DateTimeField('date ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@File: amapRegionSearch.py
@Project: amap
@Desc: 查询给定坐标点所属的行政区域信息
@Time: 2020/05/14 13:42:20
@Author: wuwenrufeng (wuwenrufeng@163.com)
@Last Modified: 2020/05/14 13:42:23
@Modified By: wuwenrufeng (wuwenrufeng@163.com)
@Version: 1.0
@License: Copyright(C) 2019 - 2020 ... |
import shlex, subprocess
import os
from os import listdir
from random import sample
import random
import numpy as np
import time
import threading
from threading import Thread
def test_fn(thread_number, number_of_task):
#path_pcap_data = "./pcap"
#dirs = os.listdir(path_pcap_data)
df_15_mins = []
... |
import os, json
class AppTheme:
def __init__(self, disk_path, *args, **kwargs):
self.disk_path = disk_path
config_file_path = os.path.join(self.disk_path, 'config.json')
with open(config_file_path, 'r') as f:
settings = json.load(f)
for key, value in settings.items()... |
# elements allowed to exist inside the HTML of a markdown text
ALLOWED_HTML_ELEMENTS = [
"a",
"abbr",
"acronym",
"br",
"blockquote",
"cite",
"code",
"em",
"figcaption",
"figure",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"img",
"li",
"ol",
... |
# Generated by Django 2.1.2 on 2018-10-24 17:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('register', '0004_user_woeid'),
]
operations = [
migrations.AlterModelOptions(
name='address',
options={'verbose_name_plural'... |
"""Lyric: Objects""" |
from atcoder import ReadInt,PrintLongN
from collections import Counter
def main():
N,Q = ReadInt(2)
s = Set()
c = Counter(ReadInt(N))
for k in c:
if c[k]%2==1:
s.add(k)
ans = []
for i in range(Q):
l,r,x = ReadInt(3)
g = s.lower_bound(l)
a = 0
... |
# Marcelo Campos de Medeiros
# ADS UNIFIP
# Estrutura de Repetição
# 24/03/2020
'''
7 - Faça um programa que leia 5 números e informe o maior número..
'''
print('=' * 40)
print('{:=^40}'.format(" 'MAIOR Nº ENTRE 5 DIGITADOS' "))
print('=' * 40, '\n')
# o maior começa do zero
maior = 0
# laço de repetição FOR pois te... |
import lab as B
import numpy as np
from mlkernels import EQ, DecayingKernel, Linear, ShiftedKernel
from ..util import approx, standard_kernel_tests
def test_shifted():
k = ShiftedKernel(2 * EQ(), 5)
# Verify that the kernel has the right properties.
assert k.stationary
# Test equality.
assert ... |
from . utils import read_csv
from . analyzer import create_report
from . converter import to_bin
from . engine import classify
|
import logging,os,sys,urllib,webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from withings_api import WithingsAuth, AuthScope
hostName = "localhost"
serverPort = 8000
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s : %(message)s', ... |
import unittest
from hsbot.utils.wbgt_api import (
get_yohou, get_jikkyou
)
from hsbot.utils.wbgt import WBGT
from requests.exceptions import HTTPError
from datetime import (
datetime, timedelta
)
class TestWbgtApi(unittest.TestCase):
"""
test class of http_client.py
"""
def test_get_yohou(se... |
# -*- coding: utf-8 -*-
import datetime
from io import BytesIO
import pytz
from django.core.files.storage import default_storage
from django.http import HttpResponse
from ledger.payments.pdf import BrokenLine
from ledger.settings_base import TIME_ZONE
from reportlab.lib.colors import red, green, blue
from reportlab.li... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from argparse import ArgumentParser, Namespace
from typing import Union
from idb.cli.commands.base import ConnectingCommand
from idb.client.client import IdbClient
from idb.common.types import Address, IdbException
def ge... |
#!/usr/bin/env python
"""
Created by howie.hu at 2018/8/13.
"""
import os
import subprocess
if __name__ == '__main__':
# os.environ['MODE'] = 'PRO'
servers = [
["pipenv", "run", "gunicorn", "-c", "config/dev_gunicorn.py", "--worker-class", "sanic.worker.GunicornWorker",
"server:app"],
... |
# Generated by Django 3.0.5 on 2020-04-20 11:03
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0011_auto_20200420_0847'),
]
operations = [
migrations.AlterField(
model_name='bo... |
from functools import partial
import torch
import Levenshtein
from holoclean.dataset import AuxTables
from .featurizer import Featurizer
def gen_feat_tensor(input, classes, total_attrs):
vid = int(input[0])
attr_idx = input[1]
init_value = input[2]
# TODO: To add more similarity metrics increase the... |
import urllib2
print "OK"
exit()
|
# -*- coding: utf-8 -*-
# This file is part of RRMPG.
#
# RRMPG is free software with the aim to provide a playground for experiments
# with hydrological rainfall-runoff-models while achieving competitive
# performance results.
#
# You should have received a copy of the MIT License along with RRMPG. If not,
# see <http... |
import matplotlib.pyplot as plt
import numpy as np
import pygame as pg
class IVProblem:
def __init__(self, rhs, y0, interval, name='IVP'):
"""
:param rhs: 'right hand side' function of the ordinary differential equation f(t,y)
:param y0: array with initial values
:param interval: s... |
#!/usr/bin/env python
#
# Copyright 2007 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 o... |
import re
from sekacek import sekejtext, sekejslovo
def text2syl(text):
t = sekejtext(" "+text+" ")
syl = []
last = None
for sl in re.split(r"( )",t):
for s in sl.split("/"):
if s == " ":
syl[-1] += s
else:
if last == " ":
s = " "+s
if "-" in s:
syl.extend([ s[:s.index("-")], s[s.ind... |
class Api(object):
def __init__(self, name, request_url, response_obj, method, desc, parameters):
self.name = name
self.request_url = request_url
self.response_obj = response_obj
self.method = method
self.parameters = parameters
self.desc = desc
class RequestParamet... |
"""
Our first fundamental value version used for the multi algorithm.
"""
from gryphon.lib.exchange.retry import exchange_retry
from gryphon.lib.money import Money
@exchange_retry()
def calculate(algo, fundamental_value_balance_map):
"""
Using the fundamental value balance map, the core fundamental value is ... |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mode', type=str, default='train', choices=['train', 'eval'])
parser.add_argument('--checkpoint-frequency', type=int, default=100)
parser.add_argument('--eval-frequency', type=int, default=500)
parser.add_argument('--batch-size', type=int, default... |
import logging
from netqasm.logging.glob import set_log_level
from netqasm.runtime.application import app_instance_from_path, network_cfg_from_path
from squidasm.run.multithread.simulate import simulate_application
APP_DIR = "../netqasm/netqasm/examples/apps/teleport"
def main():
set_log_level(logging.INFO)
... |
from kmn.util import *
import matplotlib.pyplot as plt
import pytest
from definitions import ROOT_DIR
VIS_TEST = False
d = 1./np.sqrt(2.)
q_axis_rot = [
(np.array([0.0, 0.0, 0.0, 1.0]), np.array([0., 0., 0.]), 0),
(np.array([1.0, 0.0, 0.0, 0.0]), np.array([1., 0., 0.]), np.pi),
(np.array([0.0, 1.0, 0.0, 0... |
from django.contrib import admin
# Register your models here.
from .models import Sorular
admin.site.register(Sorular)
|
## -*- coding: utf-8 -*-
"""
Created on Tue 27 Oct 2020
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 ... |
from bs4 import BeautifulSoup
import requests
# Save the HTML page of interest, and pass the HTML File address here
r = requests.get("http://gridlab-d.shoutwiki.com/wiki/Power_Flow_User_Guide")
data = r.text
soup = BeautifulSoup(data, features="lxml")
tables = soup.findAll("table")
syntax_list = []
for t in ta... |
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from app import app
from modules import constant
layout = dbc.Container(
[
dbc.Row([
dbc.Col([
html.A(
dbc.Row(
... |
"""
SynthesisModelHybrid.py
Author: Henri Lamarre
Affiliation: UCLA
Created on: Tue Oct 1 16:57:45 PDT 2019
Description:
"""
import numpy as np
from .SynthesisModel import SynthesisMaster, SynthesisModel
import scipy.interpolate as sci
from .Source import Source
# Not in test suite because we only pull-down BPAS... |
import logging
from urllib.parse import urlparse
from locr import Fetcher
from locr.exceptions import AmbiguousText, ObjectNotOnline
import requests
from .utilities import paginate_search, filter_results, filenamify
def slurp_collections(collections, filter_for_dates=False):
found = 0
total_words = 0
tot... |
import sublime, sublime_plugin
from time import time, sleep
import threading, thread
from Tag import Tag
import re
Tag = Tag()
s = sublime.load_settings('Tag Package.sublime-settings')
class Pref:
def load(self):
Pref.view = False
Pref.modified = False
... |
"""
@author: gsivaraman@anl.gov
"""
import torch
import gpytorch
from ECGMOD.GPmodels import InferGPModel, estimate_gpnoise
##DKL feature extractor
class LargeFeatureExtractor(torch.nn.Sequential):
def __init__(self, data_dim, l1out, l2out, l3out, final):
super(LargeFeatureExtractor, self).__init__()
... |
import fnmatch
from genbank.fileOps import prRowv
from genbank.GenomeSeqs import GenomeSeqs
class UnplacedChroms(object):
"object used to determine if a chromosome is unplaced"
def __init__(self, unSpecs):
self.unplaced = set()
self.pats = []
# separate into patterns and simple names ... |
from functools import wraps
from .exceptions import ArgumentError, CheckpointError
import torch
import os, errno, json, datetime
class BunchDictionary(object):
def reset_values(self):
self.__dict__ = {k: None for k, v in self.__dict__.items()}
def __getitem__(self, item):
return self.__dict__... |
from selenium.webdriver import Firefox
browser = Firefox()
browser.get('http://selenium.dunossauro.live/aula_11_a')
browser.find_element_by_id('alert').click()
alerta = browser.switch_to.alert
alerta.accept() # Confirma, clica no OK
alerta.dismiss() # Confirma, clica no OK
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 22:55:46 2020
@author: lukemcculloch
"""
from FileTools import GetLines
class DataHandler(object):
def __init__(self, project_name, path_to_inputs_folder):
self.GetLines = GetLines
self.path_to_inputs... |
#!/usr/bin/env python3
import os
import subprocess
os.environ['FLASK_APP'] = 'referee.server.flask'
subprocess.run(['python', '-m', 'flask', 'run'])
|
import numpy as np
import pandas as pd
import time
import simulation_tool.data as dax
import simulation_tool.initialization as init
import simulation_tool.measures as ms
import simulation_tool.distance as ds
import simulation_tool.batching as bt
import simulation_tool.evaluation as ev
import simulation_tool.simulation ... |
"""
MIT License
Copyright (c) 2021 Jojo#7711
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 restriction, including without limitation the rights
to use, copy, modify, merge, publish, dis... |
# Generated by Django 3.2.7 on 2021-10-15 09:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reservation_management', '0004_auto_20211001_1948'),
]
operations = [
migrations.AlterField(
model_name='lesson',
na... |
"""
Plot circular embedding
-----------------------
This example shows how to plot absorption probabilities using circular a posteriori projection :cite:`velten:17`.
"""
import cellrank as cr
adata = cr.datasets.pancreas_preprocessed("../example.h5ad")
adata
# %%
# First, we compute the absorption probabilities.
cr... |
"""Names of primitive types understand by raco.
Note that raco internally supports a limited set of types. Different backends
can support a richer set of types, but these aren't understood by raco's
type system. For example, raco doesn't distinguish between int and long,
so unsafe casts are not detected inside raco... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
from activityio._util import xml_reading
data = '''<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase>
<Activities>
<Activity Sport="Biking">
<Id>2015-03-24T15:19:06.000Z</Id>
<Lap StartTime="2015-03-24T15:19:06.000Z">
<To... |
import collections
from canvas.core.accounts import program_account
from canvas.core.courses import get_courses
from canvas.core.io import tada
from canvas.core.outcome_groups import delete_group, get_program_groups, get_root_group, get_subgroups
from canvas.core.outcomes import get_outcomes, link_outcome, unlink_outc... |
from ecg_record import EcgRecord
from random import randint
def get_sample_factor(strt, end):
return max(_get_sample_factor(strt, end), 8)
def _get_sample_factor(strt, end):
# If showing too a small range, sample_factor which is incremental steps should be at least 1
return max((end - strt + 1) // 600,... |
from flask import Flask, render_template
def create_app(config=None):
app = Flask(__name__)
if isinstance(config, dict):
for key in config:
app.config[key] = config[key]
app.config.from_object('recipebox.default_settings')
app.config.from_envvar('RECIPEBOX_SETTINGS', silent=True)
... |
import unittest
import cp_parse
class TestToken(unittest.TestCase):
def test_read_token(self):
test_cases = [
("\t:test_data (remainder)", "test_data", "(remainder)"),
("\t(test_data) remainder", "test_data", ") remainder"),
('\t("test_data") remainder', "test_data", "... |
#Importing the telebot module
import telebot
import os
import re
from modules import *
#Call the Telebot created in telegrm thanks to its TOKEN
bot = telebot.TeleBot("896532495:AAGNXUeLtWnoS5E8D-uei6Oql27CxWiFF9c")
#This function will accept documents like PDF articles
@bot.message_handler(content_types=['document'])... |
import unittest
import pyperclip
from credentials import Credentials
class TestCredentials(unittest.TestCase):
"""Test class that defines test cases for the credentials class behaviors
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
"... |
global_aliases = {}
def conflict(command_aliases):
"""Determines if there are conflicting commands
Args:
command_aliases: list of str, aliases for this command
Returns:
True if there is a conflict, false otherwise
"""
for alias in command_aliases:
if alias in global_aliase... |
from yolo_evm.constants import MAX_UINT256
from yolo_evm.stack import Stack, StackOverflow, StackUnderflow, InvalidStackItem
import pytest
@pytest.fixture
def stack() -> Stack:
return Stack()
def test_underflow(stack):
with pytest.raises(StackUnderflow):
stack.pop()
def test_overflow():
stack = ... |
from flask import Flask, make_response, request, abort
import pickle
import threading
import requests
import datetime
import hashlib
import time
import sys
import logging
import pathlib
import copy
import os
import os.path
import impact #ERASEHERE
import itertools
import hashlib
try:
with open("slack_webhook.txt"... |
import mysql.connector
# Insere informações no bando de dados MySql
def insertDataBase(id, initial_dat, initial_time, final_dat, final_time, work_time):
connection = mysql.connector.connect(host='localhost', database='db_projects',
user='root', password='196404', auth_plugi... |
############################################################
# -*- coding: utf-8 -*-
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 for python
# Python v3.5
#
# Michael Würtenberger
# (c) 2016, 2017
#
# Licence APL2.0
#
############################################################
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016, 2017, 2018 Guenter Bartsch
#
# 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.... |
# 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.
# pyre-unsafe
import json
import logging
from typing import List, Optional, Any, Dict, Union, Tuple
import numpy as np
import torch
from k... |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2012-2015 Peter Williams <peter@newton.cx> and collaborators.
# Licensed under the MIT License.
"""pwkit.cli - miscellaneous utilities for command-line programs.
Functions:
backtrace_on_usr1 - Make it so that a Python backtrace is printed on SIGUSR1.
check_usage ... |
import socket
import time
import json
import threading
Thread_Flag=1 #死锁计时进程
qian_Flag=0 #五次签到统计一次成员个数,五次签到一次都算
New_table=[] #新的成员列表,签到的就放里面
def sever():
global Thread_Flag,qian_Flag,New_table
HOST = '<broadcast>'
#HOST = "192.168.31.255"
ADDR = (HOST, 8884)
s = socket.socket(family=socket.AF_I... |
#
# @lc app=leetcode id=33 lang=python3
#
# [33] Search in Rotated Sorted Array
#
# @lc code=start
class Solution:
def search(self, nums, target):
if nums == []:
return -1
if len(nums) == 1:
if nums[0] == target:
return 0
return -1
if len(... |
from .meters import RunningValue,AverageMeter,SumMeter,AUCMeter |
import pytorch_lightning as pl
from ray import tune
from pytorch_lightning.callbacks import Callback
from train_ns_lstm import get_data, Model
from src.hyperparameters.search import main_tune
from src.args import init_lstmgnn_args, add_tune_params, add_configs
class ihm_TuneReportCallback(Callback):
def on_valida... |
import numpy as np
# equivalent to MATLAB sph2cart & cart2sph
def cart2sph(x,y,z):
azimuth = np.arctan2(y,x)
elevation = np.arctan2(z,np.sqrt(x**2 + y**2))
r = np.sqrt(x**2 + y**2 + z**2)
return azimuth, elevation, r
def sph2cart(azimuth,elevation,r):
x = r * np.cos(elevation) * np.cos(azimuth)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.