content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from pathlib import Path
from tempfile import NamedTemporaryFile
import numpy as np
import pandas as pd
import pytest
from etna.datasets import generate_ar_df
@pytest.fixture
def base_pipeline_yaml_path():
tmp = NamedTemporaryFile("w")
tmp.write(
"""
_target_: etna.pipeline.Pipeline
... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... | python |
##########################################################################
# MediPy - Copyright (C) Universite de Strasbourg
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for de... | python |
# # # # # # # # # # # # #
# #
# #
# #
# Pi Radio #
# By #
# Jackson #
# Hoggard #
# (c)2018 #
# #
# #
# #
# # # # # # # # # # # # #
import os, argparse, random
from colorama import Fore, Back, Style
from multiprocessing import Process
parser = argparse.ArgumentParser(pr... | python |
import struct, base64
import numpy as np
mdmr_dtypes = { 0: 's', 1: 'I', 2: 'q', 3: 'f', 4: 'd'}
# output of test_encode
b64data = """TURNUjAwMDECAAAABAAAAKUAAAAAAAAABAAAADcAAAAAAAAAAAAAAAAAAAB47j1cctzBv2t9kdCWc8G/fSJPkq6ZwL/PSe8bX3u+v6TC2EKQg7q/6iEa3UHstL8YQznRrkKqv4NuL2mM1oG/GEM50a5Cqj96Nqs+V1vBPxR5knTN5M8/yol2FVJ+... | python |
from app import app
from config import MONGO_URI, client
from flask import session, request, jsonify
import pymongo
import requests
import json
from datetime import datetime
# 連進MongoDB
db = client['aiboxdb']
@app.route('/api/android/getRemind', methods=['GET'])
def android_get_remind():
'''取得沒有user_nickname(未登入)... | python |
from pathlib import Path
from typing import Tuple, Callable, Union
ReadPaths = Union[Tuple[Path], Tuple[Path, Path]]
def _make_paired_paths(
dir_path: Path,
paired: bool,
mkstr: Callable[[int], str]
) -> ReadPaths:
path1 = dir_path/mkstr(1)
return (path1, dir_path/mkstr(2)) if paired ... | python |
import json
from lib import action
class VaultWriteAction(action.VaultBaseAction):
def run(self, path, values):
return self.vault.write(path, **json.loads(values))
| python |
import numpy as np
import operator
def TI_Forward_Neighborhood(D, p, Eps):
""" ."""
seeds = []
forwardThreshold = p.dist + Eps
# You have to declare the list to traverse.
# First is the index with element "p"
# Items are selected from start to item "p"
# And finally it turns around
in... | python |
import time
import os
from coala_utils.decorators import enforce_signature
from coalib.output.printers.LogPrinter import LogPrinterMixin
from coalib.misc.CachingUtilities import (
pickle_load, pickle_dump, delete_files)
class FileCache:
"""
This object is a file cache that helps in collecting only the ch... | python |
from flask import Flask
from flask import render_template, url_for, request
import datetime
from person import Person
from my_lib import get_week
from parser_price import Parser_price
from head_hunter_vacancies import HeadHunter_vacancies
from bd_apartment import Appartment_BD
from sqlalchemy import create_engine
fro... | python |
#from __future__ import absolute_import
from celery import shared_task
#from celery.contrib import rdb #DEBUG
@shared_task
def myflqTaskRequest(analysisID):
from django.conf import settings
from myflq.models import Analysis,AnalysisResults
from django.core.files import File
import subprocess,time,tempf... | python |
import json
from importlib import resources
import requests
import explorer
from explorer import configs
from explorer.enums.fields_enum import FieldsEnum as fields
from explorer.utils.parsing import ResponseParser as parser
class BlockchainExplorer:
def __new__(cls, api_key: str, net: str, prefix: str):
... | python |
import feedparser
import justext
import requests
import sys
from database import Database
from bs4 import BeautifulSoup
import re
import mistune
from unidecode import unidecode
def get_text_from_reuters(link):
response = requests.get(link)
resText = response.content.decode("UTF-8", 'ignore')
soup = Beautif... | python |
from typing import Dict, Type
from .setting import Setting
class SettingRegistry:
def __init__(self):
self._registry: Dict[Type, Type[Setting]] = {}
def register_setting(self, type_hint: Type, setting_cls: Type[Setting]):
self._registry[type_hint] = setting_cls
def get_setting_class_for... | python |
import boto3
from botocore.exceptions import ClientError
from .config import s3, bucket_name
import logging
log = logging.getLogger("my-logger")
def generate_presigned_url(s3_client, client_method, method_parameters, expires_in):
"""
Generating a presigned Amazon S3 URL that can be used to perform an action... | python |
#!/usr/bin/env pytest-3
# -*- coding: utf-8 -*-
#
# This file is part of the minifold project.
# https://github.com/nokia/minifold
__author__ = "Marc-Olivier Buob"
__maintainer__ = "Marc-Olivier Buob"
__email__ = "marc-olivier.buob@nokia-bell-labs.com"
__copyright__ = "Copyright (C) 2018, Nokia"
__license__ ... | python |
import numpy as np
import matplotlib.pyplot as plt
#Für jeden Wert in der Liste neuen e-Wert errechnen
def e_function(my_list):
return [np.exp(val) for val in my_list]
#Funktion plotten
def plot_func(x, y, farbe, windowName):
plt.figure(windowName)
plt.plot(x, y, color=farbe)
plt.title("My Image")
... | python |
from recon.core.module import BaseModule
import re
class Module(BaseModule):
meta = {
'name': 'Shodan Hostname Enumerator',
'author': 'Tim Tomes (@LaNMaSteR53)',
'description': 'Harvests hosts from the Shodan API by using the \'hostname\' search operator. Updates the \'hosts\' table with t... | python |
from .imports import *
def bn_drop_lin(inp, n_out, bn=True, p=0., actn=None):
out = inp
if bn:
out = BatchNormalization()(out)
if p>0:
out = Dropout(p)(out)
use_bias = False if bn else True
out = Dense(n_out, activation=actn, use_bias=use_bias)(out)
return out
| python |
# -*- coding: utf-8 -*-
highestNumber = -1
highestNumberPosition = -1
for i in range(100):
number = int(input())
if number > highestNumber:
highestNumber = number
highestNumberPosition = i + 1
print(highestNumber)
print(highestNumberPosition) | python |
import requests, re
def fbvid(url):
req=requests.get(url)
if req.status_code == 200:
try:
return {"status":True,"url":re.search('hd_src:"(.+?)"', req.text)[1]}
except TypeError:
return {"status":False,"msg":"private_video"}
else:
return {"status":False,"msg":... | python |
import pandas as pd
import numpy as np
import datetime
import numba
import time
import os
def cummul(array):
temp = 1
ret = []
for element in array:
temp *= element
ret.append(temp)
return np.array(ret)
def listdirs(folder):
return [
d for d in (os.path.join(folder, d1) fo... | python |
text = input("entrez une chaine de caracteres : ")
isPalindromic = text[0] == text[len(text) - 1]
i, j = 0, len(text)- 1
while i < j and isPalindromic:
isPalindromic = text[i] == text[j]
i, j = i + 1, j - 1
print(isPalindromic)
| python |
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.properties import ListProperty
from kivy.uix.behaviors import ButtonBehavior
import urllib.requ... | python |
#!/bin/python3
import json
import os
import sys
import io
import time
from specimen import specimen
from growlab_v1_http_client import growlab_v1_http_client
from readingsbuilder import readingsbuilder
from pathbuilder import pathbuilder
if __name__ == "__main__":
print("Starting growlab")
config = {}
t... | python |
#!/usr/bin/env python
# encoding: utf-8
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
r = 0
hd... | python |
import atexit
from pathlib import Path
from typing import Dict, Union
from .template import BaseTemplate
from .exceptions import NotFoundError
class MemoryEngine(object):
_data: Dict
_path: Path
_template: BaseTemplate
def __init__(self, path: Union[Path, str], template: BaseTemplate, auto_load=True... | python |
#!/usr/bin/python
#Libraries
import RPi.GPIO as GPIO
import time
#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)
#set GPIO Pins
GPIO_TRIGGER = 18
GPIO_ECHO = 24
GPIO_IR = 6
#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
GPIO.setup(GPIO_IR, GPIO.IN, pull_up_down=GPI... | python |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from projects.tokens import token_generator
from rest_framework import permissions
class HasAPIAccess(permissions.BasePermission):
""" """
message = _('Invalid or missing API Key.')
def has_permission(self, request, view):
... | python |
# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... | python |
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# A script to test the mask filter.
# replaces a circle with a color
# Image pipeline
reader = vtk.vtkPNMReader()
reader.ReleaseDataFlagOff()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm")
reade... | python |
"""
Testing area package
"""
from shapes.square.area import area_square
from shapes.square.perimeter import perimeter_square
import pytest
def test_square_area():
"""
testing function area_square
"""
length = 2
A = area_square(length)
assert pytest.approx(A) == 4.0
def test_square_perimeter... | python |
from dataset import FontData, make_tfrecodes
gspath='gs://your-bucket-name/'
def make1():
d = FontData()
make_tfrecodes(d, gspath, 512, 64, 8, train=True)
make_tfrecodes(d, gspath, 512, 64, 8, train=False)
if __name__ == "__main__":
make1()
| python |
import zipfile
import pytest
from git_taxbreak.modules.writer import Writer
@pytest.fixture
def patch_zip_file(monkeypatch):
class ZipFileMock(zipfile.ZipFile):
def __init__(self, *args, **kwargs):
self.output = args[0]
self.content = []
def __enter__(self):
r... | python |
import sys
import shutil
from pathlib import Path
import logging
from pcv import DEFAULTS_PATH, CALLER_PATH, SOURCE, STATIC, DIST
"""
Initializes a pcv project in the current folder.
Run from command line:
python -m pcv.start
This will create the following directory tree in the current folder:
.... | python |
import numpy as np
import PatternToNumber
def computing_frequencies(text, k):
m = 4**k
frequency_array = np.zeros(shape = (1, m), dtype = int)
for i in range(len(text) - k + 1):
pattern = text[i:i+k]
j = PatternToNumber.pattern_to_number(pattern)
frequency_array[0 , j] = frequency_array[0, j] + 1
return... | python |
# Copyright(C) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Dict, List
import numpy as np
import xarray as xr
from .base_jags_impl import BaseJagsImplementation
class RobustRegression(BaseJagsImplementation):
def __init__(self, **attrs: Dict) -> None:
self.attrs = attrs
... | python |
import discord
import os
from keep_alive import keep_alive
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if str(message.author) in ["robbb... | python |
""" Command line utility for repository """
import fire
from repo_utils import get_repository_path
import os
import importlib
# This will make available all definitions found under the same package that this file is found.
# This allows making a command line out of any package with the repo_utils template by putting s... | python |
from random import choice
from typing import Union
from datetime import datetime
from discord import User, Member, Embed
from discord.ext import commands
from bot.main import NewCommand
class Hug(commands.Cog):
def __init__(self, client):
self.client = client
def randomise(self, users:list):
... | python |
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import timezone
from transductor.models import EnergyTransductor, TransductorModel
class EnergyTransductorViewsTestCase(TestCase):
def setUp(self):
t_model = TransductorModel()
t_model.name = "TR 4020"
... | python |
'''
Created on March 30, 2018
@author: Alejandro Molina
'''
import numpy as np
from spn.algorithms.StructureLearning import get_next_operation, learn_structure
from spn.algorithms.Validity import is_valid
from spn.algorithms.splitting.Clustering import get_split_rows_KMeans, get_split_rows_TSNE
from spn.algorithms.s... | python |
__version__ = "0.0.1"
from ._widget import LiveIDS
from .video_ui import initui
| python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('eventlog', '0037_auto_20180911_1252'),
]
operations = [
migrations.RemoveField(
model_name='celerytaskprogress',... | python |
import pytest
from kaneda.backends import BaseBackend
class DummyBackend(BaseBackend):
reported_data = {}
def report(self, name, metric, value, tags, id_=None):
payload = self._get_payload(name, value, tags)
payload['metric'] = metric
self.reported_data[name] = payload
@pytest.fixt... | python |
#!/usr/bin/env python
"""
Copy one netCDF file to another with compression and sensible
chunking
Adapted from nc3tonc4
https://github.com/Unidata/netcdf4-python/blob/master/utils/nc3tonc4
"""
from netCDF4 import Dataset
import numpy as np
import numpy.ma as ma
import os
import sys
import math
import op... | python |
#!/usr/bin/python3
__author__ = 'yangdd'
'''
example 034
'''
def hello_world():
print('Hello World')
def three_hello():
for i in range(3):
hello_world()
if __name__ == '__main__':
three_hello() | python |
from xml.etree import ElementTree
import csocha
from . import board, moves
class GameState:
def __init__(self, c: str, t: int, b: board.Board, undep: list):
self.color = c
self.opponent = "BLUE" if c == "RED" else "RED"
self.turn = t
self.board = b
self.undeployed = undep
... | python |
from fastapi import FastAPI
TAREFAS = [
{"id": 1, "titulo": "Cristiano"},
{"id": 2, "titulo": "Araujo"}
]
app = FastAPI()
@app.get('/tarefas')
def listar():
return TAREFAS | python |
import string
from model_mommy import mommy
from datetime import datetime
from django_rq import job
from django.contrib.auth.models import User
from django.utils import timezone
from dateutil.parser import parse as extract_date
from django.conf import settings
from survey.models import *
from survey.utils.decorators im... | python |
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 = ... | python |
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... | python |
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,... | python |
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... | python |
# -*- 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... | python |
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()
... | python |
'''Tools for interaction with IDF build system'''
def build_name(name):
name_parts = name.split('/')
return '__'.join(name_parts)
| python |
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... | python |
#!/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... | python |
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
... | python |
# -*- 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... | python |
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]]
... | python |
# -*- 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(
... | python |
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... | python |
"""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 = []
... | python |
#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... | python |
from cansfr import *
class can11xx (object):
'''
can11xx hierarchy
----------------- canm0
{sfr /
updrpl - ams ~ ~
{i2c / ... | python |
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)... | python |
# 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... | python |
# -*- 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, ... | python |
#!/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... | python |
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()
... | python |
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",
... | python |
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... | python |
'''
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... | python |
#!/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":
... | python |
# 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... | python |
#!/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... | python |
"""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... | python |
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... | python |
def is_lock_ness_monster(s):
return any(phrase in s for phrase in ["tree fiddy", "three fifty", "3.50"]) | python |
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... | python |
# 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... | python |
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()
| python |
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('=')
... | python |
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):
... | python |
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... | python |
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... | python |
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... | python |
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... | python |
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... | python |
from typing import Literal
foo: Literal[""] = ""
bar: Literal[''] = ''
| python |
time_travel = int(input())
speed_travel = int(input())
liters = (speed_travel * time_travel) / 12
print('{:.3f}'.format(liters))
| python |
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... | python |
# 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... | python |
# 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,... | python |
#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],... | python |
# 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
#
# 示例 :
# 给定二叉树
#
# 1
# / \
# 2 3
# / \
# 4 5
# 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
#
# 注意:两结点之间的路径长度是以它们之间边的数目表示。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
# 著作权归领扣网络所有。商... | python |
#!/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:
-... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.