content stringlengths 5 1.05M |
|---|
# http://www.pythonchallenge.com/pc/def/channel.html
# I find a zip in the comment of the source code
# try http://www.pythonchallenge.com/pc/def/channel.zip and get a zipfile
# use 7-zip to unzip the file and get detail output, save it in channel.txt
# see the readme.txt to know that we need to begin at 90052
import... |
import iso8601
from naas.models.links import Links
class AccountAddon(object):
"""
AccountAddon
===============
This returns an instance of the AccountAddon domain model
"""
def __init__(self, attributes):
self.attributes = attributes
def id(self):
"""Returns the accou... |
# -*- coding: utf-8 -*-
"""
circles.py
Created by Stephan Hügel on 2014-05-22
Copyright Stephan Hügel
Convenience functions for calculating and drawing circles on a projected map,
based on great-circle distances
Almost all code from:
http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/... |
""" Global Flask Application Settings """
import os
from app import app
class Config(object):
DEBUG = False
TESTING = False
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
CLIENT_DIR = os.path.join(BASE_DIR, 'client', 'vue_app')
UPLOAD_DIR = os.path.join(BASE_DIR, 'uploads')
... |
class Display:
"""
Abstract class providing common interface to the set of pixels
"""
def set_pixel(self, idx, r, g, b):
raise NotImplementedError
|
"""
Unit system class.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#--------------------------... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
#!/usr/bin/env python
"""
@package ion.agents.platform.rsn.rsn_platform_driver
@file ion/agents/platform/rsn/rsn_platform_driver.py
@author Carlos Rueda
@brief The main RSN OMS platform driver class.
"""
import functools
from xmlrpclib import Fault
from xmlrpclib import ProtocolError
from socket import error as ... |
import debug_toolbar
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from ralph.urls import urlpatterns as base_urlpatterns
from ralph.urls import handler404 # noqa
urlpatterns = base_urlpatterns
urlpatterns += [
url(r'^__debug__/', include(d... |
# coding: utf-8
"""
Metal API
This is the API for Equinix Metal. The API allows you to programmatically interact with all of your Equinix Metal resources, including devices, networks, addresses, organizations, projects, and your user account. The official API docs are hosted at <https://metal.equinix.com/dev... |
import subprocess
import boto3
import os
import datetime
now = datetime.datetime.now()
print("=====Starting Server Check=====")
print("Time: {}".format(now))
cmd = subprocess.Popen(['sudo', 'service', 'factorio', 'players-online'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = cmd.communicate()
outpu... |
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.ticker as mticker
import matplotlib.pyplot as plt
import numpy as np
def quantum_walk_data(n):
probs = np.loadtxt("./../Max2SAT_quantum/inf_time_probs_n_" + str(n) + ".txt")
return np.reciprocal(probs)
def adiabatic_data(... |
class suffix:
def __init__(self):
self.index = 0
self.rank = [0, 0]
# Counting Sort
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 27
# Store count of occurrences in count[]
for i in range(n):
count[arr[i].rank[ex... |
import Image
def vectorToRGBA(vec):
x1 = x2 = y1 = y2 = 0
if vec[0] < 0:
x2 = -vec[0]
else:
x1 = vec[0]
if vec[1] < 0:
y2 = -vec[1]
else:
y1 = vec[1]
return (x2, x1, y2, y1)
img = Image.new('RGBA',(256, 256))
pix = img.load()
for x in range(img.size[0]):
for y in ... |
import numpy as np
from scipy.optimize import curve_fit
import argparse
import sys
def get_args():
"""Define the task arguments with the default values.
Returns:
experiment parameters ... |
import os
sizes = [512, 1024, 1536, 2048, 2560, 3072, 4096, 8192, 16384, 32768]
path = "Verify"
os.system("mkdir -p " + path)
for size in sizes:
os.system("./sor_2d_verify " + str(size + 2) +
" 1> " + path + "/" + str(size) + ".out"
" 2> " + path + "/" + str(size) + ".err") |
import os
import time
from copy import deepcopy
from typing import Dict, List, Tuple, NoReturn
from deriv8.datasets.utils import shuffle_truncate_dataset, split_into_batches
from deriv8.matrix2d import (Tensor2D, add, argmax, element_equals, element_multiply, element_sq, l2_norm,
matrix_mu... |
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "COSAL"
import re
import random
import multiprocessing
from copy import deepcopy
from utils import cache, logger, lib
from sos.function import Function, Outputs, FunctionCache, InputCache
from sos.cluster import c... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from pandas import *
import os, os.path
import csv
os.chdir('/home/will/HIVSystemsBio/')
# <codecell>
cocaine_genes = read_csv('CocaineGeneList.csv')
hiv_genes = read_csv('HIVGeneList.csv', sep = '\t')
biomart_conv = read_csv('mart_export.txt', sep = ... |
#!/usr/bin/env python3
# minimal qt application that show empty window (with title)
## need sys.exit() and sys.argv
import sys
## using PyQt
from PyQt4 import QtGui
################################################################################
## the only window class derived form QWidget
########################... |
from .coverage import Coverage
from .numLeaps import numLeaps |
class Accelerator:
commandKey = "A"
# Accelerate
accelerateMid = 1500
brakePos = 1500
maxSpeed = False
minSpeed = False
midSpeed = False
step = 10
connection = None
curPos = False
def __init__(self, config, connection):
"""
:param config: Config
:pa... |
#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
# Modifications Copyright 2021 QuantRocket LLC
#
# 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... |
from zope.cachedescriptors.property import Lazy as lazy_property
from zope.component import adapts
from zope.interface import implements
from zope.schema import getFieldsInOrder
from zope.schema.interfaces import ITextLine, IText
from plone.uuid.interfaces import IUUID
from plone.dexterity.interfaces import IDexterity... |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns
urlpatterns = patterns(
'saas_exam_jacky.views',
(r'^test/$', 'api_test'),
) |
from acq4.util.FileLoader import FileLoader
from PyQt4 import QtCore, QtGui
class STDPFileLoader(FileLoader):
def __init__(self, dataManager, host=None, showFileTree=True):
FileLoader.__init__(self, dataManager, host, showFileTree)
self.ui.loadBtn.setText('Load EPSP File')
self.ui.loadBtn... |
"""Unit test package for pypda."""
|
from operator import imod
from flask_wtf import FlaskForm
from wtforms import TextAreaField, SubmitField
from wtforms.validators import Required
from wtforms_sqlalchemy.fields import QuerySelectField
from ..models import Category
from flask_wtf.file import FileField, FileAllowed, FileRequired
class PitchForm(FlaskFor... |
from time import sleep
from threading import Event, Thread
from queue import Queue
from urllib.parse import urljoin
from requests import get
from functions import target, timeit
base_url = 'http://pokeapi.co/api/v2/'
event = Event()
fila = Queue(maxsize=101)
def get_urls():
pokemons = get(urljoin(base_url, 'poke... |
"""
=========================================================================
HypothesisTest.py
=========================================================================
Hypothesis test with cache
Now with Latencies!!
Author : Xiaoyu Yan (xy97), Eric Tang (et396)
Date : 25 December 2019 Merry Christmas!! UWU
"""
i... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RRandomfields(RPackage):
"""Methods for the inference on and the simulation of Gaussian fi... |
import json
import logging
import os
import traceback
from m3d.util.util import Util
class SparkExecutor(object):
def __init__(self, execution_system):
self._execution_system = execution_system
def run(self):
"""
Run Spark application.
:raises Exception: in case the selecte... |
import os
import shutil
import subprocess
import tarfile
from time import time
from datetime import datetime
from tempfile import TemporaryDirectory
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from orchestration.run_container import Bind
from orchestration.run_container.base_... |
import dataclasses
from datetime import datetime, timedelta
from math import floor
import os
from dateutil import parser
import discord
from discord import voice_client
from teamo.models import Entry, Settings
def get_update_interval():
return int(os.getenv('TEAMO_UPDATE_INTERVAL'))
def get_check_interval():
... |
n = int(input("quantidade de testes: "))
while n!=0:
n+=1
x = int(input())
i=0
c=0
while x>=i:
i+=1
if x%i==0:
c+=1
if c==2:
print(str(x)+" eh primo")
else:
print(str(x)+" nao eh primo")
|
print(">>>>>> import schemas_invitation.py > Invitation ...")
from typing import List, Optional, Any
import datetime
from pydantic import BaseModel, EmailStr
# from uuid import UUID
from .schemas_choices import ItemType, InvitationStatus, InviteeType, InvitationStatusAction
from .schemas_auths import AuthsInfosBasic... |
class StringProcessor:
# Creates a string based on the arguments. If no args are applied, then we want to just return the message
# @param message The message being used
# @param args The arguments being used
# @return A final string
def safe_formatter(self, message, args):
try:
return ''.join(me... |
if __name__ == '__main__':
s = input()
alfa = False
for i in s:
if i.isalpha() or i.isdigit() :
alfa = True
print(alfa) #alphanumeric
print(alfa and not s.isdigit()) # alphabetical
print(alfa and not s.isalpha()) # digits
print(alfa and not s.isdigit() and not s.is... |
from .shared import get_model
hmodel1 = get_model("model1.yml", model_id=1)
query = ["cars[0].price"]
hmodel2 = get_model("model2.yml", model_id=2)
query = ["cars[0].price"]
hmodel1.render()
hmodel1.render(query)
hmodel2.render()
hmodel2.render(query)
|
__all__ = ('RoleManagerType',)
from ..bases import PreinstancedBase, Preinstance as P
class RoleManagerType(PreinstancedBase):
"""
Represents a managed role's manager type.
Attributes
----------
name : `str`
The name of the role manager type.
value : `int`
The identifier valu... |
import os
import cv2
import time
import argparse
import logging
import numpy as np
import tensorflow as tf
import multiprocessing
from multiprocessing import Queue, Pool, Value, Lock
from utils.app_utils import FPS, WebcamVideoStream, HLSVideoStream
from object_detection.utils import label_map_util
from object_detectio... |
"""
Small class to create the table necessary for this project.
"""
from flask import Flask
from shortened_url_data import shortenedUrlDb
app = Flask(__name__);
app.config.from_pyfile('config.py');
shortenedUrlDb.init_app(app);
shortenedUrlDb.create_all(app = app); |
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.transforms import trigger
from utils import GetElementTimestamp, PrettyPrint
from samples import samples
def simple_stream():
with beam.Pipeline(options=PipelineOptions(streaming=True)) as p:
wind... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
d... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('omaha', '0022_auto_20150909_0755'),
]
operations = [
migrations.AddField(
model_name='request',
name='ip... |
import mouseinfo
mouseinfo.mouseInfo()
|
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer
from apps.categories.models import Category, Framework, Language, Team
class CategoryReadSerializer(ModelSerializer):
"""Serializer for all categories from Framework/Team/Language."""
class Meta:
... |
from scannerpy import Database, Job
import sys
import os.path
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
import util
################################################################################
# This tutorial shows how to organize your videos into Collections. #
###############... |
from rest_framework import viewsets
from .serializers import MapLocationSerializer
from .models import MapLocation
class MapLocationViewSet(viewsets.ModelViewSet):
queryset = MapLocation.objects.all()
serializer_class = MapLocationSerializer
|
# ----------------------------------------------------------------------------
# Copyright (c) 2017-2018 FIRST. All Rights Reserved.
# Open Source Software - may be modified and shared by FRC teams. The code
# must be accompanied by the FIRST BSD license file in the root directory of
# the project.
# ------------------... |
# -*- coding: utf-8 -*-
import pytest
from data.project_data import projects
from model.project import Project
@pytest.mark.parametrize("project", projects, ids=[repr(x) for x in projects])
def test_add_project(app, project):
old_projects = app.soap.get_list_project('administrator', 'root1')
app.project.add_p... |
#
# PySNMP MIB module CISCO-TELEPRESENCE-EXCHANGE-SYSTEM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TELEPRESENCE-EXCHANGE-SYSTEM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:57:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4... |
# -*- coding: utf-8 -*-
import pytest_rpc.helpers
"""Test cases for the 'parse_swift_recon' helper function."""
def test_empty():
"""Verify parse_swift_recon returns an empty lists when provided an
empty string to parse."""
recon_str = ''
assert pytest_rpc.helpers.parse_swift_recon(recon_str) == []... |
class Solution:
def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
AdjMat = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
AdjMat[i][i] = 1;
for (u, v) in prerequisites:
AdjMat[u][v] = 1
... |
#Fake zope.interface Module
class InterfaceClass(object):
pass
Interface = InterfaceClass()
|
# flake8: noqa
from .class_views import ExecView, View
from .create_app import create_default_app
from .exceptions import JsonErrors, RequestError
from .patch_methods import patch
from .settings import BaseSettings
from .utils import *
from .version import VERSION
|
"""
→ lambda function = function in 1 line using lambda keyword;
accepts any number of arguments, but only has one expression;
(think of it as s shortcut);
(useful if needed for a short period of time, throw-away)
"""
# lambda parameters: expression
def doubl... |
import netomaton as ntm
import numpy as np
if __name__ == '__main__':
"""
Generates a Bifurcation plot for the logistic map.
"""
timesteps = 200
num_nodes = 1000
growth_rates = np.linspace(0.0, 4.0, num_nodes)
network = ntm.topology.disconnected(num_nodes)
[network.add_edge(i, i, gro... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore... |
""" from https://github.com/keithito/tacotron """
import re
from dataset.texts import cleaners
from dataset.texts.symbols import (
symbols,
_eos,
phonemes_symbols,
PAD,
EOS,
_PHONEME_SEP,
)
from dataset.texts.dict_ import symbols_
import nltk
from g2p_en import G2p
# Mappings from symbol to num... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import time
import tensorflow as tf
from sklearn.cross_validation import train_test_split
from utils import *
# In[2]:
trainset = sklearn.datasets.load_files(container_path="data", encoding="UTF-8")
trainset.data, trainset.target = separate_dataset(trainset, 1.0)
p... |
# The MIT License (MIT)
# Copyright (c) 2016-2021 Postsai
#
# 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... |
from __future__ import print_function
from sys import stderr
import subprocess as sp
import threading
import socket
import time
import os
import os.path
import signal
import redis
from shlex import (split)
from catch_memory_leaks import LeakDetector
def invoke(s, **kwargs):
pieces = split(s)
p = sp.Popen(piece... |
"""Unit tests for train.py"""
import unittest
import numpy as np
import xarray as xr
from littlenet import neural_net as nn
from littlenet import train as train
class TrainTest(unittest.TestCase):
def test_shuffle_indexes(self):
arr1 = xr.DataArray(np.arange(100).reshape((50, 2)), dims=(nn.DIM_CASE, nn.D... |
# Generated by Django 3.1 on 2020-10-02 06:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0014_auto_20200930_0550'),
]
operations = [
migrations.RenameModel(
old_name='ReviewComment',
new_name='OwnerCommen... |
# coding: utf-8
from smhsan.common.util import create_and_set_iterators
|
import importlib
import logging
import sys
log = logging.getLogger(__name__)
def load_module(module_name, path=None):
"""Load and return the given module, recursively loading containing packages as necessary."""
if module_name in sys.modules:
log.debug('module %r already loaded' % module_name)
... |
from django.views.generic import View
from django.shortcuts import render
from django.http import JsonResponse
from core import models
import datetime
"""
Требования к выполнению
Back-end: Python 3, Django 1.11, MySQL и предпочтительно DRF.
Front-end: должно быть общение с беком через АПИ.
Проект можно задеплоить ... |
# !/usr/bin/python
# -*- coding:utf-8 -*-
# time: 2019/07/21--20:12
__author__ = 'Henry'
'''
项目: B站动漫番剧(bangumi)下载
版本2: 无加密API版,但是需要加入登录后cookie中的SESSDATA字段,才可下载720p及以上视频
API:
1.获取cid的api为 https://api.bilibili.com/x/web-interface/view?aid=47476691 aid后面为av号
2.下载链接api为 https://api.bilibili.com/x/player/playurl?avid=4... |
import multiprocessing
from servicelayer import env
# Redis cache
# URL format: redis://localhost:6379/0
REDIS_URL = env.get("REDIS_URL")
REDIS_SHORT = 84700
REDIS_LONG = REDIS_SHORT * 200
REDIS_EXPIRE = env.to_int("REDIS_EXPIRE", REDIS_SHORT * 7)
REDIS_PREFIX = "sla"
# Persistent database tags
TAGS_DATABASE_URI = en... |
# -*- coding: utf-8 -*-
import Image, ImageDraw, ImageFont
org = Image.open('./origin.jpg')
draw = ImageDraw.Draw(org)
w, h = org.size
fontsize = min(w, h) / 4
font = ImageFont.truetype('GenBkBasI.ttf', fontsize)
draw.text((w - fontsize, 0), '3', font = font, fill = (255, 0, 0))
org.save('rst.jpg', 'jpeg')
|
from django.contrib import admin
from profiles_app import models
admin.site.register(models.UserProfile)
admin.site.register(models.DeviceInfo)
|
from typing import Dict
from Utils.Array import input_array
# memo: Dict[tuple[int, int]] = {}
memo = {}
def helper(array_sum, n, x, arr, index, subset_sum) -> bool:
if index >= n:
if array_sum - subset_sum <= x:
return True
return False
# check if already found out earlier
... |
#!/usr/bin/env python3
import logging
from copy import copy
from enum import Enum
import numpy as np
log = logging.getLogger('LabberDriver')
class BaseGate:
"""Base class for a qubit gate.
Attributes
----------
phase_shift : float
The phase shift applied when compiling into pulsesself.
... |
from __future__ import annotations
from empire.data_structures.struct import Struct
from empire.system.enums.temperature_states import TemperatureStates
class TemperatureStruct(Struct):
def __init__(self, raw=None):
super().__init__()
self._current: float = 0.0
self._high: float = 0.0
... |
from flask import Flask, render_template, request, flash, redirect, url_for, send_file
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from flask_sqlalchemy import SQLAlchemy
from flask... |
from tkinter import *
from time import *
from math import *
tk = Tk()
screen = Canvas(tk, width=600, height=600, background="black")
screen.pack()
colors = ["purple", "green", "blue", "red", "orange", "yellow", "pink"]
ringx1 = 0
ringy1 = 0
ringx2 = 600
ringy2 = 600
#draw rings
for i in range(6):
... |
from clstorch import *
from transform import myTransform
from dataloader import Dataloader
import matplotlib.pyplot as plt
import tqdm
data = scipy.io.loadmat("./digits.mat")
Xtest,ytest = np.array(data["Xtest"]), np.array(data["ytest"]-1)
X,y = np.array(data["X"]), np.array(data["y"]-1)
Xvalid, yvalid = np.array(d... |
# -*- coding: utf-8 -*-
"""
Patterns for finding info in seismic headers heuristically.
:copyright: 2016 Agile Geoscience
:license: Apache 2.0
"""
import numpy as np
def flat(arr):
"""
Finds flat things (could be zeros)
___________________________
"""
arr = np.array(arr)
if arr.size == 0... |
import pandas as pd
# Keyword Method with iterrows()
# {new_key:new_value for (index, row) in df.iterrows()}
# TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
df = pd.read_csv("./nato_phonetic_alphabet.csv")
df_list = df.values.tolist()
df_dict = {x[0]: x[1] for x in df_list}
# print(df_d... |
#!/usr/bin/env python
# Copyright (C) 2020 Ashwin Nayak
#
# 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... |
import numpy as np
from UnionFind import UnionFind
class ConnectedComponentsLabeling(object):
def __init__(self, neighbor_number=4, max_components=100):
self.neighbor_number = neighbor_number
self.current_uf = UnionFind(max_components)
def image_label(self, image_array):
image_height... |
import numpy as np
from scipy.stats import rankdata, mode
from collections import OrderedDict
from warnings import warn
def shares_at_rank(h,r=None, rk=None, bar_s=None):
"""
Given a matrix of (n_sims, n_dists) voteshares, this provides the distributions of voteshares within
each rank over all simulations... |
##################################
### Tests behind legal moves ###
### and words in Boggle, ###
### what screen it's on and ###
### which game is being played ###
##################################
# Megan Cahill
# mcahill
def whichGameDice(canvas):
four = canvas.data["fourByFour"]
five = canvas.... |
import os
import sys
import json
import time
import socket
import select
import logging
import threading
from twisted.internet import reactor
from twisted.internet.endpoints import UNIXServerEndpoint as ServerEndpoint
import path
import connection
import instance
__all__ = ('path', 'connection', 'instance',
'... |
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
"""
Information for the pgmpl module.
This would normally go in __init__.py, but importing __init__ in setup.py to get info causes a segfault during package
installation. So, this information is placed here and imported into __init__.py and into setup.py.
"""
# Define ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2021, Sandflow Consulting LLC
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, ... |
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License 2.0;
# 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... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import numpy as np
import os
import pandas as pd
def generate_graph_seq2seq_io_data(df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_week=Fals... |
#!/usr/bin/env python3
"""Example file for eternalegypt library."""
import sys
import asyncio
import aiohttp
import eternalegypt
import logging
logging.basicConfig(level=logging.DEBUG)
async def reconnect():
"""Example of disconnecting and reconnecting."""
jar = aiohttp.CookieJar(unsafe=True)
websessio... |
# -*- coding: utf-8 -*-
"""
Обработчики запросов для взаимодействия с API PayMaster
https://paymaster.ru/Partners/ru/docs/protocol
@author: Vlasov Dmitry
@contact: scailer@russia.ru
@status: stable
"""
import base64
import urllib
import hashlib
from datetime import datetime, timedelta
from djang... |
"""This module contains tests for the benchmark utilities.
"""
import sys
import time
import pytest
from pywrangler.benchmark import (
BaseProfiler,
MemoryProfiler,
TimeProfiler,
allocate_memory
)
from pywrangler.exceptions import NotProfiledError
MIB = 2 ** 20
@pytest.fixture()
def func_no_effec... |
import sys, os, time
from PyQt5 import QtCore, QtWidgets
from application import *
from Arhives_Queue import *
import threading, time
from queue import Queue, Empty, Full
#*************************** ПЕРЕМЕННЫЕ ********************************************
start_dir = '' #
item_co... |
import pickledb
import yaml
from datetime import *
from dateutil.parser import *
from dateutil.tz import *
pttzinfo = {
"PT": gettz("America/Los_Angeles"),
"PDT": gettz("America/Los_Angeles"),
"PST": gettz("America/Los_Angeles")
}
default_date = datetime.combine(datetime.now(), time(0, tzinfo=gettz("Ameri... |
from unidecode import unidecode
from re import sub
def decode(s):
# Does its best to substitute ASCII characters for
# Unicode characters
return unidecode(s)
def sanitize(s):
# Removes spaces, apostrophes, and Unicode
return sub('[ \']', '', decode(s))
def sane(s):
# I'm sure there used to... |
from collections import OrderedDict
class Classes():
"""Define which labels are used for the labs. fineGrained decide if few or many labels should be used."""
def __init__(self,fineGrained=False):
self.fineGrained = fineGrained
@property
def classes(self):
""" """
return [
... |
import pytest
from requests.exceptions import HTTPError
from sfa_dash.api_interface.util import handle_response
from sfa_dash.errors import DataRequestException
@pytest.fixture()
def mock_response(mocker):
def fn(status_code):
def raise_for():
raise HTTPError()
resp = mocker.Mock()
... |
import time
from datetime import timedelta
from sauna.plugins import Plugin, PluginRegister
my_plugin = PluginRegister('PuppetAgent')
@my_plugin.plugin()
class PuppetAgent(Plugin):
def __init__(self, config):
super().__init__(config)
self.config = {
'summary_path': config.get(
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/hex_pb_package.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import ... |
import datetime
import hashlib
import base64
import hmac
import requests
import logging
import os
import time
import re
#s3 userguid 991page
#BTKZY9YC08AKLAWGN6RY
#47pxhXLNNqWjDb2GfOCbg3BEPxLHHlwQkmEJnOAj
ACCESS_KEY = 'BTKZY9YC08AKLAWGN6RY'.encode("UTF-8")
SECRET_KEY = '47pxhXLNNqWjDb2GfOCbg3BEPxLHHlwQkmEJ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.