content stringlengths 5 1.05M |
|---|
from scraper.web_scraper import WebScraper
from loguru import logger
uri = 'https://www.investing.com/technical/technical-summary'
class SummaryTableScraper(WebScraper):
def __init__(self, uri, class_name):
super(SummaryTableScraper, self).__init__()
self.goto(uri)
self.n_table_pairs = ... |
import Bdecode as BD
import pprint
class Torrent:
def __init__(self, filename):
decoder = BD.Bdecode(filename)
self.torrentData = decoder.decode()
# self.meta_info = bencoding.Decoder(meta_info).decode()
def __str__(self):
whatever = pprint.pprint(self.torrentDa... |
import collections
from collections import OrderedDict
class ValidationError(Exception):
def __init__(self, errors):
self.errors = ValidationError.normalise(errors)
@staticmethod
def normalise(errors):
if isinstance(errors, dict):
new_errors = OrderedDict()
for k,... |
from school.models.class_model import Class
from account.models.instructor_model import InstructorProfile
from country.models.country_model import Country
from country.models.city_model import City
from school.models.school_model import School
from django.urls.base import reverse
from rest_framework.test import APITest... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Persistent identifier minters."""
from __future__ import absolute_import, print_f... |
from threading import local
from django.test import TestCase
from django.test import override_settings
from cid.locals import generate_new_cid
from cid.locals import get_cid
from cid.locals import set_cid
_thread_locals = local()
class TestCidStorage(TestCase):
def setUp(self):
self.clear_cid()
... |
'''Tools for interaction with IDF build system'''
def build_name(name):
name_parts = name.split('/')
return '__'.join(name_parts)
|
from torch.utils.data import Dataset, DataLoader
from albumentations import (ShiftScaleRotate, Compose, CoarseDropout, RandomCrop, HorizontalFlip, OneOf, ElasticTransform,
OpticalDistortion, RandomGamma, Resize, GaussNoise, VerticalFlip, RandomBrightnessContrast)
import cv2
import os
i... |
#!/usr/bin/env python
from subprocess import check_call
import sys
import os
import traceback
def safe_remove(f):
try:
if os.path.exists(f):
os.remove(f)
except:
traceback.print_exc()
pass
def tsprint(msg):
sys.stderr.write(msg)
sys.stderr.write("\n")
if __name... |
from .__init__ import *
def gen_func(maxRadius=100, format='string'):
r = random.randint(1, maxRadius)
ans = round((2 * math.pi / 3) * r**3, 3)
if format == 'string':
problem = f"Volume of hemisphere with radius {r} m = "
solution = f"{ans} m^3"
return problem, solution
... |
# -*- coding:utf8 -*-
'''
export data
'''
import logging
import xlwt
from LMDI import Lmdi
from SinglePeriodAAM import Spaam
from MultiPeriodAAM import Mpaam
class WriteLmdiData(object):
'''
write data using with surrounding
'''
def __init__(self, xls_file_name, *lmdis):
'''
constructio... |
from pathlib import PurePath
def part1(l: list[int]) -> int:
l = l.copy()
i = 0
while i < len(l):
match l[i]:
case 1:
l[l[i + 3]] = l[l[i + 1]] + l[l[i + 2]]
i += 3
case 2:
l[l[i + 3]] = l[l[i + 1]] * l[l[i + 2]]
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-06 21:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('marketgrab', '0008_remove_data_v'),
]
operations = [
migrations.AddField(
... |
from django.contrib import admin
from . import models
def push_to_influxdb(modeladmin, request, queryset):
for row in queryset:
row.push_to_influxdb()
@admin.register(models.Instance)
class InstanceAdmin(admin.ModelAdmin):
list_display = [
'name',
'url',
'users',
's... |
"""https://open.kattis.com/problems/provincesandgold"""
from collections import OrderedDict
vic, tres = OrderedDict(), OrderedDict()
vic = {"Province": 8, "Duchy": 5, "Estate": 2}
tres = {"Gold": 6, "Silver": 3, "Copper": 0}
inp = list(map(int, input().split()))
money = inp[0] * 3 + inp[1] * 2 + inp[2]
options = []
... |
#This script is hijacked from targetscan_parsecontextscores.py. It asks which miRNAs
#are enriched for having sites in a particular sequence set. Actually, more precisely,
#it just gives the density of sites for each miRNA. Number of sites for a miRNA / total sequence
#search space.
import os
import gffutils
impor... |
from cansfr import *
class can11xx (object):
'''
can11xx hierarchy
----------------- canm0
{sfr /
updrpl - ams ~ ~
{i2c / ... |
from __future__ import print_function
import argparse
import pickle
import os
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from torchvision import datasets, transforms
class Net(nn.Module):
def __init__(self):
super(Net, self)... |
# coding: utf-8
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2020 all rights reserved
#
"""
This package provides the implementation of a simple evaluation network.
There are three fundamental abstractions: variables, operators, and literals. Variables hold
the values computed by the evaluation network, ... |
#!/usr/bin/env python3
# coding: utf-8
import os
import glob
import sfml as sf
class Animation:
"""
An animated texture.
"""
def __init__(self, frames, interval=0):
"""
:param frames: Iterable of sf.Texture objects
:param interval: Time between two frames (default: 0.0s)
"""
self.frames = frames
s... |
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from utils import get_args, get, print_args, get_seed, extract_seed_from_ckpt
from logger import set_logger
from vilmedic.executors import Trainor, Validator
def main():
# Get args and create seed
config, override = get_args()
... |
import h5py
import os
from ._core import hfile
from .. import utils
from .. import h5tree
def test_h5tree(hfile):
assert hfile is not None
assert os.path.exists(hfile)
assert not utils.isHdf5FileObject(hfile)
str_list = [
b"Q=1",
b"Q=0.1",
b"Q=0.01",
b"Q=0.001",
... |
from uuid import uuid1
POSTGRES_MAX_TABLE_NAME_LEN_CHARS = 63
NULL_CHARACTER = "\\N"
def generate_table_name(source_table_name: str) -> str:
table_name_template = "loading_{source_table_name}_" + uuid1().hex
# postgres has a max table name length of 63 characters, so it's possible
# the staging table nam... |
'''
black_scholes.py
Created on Oct 11, 2018
@author: William Quintano
'''
from scipy.stats import norm
import math
'''
Calculates the price of a stock option using the black scholes model
:param s strike price
:param t remaining lifespan of option in years
:param u price of underlying stock (To get call... |
#!/usr/bin/env python
from argparse import ArgumentParser
from distutils.util import get_platform
from setuptools import find_packages, setup
parser = ArgumentParser()
parser.add_argument("--plat-name", type=str, default=get_platform())
args, unknown_args = parser.parse_known_args()
if args.plat_name == "win32":
... |
# Generated by Django 3.2.3 on 2021-06-06 17:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('asset', '0001_initial'),
('category', '0001_initial'),
]
operations = [
migrati... |
#!/usr/bin/env dls-python2.7
"""Write coordinated magnet moves to different outputs.
A PvWriter and a Simulation writer are available to take magnet_jogs.Moves
and apply them to their respective interfaces.
"""
from cothread.catools import caput
from controls import PvReferences, PvMonitors, Arrays
import magnet_jo... |
"""Test BrownianExcursion."""
import pytest
from stochastic.processes.continuous import BrownianExcursion
def test_brownian_excursion_str_repr(t):
instance = BrownianExcursion(t)
assert isinstance(repr(instance), str)
assert isinstance(str(instance), str)
def test_brownian_excursion_sample(t, n, thresh... |
import random
class RandomFlip(object):
"""Flips node positions along a given axis randomly with a given
probability.
Args:
axis (int): The axis along the position of nodes being flipped.
p (float, optional): Probability that node positions will be flipped.
(default: :obj:`0.5... |
def is_lock_ness_monster(s):
return any(phrase in s for phrase in ["tree fiddy", "three fifty", "3.50"]) |
import json
import pandas as pd
import time
#################################
#
#with open('logs.json', 'r') as data:
# data = data.read()
#
#logs = json.loads(data)
#
########################
def get_data(file):
with open(file, 'r') as data:
data = data.read()
logs = json.loads(data)
#s = Sender('Test', '192... |
# coding: utf-8
import datetime
import random
from http import HTTPStatus
from unittest.mock import Mock
from django.test.client import RequestFactory
import pytest
from src.infrastructure.api.views.exchange_rate import (
CurrencyViewSet, CurrencyExchangeRateViewSet)
from tests.fixtures import currency, exchang... |
import mysql.connector
# Multicraft Cred
mydb = mysql.connector.connect(
host="",
user="",
password="",
database=""
)
mycursor = mydb.cursor()
# WHMCS Cred
mydb_whmcs = mysql.connector.connect(
host="",
user="",
password="",
database=""
)
mycursor_whmcs = mydb_whmcs.cursor()
|
import argparse
import sys
import analyse
import calibration
from logginghelpers import configure_logging
ALL_CMD = 'all'
MUNICIPALITY_CMD = 'municipality'
def parse_settings(settings) -> dict:
result = {}
if settings is not None:
for setting in settings:
k, v = setting.split('=')
... |
import sys
import time
import pygame
from pygame.locals import *
from classes.disk import Disk
from classes.robot import Robot
from classes.exit import Exit
"""
This class is used for the simulation
It loops 60 times a second so it can draw and update the simulation
"""
class Window:
def __init__(self):
... |
from os import name
from django.urls import path, include
from .views import *
urlpatterns = [
path('latest-products/', LatestProductsList.as_view(), name="latest-products"),
path('checkout/', checkout, name="checkout"),
path('orders/', OrdersList.as_view(), name="orders"),
path('products/search/', sea... |
from Cartas import Baraja, Carta
import os
Line = '---------------------------'
def clear():
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
class Jugador:
def __init__(self, nombre: str, mazo: Baraja):
self.nombre = nombre
self.cardSum = 0
self.aca... |
import time
import random
import itertools as it
from pathlib import Path
from collections import namedtuple
import numpy as np
import torch.nn.functional as F
from vizdoom import DoomGame, ScreenResolution, \
ScreenFormat, GameVariable, Mode, Button
from utils.helpers import get_logger
logger = get_logger(__fil... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.graph_objs as go
dataset_train = pd.read_csv('sg_train.csv')
dataset_train_copy = dataset_train.copy()
dataset_train_copy = dataset_train_copy.sort_value... |
import unittest
import xmlconfigparse
import xml.etree.ElementTree as ET
import xml.etree.ElementPath as EP
class XmlToDictTest(unittest.TestCase):
"""
"""
@classmethod
def setUpClass(cls):
"""Creates new xml file to test"""
# Creates xml file to be modified by test
root = ET... |
from typing import Literal
foo: Literal[""] = ""
bar: Literal[''] = ''
|
time_travel = int(input())
speed_travel = int(input())
liters = (speed_travel * time_travel) / 12
print('{:.3f}'.format(liters))
|
import os
import re
import ssl
from operator import itemgetter
import requests
import urllib3
from bs4 import BeautifulSoup
from smart_open import open
ssl._create_default_https_context = ssl._create_unverified_context
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
MAIN_PAGE = "https://tff.org/d... |
# Copyright 2020 Dylan Baker
# 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, sof... |
# FinSim
#
# Copyright 2019 Carnegie Mellon University. All Rights Reserved.
#
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING,... |
#Follow up for "Unique Paths":
#
#Now consider if some obstacles are added to the grids. How many unique paths would there be?
#
#An obstacle and empty space is marked as 1 and 0 respectively in the grid.
#
#For example,
#There is one obstacle in the middle of a 3x3 grid as illustrated below.
#
#[
# [0,0,0],
# [0,1,0],... |
# 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
#
# 示例 :
# 给定二叉树
#
# 1
# / \
# 2 3
# / \
# 4 5
# 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
#
# 注意:两结点之间的路径长度是以它们之间边的数目表示。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
# 著作权归领扣网络所有。商... |
#!/usr/bin/env python
"""
Creates MRI axial pictures for custom T-shirt.
Usage:
mripicture.py [options] <study>
mripicture.py [options] <study> [-s <subject>]...
mripicture.py [options] <study> [-s <subject>]... [-t <tag>]
Arguments:
<study> Nickname of the study to process
Options:
-... |
#!/usr/bin/env python3
from calendar import monthrange
year = int( input() )
( startDay, endDay ) = monthrange( year-543, 2 )
print( endDay )
|
#!/usr/bin/python3
import os
import time
from datetime import datetime as dt
import logging
#from .database.database import *
from threading import Thread
class BloquearSites:
def __init__(self):
logging.basicConfig(filename="C:\\ConectaIT\\modules" + '\\logs\\logBloquearSites.log')
#s... |
#numeric integration using the 2-point trapezoidal rule
from math import *
EPSILON = .0001 #base length of trapezoids
def evaluate_function(func, a):
func_at_a = eval(func.replace('x', str(a)))
return func_at_a
#doesnt yet take into account ability of domain a,b to have b<a
def integrate(func, domain):
... |
__author__ = 'Jay Hennessy <tjay.hennessy@gmail.com>'
__license__ = 'MIT'
import os
__version__ = '0.0.1' # fantraxpy version
VERSION = '17.0.0' # fantrax version
URL = 'https://www.fantrax.com/fxpa/req'
FANTRAX_TOKEN = os.environ.get('FANTRAX_TOKEN', None)
|
"""
This module contains tests for the utility functions in the test_mapping module.
"""
import pytest
from sqlalchemy import (
Column,
Index,
Integer,
UniqueConstraint,
)
from sqlalchemy.orm import registry
from galaxy.model import _HasTable
from . import (
collection_consists_of_objects,
has_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-03-22 14:40
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
# Mod01.py
from MyCalc01 import Calc01
from MyCalc01.Calc01 import *
x= 100; y= 200
print(Calc01.__name__)
Calc01.Sum(x, y)
Mul(x,y)
|
class ValidationException(Exception):
pass
class DataApiException(Exception):
"For errors raised when reading from data api"
|
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is
# licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... |
# -*- coding: utf-8 -*-
"""
Class for a multi-panel structure
"""
__version__ = '1.0'
__author__ = 'Noemie Fedon'
import sys
import numpy as np
sys.path.append(r'C:\BELLA')
from src.BELLA.parameters import Parameters
from src.BELLA.constraints import Constraints
from src.BELLA.panels import Panel
from s... |
import warnings
import dateutil.parser
from requests import Session
from time import sleep
from .config import ( # noqa
__version__,
API_ROOT,
DEFAULT_USER_AGENT,
API_KEY_ENV_VAR,
ENVIRON_API_KEY,
)
session = Session()
session.headers.update({"Accept": "application/json"})
session.headers.update(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Distributed under the terms of the MIT License.
"""
Script to append window and cage COM's to a CIF.
Author: Andrew Tarzia
Date Created: 19 Feb 2019
"""
import sys
from ase.io import read
import pywindow as pw
import logging
import os
import atools
def main():
i... |
# Copyright (C) 2013 by Brian Neal.
# This file is part of m209, the M-209 simulation.
# m209 is released under the MIT License (see LICENSE.txt).
"""test_converter.py - Unit tests for the M209 class for the M-209 simulation."""
import unittest
from .. import M209Error
from ..converter import M209
# Data taken fro... |
from os import listdir
import json
from pymongo import MongoClient
prediction_output = '../data/prediction_output/' # Edit
def connect_db(mode, db_name):
client = MongoClient('localhost', 27017)
db = client[db_name]
collection = db['train'] if mode == 'train' else db['val']
return collection
if __nam... |
from wsgiref.util import FileWrapper
from django.conf import settings
from django.http import Http404, HttpResponse, StreamingHttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.urls import reverse
from wagtail.core import hooks
from ... |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from datadog_api_client.v1.model_utils import (
ModelNormal,
cached_property,
... |
import demistomock as demisto
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
# IMPORTS
from typing import Tuple, Optional
import traceback
import dateparser
import httplib2
import urllib.parse
from oauth2client imp... |
from django.shortcuts import render, redirect
from django import forms
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import authenticate, login, update_session_auth_hash
from django.contrib.auth.models import User
from django.contrib.auth.decorator... |
import math, itertools
from functools import lru_cache
def distance_squared(p1, p2):
x1, y1 = p1
x2, y2 = p2
dx, dy = x1 - x2, y2 - y1
return dx * dx + dy * dy
def points_up_tile_size_px(size):
return math.floor(size * math.sqrt(3)), size * 2
def flats_up_tile_size_px(size):
return size * ... |
class Board:
ROW_COL_BASE = 1
def __init__(self, board, N):
"""
Builds a Board from a list of blocks and the size of the board. The list must hold N^2 blocks.
:param board: the list with the blocks.
:param N: the size of the board (length = width = N)
:return: a new B... |
#!/usr/bin/env python3
"""
Clean up (making tar) a single simulation directory after successful cybershake submissions
"""
import os
import glob
import shutil
import tarfile
import argparse
from qcore import utils
SUBMISSION_DIR_NAME = "submission_temp"
SUBMISSION_TAR = "submission.tar"
SUBMISSION_FILES = [
"fli... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
APRI和FIB4推测肝纤维化或肝硬化情况
This is a temporary script file.
"""
import math
#APRI缩写:AST to Platelet Ratio Index
#AST单位iu/l
#PRI单位10**9/L
#如果APRI>2,可能有肝硬化
def APRI(AST,upper_AST,PRI):
apri=((AST*1.0/upper_AST)*100)/PRI
return apri
#FIB-4缩写Fibrosis-4
#age单位:年
#AST和ALT单... |
"""
:class:`Registrable` is a "mixin" for endowing
any base class with a named registry for its subclasses and a decorator
for registering them.
"""
import importlib
import logging
from collections import defaultdict
from typing import (
Callable,
ClassVar,
DefaultDict,
Dict,
List,
Optional,
... |
import functools
import os
import pickle
# decorator for pickle-caching the result of a function
def pickle_cache(cache_filename, compare_filename_time=None, overwrite=False):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
exists = os.path.exists(cache_filena... |
# Generated by Django 3.0.4 on 2021-04-13 19:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0004_uploader_image_l'),
]
operations = [
migrations.AlterField(
model_name='uploader',
name='id',
... |
# "THE BEER-WARE LICENSE" (Revision 42):
# <flal@melix.net> wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return
# read a json describing people do the magic to pick two different peop... |
'''
Python program to add two positive integers without using the '+' operator
'''
'''
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the ... |
import timer.helper.thread as thread
class TestThreadIsNone():
def test_real_none(self) -> None:
assert thread.is_none(None) is True
def test_text_none_uppercase(self) -> None:
assert thread.is_none("NONE") is True
def test_text_none_lowercase(self) -> None:
assert thread.... |
# Copyright (c) 2019, Stefan Grönke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... |
# todo
|
import pickle
from pathlib import Path
import torch
import os
from sklearn.model_selection import GroupKFold
from torch.utils.data import DataLoader
from classifier.config import get_conf
from classifier.fracture_detector.data import get_meta, WristFractureDataset
from classifier.fracture_detector.data._transform im... |
# pylint: disable=all
__version__ = "2.12.0"
__author__ = "Criteo"
|
from ray.util.collective.collective import nccl_available, gloo_available, \
is_group_initialized, init_collective_group, destroy_collective_group, \
create_collective_group, get_rank, get_collective_group_size, \
allreduce, allreduce_multigpu, barrier, reduce, reduce_multigpu, \
broadcast, broadcast_mu... |
from sys import argv, exit
import sys
sys.path.append('src')
import os
import pandas as pd
import numpy as np
import random
from matplotlib import pyplot as plt
from ag import Ag
from graph import Graph
from pprint import pprint
from utils import readFiles
if __name__=='__main__':
vertexes, edges, cities_df, cit... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64
import time
import gzip
from hashlib import md5
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8', line_buffering=True)
def Decrypt(key:str, text:str) -> str:
if len(key) < 32: key += ' '... |
import pytest
from time import time
from bitmex_async_rest import BitMEXRestApi
@pytest.fixture
def testnet():
return BitMEXRestApi('testnet')
async def test_throttle(testnet: BitMEXRestApi):
# for i in range(120):
# funding = await testnet.funding(count=1)
# assert i == 119
assert True
asyn... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unsupervised Kernel Regression (UKR) for Python.
Implemented as a scikit-learn module.
Author: Christoph Hermes
Created on Januar 16, 2015 18:48:22
The MIT License (MIT)
Copyright (c) 2015 Christoph Hermes
Permission is hereby granted, free of charge, to any pers... |
from typing import *
@overload
def check_array_indexer(array: geopandas.array.GeometryArray, indexer: numpy.ndarray):
"""
usage.geopandas: 4
"""
...
@overload
def check_array_indexer(
array: geopandas.array.GeometryArray, indexer: slice[None, int, None]
):
"""
usage.geopandas: 2
"""
... |
import pandas as pd
from scipy import stats
def my_oneway_anova(x):
my_data = pd.read_csv(x)
normal = my_data[my_data['condition']=='condition_a']['response_time']
degraded = my_data[my_data['condition']=='condition_b']['response_time']
return stats.f_oneway(normal, degraded)
|
#!/usr/bin/env python
import argparse
from argparse import RawTextHelpFormatter
import bammend as bm
def parse_args():
"""Parse command-line arguments"""
summary = ('Remove pulses from reads in Pacbio Bam. Annotation indices \n'
'are indexed from the beginning of the ZMW read (i.e. query \n'
... |
"""
The API, responsible for receiving the files, submitting jobs, and getting their results.
"""
import asyncio
from contextlib import suppress
import os
from typing import Optional
from uuid import UUID, uuid4
from fastapi import (
Depends,
FastAPI,
File,
HTTPException,
Path,
Query,
Resp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Safe
a commandline password manager using AES encryption, written in python.
:: author Erick Daniszewski
:: date 05 December 2015
"""
import json
import getpass
import argparse
import struct
from os import mkdir, remove
from os.path import join as join_path
fr... |
# coding: utf-8
from __future__ import absolute_import
from unittest.mock import patch
from xcube_hub import api
from xcube_hub.controllers.callbacks import put_callback_by_cubegen_id
from xcube_hub.models.callback import Callback
from test import BaseTestCase
class TestCallbacksController(BaseTestCase):
"""Ca... |
"""AI Engines
Here is a set of AI- and ML-patterns for adavanced research of business data.
"""
|
from unittest.mock import MagicMock
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super().__call__(self, *args, **kwargs)
|
from django.db import models
from django.test import TestCase
from django_fsm import FSMField, transition, can_proceed
class TestExceptTargetTransitionShortcut(models.Model):
state = FSMField(default="new")
@transition(field=state, source="new", target="published")
def publish(self):
pass
@t... |
# Problem: https://www.hackerrank.com/challenges/py-check-strict-superset/problem
set_A = set(input().split())
n = int(input())
ind = 0
for _ in range(n):
set_n = set(input().split())
union_set = set_A.union(set_n)
if (union_set == set_A) and (len(set_A) > len(set_n)):
ind += 1
if ind == n:
pri... |
import sys
import os
import os.path
import glob
def compareOutputs( expected, actual, message ):
expected = expected.strip().replace('\r','').split('\n')
actual = actual.strip().replace('\r','').split('\n')
diff_line = 0
max_line_to_compare = min( len(expected), len(actual) )
for index in xrange(0... |
from unittest import mock
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
from django_countries.fields import Country
from django_prices_vatlayer.models import VAT
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from saleor.core.taxes.vatlayer im... |
#These variables are needed to make local variables in functions global
custom_end=''
homework_end=''
assignment_end=''
test_end=''
quiz_end=''
final_end=''
custom_advance_details=''
def quizzes():
while True:
quiz_weight=input('How much does your quizzes weigh? or if not applicable type n/a ')
... |
from msal.authority import *
from msal.exceptions import MsalServiceError
from tests import unittest
class TestAuthority(unittest.TestCase):
COMMON_AUTH_ENDPOINT = \
'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
COMMON_TOKEN_ENDPOINT = \
'https://login.microsoftonline.com/co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.