content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import random
def busqueda_local(solucion_inicial, evaluacion, obtener_vecinos,
T_max, T_min, reduccion):
"""
Simulated Annealing.
"""
from random import random
solucion_mejor = solucion_actual = soluc... | python |
#!/usr/bin/python3
#-*-coding:utf-8-*-
from threading import Thread
import pymysql
from Sqlcore import Sqlcore
'''
入口功能
'''
'''vmode打印显示模式full/standard/simple'''
#生产环境的photo相册
conn = {"hostname":"xxxxxx.mysql.rds.aliyuncs.com","username":"forpython","password":"Ffu398fh_GFUPY","database":"dbuser","hostport":3708... | python |
#!/usr/bin/env python
import sys
import os
import shutil
def cleanup_dump(dumpstr):
cardfrags = dumpstr.split('\n\n')
if len(cardfrags) < 4:
return ''
else:
return '\n\n'.join(cardfrags[2:-1]) + '\n\n'
def identify_checkpoints(basedir, ident):
cp_infos = []
for path in os.listdir(b... | python |
a, b = map(int, input())
if a <= 9 and b <= 9:
ans = a * b
else:
ans = -1
print(ans)
| python |
# Test the frozen module defined in frozen.c.
from test.test_support import TestFailed
import sys, os
try:
import __hello__
except ImportError, x:
raise TestFailed, "import __hello__ failed:" + str(x)
try:
import __phello__
except ImportError, x:
raise TestFailed, "import __phello__ fail... | python |
# Generated by Django 3.2.6 on 2021-08-21 12:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('education', '0021_alter_materialblocks_icon'),
]
operations = [
migrations.AlterField(
model_name='materialblocks',
... | python |
from __future__ import annotations
from typing import TYPE_CHECKING
from openhab_creator import _
from openhab_creator.models.common import MapTransformation
from openhab_creator.models.configuration.equipment.types.sensor import (
Sensor, SensorType)
from openhab_creator.models.items import (DateTime, Group, Gro... | python |
# -*- coding: utf-8 -*-
"""Library to easily manage Host Health"""
from __future__ import division
import logging
import psutil
import threading
import time
COLOR_GREEN = '#4caf50'
COLOR_ORANGE = '#ff5722'
COLOR_RED = '#f44336'
CPU_THRESHOLD_WARNING = 70
CPU_THRESHOLD_DANGER = 85
duplex_map = {
psutil.NIC_DUPL... | python |
__author__ = 'Rob Edwards'
import sys
from matrices import blosum62
def score(a, b):
"""score dna as match/mismatch"""
if a == b:
return 1
return -1
def dna_score_alignment(seq1, seq2, gap_open=11, gap_extend=1):
"""
Generate a score for an alignment between two sequences. This does not ... | python |
from libs.matrix_client.matrix_client.client import MatrixClient
from libs.matrix_client.matrix_client.api import MatrixRequestError
from libs.matrix_client.matrix_client.user import User
from requests.exceptions import MissingSchema
from helpers import setup_logger
logger = setup_logger(__name__, 'info')
class Clie... | python |
import unittest
import uuid
from unittest.mock import patch
from microsetta_private_api.model.interested_user import InterestedUser
from microsetta_private_api.repo.interested_user_repo import InterestedUserRepo
from microsetta_private_api.repo.transaction import Transaction
from psycopg2.errors import ForeignKeyViola... | python |
import binascii
import socket
import struct
from twampy.utils import generate_zero_bytes, now
from twampy.constants import TIMEOFFSET, TWAMP_PORT_DEFAULT, TOS_DEFAULT, TIMEOUT_DEFAULT
import logging
logger = logging.getLogger("twampy")
class ControlClient:
def __init__(self, server, port=TWAMP_PORT_DEFAUL... | python |
from helpers import test_tools
from graph import GraphRoutingProblem
from dungeon import DungeonProblem | python |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.models import AuthIdentity, AuthProvider
from sentry.testutils import APITestCase
class DeleteUserIdentityTest(APITestCase):
def test_simple(self):
user = self.create_user(email="a@example.com")
org =... | python |
#
# build the vocab/dictionary from outside to all related lexicons
from __future__ import print_function
import os
import sys
import argparse
sys.path.append(".")
sys.path.append("..")
sys.path.append("../..")
from neuronlp2 import utils
from neuronlp2.io import get_logger, conllx_stacked_data
#
# Only use for ... | python |
# Copyright 2021 Universität Tübingen, DKFZ and EMBL
# for the German Human Genome-Phenome Archive (GHGA)
#
# 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/license... | python |
def ones(l):
#return l + [x + '_1' for x in l]
#return sorted(l + [x + '_1' for x in l])
ret = []
for x in l:
ret.append(x)
ret.append(x + '_1')
return ret
# The complete primitive sets
ffprims_fall = ones(
[
'FD',
'FDC',
'FDCE',
'FDE',
'... | python |
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name = 'django-pimp-my-filter',
version = '0.1.1',
... | python |
#!/usr/bin/env python
# Python imports
import matplotlib as plt
import numpy as np
import time
import argparse
# Other imports
import srl_example_setup
from simple_rl.tasks import GridWorldMDP
from simple_rl.planning.ValueIterationClass import ValueIteration
# INSTRUCTIONS FOR USE:
# 1. When you run the program [eit... | python |
import socket
import time
HOST='data.pr4e.org'
PORT=80
mysock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect((HOST,PORT))
mysock.sendall(b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n')
count=0
picture=b""
while True:
data=mysock.recv(5120)
if(len(data)<1):
break
time.slee... | python |
#!/usr/bin/env python
"""
Tropical Cyclone Risk Model (TCRM) - Version 1.0 (beta release)
Copyright (C) 2011 Commonwealth of Australia (Geoscience Australia)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the... | python |
import pandas as pd
import numpy as np
from os import listdir
import config
def read(bound_file_path, compounds_file_path, adducts_file_path):
'''
Read in excel files as pd.DataFrame objects
'''
bound_df = pd.read_excel(bound_file_path)
compounds_df = pd.read_excel(compounds_file_path)
adduc... | python |
#! /usr/bin/env python
import onnx.backend
import argparse
import caffe2.python.workspace as c2_workspace
import glob
import json
import numpy as np
import onnx
import caffe2.python.onnx.frontend
import caffe2.python.onnx.backend
import os
import shutil
import tarfile
import tempfile
import boto3
from six.moves.url... | python |
# Copyright (c) 2018 Graphcore Ltd. All rights reserved.
# This script is run by the release agent to create a release of PopTorch
def install_release(release_utils, release_id, snapshot_id, version_str):
# Tag must contain the string 'poptorch' to keep it unique.
tag = "{}-poptorch".format(version_str)
... | python |
import json
import pytest
from ermaket.api.database import DBConn
from ermaket.api.scripts import ScriptManager
from ermaket.api.system.hierarchy import Activation, Trigger, Triggers
CHAIN_ID = 1
TEAPOT_ID = 2
ADD_ID = 3
ADD2_ID = 4
def login(client, user):
return client.post(
'/auth/login', data={
... | python |
from django.conf.urls import url
from django.views.generic.base import RedirectView
from tests.views import foo, foo_api
urlpatterns = [
url(r"^api/foo/$", foo_api),
url(r"^foo/$", foo),
url(r"^bar/$", RedirectView.as_view(url="/foo/", permanent=False)),
]
| python |
from math import sqrt
from django.test import TestCase
from ..models import InstructionSet
class InstructionSetModelTest(TestCase):
def setUp(self):
self.test_set = InstructionSet.objects.create(up=1, down=3, left=5, right=7)
def test_model_fields(self):
self.assertEqual(self.test_set.up, ... | python |
from .site import SiteCommand
from .platform import PlatformCommand
from .system import SystemCommand
AVAILABLE_COMMANDS = [SiteCommand(), PlatformCommand(), SystemCommand()]
| python |
# Generated by Django 2.0.8 on 2018-08-25 09:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('information_pages', '0004_auto_20180825_1114'),
]
operations = [
migrations.AlterModelOptions(
name='informationdocument',
o... | python |
"""
This script is used to construct, test and analyze the various variants
for digit addition and subtraction.
"""
import re
import sys
import subprocess
import colorama
# snippet construction
def define_all():
global ADD_09_09, ADD_09_90, ADD_90_09, ADD_90_90
global SUB_09_09, SUB_90_09, SUB_09_90, SUB_90... | python |
# -*- coding: utf-8 -*-
"""
Spyder Editor
AutoGIS lesson 2 geopandas
This is a temporary script file.
"""
import geopandas as gpd
# set filepath
fp = r'F:\GS\harrisab2\S18\GeoViz\autoGIS_2\Data\DAMSELFISH_distributions.shp'
# read file using gpd.read_file()
data = gpd.read_file(fp)
# write first 50 r... | python |
# -*- coding: utf-8 -*-
from __future__ import division
from pyevolve import G1DList, GSimpleGA, Selectors, Statistics
from pyevolve import Initializators, Mutators, Consts, DBAdapters
import os
from math import log, log1p, exp
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
... | python |
import datetime
import random
import matplotlib.pyplot as plt
from graphpkg.live.graph import LiveTrend,LiveScatter
# plt.style.use('')
count1 = 0
cluster = 0.30
def func1():
global count1
count1 += 1
return datetime.datetime.now(), [random.randrange(1, 10) + count1,random.randrange(1,10)+ count1]
def... | python |
'''
Created on 2016/9/20
:author: hubo
'''
from __future__ import print_function
from vlcp.server import main
from vlcp.event import Client
from vlcp.server.module import Module
from vlcp.config import defaultconfig
from vlcp.protocol.zookeeper import ZooKeeper, ZooKeeperConnectionStateEvent,\
ZooKeeperWatcherEven... | python |
from mbdata import models
from sqlalchemy import inspect
from sqlalchemy.orm.session import object_session
ENTITY_TYPES = {
'artist': models.Artist,
'label': models.Label,
'place': models.Place,
'release_group': models.ReleaseGroup,
'release': models.Release,
'url': models.URL,
'work': mod... | python |
import enum
class Encrypting:
def __init__(self):
encrypting_type = "" #szyfr wybrany w gui
class Cipher(enum.Enum):
NO_CIPHER = 1
CAESAR = 2
FERNET = 3
POLYBIUS = 4
RAGBABY = 5
| python |
from flask import Flask
from flask import render_template
from flask import request, jsonify
import argparse
import itertools
import dateutil.parser
import os
from flask_sqlalchemy import SQLAlchemy
from libs import gcal_client
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
app = Flask(__name__)
app.conf... | python |
#!/usr/bin/env python
#
import webapp2
import re
from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.api import users
from google.appengine.ext.webapp import blobstore_handlers
import logging
import parsers
import headers
# This is the triple store api.
# We have a n... | python |
'''
Created By ILMARE
@Date 2019-3-1
'''
from bs4 import BeautifulSoup
from urllib.request import urlretrieve
import requests
from PIL import Image
import os
import re
totalCount = 0
pre_path = r"/home/ilmare/Desktop/FaceReplace/data/image/"
class PhotoScrawler:
def __init__(self, savePath, destUrl, maxPage):
... | python |
from diary.models import Note
from django.forms import Textarea, ModelForm
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.html import format_html
from django.views.generic import ListView, CreateView
class NoteListView(ListView):
... | python |
# -*- coding: utf-8 -*-
import os
from lib.ipc import ActorProcess
from lib.systray import SysTrayIcon
from lib.utils import init_logging
class UI(ActorProcess):
def __init__(self, coordinator):
super(UI, self).__init__()
self.coordinator = coordinator
def systray_quit(self, systray_... | python |
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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... | python |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# Copyright 2019 Kakao Brain
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f... | python |
import numpy as np
import string
wrd_fname = 'p042_words.txt'
def gen_triang_list(elems = 1000):
out_list = []
for x in xrange(1, elems):
out_list.append((x*(x+1))/2)
return out_list
def word_to_sum(word):
total_sum = 0
word = string.lower(string.strip(word))
base_sub = ord('a')-1
... | python |
from flask import Flask, jsonify
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_restful import Api
from flask_jwt_extended import JWTManager
ma = Marshmallow()
cors = CORS()
bcrypt = Bcrypt()
jwt = JWTManager()
def create_app(config_object=None):
... | python |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# bot_bcad_3.6.py
import utilities, os, fnmatch, re
async def membersDump(ctx):
serverName = (f"*{ctx.message.guild.name.replace(' ', '-')}*")
membersList = []
for file in os.listdir('./logs'):
if fnmatch.fnmatch(file, 'members-server*'):
... | python |
# Greedy
class Solution:
def maxProfit(self, prices):
profit = 0
for i in range(len(prices) - 1):
profit += max(0, prices[i + 1] - prices[i])
return profit
if __name__ == "__main__":
i = [7, 1, 5, 3, 6, 4]
s = Solution()
print(s.maxProfit(i)) | python |
# source code: binary_decoder.py
# author: Lukas Eder
# date: 13.02.2018
#
# Descr.:
# Userinput wird von ASCII in binaere Byte-Strings gewandelt oder umgekehrt.
# Funktion Binaer zu Ascii
def bin_read(binCode):
for line in file:
line_split = line.strip('\n').split(",")
... | python |
#!/usr/bin/env python3
"""main.py: The main file used to execute MindFull."""
__author__ = "Rhys Read"
__copyright__ = "Copyright 2019, Rhys Read"
import logging
from display import Display
logging.basicConfig(level=logging.DEBUG)
class Main(object):
def __init__(self):
self.__display = Display()
... | python |
from Utils.alerter import send
from Utils.urlShortener import short
import discord
from discord.ext import commands
import config
class AntiCaps(commands.Cog):
def __init__(self, client):
self.client = client
self.title = "Anti-Caps System"
self.type = config.CAPS_TYPE
if self.t... | python |
import numpy as np
def get_quantization_matrix(quality: int = 100) -> np.ndarray:
"""
Get quantization matrix denpends on quality.
Args:
quality: quality of quantization
Returns:
quantiazation matrix
"""
# quantization matrix
q = [[16, 11, 10, 16, 24, 40, 51, 61],
... | python |
# -*- coding: utf-8 -*-
#
# Hash/CMAC.py - Implements the CMAC algorithm
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perp... | python |
# Copyright (c) 2013 Hortonworks, Inc.
#
# 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 ... | python |
from abc import ABCMeta, abstractclassmethod
class iDocGenerator(metaclass=ABCMeta):
"""
Generate documents
"""
def __init__(self):
pass
@abstractclassmethod
def createDocumentTuple(self):
"""
Yield list of documents
"""
pass
@abstractclassmethod
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Setup script for the pyexodus module.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2016
:license:
MIT License
"""
import inspect
import os
import sys
from setuptools import setup, find_packages
# Import the version string.
path = os.path.j... | python |
import numpy as np
import os
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
import pandas as pd
if __name__ == '__main__':
data_path = './augmentation_vtk_data/'
output_path = './'
num_augmentations = 20
train_size = 0.8
with_flip = True
num_sam... | python |
# -*- encoding: utf-8 -*-
# Copyright (c) 2017 Servionica
#
# 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 l... | python |
"""Utility code for facilitating collection of code coverage when running tests."""
from __future__ import annotations
import atexit
import os
import tempfile
import typing as t
from .config import (
IntegrationConfig,
SanityConfig,
TestConfig,
)
from .io import (
write_text_file,
make_dirs,
)
f... | python |
import argparse
p = argparse.ArgumentParser()
p.add_argument("--foo", action="store_true")
args = p.parse_args()
print(args.foo)
| python |
#!/usr/bin/env python3
""" Tests for processing microsegment data """
# Import code to be tested
import mseg as rm
# Import needed packages
import unittest
import re
import numpy as np
import os
import itertools
# Skip this test if running on Travis-CI and print the given skip statement
@unittest.skipIf("TRAVIS" i... | python |
# -*- coding: utf-8 -*-
import openingbook
book = openingbook.build_table(10)
assert len(book) > 0, "Your opening book is empty"
assert all(isinstance(k, tuple) for k in book), \
"All the keys should be `hashable`"
assert all(isinstance(v, tuple) and len(v) == 2 for v in book.values()), \
"All the values sho... | python |
"""
Insertion resources for SGAS.
Used for inserting usage records into database.
Author: Henrik Thostrup Jensen <htj@ndgf.org>
Magnus Jonsson <magnus@hpc2n.umu.se>
Copyright: NorduNET / Nordic Data Grid Facility (2009, 2010, 2011)
"""
from twisted.internet import defer
from twisted.python import log
from tw... | python |
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | python |
# Generated by Django 3.2.8 on 2021-11-01 19:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('neighbor', '0002_rename_neighbourhood_neighborhood'),
]
operations = [
migrations.RemoveField(
model_name='business',
name='... | python |
# -*- coding: utf-8 -*-
"""The Windows EventLog (EVT) file event formatter."""
from plaso.formatters import interface
from plaso.formatters import manager
from plaso.lib import errors
class WinEVTFormatter(interface.ConditionalEventFormatter):
"""Formatter for a Windows EventLog (EVT) record event."""
DATA_TYPE... | python |
"""
Some basic admin tests.
Rather than testing the frontend UI -- that's be a job for something like
Selenium -- this does a bunch of mocking and just tests the various admin
callbacks.
"""
import mock
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.test import TestCase
fro... | python |
import os
import json
import functools
from tornado import web
from notebook.base.handlers import IPythonHandler
from nbgrader.api import Gradebook
from nbgrader.apps.api import NbGraderAPI
class BaseHandler(IPythonHandler):
@property
def base_url(self):
return super(BaseHandler, self).base_url.rstr... | python |
"""Test creating new settings """
import pytest
from bot.core.database.settings_collection import SettingsCollection
from test_framework.asserts.database_asserts.check_settings_collection import check_create_new_settings
from test_framework.scripts.common.data_factory import get_test_data
@pytest.mark.asyncio
@pytes... | python |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
# pylin... | python |
import unittest
import mock
from able.queue import ble_task
class TestBLETask(unittest.TestCase):
def setUp(self):
self.queue = mock.Mock()
self.task_called = None
@ble_task
def increment(self, a=1, b=0):
self.task_called = a + b
def test_method_not_executed(self):
s... | python |
#!/usr/bin/env python
# encoding: utf-8
"""@package Operators
This module offers various methods to process eye movement data
Created by Tomas Knapen on .
Copyright (c) 2010 TKLAB. All rights reserved.
More details.
"""
from __future__ import division
import os, pickle, inspect
import numpy as np
import scipy as s... | python |
class LOG:
""" This class specifies the different logging levels that we support.
Levels can be trivially added here and in src/core/utility.py#Msg along
with their pretty output information.
"""
INFO = 1 # green
SUCCESS = 2 # bold green
ERROR = 3 # red
DEBUG = 4 ... | python |
# -*- coding: utf-8 -*-
"""
Marker Property
===============
"""
# %% IMPORTS
# Package imports
from matplotlib import rcParams
# GuiPy imports
from guipy import widgets as GW
from guipy.plugins.figure.widgets.types.props import BasePlotProp
from guipy.widgets import set_box_value
# All declaration
__all__ = ['Lin... | python |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.metrics import r2_score
import pandas as ... | python |
import flask
from pypi_vm.infrastructure.view_modifiers import response
from pypi_vm.viewmodels.packages.package_details_viewmodel import PackageDetailsViewModel
from pypi_vm.viewmodels.packages.popular_viewmodel import PopularPackageViewModel
blueprint = flask.Blueprint('packages', __name__, template_folder='templat... | python |
#!/usr/bin/python3
import requests as rq
from hbtn_api.urls import URL_AUTH
def auth(apikey, email, psswd, *args):
data = {
'api_key': apikey,
'email': email,
'password': psswd,
'scope': 'checker'
}
r = rq.get(URL_AUTH, data=data)
return r.json()
| python |
import configparser
import datetime
import wx
import os
# local imports
from . import core
class Config:
"""
Used as a common config manager thorought the application,
it uses configparser functionality to load configuration files
and theme files.
"""
def __init__(self):
self.load_c... | python |
valores: list = list()
maior = menor = 0
for cv in range(0, 5):
valores.append(int(input(f'Digite um valor na posição {cv}: ')))
maior = max(valores)
menor = min(valores)
# if cv == 0:
# maior = menor = valores[cv]
# else:
# if valores[cv] > maior:
# maior = valores[cv]
... | python |
import random
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUMBERS = "0123456789"
class Robot(object):
ROBOT_NAME_CHARS_NUMBER = 2
ROBOT_NAME_NUM_NUMBERS = 3
def __init__(self):
self.reset()
@staticmethod
def _generate_name_section(collection, number_of_iteration):
"""_generate_name... | python |
import sublime,sublime_plugin,threading,json,os,threading,subprocess,socket,shutil
from base64 import b64encode, b64decode
# python 2.6 differences
try:
from hashlib import md5, sha1
except: from md5 import md5; from sha import sha as sha1
from SimpleHTTPServer import SimpleHTTPRequestHandler
from struct import pac... | python |
"""Providers services related to the cache."""
from typing import Optional
from limberframework.cache.cache import Cache
from limberframework.cache.lockers import Locker, make_locker
from limberframework.cache.stores import Store, make_store
from limberframework.foundation.application import Application
from limberfra... | python |
#!/usr/bin/env python2.7
# Distributed under the terms of MIT License (MIT)
# Based on fa.wikipedia's AbarAbzar tool
##https://fa.wikipedia.org/wiki/Mediawiki:Gadget-Extra-Editbuttons-persianwikitools.js
##https://fa.wikipedia.org/wiki/Mediawiki:Gadget-Extra-Editbuttons-persiantools.js
##https://fa.wikipedia.org/wiki... | python |
# -*- coding: utf-8 -*-
import logging
import sys
LOG_FORMAT = "[%(process)d] %(asctime)s.%(msecs)03d [%(levelname).1s] %(message)s"
LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
def setup_logging() -> None:
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE_FORMAT)
handler = logging.StreamHandler(sys... | python |
#!/usr/bin/env python
# ClusterShell.Node* test suite
"""Unit test for NodeSet with Group support"""
import copy
import shutil
import sys
import unittest
sys.path.insert(0, '../lib')
from TLib import *
# Wildcard import for testing purpose
from ClusterShell.NodeSet import *
from ClusterShell.NodeUtils import *
... | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import io
import math
import numpy as np
import random
import torch
from PIL import Image
def temporal_sampling(hdf5_video, hdf5_video_key, start_idx, end_idx, num_samples, video_length):
"""
Given the start and en... | python |
from setuptools import setup, Extension
import setuptools
stream_json_parser_utils = Extension('stream_json_parser_utils', extra_compile_args = [ '--std=c++11' ], sources = [ 'utils/src/utils.cpp' ])
if __name__ == '__main__':
setup(
name='streamjsonparser',
version='1.1',
description='Stream ... | python |
from collections import OrderedDict
from datetime import datetime, timezone
from pytest import raises
from qsck import serialize
def test_serialize_is_a_function():
assert hasattr(serialize, '__call__')
def test_it_formats_identifier_and_timestamp_as_unix_epoch():
identifier = 'LOG'
some_key_value_pa... | python |
"""
This build static figures with dataset from
the google drive : "study_mearec_SqMEA1015um".
"""
import sys
sys.path.append('../../examples/modules/comparison/')
from generate_erroneous_sorting import generate_erroneous_sorting
import spikeinterface.extractors as se
import spikeinterface.comparison as sc
impor... | python |
from optparse import OptionParser
from random import randint
import random
import sys
import io
import queue
#import statprof
from contextlib import contextmanager
#@contextmanager
#def stat_profiler():
#statprof.start()
#yield statprof
#statprof.stop()
#statprof.display()
class Edge:
def __in... | python |
from moneywave.account import Account
from moneywave.resources import Resource
from moneywave.transaction import Transaction
from moneywave.utils import Util, Settings
from moneywave.wallet import Wallet
class MoneyWave:
def __init__(self, api_key, secret_key, mode="test"):
self.settings = Settings(api_ke... | python |
class PropsdDictionary(dict):
"""A dictionary backed by propsd
This dictionary enables the use of a standard python dictionary
that is backed by the propsd service. The dictionary must be
refreshed by calling the refresh method.
"""
def __init__(self, propsd_client):
self.__propsd_client = propsd_cli... | python |
import argparse
import seaborn as sns # noqa
from matplotlib import pyplot as plt
from pathlib import Path
from dask import dataframe as dd
import const
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True)
args = parser.parse_args()
data_dir = Path(args.... | python |
default_chunk_size = 32 * 1024 * 1024
gs_max_parts_per_compose = 32
upload_chunk_identifier = "gs-chunked-io-part"
reader_retries = 5
writer_retries = 5
| python |
import cmath
def usual(tab):
N = len(tab)
tab2 = [0] * N
for n in range(0, N):
for k in range(0, N):
tab2[n] = tab2[n] + tab[k] * cmath.exp(-2 * 1j * cmath.pi * n * (k / N))
return tab2
def inverse(tab):
N = len(tab)
tab2 = [0] * N
for n in range(0, N):
for ... | python |
from sklearn import preprocessing
from desafio_iafront.jobs.common import transform
from desafio_iafront.data.saving import save_partitioned
class Preprocessing:
def __init__(self, result, saida):
self.result = result
self.saida = saida
def normalizer(self):
# Faz a escala dos valor... | python |
from typing import TYPE_CHECKING
from contextlib import closing
from nonebot.rule import Rule
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import MessageEvent
from .. import crud
from ..db import get_db
if TYPE_CHECKING:
from nonebot.typing import Bot, Event
def validate_user() -> Rule:
... | python |
from django.utils.encoding import force_text
import pytest
from apps.core.tests.base_test_utils import (
generate_uid_and_token,
mock_email_backend_send_messages,
)
from apps.users.constants.messages import EXPIRED_LINK_MESSAGE
from .constants import NEW_TEST_PASSWORD, PASS_RESET_CONFIRM_URL, PASS_RESET_URL
... | python |
from pftools.module_conv_utils import PFConversion
class pncConversion(PFConversion):
"""Class for probe data conversion
inherits from PFConversion
Parameters
----------
pfFile : string
probe file (surface or volume)
verbose : bool
Activate or desactivate informative prints (d... | python |
# Generated by Django 3.0.8 on 2020-08-20 19:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0019_auto_20200820_1508'),
]
operations = [
migrations.AlterField(
model_name='course',
name='hours',
... | python |
""" This module contains the code that allows the LWR to stage file's during
preprocessing (currently this means downloading or copying files) and then unstage
or send results back to client during postprocessing.
:mod:`lwr.managers.staging.preprocess` Module
-------------------------------
.. automodule:: lwr.manage... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.