code stringlengths 1 199k |
|---|
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"
from androlyze.error.WrapperException import WrapperException
def _create_delete_error_msg(content, destination):
return "Could not delete %s from %s" % (content, destination)
def _create_store_error_msg(content, destination):
... |
import os, sys
import commands
import optparse
import shutil
INSTALL_DIR = ""
BASE_DIR = os.path.dirname(__file__)
SIP_FILE = "poppler-qt4.sip"
BUILD_DIR = "build"
SBF_FILE = "QtPoppler.sbf"
def _cleanup_path(path):
"""
Cleans the path:
- Removes traling / or \
"""
path = path.rstrip('/')
pat... |
'''
Examples of advanced Python features:
- metaclass
- descriptor
- generator/forloop
'''
from __future__ import print_function
import sys
if sys.version_info > (3, ): # Python 3
exec('''
def exec_in(code, glob, loc=None):
if isinstance(code, str):
code = compile(code, '<string>', 'exec', dont_i... |
"""
Prefill an Array
(6 kyu)
https://www.codewars.com/kata/54129112fb7c188740000162/train/python
Create the function prefill that returns an array of n elements that all have
the same value v. See if you can do this without using a loop.
You have to validate input:
- v can be anything (primitive or otherwise)
- if v is... |
from .mdl_user import *
from .mdl_club import *
from .mdl_event import *
from .mdl_receipt import *
from .mdl_budget import *
from .mdl_division import *
from .mdl_eventsignin import *
from .mdl_joinrequest import * |
__author__ = 'deevarvar'
import string
import random
import os
def string_generator(size=6, chars=string.ascii_letters+string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def touchFile(fname, time=None):
with open(fname, 'a'):
os.utime(fname,time) |
import typing
from flask import json
FlaskHeaders = typing.Union[typing.List[typing.Tuple[str, str]], typing.Dict[str, str]]
FlaskResponse = typing.Tuple[str, int, FlaskHeaders]
def success(data, status=200) -> FlaskResponse:
return json.dumps(data, indent=2), status, [("Content-Type", "application/json")]
def fail... |
import sys
import random
import time
import pauschpharos as PF
import lumiversepython as L
SEQ_LIM = 200
def memoize(ignore = None):
if(ignore is None):
ignore = set()
def inner(func):
cache = dict()
def wrapper(*args):
memo = tuple(filter(lambda x: x,
map(lambda (i, e):
... |
from .circleclient import __version__ |
"""Test the wallet keypool and interaction with wallet encryption/locking."""
from test_framework.test_framework import DoriancoinTestFramework
from test_framework.util import *
class KeyPoolTest(DoriancoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
def run_test(self):
nodes = ... |
"""Unit tests for SCardConnect/SCardStatus/SCardDisconnect
This test case can be executed individually, or with all other test cases
thru testsuite_scard.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
This file is part of pyscard.
... |
from argparse import ArgumentParser
from collections import defaultdict
import sys
import os
from sonLib.bioio import cigarRead, cigarWrite, getTempFile, system
def getSequenceRanges(fa):
"""Get dict of (untrimmed header) -> [(start, non-inclusive end)] mappings
from a trimmed fasta."""
ret = defaultdict(li... |
import pickle
from pueue.client.socket import connect_socket, receive_data, process_response
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which is r... |
__author__ = 'zhonghong' |
"""
Title : Java program file
Author : JG
Date : dec 2016
Objet : script to create Propertie File Program
in : get infos from yml
out : print infos in properties file
"""
import sys,os
import yaml
import util as u
from random import randint
def create_properties_file(yml,armaDir):
progDir = u.d... |
import os
os.environ['KIVY_GL_BACKEND'] = 'gl' #need this to fix a kivy segfault that occurs with python3 for some reason
from kivy.app import App
class TestApp(App):
pass
if __name__ == '__main__':
TestApp().run() |
import os.path, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import json
import falcon
import urllib
import uuid
import settings
import requests
from geopy.geocoders import Nominatim
import geopy.distance
from geopy.distance import vincenty
import datetime
radius = []
radius... |
def main(**kwargs):
print('foo foo') |
"""Test mempool persistence.
By default, bitcoind will dump mempool on shutdown and
then reload it on startup. This can be overridden with
the -persistmempool=0 command line option.
Test is as follows:
- start node0, node1 and node2. node1 has -persistmempool=0
- create 5 transactions on node2 to its own address. N... |
import argparse
from collections import defaultdict, Counter, deque
import random
import json
import time
from tqdm import tqdm
import wikipedia
class MarkovModel(object):
def __init__(self):
self.states = defaultdict(lambda: Counter())
self.totals = Counter()
def add_sample(self, state, followu... |
from sanic.exceptions import *
class GatcoException(SanicException):
pass |
SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3,
'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25,
'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405,
'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23}
def sexy_name(name):
name_score = s... |
l = list(range(1, 20 + 1, 2)) # this is wasteful in this program
for i in l:
print(i) |
import json
import os
import unittest
import requests
AGNOS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)))
MANIFEST = os.path.join(AGNOS_DIR, "agnos.json")
class TestAgnosUpdater(unittest.TestCase):
def test_manifest(self):
with open(MANIFEST) as f:
m = json.load(f)
for img in m:
r... |
import argparse
import smtplib
import mimetypes
import os.path as path
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def parseOptions():
parser = argparse.ArgumentParser(description='Send e-books to my Kindle Paperwhite.')
parser.add_argument('file', ty... |
import deep_architect.searchers.common as se
import numpy as np
class SuccessiveNarrowing(se.Searcher):
def __init__(self, search_space_fn, num_initial_samples, reduction_factor,
reset_default_scope_upon_sample):
se.Searcher.__init__(self, search_space_fn,
reset... |
'''
Dummy Socks5 server for testing.
'''
from __future__ import print_function, division, unicode_literals
import socket, threading, Queue
import traceback, sys
class Command:
CONNECT = 0x01
class AddressType:
IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
def recvall(s, n):
'''Receive n bytes from a soc... |
"""Implement directed graph abstract data type."""
from __future__ import print_function
from .stack import Stack
from .queue import Queue
class Graph(object):
"""Implement a directed graph."""
def __init__(self):
"""Initialize a graph with no nodes or edges."""
self._nodes = {}
def add_node... |
import os
import shutil
import unittest
from django.utils import six
from django_node import node, npm
from django_node.node_server import NodeServer
from django_node.server import server
from django_node.base_service import BaseService
from django_node.exceptions import (
OutdatedDependency, MalformedVersionInput,... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
WGS = ['G69145', 'G71602', 'G71608', 'G76270']
metric_dict = {}
for wg in WGS:
fname = "/seq/picard_aggregation/" + wg + "/NA12878/current/NA12878.duplicate_metrics"
lines=list(csv.reader(open(fname)))
nMetrics = lines[6][0].split('\t')
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questions', '0013_auto_20160210_0400'),
]
operations = [
migrations.AlterField(
model_name='category',
name='order',
... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
class BaseReader(object):
def read(self):
raise NotImplementedError()
class ImageReader(BaseReader):
def __init__(self):
self.width = None
self.height = None
def get_image_size(self):
return self.width, self.heigh... |
from django.http import HttpResponse
from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException
from reminder.models import Reminder
import sys
import os
import django
sys.path.append("/home/foxtrot/Dropbox/tunza_v2/")
os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.local"
django.se... |
import requests
from gevent import monkey
def stub(*args, **kwargs): # pylint: disable=unused-argument
pass
monkey.patch_all = stub
import grequests
import os
import json
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
meraki_api_token = os.getenv("MERAKI_API_TOKEN")
meraki_org = os.... |
"""
Created on 19 Nov 2020
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Two-Channel I2C-Bus Switch With Interrupt Logic and Reset
https://www.ti.com/product/PCA9543A
"""
from scs_host.bus.i2c import I2C
class PCA9543A(object):
"""
classdocs
"""
___I2C_ADDR = 0x70
# --------------------... |
"""
A 2d grid map of m rows and n columns is initially filled with water.
We may perform an addLand operation which turns the water at position
(row, col) into a land. Given a list of positions to operate,
count the number of islands after each addLand operation.
An island is surrounded by water and is formed by connec... |
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS ... |
import argparse
import h5py
import numpy as np
import os
import sys
def main():
""" Create train/test indices for one repeat of a 10-fold sampled leave-one-study-out
experiment on the RFS data.
The indices will be stored under
<data_dir>/outputs/U133A_combat_RFS/sampled_loso/repeat<repeat idx>
w... |
import collections
import unittest
from kobold import assertions
class TestAssertEqual(unittest.TestCase):
def test_empty_hashes(self):
assertions.assert_equal({}, {})
def test_distinct_keys(self):
self.assertRaises(
AssertionError,
assertions.assert_equal,
... |
from msrest.pipeline import ClientRawResponse
import uuid
from .. import models
class ParameterGroupingOperations(object):
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = c... |
"""Get app info with AppKit via objc bridge."""
from __future__ import print_function, unicode_literals, absolute_import
import time
import unicodedata
from AppKit import NSWorkspace
def decode(s):
"""Decode bytestring to Unicode."""
if isinstance(s, str):
s = unicode(s, 'utf-8')
elif not isinstance... |
"""Contains utility methods used by and with the pyebnf package."""
import math
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []
f... |
import glob
import sys
sys.path.append('..')
from lib.mppaper import *
import lib.mpsetup as mpsetup
import lib.immune as immune
files = sorted((immune.parse_value(f, 'epsilon'), f) for f in glob.glob("data/*.npz"))
import run
sigma = run.sigma
epsilons = []
similarities = []
similaritiesQ = []
similaritiesPtilde = []
... |
import random
import string
def random_string(n):
result = ''
for _ in range(10):
result += random.SystemRandom().choice(
string.ascii_uppercase + string.digits)
return result |
from os import getcwd, listdir
from os.path import abspath, dirname, isdir, join as path_join
from shutil import rmtree
from sys import exc_info
from tempfile import mkdtemp
from unittest import TestCase
from mock import patch, MagicMock
from robot.libraries.BuiltIn import BuiltIn
CURDIR = abspath(dirname(__file__))
cl... |
import tkinter.filedialog as tkFileDialog
import numpy as np
from numpy import sin,cos
import os
def InnerOrientation(mat1,mat2):
"""
mat1 为像素坐标,4*2,mat2为理论坐标4*2,
h0,h1,h2,k0,k1,k2,这六个参数由下列矩阵定义:
[x]=[h0]+[h1 h2] [i]
[y]=[k0]+[k1 k2] [j]
返回6个定向参数的齐次矩阵,x方向单位权方差,y方向单位权方差
[h1 h2 h0]
[k1 k2 k... |
"""Unit tests for mapi/endpoints/tmdb.py."""
import pytest
from mapi.endpoints import tmdb_find, tmdb_movies, tmdb_search_movies
from mapi.exceptions import MapiNotFoundException, MapiProviderException
from tests import JUNK_TEXT
GOONIES_IMDB_ID = "tt0089218"
GOONIES_TMDB_ID = 9340
JUNK_IMDB_ID = "tt1234567890"
@pytest... |
"""Provide infrastructure to allow exploration of variations within populations.
Uses the gemini framework (https://github.com/arq5x/gemini) to build SQLite
database of variations for query and evaluation.
"""
import collections
import csv
from distutils.version import LooseVersion
import os
import subprocess
import to... |
from Operators.Mutation.Mutator import Mutator
from Operators.Mutation.DisplacementMutator import DisplacementMutator
from Operators.Mutation.InversionMutator import InversionMutator |
class Solution(object):
def dfs(self,rooms):
# get all gate position
queue=[(i,j,0) for i,rows in enumerate(rooms) for j,v in enumerate(rows) if not v]
while queue:
i,j,depth=queue.pop()
# has a min path to gate and update
if depth<rooms[i][j]:
... |
from .base import BASE_DIR, INSTALLED_APPS, MIDDLEWARE_CLASSES, REST_FRAMEWORK
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1']
SECRET_KEY = 'secret'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'holonet',
'USER': 'holonet',
'PASSWORD': '',
... |
import requests
import copy
def fb_get_group_members(fb_page_id, access_token):
url = 'https://graph.facebook.com/v2.8/%s/members?limit=1000&access_token=%s' % (fb_page_id, access_token)
fb_group_members = {'status':'OK', 'data':{'members':[], 'users_count':0}}
while True:
response = requests.get(ur... |
"""
frest - flask restful api frame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This project is the frame of the restful api server created with flask.
:copyright: (C) 2017 h4wldev@gmail.com
:license: MIT, see LICENSE for more details.
"""
import os
from flask_script import Server, Manager
from flask_migrate im... |
import sys
class abstract:
params = {}
windowId = None
terminated = False
def initParams(self):
return self
def __init__(self):
self.initParams().init()
return
def init(self):
return
def mouse(self, button, state, x, y):
return
def mouseMotion(self... |
import event
import nxt.locator
import nxt.motor as motor
brick = nxt.locator.find_one_brick()
height_motor = motor.Motor(brick, motor.PORT_A)
height_motor.turn(127, 5000, brake=False) |
from GestureAgentsTUIO.Tuio import TuioAgentGenerator
import GestureAgentsPygame.Screen as Screen
from pygame.locals import *
class MouseAsTuioAgentGenerator(object):
def __init__(self):
self.pressed = False
self.myagent = None
self.sid = -1
self.screensize = Screen.size
def even... |
"""
A Machine learning algorithm for K mean clustering.
Date: 24th March, 2015 pm
"""
__author__ = "Anthony Wanjohi"
__version__ = "1.0.0"
import random, fractions
def euclidean_distance(point, centroid):
'''Returns the euclidean distance between two points'''
assert type(point) is tuple
assert type(centroid) is tup... |
import subprocess
import os
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
subprocess.check_call(args)
return True
... |
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from orcid_api_v3.models... |
from django.contrib import admin
from Players.models import Player
@admin.register(Player)
class PlayerAdmin(admin.ModelAdmin):
view_on_site = True
list_display = ('pk', 'first_name', 'last_name', 'number', 'team', 'position', 'age', 'height', 'weight')
list_filter = ['team', 'position']
search_fields =... |
"""Th tests for the Rfxtrx component."""
import unittest
import time
from homeassistant.bootstrap import _setup_component
from homeassistant.components import rfxtrx as rfxtrx
from tests.common import get_test_home_assistant
class TestRFXTRX(unittest.TestCase):
"""Test the Rfxtrx component."""
def setUp(self):
... |
import sys
import os.path
import subprocess
PY3 = sys.version >= '3'
from setuptools import setup, find_packages
version_py = os.path.join(os.path.dirname(__file__), 'dame', 'version.py')
try:
version_git = subprocess.check_output(
["git", "describe", "--always"]).rstrip()
# Convert bytes to str for Pyt... |
import socket, traceback
host=''
port=8080
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
print "Waiting for connections..."
s.listen(1)
while True:
try:
clientsock, clientaddr=s.accept()
except KeyboardInterrupt:
... |
'''
Auxiliary code providing vector-valued scoring functions
for convenient use in the parameter-free Ladder Mechanism.
Original algorithm by Avrim Blum and Moritz Hardt
Python implementation by Jamie Hall and Moritz Hardt
MIT License
'''
from sklearn.utils import check_consistent_length
from functools import wraps
imp... |
import sys
import os
import glob
import inspect
import pylab as pl
from numpy import *
from scipy import optimize
import pickle
import time
import copy
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]) + "/templates")
if cmd_folder not in sys.path:
sys.path.ins... |
from tailorscad.builder.openscad import build_with_openscad
from tailorscad.builder.coffeescad import build_with_coffeescad
from tailorscad.constants import OPENSCAD
from tailorscad.constants import COFFEESCAD
def build_from_state(state):
if state.scad_type is OPENSCAD:
build_with_openscad(state)
if sta... |
import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_dir"... |
import sys
text = sys.stdin.read()
print 'Text:',text
words = text.split()
print 'Words:',words
wordcount = len(words)
print 'Wordcount:',wordcount |
import socket
import sys
HOST, PORT = "24.21.106.140", 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Connected to ", HOST, ":", PORT, "\n","Awaiting input\n"
data = sys.stdin.readline()
sock.connect((HOST, PORT))
print "Connected to ", HO... |
DATASET_DIR = '/tmp'
BRAIN_DIR = '/tmp'
GENRES = [
'blues', 'classical', 'country', 'disco', 'hiphop',
'jazz', 'metal', 'pop', 'reggae', 'rock'
]
NUM_BEATS = 10
KEEP_FRAMES = 0
TRAIN_TEST_RATIO = [7, 3]
MODE = 'nn'
PCA = False
FEATURES = ['mfcc', 'dwt', 'beat']
MFCC_EXTRA = ['delta', 'ddelta', 'energy']
DWT = [... |
'''
@author: KyleLevien
'''
from ..defaultpackage.package import Package
class _Ghostview(Package):
def __init__(self):
Package.__init__(self) |
import os, sys
module = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, module)
from netkiller.docker import *
extra_hosts = [
'mongo.netkiller.cn:172.17.195.17', 'eos.netkiller.cn:172.17.15.17',
'cfca.netkiller.cn:172.17.15.17'
]
nginx = Services('nginx')
nginx.image('nginx:lates... |
"""
Module for running keyword-driven tests
"""
from __future__ import with_statement
import time
import datetime
import re
from adapterlib.ToolProtocol import *
from adapterlib.ToolProtocolHTTP import *
import adapterlib.keyword as keyword
import adapterlib.keywordproxy as keywordproxy
from adapterlib.logger import Ke... |
HOST = '127.0.0.1'
PORT = 8080
from Tkinter import *
import tkColorChooser
import socket
import thread
import spots
def main():
global hold, fill, draw, look
hold = []
fill = '#000000'
connect()
root = Tk()
root.title('Paint 1.0')
root.resizable(False, False)
upper = LabelFrame(root, tex... |
/*Owner & Copyrights: Vance King Saxbe. A.*/""" Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxb... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from textwrap import dedent
import pytest
import pytablewriter
from ...._common import print_test_result
from ....data import (
Data,
headers,
mix_header_list,
mix_value_matrix,
null_test_data_list,
value_matrix,
value_m... |
"""
demos reading HiST camera parameters from XML file
"""
from histutils.hstxmlparse import xmlparam
from argparse import ArgumentParser
if __name__ == "__main__":
p = ArgumentParser()
p.add_argument("fn", help="xml filename to parse")
p = p.parse_args()
params = xmlparam(p.fn)
print(params) |
from traits.api import HasTraits, Float
class Person(HasTraits):
weight = Float(150.0) |
import struct
import uuid
from enum import IntEnum
from typing import List, Optional, Set
from .sid import SID
class ACEFlag(IntEnum):
""" ACE type-specific control flags. """
OBJECT_INHERIT = 0x01
CONTAINER_INHERIT = 0x02
NO_PROPAGATE_INHERIT = 0x04
INHERIT_ONLY = 0x08
INHERITED = 0x10
SUCC... |
from django import forms
from djwed.wedding.models import *
from djwed.wedding.admin_actions import *
from django.contrib import admin
class RequireOneFormSet(forms.models.BaseInlineFormSet):
"""Require at least one form in the formset to be completed."""
def clean(self):
"""Check that at least one form... |
import calendar
import collections
try:
from collections.abc import Iterable
except:
from collections import Iterable
from time import strptime
from six import string_types
from lxml import etree
from itertools import chain
def remove_namespace(tree):
"""
Strip namespace from parsed XML
"""
for ... |
import time
import random
class Battle:
def __init__(self, user1, user2):
self.user1 = user1
self.user2 = user2
self.turn = user1
self.notTurn = user2
self.accepted = False
self.finished = False
self.auto = False
self.turnCount = 1
def fight(self, ... |
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
import misaka
from groups.models import Group
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts')
created_a... |
import mysql.connector
import time
import datetime
conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal")
cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather")
cursor = conn.cursor()
cursar = cann.cursor()
c... |
""" Start the containers """
import argparse
from lib.docker_compose_tools import set_up
def main():
""" Start the containers """
parser = argparse.ArgumentParser(description="Set up testing environment.")
parser.add_argument("--pg", help="PostgreSQL version")
parser.add_argument("--es", help="Elasticse... |
"""
Shopify Trois
---------------
Shopify API for Python 3
"""
from setuptools import setup
setup(
name='shopify-trois',
version='1.1-dev',
url='http://masom.github.io/shopify-trois',
license='MIT',
author='Martin Samson',
author_email='pyrolian@gmail.com',
maintainer='Martin Samson',
ma... |
"""
RPG: Operation
These are any operations we want to carry out from our YAML files. Operations
are strings that are tied to Python code, to carry out things that arent
possible to easily make YAML tags for directly.
"""
from rpg_log import Log
import rpg_combat
def HandleOperation(game, operation, data):
"""Handle... |
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime
from xlsxwriter.workbook import Workbook
import tablib
from utils.tools import get_product_size
def get_customers(customer_list=None, file_format='csv'):
"""Generate customer data file for download."""
if customer_list is ... |
{'level_mc': {'_txt': {'text': '6'},
'currentLabel': 'up',
'progress_mc': {'currentLabel': '_0'}}} |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
import os
from kivy.lang import Builder
from kivy.properties import NumericProperty, StringProperty
from kivy.uix.anchorlayout import AnchorLayout
from cobiv.modules.core.hud import Hud
Builder.load_file(os.path.abspath(os.path.join(os.path.dirname(__file__), 'progresshud.kv')))
class ProgressHud(Hud, AnchorLayout):
... |
"""Non-application-specific convenience methods for GPkit"""
import numpy as np
def te_exp_minus1(posy, nterm):
"""Taylor expansion of e^{posy} - 1
Arguments
---------
posy : gpkit.Posynomial
Variable or expression to exponentiate
nterm : int
Number of non-constant terms in resulting... |
from django.contrib import admin
from modeltranslation.admin import TabbedTranslationAdmin
from .models import Person, Office, Tag
class PersonAdmin(TabbedTranslationAdmin):
list_display = ('name', 'surname', 'security_level', 'gender')
list_filter = ('security_level', 'tags', 'office', 'name', 'gender')
ac... |
import atexit
from flask import Flask, jsonify, g, request, make_response
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_jwt_extended import JWTManager, set_access_cookies, jwt_required, unset_jwt_cookies
from apscheduler.schedulers.background import Bac... |
from __future__ import absolute_import, division, print_function
from abc import abstractmethod, ABCMeta
from collections import OrderedDict
from ....core.tools.logging import log
from ..component import FittingComponent
class ModelGenerator(FittingComponent):
"""
This class...
"""
__metaclass__ = ABCMe... |
from django.apps import AppConfig
class DonateAppConfig(AppConfig):
name = 'readthedocs.donate'
verbose_name = 'Donate'
def ready(self):
import readthedocs.donate.signals # noqa |
from flask import Flask, Response, request
from twilio.util import TwilioCapability
app = Flask(__name__)
@app.route('/token', methods=['GET'])
def get_capability_token():
"""Respond to incoming requests."""
# Find these values at twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
aut... |
import os.path
import os
import argparse
import pickle
from util import *
from collections import defaultdict
import base64
import logging
import sys
import json
import shelve
from LangProc import docTerms
class DBMIndex:
pass
class BaseIndexer():
def __init__(self):
self.invertedIndex = defaultdict(list)
self.fo... |
import mobula.layers as L
import numpy as np
def test_acc():
X = np.array([[0, 1, 2],
[1, 2, 0],
[0, 1, 2],
[1, 2, 0]])
Y = np.array([1, 0, 2, 1]).reshape((-1, 1))
# top-k
# 1 [False, False, True, True]
# 2 [True, True... |
from distutils.core import setup
import strfrag
setup(
name='Strfrag',
version=strfrag.__version__,
description=('StringFragment type to represent parts of str objects; '
'used to avoid copying strings during processing'),
url="https://github.com/ludios/Strfrag",
author="Ivan Kozik",
author_email="ivan@ludios.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.