content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
from gi.repository import Gtk
import os
import os.path
from sys_handler import language_dictionary
# Folder use for the installer.
tmp = "/tmp/.gbi/"
installer = "/usr/local/lib/gbi/"
query = "sh /usr/local/lib/gbi/backend-query/"
if not os.path.exists(tmp):
os.makedirs(tmp)
logo = "/usr/lo... |
import webbrowser
import os
import socket
from urllib.parse import urlparse
from plugin import plugin, alias, require
FILE_PATH = os.path.abspath(os.path.dirname(__file__))
@require(network=True)
@alias("open website")
@plugin("website")
class OpenWebsite:
"""
This plugin will open a website using some param... |
from random import randint
from PIL import Image,ImageDraw
import sys
PRE = "SHOW.png"
if len(sys.argv) == 2:
PRE = sys.argv[1] + ".png"
WIDTH, HEIGHT = 1920,1080
COLOUR = (25,25,255)
image = Image.new("RGB", (WIDTH, HEIGHT), (0,0,0))
pixels = image.load()
pixels[randint(1,WIDTH-2),1] = COLOUR
def check(x,y):
... |
from .base import Base
from deoplete.util import load_external_module
load_external_module(__file__, 'source')
from data import GREEK_DICT
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'greek'
self.mark = '[greek]'
self.min_pattern_length = 1
de... |
"""Pins views."""
# Django REST Framework
from rest_framework import viewsets
# from rest_framework.generics import get_object_or_404
# Model
from pinterest.pin.models import Pin
# Serializers
from pinterest.pin.api.serializers import (
PinModelSerializer,
CreateUpdatePinSerializer,
)
# Permissions
from res... |
class WellsAndCoppersmith:
@staticmethod
def mag_length_strike_slip(mag):
""" Returns average rupture length for a given magnitude from Wells and Coppersmith
Args:
mag: magnitude
Returns:
rupture_legnth: average rupture length for a given magnitude in kilometer... |
from django.http import HttpResponse
from django.template import loader
from django.views.decorators.cache import never_cache
@never_cache
def home(request):
"""
rendering ui by template for homepage
this view never cache for delivering correct translation inside template
"""
template = loader.get... |
# Project
# -----------------------------------------------------------------------------
# Title : Dynamic Programming for Optimal Speedrun Strategy Exploration
# Author : [Twitter] @samuelladoco [Twitch] SLDCtwitch
# Contents: Dynamic programming algorithm (Dijkstra's algorithm for DAG)
# -------------------... |
from datetime import datetime
def regularMonths(currMonth):
splitted = currMonth.split('-')
month = int(splitted[0])
year = int(splitted[1])
found = False
while not found:
month += 1
if month > 12:
month = 1
year += 1
aux = datetime(year, month, 1)
... |
'''
Make sure the active directory is the directory of the repo when running the test in a IDE
'''
from skimage.data import chelsea
import matplotlib.pyplot as plt
import MTM
print( MTM.__version__ )
import numpy as np
#%% Get image and templates by cropping
image = chelsea()
template = image[80:150, 130:210]
lis... |
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
import django.views.generic.simple
from django.conf.urls import * # pylint: disable=W0401
from django.views.generi... |
# Generated by Django 2.2.4 on 2019-09-05 22:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='userpart',
name='qty',
fi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-14 19:33
from __future__ import unicode_literals
from django.db import migrations
import location_field.models.spatial
class Migration(migrations.Migration):
dependencies = [
('place', '0002_place_city'),
]
operations = [
m... |
def key(arg):
return arg
|
# -*- coding:utf-8 -*-
"""
@file interrupt.py
@brief 中断检测传感器的运动,当传感器的运动强度超过阈值时,会在int1或
@n者int2产生中断脉冲信号(set_int1_event()函数或者set_int2_event函数选择引脚)
@n在使用SPI时,片选引脚时可以通过改变RASPBERRY_PIN_CS的值修改
@copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
@licence The MIT License (MIT)
@autho... |
#This program is an item counter
def main():
#open the file
user_file = open('filename.txt', 'r')
count = 0 #This counts the number of items in the file
for line in user_file:
count += 1
user_file.close()
print('The total number of items in the file =',count)
main()
|
"""Tests for the Meteoclimatic component."""
|
# Generated by Django 3.1 on 2020-12-06 09:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('classes', '0006_auto_20201205_2224'),
]
operations = [
migrations.RemoveField(
model_name='classsyllabus',
name='compo... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 21:36:09 2018
Python2 code for Landscape Modeling class exercise 3 - Part 2
Finite difference method using forward in time and centered in space
@author: nadine
"""
#%% PART 2 - FINITE DIFF SOLUTION
import numpy as np
import matplotlib.pyplot a... |
import logging
import sys
from collections import namedtuple
from queue import Empty
from time import sleep
from types import GeneratorType
from bonobo.config import create_container
from bonobo.config.processors import ContextCurrifier
from bonobo.constants import NOT_MODIFIED, BEGIN, END, TICK_PERIOD, Token, Flag, I... |
__author__="KOLANICH"
__license__="Unlicense"
__copyright__=r"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-comme... |
#
# Facharbeit2021WatchCat dies ist der Bot welcher die Alarmanlage Steuert und die Schnitstelle zwichen User und Programm darstellt
# Also quasi DER rosa Elephant unter den Rosa Elephanten
#
# v3.2
#
import discord # Wie immer die Discord Lib
import asyncio # Für asyncrone Methoden
import time # Für die Zeit
impor... |
from datetime import datetime
from optparse import OptionParser
import pymysql
from dateutil.relativedelta import relativedelta
def main(options):
curr = datetime.now()
print("Current time : ", curr)
partitionQuery = "SELECT PARTITION_NAME FROM information_schema.partitions WHERE TABLE_SCHEMA = '{db}' " ... |
from ._version import get_versions
from .base import Client
from .config import Configuration
from .exceptions import QuetzalAPIException
__version__ = get_versions()['version']
del get_versions
__all__ = (
'__version__',
'Client',
'Configuration',
'QuetzalAPIException',
)
|
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... |
from maneuvers.kit import *
from maneuvers.strikes.dodge_strike import DodgeStrike
class DodgeShot(DodgeStrike):
max_base_height = 220
def intercept_predicate(self, car: Car, ball: Ball):
max_height = align(car, ball, self.target) * 60 + self.max_base_height
contact_ray = ball.wall... |
import _plotly_utils.basevalidators
class HoveronValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name='hoveron', parent_name='parcats', **kwargs):
super(HoveronValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
#
# PySNMP MIB module IB-DNSONE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IB-DNSONE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:50:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
import torch
from mobilenetv3 import MobileNetV3_forFPN, MobileNetV3, load_pretrained_fpn
def test_loaded_weights():
torch.backends.cudnn.deterministic = True
path = '/home/davidyuk/Projects/backbones/pytorch-mobilenet-v3/mobilenetv3_small_67.4.pth.tar'
mn3_fpn = MobileNetV3_forFPN()
mn3_fpn = l... |
#!/usr/bin/env python
# this scripts calculates the mean coverage and SD in a bam
# USE: add_meanCov_SD.py
# NOTE: change "my_dir" to the directory of interest
# NOTE: elements of this script are ran in depth_TFPD_ins.py
import os
import re
from subprocess import Popen, PIPE
import statistics
my_dir="/lscr2/andersenl... |
import numpy as np
from random import randrange, shuffle
class LogisticRegression:
@staticmethod
def sigmoid(scores):
return 1 / (1 + np.exp(-scores))
def __init__(self, learning_rate=1, regularization_loss_tradeoff=1):
self.learning_rate = learning_rate
self.regularization_loss_t... |
from guillotina import configure
from guillotina.db.interfaces import IDBTransactionStrategy
from guillotina.db.interfaces import ITransaction
from guillotina.db.strategies.simple import SimpleStrategy
import logging
logger = logging.getLogger("guillotina")
@configure.adapter(for_=ITransaction, provides=IDBTransac... |
import hashlib
import execjs
from common import http_util,MyLogger
from concurrent.futures import ThreadPoolExecutor
import socket
log = MyLogger.Logger('all.log',level='info')
socket.setdefaulttimeout(30)
'''
avatar_url: "https://pic2.zhimg.com/50/8658418bc_720w.jpg?source=54b3c3a5"
excerpt: "学科该词有以下两种含义:①相对独立的知识体系... |
######################################################
# --- Day 20: Infinite Elves and Infinite Houses --- #
######################################################
import AOCUtils
maxHouses = 1000000
######################################################
presents = AOCUtils.loadInput(20)
houses = dict()
for elf i... |
"""
Oscillators.
"""
import souffle.datatypes as dtt
##### Default constants #####
# Brusselator, unstable regime
BRUSS_A = 1.0
BRUSS_B = 3.0
# Lotka-Volterra
LOTKA_ALPHA = 1.5
LOTKA_BETA = 1.0
LOTKA_GAMMA = 2.0
LOTKA_DELTA = 1.0
# van der Pol oscillator
VANDERPOL_MU = 5.0
VANDERPOL_OMEGA = 1.0
######################... |
import pytest
from anchore_engine.subsys import object_store
from anchore_engine.subsys.object_store.config import (
DEFAULT_OBJECT_STORE_MANAGER_ID,
ALT_OBJECT_STORE_CONFIG_KEY,
)
from anchore_engine.subsys.object_store import migration
from anchore_engine.subsys import logger
from tests.fixtures import anchor... |
# Array operation
# Type: list, map() call. This method requires allocation of
# the same amount of memory as original array (to hold result
# array). On the other hand, input array stays intact.
import bench
def test(num):
for i in iter(range(num//10000)):
arr = bytearray(b"\0" * 1000)
arr2 = byte... |
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
from scipy.spatial.distance import cdist
from scipy.special import comb
import time
import copy
import itertools
import imageio
import heapq
import pickle
sns.set()
__author__ = "Chana Ross, Yoel Ross"
__copyright__ = "Copyright 2018"
__... |
import os
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Command create .docker folder structure"""
help = "Create .docker folder structure"
def create(self, path: str):
"""Create path if not exist"""
if not os.path.ex... |
from .swagger.models.answer import Answer as SwaggerAnswer
from .swagger.models.question import Question as SwaggerQuestion
from .swagger.models.quiz import Quiz as SwaggerQuiz
class Answer(SwaggerAnswer):
pass
class Question(SwaggerQuestion):
pass
class Quiz(SwaggerQuiz):
pass |
import amulet
from juju.client.connection import JujuData
import logging
import os
import requests
import subprocess
import yaml
log = logging.getLogger(__name__)
def get_juju_credentials():
jujudata = JujuData()
controller_name = jujudata.current_controller()
controller = jujudata.controllers()[contro... |
class DownloadProgressChangedEventArgs(ProgressChangedEventArgs):
""" Provides data for the System.Net.WebClient.DownloadProgressChanged event of a System.Net.WebClient. """
BytesReceived=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the number of bytes received.
Get: BytesRec... |
# encoding: utf-8
from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
metadata = MetaData()
metadata.bind = migrate_engine
migrate_engine.execute('''
CREATE TABLE user_following_dataset (
follower_id text NOT NULL,
object_id text NOT NULL,
datetime timestamp without tim... |
def multi(l_st):
output = 1
for x in l_st:
output *= x
return output
def add(l_st):
return sum(l_st)
def reverse(string):
return string[::-1] |
from __future__ import absolute_import
from .links import link_api, link_api_documentation
tool_links = [link_api, link_api_documentation]
|
"""
A hack to make pawt.swing point to the java swing library.
This allows code which imports pawt.swing to work on both JDK1.1 and 1.2
"""
swing = None
try:
import javax.swing.Icon
from javax import swing
except (ImportError, AttributeError):
try:
import java.awt.swing.Icon
... |
from faker import Faker
from nig.endpoints import INPUT_ROOT, OUTPUT_ROOT
from nig.tests import create_test_env, delete_test_env
from restapi.tests import API_URI, BaseTests, FlaskClient
class TestApp(BaseTests):
def test_api_study(self, client: FlaskClient, faker: Faker) -> None:
# setup the test env
... |
import os
def remove_files0():
root_dir = '/home/yche/mnt/wangyue-clu/csproject/biggraph/ywangby/yche/git-repos/SimRank/python_experiments/exp_results/varying_eps_exp'
data_set = 'ca-GrQc'
pair_num = 100000
eps_lst = list(([0.001 * (i + 1) for i in xrange(30)]))
file_name_lst = ['reads-d-rand-benc... |
import argparse
import asyncio
import json
import aiohttp
import aiohttp_jinja2
from aiohttp import web
import jinja2
from typing import Dict
from dataclasses import dataclass, field
from pycards import game
parser = argparse.ArgumentParser(description='dapai')
parser.add_argument('--port')
def json_dumps(content)... |
from string import hexdigits
from random import choice
import aiohttp
from type.credentials import GoogleCredentials, FirebaseCredentials
from type.settings import FirebaseSettings
from dataclasses import dataclass
from typing import Optional
@dataclass()
class Installation:
token: str
iid: str
class Fireb... |
import json
from setuptools import setup, find_packages
with open('install.json', 'r') as fh:
version = json.load(fh)['programVersion']
if not version:
raise RuntimeError('Cannot find version information')
setup(
author='',
description='Playbook app wrapper for TextBlob (https://github.com/sloria/Tex... |
#Loading dependencies
import pandas as pd
import sys
from utils.GeneralSettings import *
from Asset.AssetTypes.Bridge import Bridge
from Asset.AssetTypes.Building import Building
from Asset.Elements.BridgeElement import BridgeElement
from Asset.Elements.ConditionRating.NBIRatingModified import NBI
from Asset.Element... |
import random
number = random.randint(1,10)
user = 0
count = 0
while user != number and user != "exit":
user = int(input("What's your guess? "))
if user == "exit":
break
count += 1
if user < number:
print("Too low!")
elif user > number:
print("Too high!")
... |
__title__ = 'glance-times'
__description__ = 'Who will watch the watchman? Glance can.'
__url__ = 'https://github.com/mrice88/glance'
__download_url__ = 'https://github.com/mrice88/glance/archive/master.zip'
__version__ = '0.3.6'
__author__ = 'Mark Rice'
__author_email__ = '[email protected]'
__license__ = 'MIT'
__... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import time
import array
import os
sys.path.append("shell")
import swapforth
class TetheredJ1a(swapforth.TetheredTarget):
cellsize = 2
def open_ser(self, port, speed):
try:
import serial
except:
pr... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator 2.3.33.0
# ... |
from cffi import FFI
import os
ffibuilder = FFI()
# cdef() expects a single string declaring the C types, functions and
# globals needed to use the shared object. It must be in valid C syntax.
ffibuilder.cdef("""
typedef int Boolean;
typedef int64_t ft_data_t;
typedef struct {
size_t length;
... |
import torch
from torch import nn
def expand_as_one_hot(input_, C, ignore_label=None):
"""
Converts NxSPATIAL label image to NxCxSPATIAL, where each label gets converted to its corresponding one-hot vector.
NOTE: make sure that the input_ contains consecutive numbers starting from 0, otherwise the scatter... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 11:36:51 2020
@author: cjburke
"""
import numpy as np
import matplotlib.pyplot as plt
import h5py
from astropy.wcs import WCS
from astropy.io import fits
import glob
import os
import argparse
try:
import pyds9 as pd
except ImportError:
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'control_app.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s... |
# -*- coding: utf-8 -*-
"""
zeronimo.helpers
~~~~~~~~~~~~~~~~
Helper functions.
:copyright: (c) 2013-2017 by Heungsub Lee
:license: BSD, see LICENSE for more details.
"""
from errno import EINTR
import zmq
__all__ = ['FALSE_RETURNER', 'class_name', 'make_repr', 'socket_type_name',
'repr_... |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''A container for timeline-based events and traces and can handle importing
raw event data from different sources. This model closely resembles that in t... |
try:
from .KsDataReader import *
except ImportError:
pass |
import os
import json
from multiplespawner.defaults import default_base_path
from multiplespawner.util import load
def get_spawner_template_path(path=None):
if "MULTIPLE_SPAWNER_TEMPLATE_FILE" in os.environ:
path = os.environ["MULTIPLE_SPAWNER_TEMPLATE_FILE"]
else:
# If no path is set programm... |
from .sensitivity import solve_sensitivity
from .monte_carlo import solve_monte_carlo
from ..model_parser import ModelParser
def solve_identifiability(model):
method = model['options']['method']
if method == 'sensitivity':
return solve_sensitivity(model, ModelParser)
elif method == 'monte_carlo':
... |
"""
GoPro splits long recordings out to multiple files (chapters).
This library is for locating movies (from a GoPro memory card)
in a directory and determining which movies belong to a sequence
and merging them into a single movie file.
>>> import gp_merge_clips
>>> gp_merge_clips.merge_clips('/path/to/root/dir')
Co... |
from django.db import models
from slugify import slugify
class Country(models.Model):
""" Country's model """
name = models.CharField(
verbose_name='Country name',
max_length=255,
)
slug = models.SlugField(
unique=True,
max_length=255,
blank=True,
edit... |
from . import bit
from .utils import Key, BaseUrl
from .bit import capture, verify_images, verify, status, setup, BiTStatus
|
#!/usr/bin/env python
"""%(prog)s - run a command when a file is changed
Usage: %(prog)s [-r] FILE COMMAND...
%(prog)s [-r] FILE [FILE ...] -c COMMAND
FILE can be a directory. Watch recursively with -r.
Use %%f to pass the filename to the command.
Copyright (c) 2011, Johannes H. Jensen.
License: BSD, see LICE... |
from ..core import Niche
from .model import Model, simulate
from .env import minigridhard_custom, Env_config
from collections import OrderedDict
DEFAULT_ENV = Env_config(
name='default_env',
lava_prob=[0., 0.1],
obstacle_lvl=[0., 1.],
box_to_ball_prob=[0., 0.3],
door_prob=[0., 0... |
import xml.dom.minidom, sys
"""Para parsear el documento con muchas noticias (cada noticia entre <doc></doc>),
necesitamos una metaetiqueta (en este ejemplo <docs>).
"""
def getKey(item):
return item[0]
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
... |
import numpy as np
from hyperopt import hp, fmin, tpe, Trials
binary_operators = ["*", "/", "+", "-"]
unary_operators = ["sin", "cos", "exp", "log"]
space = dict(
# model_selection="best",
model_selection=hp.choice("model_selection", ["accuracy"]),
# binary_operators=None,
binary_operators=hp.... |
import math
import random
import numpy as np
class Register(object):
def __init__(self, num_qubits, state):
"""Initialise quantum register
A register can be in a measured state superposition of states e.g.
if a Hadamard gate is applied to a 1-qubit system then the qubit
would be ... |
import tkinter as tk
class Plot4Q(tk.Frame):
DEFAULT_BG_COLOR = 'grey'
DEFAULT_LINE_COLOR = '#39FF14'
def __init__(self, master, x_pixels=200, y_pixels=200, xrange=1.0, yrange=1.0, grid=False, x_axis_label_str=None, y_axis_label_str=None):
self.parent = master
super().__init__(self.parent... |
#BASIC IMAGE READING AND SAVING/COPYING
# import cv2 as cv
# import sys
# img = cv.imread(cv.samples.findFile("dp2.jpg"))
# if img is None:
# sys.exit("Could not read the image.")
# cv.imshow("A Human", img)
# k = cv.waitKey(0)
# if k == ord("s"):
# cv.imwrite("dp3.png", img)
#SIMPLE/GLOBAL THRESHOLDING
... |
# -*- coding: utf-8 -*-
import pytest
# TODO: implement all unit tests
def test_fib():
assert True
|
from core.settings import settings
from core.security import generate_confirmation_code
from .sender import BaseMessage
# To developers: KISS is much more important than DRY!
# So do OOP-inheritance ONLY if your new classes has same validation fields,
# same purpose AND MANY common logic.
# If you have to do some s... |
from .download import start, get_pdf_list
|
import bpy
from ... base_types import AnimationNode, VectorizedSocket
class ReverseTextNode(bpy.types.Node, AnimationNode):
bl_idname = "an_ReverseTextNode"
bl_label = "Reverse Text"
useList: VectorizedSocket.newProperty()
def create(self):
self.newInput(VectorizedSocket("Text", "useList",
... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, DataType
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class BinarySchema:
"""
A resource that represents the data of a single raw artifact as ... |
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
from skimage import io
import numpy as np
import argparse
import datetime
import pickle
import time
import cv2
import sys
import os
sys.path.append(os.path.abspath(".."))
from src.runner import JestureSdkRunner
from src.utils import load_imag... |
"""Translation stats collection and reporting."""
import datetime
import io
import logging
import traceback
import texttable
class TranslationStats(object):
ROW_COUNT = 7
def __init__(self):
self._locale_to_message = {}
self._untranslated = {}
self._stacktraces = []
self._un... |
class GetSeries(object):
def get_series(self, series):
"""
Returns a census series API handler.
"""
if series == "acs1":
return self.census.acs1dp
elif series == "acs5":
return self.census.acs5
elif series == "sf1":
return self.cens... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def _cr2a(c1, r1, c2=None, r2=None):
"""
r1=1 c1=1 gives A1 etc.
"""
assert r1>0 and c1>0, "negative coordinates not allowed!"
out=_n2x(c1)+str(r1)
if c2 is not None:
out +=':'+ _n2x(c2) + str(r2)
return out
def _a2cr(a,f4=False):
... |
import logging
from flask import Blueprint, render_template
import MySQLdb
import MySQLdb.cursors
from pprint import pprint
import sys
import json
main = Blueprint('main', __name__)
#@main.route('/')
def index():
return "Main"
@main.route('/')
def display_books():
#import _mysql.cursors
db=MySQLdb.connect... |
def exercise_log_op(is_magician = True, is_expert = False):
#check if magician AND expert: "you are a master magician"
#check if magician but not expert: "at least you're getting there"
#if you're not magician: "you need magic powers"
if is_magician and is_expert:
print("you are a master magician")
elif ... |
# Generated by Django 3.1.2 on 2020-10-05 21:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... |
import logging
import threading
import os
import time
from webcamlib.ConfigureLogging import logging_setup
class myThread (threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.logger = logging.getLogger("test-{}-{}".format(name, threadID))
self... |
import os
settings = {}
def refresh():
"""
Refresh environment.settings dict
"""
APP_DATA_DIR = os.environ.get('APP_DATA_DIR', os.getcwd())
settings.clear()
settings.update({
'APP_DATA_DIR': APP_DATA_DIR,
'LOG_DIR': os.path.join(APP_DATA_DIR, 'logs'),
'LOG_FILE': os.p... |
"""
API test example that tests various auths.
"""
from screenpy import Actor, given, then, when
from screenpy.actions import AddHeader, See, SendGETRequest
from screenpy.questions import StatusCodeOfTheLastResponse
from screenpy.resolutions import IsEqualTo
from ..urls import BASIC_AUTH_URL, BEARER_AUTH_URL
def te... |
import pandas as pd
import numpy as np
import sys
# > > > Load Input Data [DYNAMIC INPUTS] < < <
LoadData = pd.read_csv('C:/UMI/temp/Loads.csv')
Output = LoadData #Reformatted Kuwait output to bypass the reformat section
WeatherData = pd.read_csv('C:/UMI/temp/DryBulbData.csv')
# > > > User-specified Parameters [DYNA... |
from theteller_api_sdk.checkout.checkout import Checkout
import unittest
from theteller_api_sdk.core.core import Client
from theteller_api_sdk.core.environment import Environment
from os import environ
class TestCheckout(unittest.TestCase):
def setUp(self) -> None:
env= Environment("test")
client =... |
#!/usr/bin/env python3
import Constants as Constants
import Solvers as Solvers
import FunctionCallers as FunctionCallers
def malthus():
return Solvers.rungeKutta4V1(
FunctionCallers.callMalthus,
Constants.INITIAL_NUMBER_OF_PREYS,
0,
Constants.DURATION,
Constants.STEP
)... |
#this is an implementation of the FFT (fast fourier transform) in python from scratch
from cmath import exp, pi, sin
import matplotlib.pyplot as plt
def fft(input):
#seperate the input vector into even and odd indexes
input_odd = input[1::2]
input_even = input[0::2]
#length of the input vector
... |
# coding: utf-8
""" Execute Step Classes """
import tmt
class Execute(tmt.steps.Step):
""" Run the tests (using the specified framework and its settings) """
def __init__(self, data, plan):
""" Initialize the execute step """
super(Execute, self).__init__(data, plan)
if len(self.dat... |
import socket
import ssl
from machine import Pin, Timer
import network
from utime import sleep
from settings import wifi_name, wifi_pass, pushover_user, pushover_token
PUSHOVER_HOST = 'api.pushover.net'
PUSHOVER_PORT = 443
PUSHOVER_PATH = '/1/messages.json'
SAFE_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDE... |
from pygal_maps_world.maps import World
from pygal.style import NeonStyle
wm = World(style=NeonStyle)
wm.title = 'Populations of Countries in North America'
wm.add('North America', {'ca': 34126000, 'us': 309349000,
'mx': 113423000})
wm.render_to_file('na_populations.svg') |
# -*- coding: utf-8 -*-
"""
qiniusupport
~~~~~~~~~~~~~~
Qiniu client wrapper.
https://developer.qiniu.com/kodo/sdk/1242/python
:copyright: (c) 2018 by fengweimin.
:date: 2018/3/21
"""
import qiniu
class QiniuSupport(object):
def __init__(self, app=None):
self.app = app
... |
from dataclasses import dataclass
import numpy as np
import pandas as pd
from statsmodels.nonparametric import kernels
from statsmodels.sandbox.nonparametric import kernels as sandbox_kernels
from statsmodels.nonparametric import bandwidths
import sys
# MINIMUM_CONTI_BANDWIDTH = sys.float_info.min
MINIMUM_CONTI_BANDWI... |
#!/usr/bin/env python3
import os
import sys
import subprocess
import string
import random
import re
import subprocess
media_re = '.(mp4|mov|wma)$'
from_dir = "ready-for-glitch"
overlay_dir = "overlays"
dest_dir = "final"
overlay_file = "tv-interference-overlay.mp4"
# unlike on the command line, complicated cli opt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.