code stringlengths 1 199k |
|---|
"""rio-mbtiles package"""
import sys
import warnings
__version__ = "1.6.0"
if sys.version_info < (3, 7):
warnings.warn(
"Support for Python versions < 3.7 will be dropped in rio-mbtiles version 2.0",
FutureWarning,
stacklevel=2,
) |
import smtplib
import email
from email.MIMEText import MIMEText
import logging
import datetime
log = logging.getLogger('pyinger')
loghandler = logging.FileHandler('/home/user/pythonscripts/pyinger/pyinger.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
loghandler.setFormatter(formatter)
log... |
import numpy as np
def model(pDict, lamSqArr_m2):
"""Simple Faraday thin source."""
# Calculate the complex fractional q and u spectra
pArr = pDict["fracPol"] * np.ones_like(lamSqArr_m2)
quArr = pArr * np.exp( 2j * (np.radians(pDict["psi0_deg"]) +
pDict["RM_radm2"] * lam... |
import RPi.GPIO as GPIO
class motorSet:
pinArray = []
def __init__(self, pinArray):
# Pass pin array to class
self.pinArray = pinArray
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Setup each pin in the array
for i in range(4):
... |
from .snippet_list import snippet_list
from .snippet_detail import snippet_detail
from .SnippetList import SnippetList
from .SnippetDetail import SnippetDetail
from .UserList import UserList
from .UserDetail import UserDetail |
from __future__ import absolute_import
import unittest
from injector.dependencies import Dependencies
from injector.exceptions import BadNameException
from injector.exceptions import CircularDependencyException
from injector.exceptions import DuplicateNameException
from injector.exceptions import MissingDependencyExcep... |
from setuptools import setup, find_packages
setup(
name='ppp_spell_checker',
version='0.2.3',
description='A spell checker for the PPP. Use the Aspell API.',
url='https://github.com/ProjetPP',
author='Projet Pensées Profondes',
author_email='ppp2014@listes.ens-lyon.fr',
license='MIT',
cl... |
import math
def workbook(n, p, chapters):
special = 0
pages = 0
for i in range(n):
pages_chapt = math.ceil(chapters[i] / p)
total = chapters[i]
read = 0
for j in range(pages_chapt):
if total > p:
total = total - p
pg_remaining = rea... |
import operator
def readFromFileAsString(fileName):
fileInput = open(fileName,"r");
inputAsAString = "";
for line in fileInput:
inputAsAString = inputAsAString + line;
fileInput.close();
return inputAsAString;
def readFromFileAsList(filename):
fileInput = open(filename,"r");
inputAsA... |
import pandas as pd
def parse(year: int, gender: str, df: pd.DataFrame) -> pd.DataFrame:
df = df.loc[4:, ['Unnamed: 2', 'Unnamed: 3']].dropna()
df.columns=['Name', 'Count']
df['Year'] = year
df['Gender'] = gender
return df |
from setuptools import setup
setup(
name='Flask-Travis',
version='0.0.2',
url='https://github.com/cburmeister/flask-travis',
license='MIT',
author='Corey Burmeister',
author_email='cburmeister@discogs.com',
description='Easily fetch Travis CI environment variables when testing.',
long_de... |
import unittest
import imp
from racconto.settings_manager import SettingsManager
class TestSettingsManager(unittest.TestCase):
def setUp(self):
self.manager = SettingsManager()
def tearDown(self):
del self.manager
def test_initializes_settings(self):
self.assertIsInstance(self.manage... |
from typing import List
from test_framework import generic_test
def find_biggest_n_minus_one_product(A: List[int]) -> int:
# TODO - you fill in here.
return 0
if __name__ == '__main__':
exit(
generic_test.generic_test_main('max_product_all_but_one.py',
'max_pro... |
import subprocess
from flask_script import Manager
from app import app, db
from app.models import User
manager = Manager(app)
@manager.command
def compile_sass():
clean()
subprocess.call(["sass", "--update", "app/static/sass:app/static/css"])
@manager.command
def watch():
subprocess.call(["sass", "--watch",... |
import sys,os
from glob import glob
from pylab import *
import numpy as n
import time
from matplotlib import colorbar as Colorbar
from matplotlib import rcParams,cm
import ipdb as PDB
rcParams['font.size'] = 14
def all_and(arrays):
#input a list or arrays
#output the arrays anded together
if len(arrays)==1:... |
import ado.model
import ado.recipe
class Step(ado.model.Model):
FIELDS = {
"archived_at" : "timestamp",
"created_at" : "timestamp",
"description" : "text",
"recipe_id" : "integer"
}
SEARCH_FIELDS = ["name", "description"]
class DoingRecipe(ado.model.Model):
"""
Class ... |
from cantools.db import get_model, get_schema, put_multi
from cantools.util import log
def index(kind, i=0): # be careful with this!
kinds = kind == "*" and list(get_schema().keys()) or [kind]
puts = []
for kind in kinds:
mod = get_model(kind)
schema = get_schema(kind)
q = mod.query()
for prop in ["created",... |
'''
Solves Schittkowski's TP37 Problem Using Gradient Parallelization
min -x1*x2*x3
s.t.: x1 + 2.*x2 + 2.*x3 - 72 <= 0
- x1 - 2.*x2 - 2.*x3 <= 0
0 <= xi <= 42, i = 1,2,3
f* = -3456 , x* = [24, 12, 12]
'''
import time
try:
from mpi4py import MPI
comm = MPI.COMM_WORLD
myr... |
import types
import logging
import time
from datetime import timedelta, datetime
import gevent
from gevent.pool import Pool
from gevent import monkey
monkey.patch_all()
def every_second(seconds):
"""
Iterator-based timer
@example
>> every(seconds=10)
:return an iterator of timedelta object
"""
... |
"""
Б.Я.Советов, Моделирование систем. Практикум: Учеб пособие для вузов/Б.Я. Советов, С.А. Яковлев.- 2-е изд., перераб. и доп.-М.:Высш. шк., 2003.-295 с.: ил.
Смоделировать процесс обслуживания потока заявок с интервалом 5+/-1 мин. дыумя каналами: обслуживание в 1-м канале длится 9+/-1 мин, 2-го 13+/-1 мин. Причём в т... |
run_trial(rws[15], duration=8.0)
run_trial(rws[7], duration=8.0)
run_trial(msm0, duration=7.000, speed=200)
run_trial(cm200, duration=8.0, speed=600)
run_trial(msm0, duration=9.000, speed=150)
run_trial(rws[22], duration=8.0)
run_trial(hori1, duration=6.000, speed=200)
run_trial(msm0, duration=5.000, speed=300)
run_tri... |
from flask import Flask, Blueprint, render_template, request, Response, jsonify, session
from directory_view.blueprint import get_all_staff
from calendar_view.blueprint import get_user_days_oncall
dashboard = Blueprint('dashboard',__name__, template_folder='templates', static_folder='static')
@dashboard.route('/', meth... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
from __future__ import print_function
import argparse
import h5py
import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.externals import joblib
from tracklib import sample_random_patches, extract_patch, PatchSelector
parser = argparse.ArgumentParser(description='Collect pupil training data from vid... |
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="pages/index.html")),
] |
__version__ = "0.3.2.dev0"
__title__ = "zs2decode"
__description__ = "read Zwick zs2 and zp2 files"
__uri__ = "https://zs2decode.readthedocs.org/"
__author__ = "Chris Petrich"
__email__ = "cpetrich@users.noreply.github.com"
__license__ = "MIT"
__copyright__ = "Copyright (C) 2015-2017 Chris Petrich" |
from src.operator.Operator import Operator
class Roll(Operator):
numberOfDice = None
numberOfSides = None
rolls = []
def dice_roll(self):
raise Exception("Error: Roll Node must implement dice_roll()")
def get_sum_of_roll(self):
sum = 0
for dice in self.rolls:
sum ... |
import sys
import os, os.path
import shutil
from optparse import OptionParser
def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
platform = sys.platform
if platform == 'win32':
if 'NUMBER_OF_PROCESSORS' in os.environ:
r... |
import re
import django
from django import forms
from django.core.urlresolvers import reverse
from django.forms.models import formset_factory
from django.middleware.csrf import _get_new_csrf_key
from django.template import (
TemplateSyntaxError, Context
)
import pytest
try:
from django.template.loader import ge... |
print(__doc__)
import sys
import ntpath
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import csv
import glob
folder_path = sys.argv[1]
fodler_name = ntpath.basename(folder_path).split(".")[0]
print(folder_path)
print(fodler_name)
dic = {}
headers = []
for full_filename in glob.glob(folder_path ... |
import unittest
from knapsack_problem import knapsack
class TestKnapsackProblem(unittest.TestCase):
def test_empty(self):
self.assertEqual(knapsack([], 10), (0,[]))
def test_single_item(self):
self.assertEqual(knapsack([[1,1]], 10), (1,[[1,1]]))
self.assertEqual(knapsack([[1,10]], 10), ... |
import pytest
from mock import patch
from sigopt.orchestrate.common import Platform, current_platform
class TestCurrentPlatform(object):
@pytest.mark.parametrize('platform', ['foobar.linux', 'foobar', ''])
def test_bad_platform(self, platform):
with patch('sigopt.orchestrate.common.sys.platform', platform):
... |
import math
import os
import random
import re
import sys
def largestRectangle(heights):
stack = list()
index = 0
largest_rectangle = 0
while index < len(heights):
if (not stack) or (heights[stack[-1]] <= heights[index]):
stack.append(index)
index += 1
else:
... |
__author__ = 'SmileyBarry'
from .core import APIConnection, SteamObject, chunker
from .app import SteamApp
from .decorators import cached_property, INFINITE, MINUTE, HOUR
from .errors import *
import datetime
import itertools
class SteamUserBadge(SteamObject):
def __init__(self, badge_id, level, completion_time,
... |
""" simple logger """
import time
class EzLogger:
"""
Simple console logger
Verbosity levels:
0 -> Don't display any messages
1 -> Only Errors will be displayed
2 -> Errors and warnings will be displayed
3 -> All messages will be displayed
"""
def __init__(self, verbose_level=3):
... |
import utilities.paths as paths
import keras_code.models as models
from keras_code.predict import predict
from evaluation.metrics import score
from scipy import spatial
import numpy as np
import math
from keras import backend as K
from random import randint
import datasets.dataset_reader
from PIL import Image, ImageFon... |
"""Unit Test with pytest"""
from unittest import mock
import pytest
from openid_wargaming.authentication import Authentication
@pytest.fixture
@mock.patch('openid_wargaming.authentication.create_return_to')
def auth(mock_requests):
mock_requests.return_value = 'http://somewhere'
return Authentication()
@mock.pa... |
from io import BytesIO
from tds.base import StreamSerializer
class SSPIStream(StreamSerializer):
TOKEN_TYPE = 0xED
def unmarshal(self, buf):
"""
:param BytesIO buf:
:rtype: bool
""" |
import numpy as np
import pytest
from gym3 import types
from gym3.concat import ConcatEnv
from gym3.testing import AssertSpacesWrapper, IdentityEnv
from gym3.wrapper import Wrapper
class AddInfo(Wrapper):
def __init__(self, id, *args, **kwargs):
super().__init__(*args, **kwargs)
self._id = id
de... |
"""Browser screenshot tests."""
import pytest
import mock
def test_browser_screenshot_normal(mocked_browser, testdir):
"""Test making screenshots on test failure.
Normal test run.
"""
testdir.inline_runsource(
"""
def test_screenshot(browser):
assert False
""",
"-... |
"""
Evrything Docs
https://dashboard.evrythng.com/documentation/api/properties
"""
from evrythng import assertions, utils
field_specs = {
'datatypes': {
'key': 'str',
'value': 'json',
'timestamp': 'time'
},
'required': ('key', 'value'),
'readonly': tuple(),
'writable': ('time... |
import os
import sys
import logbook
import psutil
import yaml
from .repo import get_repo
from .util import Command
from .core import DiffRunner
class Squeeze(object):
"""Implementation of the squeeze library"""
def __init__(self):
"""Initialize the Application Runner"""
self.project_base_dir = self.ge... |
from unittest import TestCase
from office365.sharepoint.userprofiles.personPropertiesCollection import PersonPropertiesCollection
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.userprofiles.peopleManager import PeopleManager
from office365.sharepoint.userprofiles.profileLoader i... |
import imageio
import glob
import numpy as np
import sys,os
from tqdm import tqdm
home = '.\\'
train_path = 'coco\\images\\train2014'
valid_path = 'coco\\images\\val2014'
images = []
for fname in tqdm(glob.glob('{}\\*.jpg'.format(home+train_path))):
img = imageio.imread(fname)
if img.shape == (64, 64, 3) and im... |
myList = [1, 2, 3, 4, 5, "Hello"]
print(myList)
print(myList[2])
print(myList[-1])
myList.append("Simo")
print(myList)
monthsOf = ("Jan","Feb","Mar","Apr")
print(monthsOf)
myDict = {"One":1.35, 2.5:"Two Point Five", 3:"+", 7.9:2}
print(myDict)
del myDict["One"]
print(myDict) |
import numpy as np
import numpy.matlib as matlib
import matplotlib.pyplot as pyplot
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("")
print(x_train[0][:][:])
print("")
print("x shape: ", x_train.shape)
x_train = x_train[:,:,:,np.newaxis]
x_train = np.repeat(x_tra... |
from localizer_services import *
class Movement():
def __init__(self):
self.DepartmentName, self.PackageName = "perception", "camera"
self.Node = rospy.init_node(self.PackageName, log_level = rospy.INFO)
self.Services = MovementServices(self.DepartmentName, self.PackageName)
rospy.spin()
if __name__ == "__... |
import os
from flask import render_template, send_from_directory, redirect, url_for, flash, session, g, jsonify, request, abort
from functools import wraps
from requests import models
from songshift import app, db, theLoginMgr
from songshift.models.songs import Song
from flask.ext.login import login_required, current_u... |
from .utils import Serialize
from .lexer import TerminalDef
class LexerConf(Serialize):
__serialize_fields__ = 'tokens', 'ignore', 'g_regex_flags'
__serialize_namespace__ = TerminalDef,
def __init__(self, tokens, ignore=(), postlex=None, callbacks=None, g_regex_flags=0):
self.tokens = tokens
... |
"""
-- Run this file first to generate the database. --
This script converts many of the dimensioned physical, chemical, and electrical conditions
into dimensionless parameters. Conversions assume a constant temperature (298.15K), with the
associated kinematic viscosity and density of water to match. See 'helper_func... |
from collections import namedtuple
from games import (Game)
from queue import PriorityQueue
from copy import deepcopy
class OthelloState: # one way to define the state of a minimal game.
def __init__(self, player, label=None, board): # add parameters as needed.
self.to_move = player
self.label =... |
"""
The problem: Let S be a string whose characters are from [0-9]. By insert some commas,
S can be splitted into some substrings and each substring can be viewed as a decimal
integer. Let X(S) be the set of non-decreasing sequence generated by splitting S. Let
L(S) be the set of longest sequences in X(S). Write a func... |
import sys
from galaxy import util
from galaxy.web.base.controller import *
from galaxy.model.orm import *
try:
set()
except:
from sets import Set as set
import logging
log = logging.getLogger( __name__ )
class LibraryAdmin( BaseController ):
@web.expose
@web.require_admin
def browse_libraries( self... |
from django.test import TestCase
from django.contrib.auth.models import User
from datacenter.models import UserProfile
class UserProfileTestCase(TestCase):
def setUp(self):
User.objects.create(username="kantanand.usk@gmail.com",email="kantanand.usk@gmail.com",first_name="kantanand")
User.objects.cre... |
"""
__Transition2QInstOUT_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Wed Feb 11 15:12:22 2015
_________________________________________________________________________________
"""
from stickylink import *
from wid... |
from __future__ import division
from random import random
import os
from csv import writer
from math import isinf
import networkx as nx
from .auxiliary import random_choice, flatten_list
from .data_record import DataRecord
from .server import Server
class Node(object):
"""
Class for a node on the network.
"... |
import tensorflow as tf
class SentenceBatchComponent:
word_embeddings = None
pos_embeddings = None
variables = None
variable_assignments = None
index = None
current_word_embeddings = None
def __init__(self, word_index, pos_index, word_dropout_rate=0.0, is_static=False):
self.variable... |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
import sys
import socket
import fcntl
import struct
import array
import os
import binascii
STATE_ESTABLISHED = '01'
STATE_SYN_SENT = '02'
STATE_SYN_RECV = '03'
STATE_FIN_WAIT1 = '04'
STATE_FIN_WAIT2 = '05'
STATE_TIME_WAIT = '06'
STATE_CLOSE = '07'
STATE_CLOSE_WAIT = '08'
STATE_LAST_ACK = '09'
STATE_LISTEN = '0A'
STATE... |
"""
ASGI entrypoint. Configures Django and then runs the application
defined in the ASGI_APPLICATION setting.
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "daphne_brain.settings")
django_asgi_app = get_asgi_application()
from channels.auth import AuthMi... |
from setuptools import find_packages, setup
setup(
name="actormodel",
version="0.0.1",
license="MIT",
author=u"László Hegedüs",
description="Python implementation of an actor-model framework",
author_email="hegedues.laszlo@gmail.com",
url="http://actor-model-blog.readthedocs.io",
package... |
"""Configuration file parser.
A setup file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries, with continuations and such in
the style of RFC 822.
The option values can contain format strings which refer to other values in
the same section, or values in a special [DEFAULT] sectio... |
class PrintTrain:
name = 'print_train'
desc = 'prints train schedules'
args = ['TRAIN_NAME']
def run(self, db, args):
train_id = list(db.get_train_id(args[0]))
if train_id == []:
print('Train not found')
return
for schedule in db.get_schedules(train_id[0][... |
class Vigenere(object):
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def __init__(self):
self.key = None
def _find_pos(self, char):
return self.alphabet.find(char)
def _char_key_pos(self, char, pos):
char_pos = self._find_pos(char)
alphabet_char = self.key[pos % len(self.key)]... |
import os
import sys
import types
import string
import thread
import threading
import logging
import version
_Error = logging.Error
_Version = version.Version
def _is_option( option ):
return isinstance( option, OptionBase )
def _is_options( option ):
return isinstance( option, Options )
def _is_dic... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class AvailableEndpointServicesOperations(object):
"""AvailableEndpointServicesOperations operations.
:param client: Client for service requests.
:param config: Configuration o... |
import re
import os.path
from io import open
from setuptools import find_packages, setup
PACKAGE_NAME = "azure-mgmt-loganalytics"
PACKAGE_PPRINT_NAME = "Log Analytics Management"
package_folder_path = PACKAGE_NAME.replace('-', '/')
namespace_name = PACKAGE_NAME.replace('-', '.')
with open(os.path.join(package_folder_pa... |
from ooo import Peebles
from midi_in import MidiInBlock
from debug import PrintBlock, MidiControlBlock
from output import OutputBlock
from synth import SynthBlock
from looper import LooperBlock
from metronome import MetronomeBlock
from seq import GridSeqBlock, unison_seq
import time
USE_LOOPER = False
pb=Peebles()
pb.a... |
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
import os
from hello import *
app.config.from_object(os.environ['APP_SETTINGS'])
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run() |
import xlrd
import re
import os
class Rat:
def __init__(self, id_rat, treatment, data={}):
self.id_rat = id_rat
self.treatment = treatment
self.data = data
def setdata(self, value):
self.data = value
def display(self):
print self.id_rat, self.treatment, self.data
def dump(self):
"""
Ret... |
"""Provides data for the ImageNet ILSVRC 2012 Dataset plus some bounding boxes.
Some images have one or more bounding boxes associated with the label of the
image. See details here: http://image-net.org/download-bboxes
ImageNet is based upon WordNet 3.0. To uniquely identify a synset, we use
"WordNet ID" (wnid), which ... |
"""
Module for loading and saving user settings.
"""
import os
import ConfigParser
config = ConfigParser.ConfigParser()
thispath = os.path.dirname(os.path.realpath(__file__))
CONFIG_FILE_PATH = os.path.join(thispath, 'settings.cfg')
try:
config.read(CONFIG_FILE_PATH)
except ConfigParser.Error:
pass
def is_debug... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yearendsite.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import click
from aeriscloud.cli.helpers import standard_options, Command
@click.command(cls=Command)
@click.option('-i', '--ip', is_flag=True,
help='Use the machine IP instead of the aeris.cd domain')
@click.argument('endpoint', default='')
@standard_options(multiple=False)
def cli(box, endpoint, ip):
... |
from .resource import Resource
class AvailabilitySet(Resource):
"""Specifies information about the availability set that the virtual machine
should be assigned to. Virtual machines specified in the same availability
set are allocated to different nodes to maximize availability. For more
information abou... |
import array
import math
import unittest
from julia import Julia, JuliaError
import sys
python_version = sys.version_info
julia = Julia()
class JuliaTest(unittest.TestCase):
def test_call(self):
julia.call('1 + 1')
julia.call('sqrt(2.0)')
def test_eval(self):
self.assertEqual(2, julia.ev... |
"""
This module provides a compact trie (``CTrie``) implementation for Python.
.. moduleauthor:: Baptiste Fontaine <b@ptistefontaine.fr>
"""
__version__ = '0.1.1'
from io import StringIO
def _cut_prefix(prefix, word):
"""
test if ``prefix`` is a prefix of ``word``. If so, return the trailing part
of ``word`... |
import struct
import socket
import asyncore
import time
import sys
import random
from binascii import hexlify, unhexlify
from io import BytesIO
from codecs import encode
import hashlib
from threading import RLock
from threading import Thread
import logging
import copy
import dash_hash
BIP0031_VERSION = 60000
MY_VERSION... |
from __future__ import with_statement
import os.path, sys
sys.path += [
os.path.dirname(__file__),
os.path.join(os.path.dirname(__file__), 'third_party.zip'),
]
import wingapi
import shared
def _normalize_path(path):
''' '''
if not sys.platform.startswith('win'):
return os.path.realpath(path)
... |
import sqlite3
import pygal
database = sqlite3.connect('server.db')
databsepointer = database.cursor()
def get_temp():
temputures = []
for t in databsepointer.execute('SELECT temp FROM tempArduino'):
te = float(t[0])
temputures.append(te)
return temputures
def get_date():
dates = []
... |
import json
import time
from .slack import User, Bot
class FakeServer(object):
def __init__(self, slack=None, config=None, hooks=None, db=None):
self.slack = slack or FakeSlack()
self.config = config
self.hooks = hooks
self.db = db
def query(self, sql, *params):
if not se... |
import pydmt.helpers.python
import config.project
from pycmdtools.main import main
package_name = config.project.project_name
console_scripts = [
pydmt.helpers.python.make_console_script(package_name, main),
]
setup_requires = [
]
run_requires = [
'pylogconf',
'pytconf',
'requests',
'tqdm',
'num... |
'''
Return True if every even index contains an even number and every odd index contains an odd number. Else return False
'''
def is_special_array(lst):
a = [i for i in lst[::2] if i % 2 == 1]
b = [i for i in lst[1::2] if i % 2 == 0]
return len(a) == len(b)
def is_special_array(lst):
return all(lst[i]%2==i%2 for i ... |
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
The Caller is an Object that helps to get an make call a function/method.
"""
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Objects.Packager"
DecorationModuleStr="ShareYourSystem.Standards.Classor... |
import math
import heapq # used for the so colled "open list" that stores known nodes
import logging
import time # for time limitation
from pathfinding.core.heuristic import manhatten, octile
from pathfinding.core.util import SQRT2
from pathfinding.core.diagonal_movement import DiagonalMovement
MAX_RUNS = float('inf')
... |
from aqt import QInputDialog
from dulwich import porcelain
from dulwich.errors import NotGitRepository, GitProtocolError
from ..config.config_settings import ConfigSettings
from ..importer.anki_importer import AnkiJsonImporter
from ..utils.notifier import AnkiModalNotifier
BRANCH_NAME = "master"
def get_repository_name... |
try:
from ucollections import OrderedDict
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
OFFSET_BITS = 17
OFFSET_MASK = (1 << OFFSET_BITS) - 1
o = OrderedDict
desc = o((
("u0", uctypes.UINT8),
("u1", uctypes.PREV_OFFSET | uctypes.UINT16),
("u2", uctypes.PREV_OFFSET | uctyp... |
import re
import sys
from urllib import quote, unquote
import xbmcaddon
from resources.lib import scraper, utils
import xbmc
import xbmcaddon
import xbmcgui
import HTMLParser
import xbmcplugin
import hashlib
import json
__addon__ = xbmcaddon.Addon()
__translation__ = __addon__.getLocalizedString
__settings__ ... |
from random import randint
def encrypt(text, key):
if key == "":
for char in range(16):
key += chr(randint(0, 127))
print("Your key is " + key)
if len(text) != len(key):
oldKey = key
key = ""
for char in range(len(text)):
key += oldKey[char % len(o... |
import os
proj=''
local_names = []
LOCAL = True if os.uname()[1] in local_names else False
DEBUG = LOCAL
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
if LOCAL:
ROOT_PATH = os.path.abspath(os.curdir)
DATABASES = {
'default': {
'ENGINE':'s... |
import resources.lib.ftp as ftp
import resources.lib.ui as ui
import resources.lib.settings as settings
import xbmc
import xbmcaddon
__addon__ = xbmcaddon.Addon(id="service.ftpretriever")
__addonname__ = __addon__.getAddonInfo('name')
__icon__ = __addon__.getAddonInfo('icon')
language = __addon__.getLocalizedString
pro... |
try:
from .daqmx import DAQmx
except OSError:
# Error Logging is handled within package
pass
try:
from .virtualbench import VirtualBench
# direct access to armstrap/pyvirtualbench wrapper:
# from .virtualbench import VirtualBench_Direct
except ModuleNotFoundError:
# Error Logging is handled ... |
from msrest.serialization import Model
class PyTorchSettings(Model):
"""Specifies the settings for pyTorch job.
All required parameters must be populated in order to send to Azure.
:param python_script_file_path: Required. The path and file name of the
python script to execute the job.
:type python... |
import json
import os
from ._shared import *
class Alias(Rule):
"""Handles aliases"""
def __init__(self, bot, basepath):
self.bot = bot
self.basepath = basepath
self.aliases = self.read_aliases()
def __call__(self, serv, author, args):
"""Handles aliases"""
args = [i.... |
__revision__ = "test/MSVS/vs-11.0-scc-legacy-files.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
"""
Test that we can generate Visual Studio 11.0 project (.vcxproj) and
solution (.sln) files that contain SCC information and look correct.
"""
import os
import TestSConsMSVS
test = TestSConsMSVS.TestSConsMS... |
import abc
import typing
class Instruction(abc.ABC):
"""
Base class for instructions.
"""
def __init__(self, lineno, line):
self.lineno = lineno
self.line = line
self.parse()
def parse(self):
return
@abc.abstractproperty
def name(self) -> str:
"""
... |
from .sub_resource import SubResource
class ApplicationGatewayRequestRoutingRule(SubResource):
"""Request routing rule of an application gateway.
:param id: Resource ID.
:type id: str
:param rule_type: Rule type. Possible values include: 'Basic',
'PathBasedRouting'
:type rule_type: str or
... |
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Jetduino for the Jetson TK1/TX1: an open source platform for connecting
Grove Sensors to the Jetson embedded supercomputers.
Permission is hereby grante... |
"""
Overview:
Encrypt the root or ALL volumes by system instance_name. Can do up to five systems at a time.
Params:
All parameters are handled by the configuration file (aws_volume_encryption_config.py)
Conditions:
Will return a log of activities and their results
"""
import boto3
import botocore
import bo... |
import os
import sys
version = '0.0.3'
VERSION = tuple(map(int, version.split('.')))
__version__ = VERSION
__versionstr__ = version
if (2, 7) <= sys.version_info < (3, 6):
import logging
DEBUG = os.environ.get('DEBUG')
logger = logging.getLogger('olx')
logging.basicConfig(level=logging.DEBUG)
BASE_URL =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.