content
stringlengths
5
1.05M
from common import db, ma from flask import jsonify from flask_restful import Resource # exam workload simple class ExamWorkloadSimple(db.Model): id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(10)) percentage = db.Column(db.Float) coverage = db.Column(db.Float) duration = ...
""" Steps: 1. If the size of array A is 1, then the array is already sorted. So, return. 2. Else, perform one pass of iterative bubble sort on the given subarray. It will place the last element at its correct position. 3. Use recursion call to perform the above steps again on a smaller subarray with size reduced by o...
import os from networkx import DiGraph from memory_profiler import profile from dotenv import load_dotenv from app.decorators.datetime_decorators import logstamp from app.decorators.number_decorators import fmt_n from app.friend_graphs.bq_grapher import BigQueryGrapher load_dotenv() USERS_LIMIT = int(os.getenv("US...
from django.conf.urls.defaults import patterns, url from django.contrib.auth.decorators import login_required import django.db from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from ..core.app import SatchlessApp fr...
#!/usr/bin/env python3 # Standard Library import inspect import os import sys from pathlib import Path from subprocess import run def _inspect_tasks(prefix): return { f[0].replace(prefix, ""): f[1] for f in inspect.getmembers(sys.modules["__main__"], inspect.isfunction) if f[0].startswith(...
import itertools import operator import string from abc import ABC, abstractmethod from functools import partial, reduce, update_wrapper from itertools import chain, repeat, starmap from random import choices from typing import Callable, Iterable, Sequence, TYPE_CHECKING, Union import pytest import torch from hypothes...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Documentation """ class Writer(object): """ show anything """ def __init__(self): """ show anything """ self.__write() def __call__(self, *args, **kwargs): self.__write() @staticmethod def __write()...
# Crie um programa que leia um número inteiro qualquer e mostre sua tabuada. num = int(input('Digite um número e vejá sua tabúada: ')) print('{} x 0 ='.format(num), num*0) print('{} x 1 ='.format(num), num*1) print('{} x 2 ='.format(num), num*2) print('{} x 3 ='.format(num), num*3) print('{} x 4 ='.format(num),...
import unittest import requests import webtest from main import init_app_without_routes from modules.users.helpers import get_or_create_user class TrottoTestCase(unittest.TestCase): def setUp(self): self.init_app() # always put some data in the database since it seems like in Linux, the datastore emulat...
import random import pytz from faker import Faker from apps.news.models import Article from apps.users.models import UserProfile from apps.user_operation.models import UserFav, UserComment fake = Faker("zh_CN") def fake_comment(count=500): """生成假评论数据的函数""" articles = Article.objects.values_list('id') art...
from Blocky.Timer import AddTask , runtime import Blocky.uasyncio as asyncio NTP_PAIR = [] def sync_ntp(): try : import usocket , ustruct NTP_QUERY = bytearray(48) NTP_QUERY[0] = 0x1b s = usocket.socket(usocket.AF_INET,usocket.SOCK_DGRAM) s.settimeout(2) res = s.sendto(NTP_QUERY,usocket.getaddrinfo("pool...
import geo import numpy as np import os def cRMSD(coo1, coo2, norm=100): rmsd = np.sqrt(np.mean(np.square(np.linalg.norm(coo1-coo2, axis=-1)))) if norm: norm_rmsd = rmsd / (1 + np.log(np.sqrt(len(coo1) / norm))) return norm_rmsd else: return rmsd def GDT(coo1, coo...
#!/usr/bin/python3 # Copyright 2021. FastyBird s.r.o. # # 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 re...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'index.html'
################################################### # pyDtsTool # # Copyright 2021, Altium, Inc. # # Author: Keith Lee # # E-Mail: keith.lee@altium.com # ################################################### from py...
########################################################################### # Check if any of the Python files touched by the commit have # code style problems. ########################################################################### import os.path import re import subprocess from beefore import diff LABEL = 'Jav...
"""Test Home Assistant remote methods and classes.""" from datetime import timedelta import pytest from homeassistant import core from homeassistant.helpers.json import ExtendedJSONEncoder, JSONEncoder from homeassistant.util import dt as dt_util def test_json_encoder(hass): """Test the JSON Encoder.""" ha_...
""" First quote out lower line starting with import... . Then, run this code and observe the outputs Runs the imported function. __name__ is imported script. meseeks() is not known Then, quote out first line starting with from... Run the code twice and observe the outputs ...
import re from mat.utils.utils import Utils, Issue class Issue(Issue): TITLE = 'Weak Random Check' DESCRIPTION = 'Checks if the application uses weak random generation functions [NOT RELIABLE]' ID = 'weak-random' ISSUE_TITLE = 'Application Generates Insecure Random Numbers' FINDING...
import contextlib @contextlib.contextmanager def nest_test(name): print('Entering', name) yield name print('Exiting', name) @contextlib.contextmanager def propagater(name, propagate): try: yield print(name, 'exited normally.') except Exception: print(name, 'received an ex...
import logging from pylons import config, app_globals from ckan import logic from ckan.logic import get_action from ckan.plugins import toolkit from ckanext.harvest.logic.dictization import harvest_job_dictize import ckan.lib.mailer as mailer log = logging.getLogger(__name__) def send_error_mail_ncar(context...
# Generated by Django 3.1.11 on 2021-07-29 21:33 from django.db import migrations, models import wagtail.core.blocks import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('questionnaires', '0007_auto_20210728_1220'), ] operations = [ migrations.AlterField( ...
# -*- coding: utf-8 -*- import os import pandas as pd # gestionar datasets import numpy as np #gestionar numeros import matplotlib.pyplot as plt # hacer gráficos os.chdir('/Users/pablobottero/github/master/python/data_analysis/tasks/first_one') print(os.getcwd()) songs = pd.read_csv('spotify.csv', sep=',...
# -*- coding: utf-8 -*- """ Created on Friday, 2/13/15 @author: Justin Madsen, 2015 """ import pandas as pd import matplotlib.pyplot as plt import matplotlib import pylab as py class ChronoTrack_pandas: ''' @class: loads, manages and plots output from any number of output files from Chrono Trac...
# Use Python 3 import timeit import gc setup = f""" gc.enable() import os, sys sys.path.insert(0, os.path.abspath(".")) from model import ForestFire import random random.seed(2) def runthemodel(fire): for i in range(0, 100): fire.step() fire = ForestFire() """ tt = timeit.Timer('runthemodel(fire)', se...
class Node: def __init__(self, val): self.val = val self.next = None self.prev = None class Cache: def __init__(self, promptinstance, mode): self.promptinstance = promptinstance self.mode = mode self.head = Node(0) self.tail = Node(0) self.head...
import numpy as np import cv2 import time def nothing(x): pass if __name__ == "__main__": start = time.time() img = cv2.imread("./Project/Tho/Linux/data/ex7.png", cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (200, 200)) img = cv2.GaussianBlur(img, (3, 3), 0) # img = np.array([[41, 57, 98, 91,...
from typing import List class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: B = sorted(A) ans = B[-1] - B[0] lmin, rmax = B[0] + K, B[-1] - K for i in range(len(B) - 1): imin, imax = min(lmin, B[i + 1] - K), max(rmax, B[i] + K) ans = min(...
import numpy as np import torch from ofa.imagenet_classification.elastic_nn.networks.ofa_mbv3 import OFAMobileNetV3 as OFA1 from tqdm import tqdm from hyperbox.datamodules.imagenet_datamodule import ImagenetDataModule from hyperbox.mutator import RandomMutator from hyperbox.networks.ofa.ofa_mbv3 import OFAMobileNetV3 ...
# coding: utf-8 import pprint import re import six class BugStatisticResponseV4: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the v...
#import setuptools from distutils.core import setup setup(name='brl_gym', version='1.0', description='Bayesian RL Environments', author='Gilwoo Lee', author_email='gilwoo301@gmail.com', license='', package_data={'': ['resource/*.json']}, include_package_data=True...
class SlowSolution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = set() N = len(nums) for i in xrange(N-2): for j in xrange(i+1, N-1): for k in xrange(j+1, N): if nums[i] + nums[j] + nums[k] == 0: res.add( tuple(sorted([nums[i], nums[j],...
from datetime import datetime, timezone from gfibot.collections import * from gfibot.model.predictor import * from gfibot.model.utils import * def test_get_update_set(mock_mongodb): threshold = 1 dataset_batch = [ Dataset.objects(name="name", owner="owner", number=5).first(), Dataset.objects(n...
import urllib import json url = 'http://maps.googleapis.com/maps/api/geocode/json?' location = raw_input('Enter location: ') url = url + urllib.urlencode({'sensor':'false', 'address': location}) print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved', len(data), 'characters' json = json.l...
# 9_movingCircle.py - for CSI-102 Lab 9: More practice with Pygame # Adds colors and user interaction # # Name: Ben Goldstone # Date: 10/20/2020 #INITIALIZE: import pygame pygame.init() # Constants WIDTH = 800 HEIGHT = 600 BOX_SIZE = 100 HALF_BOX = BOX_SIZE // 2 SPEED = 5 # Color Constants RED = (255, 0, 0) GREEN =...
from pathlib import Path import librosa import numpy as np import torch from torch.utils.data import Dataset, DataLoader from configs.train_config import SpectConfig from models.model import get_conv_output_sizes def load_audio(audio_path, samp_rate=16000): """Loads the audio signal stored at the given path.""" ...
# *-* coding=utf-8 *-* from django import template from django.conf import settings from django.contrib.sites.models import Site from django.utils.html import format_html, mark_safe, strip_tags from django.utils.text import capfirst, Truncator from blogoland.confs import DEFAULT_DATE_FORMAT from blogoland.models impor...
from matplotlib import pyplot as plt from matplotlib.axes import Axes import pandas as pd import numpy as np from typing import * from yo_fluq_ds._fluq._common import * def default_ax(ax): if ax is None: _, ax = plt.subplots(1,1) return ax
import numpy as np from scipy.integrate import quad __all__ = ["make_roundflat"] def make_roundflat( lower_bound=0.1, upper_bound=0.6, lower_steepness=2.0, upper_steepness=8.0, integration_bounds=(0.0, 10.0), ): """Construct a round-flat prior with a certain shape. The resulting prior is...
import time from adafruit_circuitplayground.express import cpx from adafruit_crickit import crickit MIN_PULSE = 750 MAX_PULSE = 2250 MAX_ANGLE = 160 STEP = 10 DELAY = 0.1 def init(servo): servo.set_pulse_width_range(MIN_PULSE, MAX_PULSE) servo.angle = 0 servo.actuation_range = MAX_ANGLE def move(servo,...
from enum import Enum from typing import Optional, Tuple class SortType(Enum): TICKET = "ticket" BID = "amount_bid" ASK = "amount_ask" LOW = "amount_low" HIGH = "amount_high" CLOSE = "amount_prev_close" CHANGE = "delta_percent" VOLUME = "volume" @classmethod def from_arg(cls,...
# -*- coding: utf-8 -*- """Module containing the GistFile object.""" from __future__ import unicode_literals from .. import models class _GistFile(models.GitHubCore): """Base for GistFile classes.""" def _update_attributes(self, gistfile): self.raw_url = gistfile['raw_url'] self.filename = g...
from typing import List from led import Led from transitions import AbstractTransition class Sudden(AbstractTransition): def __init__(self, red: float, green: float, blue: float) -> None: super().__init__() self.target = Led(red, green, blue) @AbstractTransition.brightness.setter def b...
import os import torch import numpy as np from torch.autograd import Variable import random from ctextgen.dataset import * from ctextgen.finalmodel import RNN_VAE from tqdm import trange from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from transformers import get_line...
import os import glob import random import numpy as np import pandas as pd from PIL import Image import torch from torch.utils.data import Dataset, DataLoader from torchvision.datasets.folder import DatasetFolder from torchvision import transforms def normalize_label(df, params): r"""Normalize labels for trainin...
"""Class to control the sockets.""" from __future__ import annotations from ..command import Command from ..const import ATTR_DEVICE_STATE, ATTR_SWITCH_PLUG from .base_controller import BaseController from .socket import Socket, SocketResponse class SocketControl(BaseController): """Class to control the sockets....
from PyQt5.QtWidgets import QGridLayout, QLabel, QGroupBox, \ QDialog, QComboBox, QDialogButtonBox, QFormLayout from PyQt5.QtGui import QIcon from serial.tools import list_ports from src import util speed = [str(v) for v in [9600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200]] class portWindow(QDialog): ...
from zipfile import ZipFile import gradio as gr def zip_to_json(file_obj): files = [] with ZipFile(file_obj.name) as zfile: for zinfo in zfile.infolist(): files.append( { "name": zinfo.filename, "file_size": zinfo.file_size, ...
from ..factory import Type class textEntityTypeMentionName(Type): user_id = None # type: "int32"
import sys import string import io # enables encoding # Opening and reading file article.txt file = io.open('article.txt', mode='r', encoding='utf-8') with file as f: found = [] longest = "" for line in f: for character in line: if character.lower().isalpha() and character.lower() not ...
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.db import models from django.urls import reverse from django.utils.translation import ugettext as _ from .managers import AlumnoManager, AlumnoMateriaManager, PlanMateriaManager from fiubar.users.models import User class Alumno(m...
from flask import Flask app=Flask(_name_) @app.route('/') def hello_world(): greeting="World" return f'Hello, {greeting}!' if _name_ == "_main_": app.run()
#import wifi #wifi.start()
import random import json import gym from gym import spaces import pandas as pd import numpy as np MAX_ACCOUNT_BALANCE = 100000000 MAX_NUM_SHARES = 100000000 MAX_SHARE_PRICE = 1000 MAX_OPEN_POSITIONS = 5 MAX_STEPS = 20000 INITIAL_ACCOUNT_BALANCE = 10000 class Discrete1EquityShort(gym.Env): """A stock trading ...
import os import cv2 import logging import numpy as np from vidaug import augmentors as va from PIL import Image, ImageSequence from multiprocessing import Process, Queue def gif_loader(path, modality="RGB"): frames = [] with open(path, 'rb') as f: with Image.open(f) as video: index = 1 ...
import os from srd import add_params_as_attr, add_schedule_as_attr from srd.ontario import template module_dir = os.path.dirname(os.path.dirname(__file__)) # wrapper to pick correct year def form(year): """ Fonction qui permet de sélectionner le formulaire d'impôt provincial par année. Parameters --...
from config import env, secrets from hvpytils import HvSession, HvCookies from multiprocessing.connection import Listener from requests import Request import logging # @todo error handling LOG = logging.getLogger('SessionWorker') LOG.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setLevel(loggi...
# -------------------------------------------------------------------------- # Copyright (c) <2017> <Lionel Garcia> # BE-BI-PM, CERN (European Organization for Nuclear Research) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='patroniser', version='0.3', description='Patreon Syncer', author='Thomas Lant', author_email='lampholder@gmail.com', packages=find_packages() #package_data={'': ['*.json', '*.csv', '*.yaml']}, #scripts=['b...
from selenium import webdriver from .driver import broswer import unittest import os class MyTest(unittest.TestCase): def setUp(self): self.driver = broswer() self.driver.implicitly_wait(10) self.driver.maximize_window() def tearDown(self): self.driver.quit()
""" Opens xyz files and returns the atoms and cooridnates in various forms """ import numpy as np def open_xyz(xyz_file): """ Opens an xyz file and returns a list of lists Parameters ---------- xyz_file: String File path Returns ---------- List of lists: List of lists O...
# vi: set softtabstop=2 ts=2 sw=2 expandtab: # pylint: disable=raise-missing-from # import json import requests from manager.db import get_db from manager.log import get_log from manager.notifier import register_notifier, Notifier, SQL_GET_NOTIFIER from manager.exceptions import BadCall # used for displaying configura...
''' Problem Statement: Given a string, find the length of the longest substring without repeating characters. Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. ''' class Solution: def lengthOfLongestSubstring(self, s: str) -> int: substr:str='' ...
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import os import sys import getopt import keras import keras.backend as K from keras.preprocessing import image import cluster_stats as cs import develop as d import analysis as a import coding_theory as code import random """This script is for tes...
''' This file is modified from: https://github.com/rishikksh20/CrossViT-pytorch/blob/master/crossvit.py ''' import torch from torch import nn, einsum import torch.nn.functional as F import math from einops import rearrange, repeat from einops.layers.torch import Rearrange class Residual(nn.Module): def __init__...
# # Blessing a disk for booting # # The runner initializes disk, loads up the GRUB boot loader # import sys from .runner import Runner from .ops_ui import console_ui from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_install_grub, task_finalize_disk, task_unmount from ..components.disk...
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='a project to analyze broadband internet acces in the US', author='Erik Kristofer Anderson', license='MIT', install_requires=['pandas', 'numpy'] )
""" Role tests """ import pytest # To run all the tests on given docker images: pytestmark = pytest.mark.docker_images( 'infopen/ubuntu-xenial-ssh-py27:0.2.0' ) def test_temporary_package_file(SystemInfo, File): """ Test downloaded package from URL """ if SystemInfo.distribution == 'ubuntu': ...
#!/usr/bin/env python3 """ Base class for Models. ALL Models should at least inherit from this class When inheriting model_data should be a list of NNMeta objects. See the class for details. """ import logging import os import sys import time from json import JSONDecodeError from shutil import copyfile, copyt...
import logging from colorama import Fore, Style, init init() def _default(message: str) -> str: return message def _info(message: str) -> str: return f'{Fore.GREEN}{message}{Style.RESET_ALL}' def _warning(message: str) -> str: return f'{Fore.YELLOW}{message}{Style.RESET_ALL}' def _error(message: s...
# -*- coding: utf-8 -*- try: from rest_framework import permissions class IsOwnerOrIsStaffOrIsReadOnly(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has...
# -*- coding: utf-8 -*-` """api.py - Create and configure the Game API exposing the resources. This can also contain game logic. For more complex games it would be wise to move game logic to another file. Ideally the API will be simple, concerned primarily with communication to/from the API's users.""" from __future__...
import pytest from django.contrib.auth import get_user_model from django.template import Context, Template from proposals.models import AdditionalSpeaker, TalkProposal def render_template(template_string, context_data=None): context_data = context_data or {} return Template(template_string).render(Context(c...
from typing import Dict, List, Optional, TypeVar, Union from pydantic import BaseModel, Field from pymatgen.analysis.magnetism.analyzer import Ordering from pymatgen.core.periodic_table import Element from pymatgen.core.structure import Structure from emmet.core.electronic_structure import BandstructureData, DosData ...
import logging import pandas as pd from ampligraph.latent_features import ComplEx from ampligraph.utils import save_model logging.basicConfig(level=logging.INFO) import click @click.command() @click.option( "--data-path", help="Path to training data stored as csv where each row is node_a, relation, node_b."...
import cgi import datetime import httplib2 import logging import socket import urllib import urlparse from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.utils import simplejson as json from django.contrib.sites.models impor...
from admin_ordering.admin import OrderableAdmin from django.contrib import admin from medication_icons.models import Icon from .models import Effect from .models import Medication from .models import MedicationEffect def medication_effect_factory(medication=None, effect=None): class MedicationEffectInline(Ordera...
# greaseweazle/tools/pin.py # # Greaseweazle control script: Set a floppy interface pin to specified level. # # Written & released by Keir Fraser <keir.xen@gmail.com> # # This is free and unencumbered software released into the public domain. # See the file COPYING for more details, or visit <http://unlicense.org>. de...
from setuptools import setup, find_packages setup( name='spot-memair', version='2018.5.28.0', description='updates memair with spot data', long_description=open('README.rst').read(), url='https://github.com/gregology/spot-memair', author='Greg Clarke', author_email='greg@gho.st', licens...
#!/usr/bin/env ambari-python-wrap """ 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...
# -*- coding: utf-8 -*- """ Created on Mon Oct 23 22:22:57 2017 @author: dzhaojie """ import ExtractIntensityMulti as EIM import multiprocessing import numpy as np if __name__ == '__main__': ################################ #process all the field of views ################################ ...
import torch import torch.nn as nn from torch.distributions import Categorical import operator def q_categorical(q_value): """ Generate a Categorical distribution object given a Q value. We construct a one-hot distribution according to the Q value. This is for prediction only and we do not require gra...
"""Internal utilities for determining cache expiration and other cache actions. .. automodsumm:: requests_cache.cache_control :classes-only: :nosignatures: .. automodsumm:: requests_cache.cache_control :functions-only: :nosignatures: """ from __future__ import annotations from datetime import datetime, t...
# Generated by Django 2.0 on 2018-01-17 14:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('django_workflow', '0008_auto_20180117_1236'), ] operations = [ migrations.AlterField( model_name=...
# pulled from https://hackersandslackers.com/scraping-urls-with-beautifulsoup/ import requests from bs4 import BeautifulSoup import re # def list all comebacks this month? headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Ty...
# -*- coding: utf-8 -*- from graphics.config import config as graph_cfg class config: # Global neurorack info class neurorack: device = 'Neurorack' version = 0.01 # Global screen info class screen: # Screen modes mode_init = 0 mode_main = 1 ...
#all functions need to be wrapped in the "run" function and pass in kwargs # JSON example to send into the /script route is as below # # { # "script":"hello_world", # "args":{ # "hello":"world" # } # } # def run(**kwargs): try: # mandatory get of kwargs - payload comes through as {'kwargs': {'hello': ...
""" Copyright (c) 2018-2019 Zhangqi Chen 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, merg...
from intficpy.ifp_object import IFPObject class DaemonManager(IFPObject): def __init__(self, game): super().__init__(game) self.active = [] def runAll(self, game): for daemon in self.active: daemon.func(game) def add(self, daemon): self.active.append(daemon) ...
import shutil import torch from torch.utils import data import utils import numpy as np import time import matplotlib.pyplot as plt import dataloader as d import models as m @torch.no_grad() def validate(cfg, model_ema, epoch, dataset, fold, analyze=False): print("INFO: validate {}".format(cfg["ML"]["model"]["type...
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
"""Insert Sort Implementation.""" def insert_sort(lst): """Insert sort.""" for i in range(len(lst)): k = lst[i] j = i while j > 0 and k < lst[j - 1]: lst[j] = lst[j - 1] j -= 1 lst[j] = k return lst if __name__ == '__main__': import timeit ...
"""Create PyTables files and the object tree. This module support importing generic HDF5 files, on top of which PyTables files are created, read or extended. If a file exists, an object tree mirroring their hierarchical structure is created in memory. File class offer methods to traverse the tree, as well as to create...
import json import os import time from datetime import datetime from collections import defaultdict import config import logging NUM_SECONDS_IN_DAYS = 60 * 60 * 24 logger = logging.getLogger(f"scraper.{__name__}") def load_properties_info() -> dict: """ Loads the properties info from the json :return: ...
from collections import Counter import os from itertools import islice import json def get_keys(): with open("backend/keys.json","r") as keys: json_keys = json.loads(keys.read()) return json_keys def count_words(string_list): return Counter(string_list) def create_directory(name): try:...
import math import numpy as np import operator import tinychain as tc import unittest from functools import reduce from testutils import ClientTest Dense = tc.tensor.Dense ENDPOINT = "/transact/hypothetical" LEARNING_RATE = 0.1 MAX_ITERATIONS = 500 NUM_EXAMPLES = 100 def truncated_normal(size, mean=0., std=None):...
global output_pdf_path global basepath global pngdpi global output_png_path global output_jpg_path global rawoutput global basepathraw global output global paper global EXPs global EXPS global EXP_NAMEs pngdpi=600 basepath='tm5-soa/' # output_png_path=basepath+'figures/draft-v0.9/png/' # output_pdf_path=basepath+'figu...
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <maurizio....
# -*- coding: utf-8 -*- import requests, datetime, base64, pymysql, time, re, datetime ###### CONFIGURATION PYTHON SCRIPT ###### # get it here: https://voe.sx/?op=my_account voe_api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Embed or Direct Link format? (1 or 0) embed = 1 # MySQL Database database_...
from tap_bronto.schemas import get_field_selector, is_selected, \ CONTACT_SCHEMA from tap_bronto.state import incorporate, save_state from tap_bronto.stream import Stream from funcy import project from datetime import datetime, timedelta import pytz import singer import socket import suds LOGGER = singer.get_log...