content stringlengths 5 1.05M |
|---|
import logging
import os
import shutil
import tempfile
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import lru_cache, partial
from typing import ContextManager, List, Optional, Tuple, Union
import fsspec
from tqdm import tqdm
@lru_cache(maxsize=8)
def cached_... |
# Copyright (c) 2021, Technische Universitรคt Kaiserslautern (TUK) & National University of Sciences and Technology (NUST).
# All rights reserved.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import sys
import re
import csv
import... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0013_auto_20151120_1029'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# remplace les accents par les codes HTML correspondants
import os
import os.path
import glob
codes = {
'ร ': 'à',
'รจ': 'è',
'รน': 'ù',
'รฉ': 'é',
'รซ': 'ë',
'รข': 'â',
'รช': 'ê',
'รฎ': 'î',
... |
# Sample Test passing with nose and pytest
import os
import sys
import pytest
import math
import random
import pprint
from reportlab.lib.units import inch, mm
from toolbox import *
from pdfdoc import *
def test_document_init():
doc = Document("test_document.pdf")
assert doc.filename == "test_document.pdf"
... |
from panoptes_aggregation.reducers.shape_reducer_dbscan import process_data as process_data_dbscan, shape_reducer_dbscan
from panoptes_aggregation.reducers.shape_reducer_hdbscan import process_data as process_data_hdbscan, shape_reducer_hdbscan
from .base_test_class import ReducerTest
import copy
extracted_data = [
... |
import matplotlib.pyplot as plt
plt.rcParams.update({
'figure.dpi': 200,
'savefig.dpi': 300,
'figure.figsize': (10.0, 5.0),
'axes.labelsize': 'medium',
'font.size': 10
})
# savefig_dpi = 300
colors = [
# Primary data color, secondary data feature color
# ('blue', 'aqua'),
('blue', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair.
JRC Biomass Project.
Unit D1 Bioeconomy.
Typically you can use this class like this:
>>> from waste_flow.treatment import waste_trt
>>> print(waste_trt.normalized)
"""
# Built-in modules #
# Internal modules #
from waste_flow.zi... |
import pandas as pd
def looking_for_team_names(temp_teams):
""" ๋ชจ์ HTML soup์์ ์ํฉํ ๋ ํ๋ช
์ ๋ฝ๋ ํจ์
๋ค์๊ณผ ๊ฐ์ HTML soup์์ "ํํ"๋ง ๋ฝ์์ ํ๋ช
์ ์ฐพ๋๋ค.
์ค์ ๋ก๋ ์๋์ ๊ฐ์ ๊ฒ์ด ๋ ํ์์ ๊ฐ ๊ฐ ํ์, ํฌ์ ์ด ๋ค ๋ฒ ๋์จ๋ค.
๊ฑฐ๊ธฐ์ ๋ ํ๋ง ๋ฝ์ผ๋ฉด ๋๋ค. ๋ํ ์๋์ฒ๋ผ "ํํ ์ด๊ธ์ค ํ์ ๊ธฐ๋ก"์์ ์ฒซ ๋ฒ์งธ ๋จ์ด๋ง ๋ฝ์ผ๋ฉด ๋๋ค.
<h6 class="tit-team" id="lblAwayHitter">
<span class="l... |
"""Utilities for BERT trainer."""
import functools
from typing import Any, Dict, Tuple, Optional, Mapping, Union, List
from absl import logging
from clu import metric_writers
import flax
from flax import jax_utils
import flax.linen as nn
import jax
import jax.numpy as jnp
import jax.profiler
import ml_collections
imp... |
default_app_config = "modoboa.ldapsync.apps.LdapsyncConfig"
|
#! /usr/bin/env python
# coding:utf-8
print "hello world ไฝ ๅฅฝๅๅ
จไธ็ๅๅๅgh้ๅฎๆน่ฆ็ๅคงๅฐsss" |
# -*- coding: utf-8 -*-
# build graph by networkx
# @author: WenYi
# @time: 2019-08-29
# @contact: wenyi@cvte.com
import networkx as nx
def bulidGraph(data):
"""
bulid a graph
:param data: DataFrame for user item history interaction must
include [['user_id', 'item_id', 'dates']] three columns
:r... |
import gzip
from functools import partial
from pathlib import Path
from menpo.compatibility import basestring, str
from .extensions import landmark_types, image_types, pickle_types, video_types
from ..utils import _norm_path
# an open file handle that uses a small fast level of compression
gzip_open = partial(gzip.op... |
from app.graphql.directives import directives
from ariadne import make_executable_schema, load_schema_from_path
from app.graphql.resolvers.queries import query
from app.graphql.resolvers.mutations import mutation
type_definitions = load_schema_from_path("/app/app/graphql")
schema = make_executable_schema(type_defini... |
import unittest as ut
import numpy as np
from games.analysis.resource_poa import ResourcePoA
from games.misc.solver import lp
class ResourcePoA_Test(ut.TestCase):
def test_I(self):
self.assertEqual(ResourcePoA.I(0), [])
self.assertListEqual(ResourcePoA.I(1), [(0, 0, 1), (0, 1, 0), (1, 0, 0)])
self.assertEqual(... |
"""This file is similar to the script_dictionary, except here we directly load a
class and there we load the whole package and eventually try to call a (main)
function.
We attempt to load all the file from the 'scripts' folder.
In some cases, one may try to open the VIP where it then tries to load a package
from ... |
"""
pyscience - python science programming
Copyright (c) 2019 Manuel Alcaraz Zambrano
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
t... |
import os
import numpy as np
class sampLib():
lib = []
path = 'SampleLibrary/'
def __init__(self):
#build array of samples in the library
for root, dir, files in os.walk(self.path):
for f in files:
self.lib.append(f)
#convert to a numpy array for easy a... |
import io
import sys
import mysqltsv
writer = mysqltsv.Writer(sys.stdout, headers=['user_id', 'user_text', 'edits'])
writer.write([10, 'Foobar_Barman', 2344])
writer.write({'user_text': 'Barfoo_Fooman', 'user_id': 11, 'edits': 20})
writer.write([None, "127.0.0.1", 42])
my_file = io.StringIO("user_id\tuser_text\ted... |
from typing import *
# usage.pandas: 1
MaskedRecords: object
# usage.pandas: 1
mrecarray: object
def fromarrays(
arraylist: Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray],
names: Tuple[Literal["float"], Literal["int"], Literal["str"]],
):
"""
usage.pandas: 1
"""
...
class MaskedRecords... |
from aioworkers.storage.base import (
AbstractBaseStorage,
AbstractExpiryStorage,
AbstractListedStorage,
FieldStorageMixin,
)
from aioworkers_redis.base import Connector, KeyEntity
class Storage(Connector, AbstractListedStorage, AbstractExpiryStorage):
_expiry = None
def set_config(self, con... |
import tigerforecast
from tigerforecast.experiments import Experiment
from tigerforecast.utils.download_tools import get_tigerforecast_dir
from tigerforecast.utils.optimizers import *
import os
def test_new_experiment(steps=5000, show=False):
exp = Experiment()
exp.initialize(problems = ['SP500-v0'], methods =... |
from moviepy.editor import *
from moviepy.video.fx.all import crop
for i in range(1):
i = i + 29
# read the video file
clip = VideoFileClip("thang/thang (" + str(i) + ").mp4")
# crop to the smallest dimension in square ratio
w = clip.size[0]
h = clip.size[1]
if w > h:
... |
from workbench.tools import admin
from . import models
@admin.register(models.ExpenseReport)
class ExpenseReportAdmin(admin.ModelAdmin):
list_display = ("created_at", "created_by", "owned_by", "total")
raw_id_fields = ("created_by", "owned_by")
@admin.register(models.ExchangeRates)
class ExchangeRatesAdmin... |
# python3
from itertools import permutations
def cost(perm, A):
c = 0
for i in range(len(perm)-1):
c += A[perm[i]][perm[i+1]]
return c
def solve(A):
res = []
m = 2**32
n = len(A)
perms = list(permutations([i for i in range(n)]))
for perm in perms:
if cost(perm, A) < m:... |
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
import mmcv
import matplotlib.pyplot as plt
img = mmcv.imread('data/test_img/03_02_01450.png')
palette = [0, 1, 2]
model.cfg = cfg
result = inference_segmentor(model, img)
plt.figure(figsize=(8, 6))
show_result_pyplot(model, img, result, p... |
import time
import sys
from datetime import datetime
from w1thermsensor import W1ThermSensor
temp_sensor = W1ThermSensor()
if len(sys.argv) != 3:
print "USAGE:"
print sys.argv[0], " <interval-in-seconds> <output-file>"
sys.exit(1)
interval = float(sys.argv[1])
f_out = open(sys.argv[2], 'a')
while True:
... |
from typing import List
from disnake import Client, File
from disnake.http import Route
from .utils import _form_files
__all__ = ("HTTPClient",)
class HTTPClient:
def __init__(self, bot: Client):
self.bot = bot
def edit_response(
self, interaction_token: str, data: dict, files: List[File]... |
# Generated by Django 2.1.7 on 2019-05-31 21:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Label',
fields=[
... |
from __future__ import absolute_import, print_function
import logging
from celery import shared_task
from flask import current_app
from inspire_utils.record import get_value
from invenio_mail.api import TemplatedMessage
from scoap3.modules.records.util import is_doi_in_db
from scoap3.utils.arxiv import get_arxiv_cat... |
from decimal import Decimal
from mm_bot.model.order import MakerOrder, TakerOrder
class TestTakerOrder:
def test_taker_order(self):
qty = Decimal('1.234')
price = Decimal('0.0234')
order_type = 'buy'
taker_order = TakerOrder(
exchange='binance',
status='ope... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 13 14:03:11 2019
@author: Parth
"""
import collections
from collections import Counter
import pickle
import string
import pandas as pd
from textblob import TextBlob
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize... |
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.ml import dsl, MLClient, Input, MpiDistribution
from azure.ai.ml.entities import load_component
from azure.ai.ml.entities import PipelineJob
from azure.ai.ml.entities import Data
from pathlib import Path
from azure.ai.ml.entities._job.sweep.search_s... |
import requests
import json
import sqlite3
conn = sqlite3.connect('f:/cinemas.db')
c = conn.cursor()
c.execute('create table if not exists cinemas(id int, name text, mark int, address text, sellPrice float, regionId int, regionName text)')
print(u'ๆฐๆฎๅบๅทฒๆๅผ')
class Cinema:
def __init__(self, name, id, mark, address... |
H, N = map(int, input().split())
h = [int(input()) for _ in range(N - 1)]
h.append(H)
h.sort(reverse=True)
for i in range(N):
if h[i] == H:
t = i + 1
break
if t % 10 == 1:
print('%dst' % t)
elif t % 10 == 2:
print('%dnd' % t)
elif t % 10 == 3:
print('%drd' % t)
else:
print('%dth' %... |
from dame.stages import Stages
from .test_classes import PlusOne, PlusTwo, ThreeNums
def test_dag():
stages = Stages(ThreeNums, (PlusTwo, PlusOne))
assert list(iter(stages)) == [
PlusOne,
PlusTwo,
]
assert list(stages.to("p1")) == [PlusOne]
|
import xml.etree.cElementTree as ET
from xml.dom import minidom
from xml.dom.minidom import parseString
from encoding import strip_non_ascii
import globals
def prettyprint(element):
if "ask_gui" in globals.new_elements:
import wx
from wx.lib.pubsub import pub
wx.CallAfter(pub.sendMessage, "update", msg="Pretty... |
import uuid
import logging
import re
from crl.interactivesessions.interactivesessionexceptions import (
InteractiveSessionError)
from .autocompletableshell import AutoCompletableShell
from .shell import (
TimeoutError,
DEFAULT_STATUS_TIMEOUT)
from .sshoptions import scpoptions
from .registershell import Reg... |
'''num = [2,5,6,9]
num[2] = 3
num.append(70)
num.sort(reverse=True)
num.insert(2, 2)
num.pop(1)
if 5 in num:
num.remove(5)
else:
print('nรฃo hรก nรบmero 4 ')
print(num)
print(f'Essa lista tem {len(num)} elementos')'''
'''valores = []
valores.append(5)
valores.append(10)
valores.append(4)
for c,v in enumerate(valo... |
import streamlit as st
import components.barplot
import components.map
import components.lines
import components.lineair
def sidebar():
st.sidebar.header('Dashboard setings')
st.header("World COVID dashboard")
st.markdown("*Welkom bij de World COVID dashboard. U bevindt zich op de landingspagina waarin een... |
"""Retrieves snowflake credentials from local file."""
import json
import snowflake.connector
with open('c:\git\degiro\config_snowflake.json', 'r') as file:
data = json.load(file)
snowflake_user = data['snowflake_user']
snowflake_password = data['snowflake_password']
snowflake_account = data['snowflake... |
from util.distill_params import DISTILL_PARAMS
from util.model_configs import GPT2Config, ModelConfig, MODEL_CONFIGS, CapsConfig, ResnetConfig
from util.train_params import TRAIN_PARAMS
class TrainParams(object):
def __init__(self, optimizer,
learning_rate=0.0001,
n_epochs=60,
... |
import tkinter
import cv2
import time
import PIL.Image, PIL.ImageTk
import math
from Message import Message
from pynput import keyboard
from tkinter import messagebox
import json
import sys
server_ep = ("127.0.0.1", 50001)
time.sleep(1)
class App:
def __init__(self, window, window_title, door_to_heaven, server,... |
"""
Plots the vorticity field of a 2D cuIBM simulation.
"""
import os
from snake.cuibm.simulation import CuIBMSimulation
from snake.body import Body
simulation = CuIBMSimulation()
simulation.read_grid()
for time_step in simulation.get_time_steps():
all_bodies = Body(file_path=os.path.join('{:0>7}'.format(time_ste... |
# ch8/example2.py
import cv2
import os
# define our clear function
def clear():
# for windows
if os.name == 'nt':
_ = os.system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = os.system('clear')
if __name__ == '__main__':
clear()
cwd = os.getcwd()
... |
from __future__ import print_function
import inspect
from .exception import DamsonException
from .constraint import DamsonConstraint
from .support import func_args_to_dict
def validate(obj, **kwargs):
"""
Apply the rules to validate the dict, and it will return the result and errors.
Examples:
impo... |
from os import PathLike
from typing import Union, Dict, Any, Iterable, Tuple
import numpy as np
import pandas as pd
from catboost import Pool
from numpy.typing import NDArray
from sklearn.model_selection import BaseCrossValidator, BaseShuffleSplit
__all__ = (
'KWARGS',
'KWARG_ITERABLE',
'KWARGS_OR_ITERABL... |
from pypy.interpreter.pycode import _code_const_eq
def test_strong_const_equal(space):
# test that the stronger equal that code objects are supposed to use for
# consts works
s = 'Python'
values = [
space.newint(1),
space.newfloat(0.0),
space.newfloat(-0.0),
space.newflo... |
from abc import abstractmethod
from app.models.game import Game
from app.schemas.game_schema import Action, PayloadType
class ActionHandler:
def __init__(
self,
game: Game,
player: str,
action: Action,
payload: PayloadType):
self.game = game
... |
#!/usr/bin/env python
import sys
import os
import myfunc
# ChangeLog 2012-08-28
# Can output only annotation line or fasta format, annotation line is one
# line per record
BLOCK_SIZE=100000
usage="""
Usage: reordermsa.py [Options] msafile -orderlist orderfile
Options:
-o FILE Output the result to file, (def... |
import unittest
from parsers import input_parser
from tests.test_environment import marses
import data_objects as do
class TestInputParser(unittest.TestCase):
def test_parse_returns_correct_data_for_sample_commands(self):
commands = ['5 5', '1 2 N', 'LMLMLMLMM', '3 3 E', 'MMRMMRMRRM']
mars = input... |
"""RNATables utility functions."""
import asyncio
import json
from io import BytesIO
from urllib.parse import urljoin
import aiohttp
import pandas as pd
from requests.exceptions import HTTPError
async def _download_file(uri, url, session, parser):
"""Download and parse single file."""
async with session.get... |
# This solution works only for non-negative integers. If there are negative integers in the array then you need to use Hashing
def subArrayWithGivenSum(arr,sum):
n = len(arr)
tot = 0
index = 0
for i in range(n):
while tot > sum:
tot -= arr[index]
index += 1
if tot == sum:
return T... |
from .game import Game, Piece
# note to self: phase 1 through 3 are hardcoded conditionals rather than actual variables
class Mill(Game):
name = "Mill"
id = 4
width = 11
height = 11
players = 2
validPoint = [
(0, 10), (0, 5), (0, 0), (2, 8), (2, 5), (2, 2), (4, 6), (4, 5), (4, 4), (... |
import os
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
import itertools
import pandas as pd
import numpy as np
from datetime import datetime
# This project
import stroke_cleaning
colors = itertools.cycle(["r", "b", "g", "k", "c", "m", "y"])
#def plot_features_from_audio(audio, fe... |
from flask import Flask, request, render_template,jsonify
from flask_restful import Resource, Api
import mysql.connector
import json
import requests
import base64
import os
import zipfile
import re
import shutil
import requests
import time
import threading
from json import loads
from kafka import KafkaConsumer
'''
S... |
"""Plot diagrams for a single hole."""
import gc
import io
import logging
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
__all__ = ["plot_hole"]
BBOX = dict(facecolor="white", alpha=0.75, edge... |
"""This is the PDFreactor 6.3 Python API
RealObjects(R) PDFreactor(R) is a powerful formatting processor for converting HTML and XML documents
into PDF.
The simplest sample for the PDFreactor Python API:
#!/usr/bin/python
from PDFreactor import *
pdfReactor = PDFreactor()
result = pdfReactor.renderDocumentFromURL(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pdb
# 3rd party imports
import numpy as np
import xarray as xr
from cdflib import cdfread
# Local imports
from ..pyrf import datetime642iso8601
from .list_files import list_files
__author__ = "Louis Richard"
__email__ = "louisr@irfu.se"
__copyright__ = "Copyrig... |
#!/usr/bin/env python3
import argparse
import logging
import sys
from dotsecrets.clean import clean
from dotsecrets.init import init
from dotsecrets.metadata import VERSION
from dotsecrets.smudge import smudge
from dotsecrets.stow import stow, unstow
from dotsecrets.test import test
logger = logging.getLogger()
log... |
import sst
import sst.actions
# navigate to populate history
sst.actions.set_base_url('http://localhost:%s/' % sst.DEVSERVER_PORT)
sst.actions.go_to('/')
sst.actions.click_element('the_band_link')
sst.actions.assert_url('/begin')
sst.actions.go_to('/')
sst.actions.assert_url('/')
sst.actions.click_element('the_band_l... |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# 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.ap... |
#!/usr/bin/env python3
"""
Takes a corpus of raw text as input and calculates comprehensive Markov
probabilities. Which then feeds into a function that solicits a seed word and a
'sentence length' parameter in order to generate probabilistic text
"""
####################################################################... |
# Copyright 2021 Regents of the University of Minnesota.
#
# 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 applic... |
import sys
import matplotlib.pyplot as plt
import numpy as np
def isReal(txt):
try:
float(txt)
return True
except ValueError:
return False
#dicionรกrios
med_dic={1:{'ID':1,'Nome Comercial':0,'Composto principal':0,'Fรณrmula Quรญmica':0,'Meia-vida de eliminaรงรฃo':0,'Nรบmero de ... |
import djangae
from django.conf.urls import url, include
from django.contrib import staticfiles
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
# ex: /blog/
url(r'^$', views.index, name='index'),
url(r'^gauth/', include(djangae.contrib.gauth.urls)),
url(r'^new/$... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.test_runner import make_test_records
from erpnext.stock.doctype.item.item import WarehouseNotSet, DuplicateVa... |
from .callback_src_enum import CallbackSrcEnum
from .callback import Callback
from ignite.engine import Events
class RunEvaluator(Callback):
def __init__(self, evaluator, valid_dl, listen_to=CallbackSrcEnum.train):
super().__init__(listen_to=listen_to)
self.evaluator = evaluator
self.vali... |
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from hashlib import sha256
import requests
from celery import shared_task
from logging import getLogger
log = getLogger()
from webapp import celery_app
from post.models import (
Board,
Post,
Push,
URLImage
)
from .models impo... |
""" Runs the default analyzer, which performs two functions...
1. Output the signal information to the prompt.
2. Notify users when a threshold is crossed.
"""
import traceback
import structlog
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import m... |
import time
from api.utils import load_config
from api.utils import gen_signature
class UAIOcrGenJobSignatureApi(object):
def __init__(self, config_file, url=''):
self.config_file = config_file
self.url = url
def _check_args(self):
public_key, private_key, resource_id = load_config(sel... |
from . import utils
from . import user
import secrets
class Stack(object):
__ticker = 0
__users = {}
__services = {}
name = None
anonymous_access = False
def __init__(self, name = 'stack', *, anonymous_access: bool = False):
self.name = name
self.anonymous_access = anonymous_... |
from sqlalchemy import Column, Integer, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from .base import Base
class Star(Base):
__tablename__ = 'star'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'))
timestamp = Column(DateTime)
query_id = Colu... |
from typing import NamedTuple, Union, Any, Type
from pyrsistent import pmap
from pyrsistent.typing import PMap
from .flags import _Flag
OverridesT = PMap[
Union[
# field name override
property,
# flag override
_Flag,
# new type extension
Type
],
Any
]
NO... |
"""
job_generator.py
=======================
Wraps and runs your commands through torque.
"""
import os
from submit_hpc.job_monitor import monitor_job_completion
def assemble_replace_dict(command, use_gpu, additions, queue, time, ngpu, self_gpu_avail, imports, work_dir):
"""Create dictionary to update BASH submis... |
import numpy as np
from cityscapes import CityscapesDataset
def convert_ids(img, has_hood=True, ignore_id=255):
img_train = np.zeros_like(img)
img_train.fill(ignore_id)
car_mask = img == 1
height = car_mask.shape[0]
if has_hood:
car_mask[height-5:,...] = True
for i, cid in enumerate(CityscapesDataset.... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains base save widget for data items
"""
from __future__ import print_function, division, absolute_import
import os
import logging
import traceback
from Qt.QtCore import Signal, QSize
from Qt.QtWidgets import QSizePolicy, QFrame, QDialogButtonBox, Q... |
from datetime import timedelta, datetime
from unittest import TestCase
from reliabilly.components.tools.date_utils import get_last_hour_epoch, get_current_epoch
class TestDateUtils(TestCase):
def test_get_last_hour_epoch(self):
response = get_last_hour_epoch()
now = int((datetime.now() - timedelt... |
# coding=utf-8
from __future__ import unicode_literals
from stroller2.controllers.manage.category import ManageCategoryController
from tg import TGController, expose
from stroller2.controllers.manage.product import ManageProductController
from stroller2.controllers.manage.user_address import ManageUserAddressesControll... |
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from ..engine_advanced_settings import EngineAdvancedSettings
from ..engine import Engine
from ..utils import PATTERN_PLACEHOLDER_TEXT
class DirectoryWatchdogEngineAdvancedSettings(EngineAdvancedSettings):
def __init__(self, engine: Engine... |
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS Authors
#
# 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
#
# Unle... |
# Solution to part 1 of day 21 of AOC 2021, Dirac Dice
# https://adventofcode.com/2021/day/21
class Die:
def __init__(self):
self.rolls = 0 # Number of times the dies has been rolled.
self.value = None # Value the die returned last time it was rolled.
def roll(self):
i... |
"""Main script for this webscraper to get data from Yahoo Finance.
Prints regular progress messages in standard output to update on the progress
of the webscraper. Logs are stored in default file called scraper.log.
"""
import numpy as np
import pandas as pd
import functions
def main() -> None:
# Enable loggi... |
# encoding: UTF-8
import requests
import json
from copy import copy
from web3.types import Wei, HexBytes
from web3 import Web3
from .util import addr_to_str, get_two_currency
from .constants import ETH_ADDRESS
from .constants import Direction
from .tokens import EthNet
from .uniswap import Uniswap
from .log_service... |
#!/usr/bin/python
# lambda.py
y = 6
z = lambda x: x * y
print (z(8))
|
# Generated by Django 2.1.2 on 2019-02-21 09:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_userprofile'),
]
operations = [
migrations.AddField(
model_name='checktask',
name='last_response_status'... |
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.config import db
from changes.constants import Result, Status
from changes.models.build import Build
from changes.models.jobplan import JobPlan
class BuildCancelAPIView(APIView):
def post(self, build_id):
build = Buil... |
from collections import defaultdict
from pygraph.algorithms.accessibility import mutual_accessibility
from pygraph.classes.digraph import digraph
from interfaces.automaton import Automaton, Node
from typing import Set, FrozenSet
def _convert_to_digraph(nodes):
g = digraph()
g.add_nodes(nodes)
for n in n... |
from setuptools import find_packages
from setuptools import setup
setup(
name='Foo',
version='0.0.0',
packages=find_packages('.'),
entry_points={
'console_scripts': ['foo = foo.main:func'],
},
)
|
# pangadfs/pangadfs/crossover.py
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Eric Truett
# Licensed under the MIT License
from typing import Tuple
import numpy as np
from pangadfs.base import CrossoverBase
from pangadfs.misc import diversity, parents
class CrossoverDefault(CrossoverBase):
def _diverse(self, *... |
import json
import sys
if __name__ == "__main__":
if len(sys.argv) >= 2:
if sys.argv[1] in ["COVID-19", "health", "climate", "global"]:
SCIENTIFIC_TOPIC = sys.argv[1]
else:
print("Please enter only 'COVID-19', 'health', 'climate' or 'global' as argument.")
exit... |
import sys
from expression_enum import OpArithmetic, OpRelational, OpLogic, OpPredicate
from datetime import date
sys.path.insert(0, '..')
from ast_node import ASTNode
class Numeric(ASTNode):
def __init__(self, val, line, column):
ASTNode.__init__(self, line, column)
self.val = val
def execu... |
PROGRAM_HEADER = """
################################################################################
# #
# Python FRagment Electronic Coupling (PyFREC) v2.7 #
# Program for calculation of electronic couplings ... |
import numpy as np
from nipy.testing import assert_true, assert_equal, assert_raises, \
assert_false, assert_array_equal, parametric
from nipy.core.reference.coordinate_map import CoordinateMap, Affine, \
compose, CoordinateSystem, reorder_input, reorder_output, product, \
replicate, linearize, drop_io_dim... |
from flask import request, Blueprint, render_template, redirect, url_for, Response
from flask_jwt_extended import jwt_required
import services.counter
import services.heat_map
import services.motion_heatmap
from werkzeug.utils import secure_filename
services_blueprint = Blueprint('services', __name__, template_folder='... |
from biocrnpyler import *
import bioscrape
import numpy as np
import pylab as plt
import time as pytime
kb, ku, ktx, ktl, kdeg = 100, 10, 3, 2, 1
parameters = {"kb":kb, "ku":ku, "ktx":ktx, "ktl":ktl, "kdeg": kdeg}
myMixture = BasicExtract(name = "txtl", parameters = parameters)
A1 = DNAassembly(name = "G1", promoter... |
import csv
import logging
import os
from datetime import datetime
class PrintOut:
def __init__(self, method):
self.method = method
self.time = datetime.now().isoformat()
def extract_headers(self, datas: dict):
return list(datas.keys())
def get_metadata(self, no_time: bool = Fals... |
# -*- coding: utf-8 -*-
"""
Simple Data Protocol example
Date: 9.11.2017
@author: Domen Jurkovic
@version 1.0
@source http://damogranlabs.com/, https://github.com/damogranlabs
Once started, press 's' to send data and press ESC to break out.
"""
import msvcrt
import sys
import sdp
PC_NODE_ID = 0
# mayimum of 50 by... |
from onnx import helper as xhelp
from onnx import onnx_ml_pb2 as xpb2
from sclblonnx.utils import _value, _data_type, _parse_element, _print
# list_inputs lists all inputs of a graph
def list_inputs(graph: xpb2.GraphProto):
""" Tries to list the inputs of a given graph.
Args:
graph the ONNX graph
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.