content stringlengths 5 1.05M |
|---|
# coding: UTF-8
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# Twitter API
API_KEY = os.environ.get("API_KEY")
API_SECRET_KEY = os.environ.get("API_SECRET_KEY")
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
ACCESS_TOK... |
__all__ = ['Optimizer', 'OptimizationFunction',
'Quadratic', 'quad1', 'quad2', 'quad3', 'quad4', 'quad5']
from ._base import Optimizer, OptimizationFunction, Quadratic, quad1, quad2, quad3, quad4, quad5
|
import os, random, sys, io
import numpy as np
from keras.models import Model
from keras.layers import Input, GRU, Dense, Embedding, Dropout
from keras.models import load_model
from keras.optimizers import Adam
"""
a simple seq2seq model prepared as a baseline model for DSTC7
https://github.com/DSTC-MSR-NLP/DS... |
import numpy as np
from spacetime.potential import Potential
###################################################################
class Schwarzschild(Potential):
def __init__(self, theta=np.pi/2, l=3.8, r_range=(2, 18), num=10000,
cont_without_eq=False, verbose=True):
super().__init__(r_ra... |
{
'def': '"A protein transport process that contributes to protein import into the nucleus, and that results in the vectorial transfer of a cargo-carrier protein complex through the nuclear pore complex from the cytoplasmic side to the nucleoplasmic side of the nuclear envelope." [GOC:curators, ISBN:019 8506732, PMID... |
#! /usr/bin/env python
def generate_power_func(n):
print "id(n): %X" % id(n)
print "entry value of n:", n
def nth_power(x):
print "the value of n:", n
print "the value of x:", x
print "the value of (power operator) x**n:", x**n
return x**n
print "id(nth_power): %X" % id(nth_power)
... |
""" Game fix for Tomb Raider I
"""
# pylint: disable=C0103
from protonfixes import util
def main():
""" Enable Glide emulation in dosbox config """
conf_dict = {'glide': {'glide': 'emu'}}
util.create_dosbox_conf('glide_fix.conf', conf_dict)
util.append_argument('-conf')
util.append_argument('glid... |
import re
from .base import (
ANNOTATIONS_REGEX,
WikipediaScraperBase,
)
from ..filters.film import WikipediaFilmFilter
class WikipediaFilmScraper(WikipediaScraperBase):
filter_class = WikipediaFilmFilter
disambiguation_id = "Film_and_television"
disambiguation_keyword = "film"
def make_data... |
#
import numpy as np
import tensorflow as tf
def read_irsi_softmax():
iris=np.loadtxt('D:\Python\DlgsPark\data\multivariable data/iris_softmax.csv', delimiter=',')
print(iris.shape) #(150,8)
#1. train_set/test_set 분리하기
#방법1) vstack
train_set=np.vstack((iris[:40], iris[50:90], iris[100:140]))
p... |
#!/usr/bin/python3
def common_elements(set_1, set_2):
return (set(set_1) & set(set_2))
|
# pygame example: github.com/pddring/pygame-examples
"""
This example shows you how to display text and combine it with images
in the pygame graphics window.
Things to try:
TODO: Change the "Press Q to quit" from red to blue
TODO: Make "Press Q to quit" appear at the bottom of the screen in the middle
TODO: "Press a... |
import shutil
from pathlib import Path
import pytest
from sending.curation_files import CurationFiles
@pytest.fixture
def curation_files(tmp_path: Path) -> CurationFiles:
old = tmp_path / "old"
old.mkdir()
temp = tmp_path / "temp"
temp.mkdir()
for f in Path("tests/fixtures/files/tremblfiles").glob... |
from .settings import (
WHERE_SPECIAL_ARGUMENTS, AUTOMATIC_JOINS_PLACEHOLDER,
FIELD_FORMAT, SELECT_FORMAT, JOIN_CLAUSE_FORMAT, WHERE_CLAUSE_FORMAT, WHERE_AND_CONNECTOR_FORMAT,
WHERE_EQUAL_OPERATION_FORMAT, ORDER_BY_CLAUSE_FORMAT, ORDER_BY_ASC_FORMAT, ORDER_BY_DESC_FORMAT,
LIMIT_FORMAT,VALUE_STRING_FORM... |
from Solution import Solution
class P014(Solution):
mem_cache = {1: 0}
def collatz(self, number):
if number in self.mem_cache:
return self.mem_cache[number]
if number % 2 == 0:
data = self.collatz((number // 2))
self.mem_cache[number] = data + 1
... |
# Largest product in a grid: https://projecteuler.net/problem=11
# Problem 11
# In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
#
# 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
# 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
# 81 49 31 73 55 79 14 29 9... |
import functools
def cache(f):
"""
Keep a cache of previous function calls
"""
@functools.wraps(f)
def wrapper_cache(*args, **kwargs):
cache_key = args + tuple(kwargs.items())
if cache_key not in wrapper_cache.cache:
wrapper_cache.cache[cache_key] = f(*args, **kwargs)
... |
#!/usr/bin/python
"""
Output Fisher matrix for experiments to a text file.
"""
import numpy as np
import pylab as P
from rfwrapper import rf
cosmo = rf.experiments.cosmo
fmroot = "fishermat"
names = ['EuclidRef_baoonly', ]
# Loop through experiments and output them
_k = range(len(names))
for k in _k:
root = "out... |
import pynq
import pynq.lib
from .constants import *
#from pynq.lib.logictools import TraceAnalyzer
__author__ = "Johannes Vanoverschelde"
__copyright__ = "Copyright 2017, Dekimo"
__email__ = "johannes.vanoverschelde@dekimo.com"
class BaseUZOverlay(pynq.Overlay):
""" The Aquantis overlay for the Microzed
... |
#!/usr/bin/python
import json
import requests
import jsonpickle
import argparse
from urllib import quote
import sys
import glob
import imghdr
def updateObjectImage(url,dimName,imgDir,objt):
objtName = objt['theName']
objtGlob = glob.glob(imgDir + '/' + objtName + '.*')
if len(objtGlob) == 0:
return
elif ... |
from django.urls import path
from serempre_todo.task.views import (
task_create_view,
task_time_worked_update_view,
task_update_view,
)
app_name = "task"
urlpatterns = [
path("create/", view=task_create_view, name="task-create"),
path("<str:pk>/", view=task_update_view, name="task-update"),
pa... |
import azure.functions as func
import six
from time import time
from chameleon import PageTemplate
BIGTABLE_ZPT = """\
<table xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<tr tal:repeat="row python: options['table']">
<td tal:repeat="c python: row.values()">
<span tal:define="d... |
# -*- coding: utf-8 -*-
import click
import os
import re
import sys
import json
import requests
import platform
from tqdm import tqdm
__version__ = "1.0.3"
def load_path():
with open(txt_path,'r') as f:
return f.readline()
print("\n当前操作系统:"+platform.system())
if platform.system()=='Windows':
i... |
# 27. Remove Element
# https://leetcode.com/problems/remove-element/
# Easy
# Time Complexity : O(N)
# Space Complexity: O(1)
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
r = len(nums) - 1
l = 0
while l <= r:
if nums[l] == val:
num... |
from styx_msgs.msg import TrafficLight
import tensorflow as tf
import numpy as np
import rospy
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
import os.path
TRAFFIC_LIGHT_COLORS = ["GREEN", "RED", "YELLOW"]
CONFIDENT_THRESHOLD = 0.5
class TLClassifier(object):
def __init__(self):
... |
# Generated by Django 2.1.2 on 2018-11-09 01:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import copy
import time
import uuid
import optuna
from tqdm import tqdm
from hana_automl.optimizers.base_optimizer import BaseOptimizer
from hana_automl.pipeline.modelres import ModelBoard
from hana_automl.preprocess.settings import PreprocessorSettings
class OptunaOptimizer(BaseOptimizer):
"""Optuna hyperpara... |
import logging
from collections import defaultdict, OrderedDict
from datetime import datetime, timedelta
from playback.studio.equalizer import Equalizer
from playback.studio.recordings_lookup import find_matching_recording_ids, RecordingLookupProperties
_logger = logging.getLogger(__name__)
class PlaybackStudio(obje... |
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
try:
from .common import *
except ImportError:
from common import *
class Prefs(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(
self, 'Preferences', parent, 0,
(Gtk.STOCK_CANCEL, Gtk.ResponseTy... |
"""Test module to check if optimizer classes are initialized correcty by the main file.
"""
import hjson
import pytest
from c3.optimizers.optimalcontrol import OptimalControl
from c3.optimizers.modellearning import ModelLearning
from c3.experiment import Experiment
from c3.main import run_cfg
@pytest.mark.integrati... |
# Ooops
"""
class shabeeb: #class creating
def IET(self,dep):
print("studying in dep of\t"+dep)
a=shabeeb() #object creating
dep="INFROMATION TECHNOLOGY"
a.IET(dep)
"""
"""
class shabeeb():
def bio(self,n):
self.name=n
def biod(self):
print(self.name)
x=shabeeb()
name="how are ... |
#!/usr/bin/python3
from math import log2
'''
Determine minimum number of operations to return n.
For n < 0 return 0
'''
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def PowerOf2Test(n):
'''
Tests if number is a power of 2.
'''
retu... |
import ast
import time
import dill
from itertools import chain
import tensorflow as tf
import numpy as np
from layers import Input, Layer, layer_from_dicts
from utils import print_headers, print_current, print_metrics, val_split
import functions
def save_model(model, filepath):
tensors = []
layers = dict()
... |
# encoding: utf-8
from ckan.plugins import toolkit
from nose.tools import assert_in, assert_not_in
import ckan.model as model
try:
from ckan.tests import factories, helpers
except ImportError:
from ckan.new_tests import factories, helpers
from ckanext.pages import db
class TestPages(helpers.FunctionalTestBa... |
# -*- coding: utf-8 -*-
import datetime
from roboarm import DeviceNotFound, Arm as RoboArm
from usb import USBError
import config
from constants import DEVICE_STATUS_KEY, STATUS_ON, STATUS_OFF, FETCH_TIMEOUT
from utils.kvs import Kvs
class DeviceFetchTimeout(Exception):
"""
timeout error
"""
pass
... |
import unittest
import importlib.util
def module_from_file(module_name, file_path):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
target_module = module_from_file("page_numbe... |
import re
from django.conf import settings
from rest_framework import serializers
from apps.users.models import User
class SimpleUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'name', 'email']
class UserSerializer(serializers.ModelSerializer):
class... |
import tensorflow as tf
from agents.network.base_network import BaseNetwork
import numpy as np
from scipy.stats import norm
from utils.boundedvar_gaussian_mixture import BoundedVarGaussianMixture
class QTOPTNetwork(BaseNetwork):
def __init__(self, sess, input_norm, config):
super(QTOPTNetwork, self).__in... |
import numpy as np
import torch
import torch.nn as nn
from torch.nn.modules import Conv1d, Linear, Dropout, Conv2d
import torch.nn.functional as F
from collections import OrderedDict
from torch.autograd import Variable
class Filtration(nn.Module):
def __init__(self, proj_vector_length, n_sino_angles, kernel_size... |
from setuptools import setup
setup(name='butterfingers',
version='0.1',
description='Package to generate highly realistic typos (fuzz-testing)',
author='',
author_email='',
license='',
packages=['butterfingers'],
zip_safe=False)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
"""
(c) 2014 Ronan Delacroix
Doremi API Requests definition
:author: Ronan Delacroix
"""
import sys
from tbx.bytes import *
from .message import MessageListWrapper, MessageDefinition as M, ResponseElement as E, ResponseBatch as Batch
RESPON... |
#! python 3
#! quickWeather.py - Prints the weather for a location from the command line.
import json, requests, sys
# Compute location from command line arguments
if len(sys.argv) < 2
print('Usage: quickWeather.py location')
sys.exit()
location = ''.join(sys.argv[1:])
#TODO: Download the JSON data from Op... |
from os.path import join
import conda.config as config
from conda.cli.common import name_prefix, error_and_exit
def read_message(fn):
res = []
for envs_dir in config.envs_dirs:
path = join(envs_dir, '.conda-help', fn)
try:
with open(path) as fi:
s = fi.read().deco... |
# | Copyright 2017 Karlsruhe Institute of Technology
# |
# | 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 ... |
from django.db import migrations
from api.metadata.constants import OrganisationType
ORGANISATIONS = [
{
"name": "The Charity Commission",
"organisation_type": OrganisationType.NON_MINISTERIAL_DEPARTMENTS
},
{
"name": "Competition and Markets Authority",
"organisation_type... |
# Вам необходимо реализовать функцию duplicate, которая должна принимать в качестве аргумента список и
# удваивать этот список "по месту" (вам нужно будет изменять исходный объект списка.
# Помним: список передаётся по ссылке!).
# Удваивание здесь означает, что после применения к нему функции список должен иметь копию ... |
import pytest
from botocore.exceptions import ClientError
from mock import patch, Mock, call
from common import constants # noqa: F401
from common.clients import boto
from common.clients.boto import ClientType
from common.secret_manager import VcenterSecret
__STAGE = "test-stage"
__ORD_ID = "c64c6ded-d07d-4e1b-8963-... |
########################################################################
#
# File Name: TreeWalker.py
#
# Documentation: http://docs.4suite.com/4DOM/TreeWalker.py.html
#
"""
Tree Walker from DOM Level 2. Allows multi-directional iteration over nodes.
WWW: http://4suite.com/4DOM e-mail: suppor... |
#!/usr/bin/env python3
#
# Based on:
# http://askubuntu.com/questions/508236/how-can-i-run-code-whenever-a-usb-device-is-unplugged-without-requiring-root/
# http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-device-inserted-events-in-linux-in-python
# https://pyudev.readthedocs.org/en/latest/guide.html#... |
from rest_framework import serializers
from team.models import Team, Contest, TeamContest, Reward
class TeamSerializer(serializers.ModelSerializer):
#users = UserSerializer(many=True, read_only=True)
class Meta:
model = Team
fields = ['id', 'name', 'disable'] # 缺user
read_only_fields = ... |
import os
import audlib
from audlib.data.dataset import LongFile
HOME = os.path.dirname(audlib.__file__)
def test_LongFile():
data = LongFile(
os.path.join(HOME, 'samples/welcome16k.wav'), 1, 1)
assert data[0].signal.shape[0] == data[1].signal.shape[0]
if __name__ == '__main__':
test_LongFile(... |
from setuptools import setup
setup(
name="electrum-dmd-server",
version="1.0",
scripts=['run_electrum_dmd_server.py','electrum-dmd-server'],
install_requires=['plyvel','jsonrpclib', 'irc >= 11, <=14.0'],
package_dir={
'electrumdmdserver':'src'
},
py_modules=[
'electrumdm... |
from util import case
from gcontext.base import method, pre_hook, post_hook
from gcontext import get_context
class A:
x = 3
@method
def run(self):
return B().walk() + 1
class B:
@method
def walk(self):
return get_context()['x']
class C(A):
def incr(self, *args, ret=None):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Copyright (c) 2015 James Gaston
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condit... |
#!/usr/bin/env python
a = 0
b = 1
c = 2
def my_function():
a = 3
print("a = %d" % (a) )
def my_b():
global b
b = 11
print("b = %d" % (b) )
def my_c():
print("c = %d" % (c) )
c = 22
print("c = %d" % (c) )
my_function()
print("a = %d" % (a) )
my_b()
print("b = %d" % (b) )
my_c()
pr... |
# Generated by Django 3.2.3 on 2022-01-12 11:56
import datetime
from django.db import migrations, models
import base.storage
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Photo",
fields=[
... |
# app.py - a minimal flask api using flask_restful
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS
from docker.errors import APIError
import docker
import logging
app = Flask(__name__)
api = Api(app)
CORS(app, resources={r"/*": {"origins": "*"}})
parser =... |
from guizero import App, ButtonGroup
def selected():
print(choice.value)
app = App()
choice = ButtonGroup(app, options=["cheese", "ham", "salad"], selected=1, command=selected)
app.display() |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas
import plotly.graph_objs as go
def load_df_as_json():
idx = pandas.IndexSlice
rs_raw = pandas.read_hdf('./data/runscanner_illumina_cache.hd5')
ins... |
# -*- coding: utf-8 -*-
from qcloudsdkcore.request import Request
class UnbindAlarmRuleReceiversRequest(Request):
def __init__(self):
super(UnbindAlarmRuleReceiversRequest, self).__init__(
'monitor', 'qcloudcliV1', 'UnbindAlarmRuleReceivers', 'monitor.api.qcloud.com')
def get_alarmRuleId... |
from .socp import Model as SOCModel
from .lp import LinConstr, Bounds, CvxConstr, ConeConstr
from .lp import Vars, VarSub, Affine, Convex
from .lp import DecRule, DecRuleSub
from .lp import RoAffine, RoConstr
from .lp import Solution
from .subroutines import *
import numpy as np
from scipy.sparse import csr_matrix
from... |
import random
import pytest
import numpy as np
import feature_utils
class TestFeatureCompiler:
@classmethod
def setup_class(cls):
pass
@classmethod
def teardown_class(cls):
pass
def setup_method(self, method):
pass
def teardown_method(self, method):
pass
... |
from scoap3.modules.search.utils import Scoap3RecordsSearch
def test_escape_query_string():
data = {
'query': {
'query_string': {
'query': '10.1016/j.nuclphysb.2018.07.004'
}
}
}
Scoap3RecordsSearch.escape_query_string(data)
assert data['query'][... |
#!/usr/bin/env python
import numpy as np
import math
# Checks if a matrix is a valid rotation matrix.
def isRotationMatrix(R) :
Rt = np.transpose(R)
shouldBeIdentity = np.dot(Rt, R)
I = np.identity(3, dtype = R.dtype)
n = np.linalg.norm(I - shouldBeIdentity)
return n < 1e-6
def rotationMatrixT... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2017 bily Huazhong University of Science and Technology
#
# Distributed under terms of the MIT license.
"""
Inference Utilities
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import co... |
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... |
r"""
===========================================
Seismic Ambient Noise (:mod:`seislib.an`)
===========================================
As shown in several theoretical studies, the cross correlation of
seismic ambient noise can be related to the surface-wave Green's
function between the two points of observation [1]_... |
import os
import numpy as np
from astropy.io import ascii
from scipy.optimize import curve_fit
from astropy.io import fits as pyfits
from astropy import wcs
############################################################################################################
#
# VIRCAM TRANSFORMATION TO RA/DEC
#
############... |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.jwt.taskrouter.capabilities import WorkspaceCapabilityToken
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
workspace_sid = "WSXXXXXXXXXX... |
from django.contrib import admin
from .models import Project, ProjectSubtitle, BulletPoint
# Register your models here.
class ProjectAdmin(admin.ModelAdmin):
pass
admin.site.register(Project)
admin.site.register(ProjectSubtitle)
admin.site.register(BulletPoint) |
"""
Hardcoded data for the blockchain (use for genesis validation)
"""
from .block import Block
__all__ = ["GENESIS_BLOCK", "developer_address"]
developer_address = "A2tddJpzOWIp1Dv81mqn4WJ/UQAjmFLPINRnkt67zMMR"
GENESIS_BLOCK = Block(index=0, previous_hash="0", forger=developer_address, timestamp=0)
|
# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
#
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
#
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7 = 9,
#... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import sys
from subprocess import call
APP_HOME = os.environ.get('APP_HOME', '/app')
APP_ENV = os.path.join(APP_HOME, '.env')
APP_ETC = os.path.join(APP_HOME, 'etc')
APP_ROOT = os.path.join(APP_HOME, 'root')
class CommandManager(object):
def __init__(self, ... |
inputs = [int(i) for i in input().split()]
def candies(vladik_a, valera_a):
amount = 0
toggle = True
while True:
amount += 1
if vladik_a < 0:
return "Vladik"
if valera_a < 0:
return "Valera"
if toggle:
vladik_a -= amount
toggl... |
#!/usr/bin/env python
class Clock:
def __init__(self, decimal_hours, decimal_minutes):
self.minutes = decimal_hours*60 + decimal_minutes
def _to_dec(self):
decimal_hours = (self.minutes//60) % 24
decimal_minutes = (self.minutes - (decimal_hours*60)) % 60
return (decimal_hours,... |
import matplotlib.pyplot as plt
import wbml.out as out
from wbml.plot import tweak
from stheno import B, Measure, GP
B.epsilon = 1e-10 # Very slightly regularise.
# Define points to predict at.
x = B.linspace(0, 10, 200)
x_obs = B.linspace(0, 10, 10)
with Measure() as prior:
# Construct a linear model.
slo... |
import argparse
import pickle
import ujson as json
from multiprocessing import Pool
from os.path import join
from typing import List, Dict
import numpy as np
from tqdm import tqdm
from docqa.config import CORPUS_DIR
from docqa.configurable import Configurable
from docqa.data_processing.multi_paragraph_qa import Multi... |
import requests
from yaml_config import config
import global_vars
from datetime import datetime
from sms_sender import send_sms
import logging
import colorlog
logger = colorlog.getLogger(__name__)
logger.addHandler(global_vars.file_handler)
logger.addHandler(global_vars.handler)
logger.setLevel(global_vars.log_level)
... |
from flask import jsonify, make_response, request
from flask_restful import Resource
from ..models.sale_model import *
class Sales(Resource):
def __init__(self):
self.sale = Sale()
def post(self):
data = request.get_json()
user_id = data['user_id']
product_id = data['product_i... |
import json
import os
import random
import re
import string
from json import JSONDecodeError
from typing import Optional, Tuple, Iterable, Callable
import dns
import dns.name
import dns.query
import pytest
import requests
from requests.exceptions import SSLError
def random_mixed_case_string(n):
k = random.randin... |
from app import create_app
app = create_app()
if __name__=='__main__':
app.run()
|
# -*- coding: utf-8 -*
import face_model_prnet_mask
import argparse
import cv2
import sys
import math
import numpy as np
import csv
import os
from deploy.FUNCTION import *
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.a... |
import numpy as np
import chipwhisperer as cw
from capture import scope, target
# Helper Functions
########################################
# ANCHOR: random_str_fn
import string
import random
def random_string(length):
# Define the alphabet of the random string
# Here we take the lowercase latin alphabet in a... |
from musicscore.musicxml.attributes.attribute_abstract import AttributeAbstract, String
from musicscore.musicxml.attributes.color import Color
from musicscore.musicxml.attributes.font import Font
from musicscore.musicxml.types.complextypes.complextype import ComplexType
class Smulf(AttributeAbstract):
def __init_... |
# This is (slightly adapted) from PyTorch:
# TODO: ADD COPYRIGHT AND LINK
import asyncio
import torch
from torch._six import queue, container_abcs, string_classes
from torch.utils.data._utils import MP_STATUS_CHECK_INTERVAL
from torch._utils import ExceptionWrapper
async def _single_task(in_queue, out_queue, device_... |
# Copyright 2021 Rosalind Franklin Institute
#
# 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 ... |
from django.contrib import admin
from .models import Ask
# Register your models here.
admin.site.register(Ask)
|
import os
path = str(os.path.dirname(os.path.abspath(__file__)))
path = path + "\errorlog.txt"
f = open(path, 'w')
print
try:
import numpy as np
message = "Numpy has been initiated successfully!\n"
f.write(message)
print message
except Exception(e):
message = str(e)+"\n"
f.write(message)
print message
try:
... |
# encoding: utf-8
"""
Matching tool for a :class:`LineView` instance.
"""
# force new style imports
from __future__ import absolute_import
# scipy
import numpy as np
# internal
from madgui.core import wx
from madgui.util import unit
# exported symbols
__all__ = [
'CompareTool',
]
class CompareTool(object):
... |
import argparse
import datetime
import re
from typing import Optional, Union
import discord
from discord.ext import commands
from ..functions import ExpiringCache
from ..util.vars import LinksAndVars, ShinobiMatch
time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {"h": 3600, "s": 1, "m": 60, "d": 8640... |
from flask_table import Table, Col
# used for front, back, total
class PlayerScoreTable(Table):
classes = ['scoring_table', 'inline_table']
name = Col('Name', td_html_attrs={'class': 'table__cell'}, th_html_attrs={'class': 'table__cell'}) # player name
gross_score = Col('Gross Score', td_html_attrs={'cla... |
from dataclasses import dataclass
from typing import Optional
from vortexasdk.api.asset_tank import AssetTank
from vortexasdk.api.serdes import FromDictMixin
from vortexasdk.api.shared_types import ISODate
from vortexasdk.api.id import ID
@dataclass(frozen=True)
class OnshoreInventory(FromDictMixin):
"""
La... |
# noinspection PyInterpreter
def register():
from datetime import datetime
from getpass import getpass
import hashlib
import random
import json
import os
print()
print("Register")
print()
file = "settings.json"
failed = 'You have failed the login process, please try again.'... |
# Copyright 2013 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 co... |
from os import makedirs, path
from shutil import rmtree
from diot import Diot
from bioprocs.utils import cmdargs, runcmd, mem2
tmpdir = path.join ({{ args.tmpdir | quote}}, "{{proc.id}}.{{i.infiles[0] | fn2}}.{{job.index}}")
if not path.exists (tmpdir): makedirs (tmpdir)
params = {{args.params}}
try:
{% case args... |
# Copyright (c) 2020 Open-E, 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
#
# Unless re... |
#!/usr/bin/env python
import json
import os
import requests
import shlex
import socket
import sys
from api_common import get_services
if __name__ == "__main__":
assert len(sys.argv) >= 1, "Usage: <scriptname> <cluster-name>"
clustername = sys.argv[1]
get_services(clustername)
|
# Copyright 2018,2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group 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
#... |
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT
"""
Parse recipes.
A package is a final user-installable software archive. A recipe is a Bash file
which contains the instructions necessary to build one or more related
packages (in the latter case, it is called a split package).
"""
from da... |
#! /usr/bin/env python3
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from bs4 import BeautifulSoup # type: ignore
from bs4.element import Tag # type: ignore
from dataclasses_json import DataClassJsonMixin
from ff14angler.constants.data_corrections import angler_fish_lodesto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.