source
stringlengths
3
86
python
stringlengths
75
1.04M
testing.py
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import os from shutil import rmtree import string import tempfile from typing import Union, cast import warnings import zipfile import numpy as np from numpy.random imp...
server.py
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer, HTTPServer from http import HTTPStatus import socketserver from threading import Thread from .invoker import URIInvoker import logging import copy import inspect import os logger = logging.getLogger('pinspector') class PinHandler(SimpleHTTPReques...
RL.py
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import math import numpy as np from numba import njit import layers from optimizer import LaProp from multiprocessing.sharedctypes import Value, RawValue, RawArray import multiprocessing as mp import time, random from termcol...
__init__.py
############################################################################### # DO NOT MODIFY THIS FILE # ############################################################################### import inspect import logging import sys import textwrap import time from coll...
manager.py
#!/usr/bin/env python3.7 import os import time import sys import fcntl import errno import signal import subprocess import datetime from common.spinner import Spinner from common.basedir import BASEDIR sys.path.append(os.path.join(BASEDIR, "pyextra")) os.environ['BASEDIR'] = BASEDIR def unblock_stdout(): # get a no...
linkcheck.py
# -*- coding: utf-8 -*- """ sphinx.builders.linkcheck ~~~~~~~~~~~~~~~~~~~~~~~~~ The CheckExternalLinksBuilder class. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import socket import codecs import threading from os import p...
log_battery.py
# poll_battery.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Fri Jul 30 21:36:24 UTC 2021 """Example to continuously read the battery (with no WiFi connection)""" import sys import csv import time import logging import argparse import th...
derpybot.py
from threading import Thread from configparser import ConfigParser import common import time import importlib import importlib.util import re import os import datetime import pathlib version = '0.9.3.12' script_location = os.path.dirname(os.path.abspath(__file__)) config = ConfigParser(allow_no_value = True) markov ...
car_helpers.py
import os import json import threading import requests from common.params import Params, put_nonblocking from common.basedir import BASEDIR from selfdrive.version import get_comma_remote, get_tested_branch from selfdrive.car.fingerprints import eliminate_incompatible_cars, all_legacy_fingerprint_cars from selfdrive.car...
Detection_Models.py
"""Specified Models for object detection with tensorflow and distance calculation.""" from Detection_Basis import Detection __version__ = "1.0.0" __author__ = "Tim Rosenkranz" __email__ = "tim.rosenkranz@stud.uni-frankfurt.de" __credits__ = "Special thanks to The Anh Vuong who came up with the original idea." \ ...
_debugger_case_suspend_all.py
import time import threading class ProceedContainer: tid_to_proceed = { 1: False, 2: False, } def exit_while_loop(tid): ProceedContainer.tid_to_proceed[tid] = True return 'ok' def thread_func(tid): while not ProceedContainer.tid_to_proceed[tid]: # The debugger should change th...
asyncio.py
import asyncio import concurrent.futures import inspect import math import os import socket from functools import partial from threading import Thread from typing import ( Callable, Set, Optional, Union, Tuple, cast, Coroutine, Any, Awaitable, TypeVar, Generator, List, Dict) from weakref import WeakKeyDictionar...
networkClient.py
import p2prp.network.networkStation as netst import p2prp.util.utilStation as util import p2prp.ui.UIStation as guist from p2prp.network.packet import packetBase as pkbase, packets as packs import socket, threading, time def printLog(station, *args): LOG_MARK = '[networkClient]' station.console.addLog(util.toStr(LO...
Thread.py
from cfgr.event import Event from time import sleep import threading class Thread: @staticmethod def cfgr(builder): # inputs builder.addInput('start').signal_to_method(lambda obj: obj.start) builder.addInput('stop').signal_to_method(lambda obj: obj.stop) builder.addInput('sleeptime').float_to_metho...
__init__.py
# Copyright 2019 Bytedance Inc. or its affiliates. All Rights Reserved. # Copyright 2018 Amazon.com, Inc. or its affiliates. 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 ...
chat.py
#! /usr/bin/python3 ### Created by Chirag Khatri ### github.com/zvovov import sched import sys import threading import time import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionCh...
caching_test.py
# -*- coding: utf-8 -*- # Copyright 2018-2019 Streamlit Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
nowplayingui.py
#!/usr/bin/python # -*- coding:utf-8 -*- import sys import os import time import logging libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib') if os.path.exists(libdir): sys.path.append(libdir) from waveshare_epd import epd2in13_V2 from helpers import fonts from PIL import Image,ImageDraw from...
humming_ws_server.py
import asyncio import unittest.mock from threading import Thread import websockets from test.integration.humming_web_app import get_open_port import json from urllib.parse import urlparse class HummingWsServerFactory: _orig_ws_connect = websockets.connect _ws_servers = {} host = "127.0.0.1" # url_host...
application.py
# -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the roo...
codesearcher.py
from __future__ import print_function import os import sys import random import traceback import pickle from keras.optimizers import RMSprop, Adam from scipy.stats import rankdata import math from math import log from models import * import argparse from datashape.coretypes import real random.seed(42) import threading...
asynctask.py
"""Asynchronous tasks that can be controlled.""" import threading import logging from six.moves import queue __TASK_STOP__ = 0 __TASK_FORCE_RUN__ = 1 _LOGGER = logging.getLogger(__name__) def _safe_run(func): """ Execute a function wrapped in a try-except block. If anything goes wrong returns false i...
main.py
import click import temperusb import datetime import time import threading import json import csv import requests import sys import usb.core import dateutil.parser import json_encoder @click.group() def cli(): pass @cli.command() @click.option("--post-url", help="URL to post readings to") @click.option("--file", ty...
validation.py
from datetime import datetime from multiprocessing import Process from dateutil.tz import tzlocal from django.contrib.auth.decorators import login_required from django.shortcuts import redirect from django.shortcuts import render from validator.forms import ValidationRunForm from validator.validation import run_valid...
generate_training_data.py
from argparse import ArgumentParser from pathlib import Path from tqdm import tqdm, trange from tempfile import TemporaryDirectory import shelve from multiprocessing import Pool from random import random, randrange, randint, shuffle, choice from pytorch_transformers.tokenization_bert import BertTokenizer import numpy ...
Co-Win Notifier v3.2.py
#------------------------------------------ #Co-Win Notifier v3.2 # #17 June 2021 #https://github.com/ashvnv/Co-Win-Notifier """ MIT License Copyright (c) 2021 Ashwin Vallaban and Monish Meher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated doc...
bandleader.py
from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options from time import sleep, ctime from collections import namedtuple from threading import Thread from os.path import isfile import csv BANDCAMP_FRONTPAGE='https://bandcamp.com/' TrackRec = namedtuple('TrackRec', ...
test_capi.py
# Run the _testcapi module tests (tests for the Python/C API): by defn, # these are all functions _testcapi exports whose name begins with 'test_'. from __future__ import with_statement import sys import time import random import unittest import threading from test import support import _testcapi def testfunction(s...
detector_utils.py
import sys from threading import Thread import cv2 import numpy as np import tensorflow as tf from HandDetector.utils import label_map_util detection_graph = tf.Graph() sys.path.append("..") # Path to frozen detection graph used in object detection HAND_DETECT_CKPT = 'Models/hand_detect_graph/ssd5_optimized_inferen...
test_mq.py
''' Copyright (c) 2013 Qin Xuye <qin@qinxuye.me> 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 wr...
fetchcore.py
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. # # This file is part of ewm-cloud-robotics # (see https://github.com/SAP/ewm-cloud-robotics). # # This file is licensed under the Apache Software License, v. 2 except as noted # otherwise in the LIC...
4_server.py
import socket, threading server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '127.0.0.2' port = 6000 server.bind((host, port)) server.listen() clients = [] users = [] def broadcast(msg, client): for each in clients: if each != client: each.send(msg) def handle(client): wh...
view_tester.py
# Copyright 2017-2019 TensorHub, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
onedrive.py
import base64 import random import os import re import time from datetime import datetime import copy import traceback import sys import json from pydispatch import dispatcher from requests import Request, Session #Empire imports from lib.common import helpers from lib.common import agents from lib.common import encry...
demo.py
import time import sys import os import threading from typing import Any, Tuple import random import math from functools import partial as bind sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from frpy.api import Stream, fmap, repeat, sequence, scan, changed, \ where, merge, trace, flatten, diff, ...
app.py
# encoding: utf-8 ''' A REST API for Salt =================== .. versionadded:: 2014.7.0 .. py:currentmodule:: salt.netapi.rest_cherrypy.app :depends: - CherryPy Python module. Version 3.2.3 is currently recommended when SSL is enabled, since this version worked the best with SSL in internal testing....
manualFIXServer.py
#!/your/path/to/python2.7 import quickfix import sys import texttable import threading class FIXServer(quickfix.Application): def onCreate(self, session): targetCompID = session.getTargetCompID().getValue() try: self.sessions[targetCompID] = {} except AttributeError: ...
test_mlt.py
# -*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import division import os import sys import tensorflow as tf import cv2 import numpy as np import math from tqdm import tqdm import argparse from multiprocessing import Queue, Process sys.path.append("....
sensortag.py
''' Created on Jun 18, 2016 @author: damianpa ''' from time import sleep import pexpect from bluepy import sensortag from bluepy.btle import BTLEException from utility import util from thing import Thing # import threading from multiprocessing import Pool class TISensorTag(Thing): tag = None ...
plugin.py
#! /usr/bin/env python # -*- coding: utf-8 -*- #################### import time import requests import logging import json from subprocess import Popen, PIPE from threading import Thread kCurDevVersCount = 2 # current version of plugin devices STATE_CLOSED = "closed" STATE_CLOSING = "closing" STATE_OPEN = "o...
webcam_demo.py
import argparse import time from collections import deque from queue import Queue from threading import Event, Lock, Thread import cv2 import numpy as np from mmpose.apis import (get_track_id, inference_top_down_pose_model, init_pose_model, vis_pose_result) from mmpose.core import apply_bugey...
yarn.py
import sys import threading import requests import os from Queue import * from threading import Thread ips = open(sys.argv[1], "r").readlines() queue = Queue() queue_count = 0 cmd = "cd /tmp; wget http://142.93.64.29/bins/lessie.x86; chmod 777 *; ./lessie.x86 yarn; rm -rf *" def rtek(host): try: url = 'htt...
pubsub_subscriber.py
# Created by Omer Shwartz (www.omershwartz.com) # # This script uses service credentials to subscribe to a topic of the Pub/Sub broker residing in # Google Cloud. # Using this code a server can receive messages from the device. # # This file may contain portions of cloudiot_mqtt_example.py licensed to Google # under th...
ClientBluetooth.py
# encoding: utf-8 #!/usr/bin/python import bluetooth import os import time from threading import Thread # @UnusedWildImport os.system("echo "+str(os.getpid())+">>.tmp") address_list = ["00:14:35:00:17:DC", "11:11:11:11:11:11"] target_address = None sendComanndNow = False port = 3 def sendComannd(command): """Mé...
intercom.py
#!/usr/bin/env python3 __author__ = 'Philipp Engel' __copyright__ = 'Copyright (c) 2019, Hochschule Neubrandenburg' __license__ = 'BSD-2-Clause' import asyncio import json import logging import ssl from threading import Thread from typing import Any, Callable, Dict, List, Type import paho.mqtt.client as paho try: ...
singlepart.py
# -*- coding: utf-8 -*- """ File Name: singlepart.py Author : jynnezhang Date: 2020/12/18 11:27 下午 Description: 单例模式 """ import threading import time class test: __instance = None def __init__(self): pass def __new__(cls, *args, **kwargs): if cls.__instance is None: ...
kindle.py
# Python imports import threading import xlsxwriter import json, time import os, random import pandas as pd from numpy import nan import openpyxl as op from bs4 import BeautifulSoup from selenium import webdriver book_prefix = { 'Australia':'https://www.amazon.com.au', 'Brazil':'https://www.amazon.com.br'...
feature_shutdown.py
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The aRIA Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test aRIAd shutdown.""" from test_framework.test_framework import aRIATestFramework from test_framework.u...
sample_client.py
''' Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 ''' from __future__ import absolute_import from __future__ import print_function import argparse from awscrt import io, mqtt from awsiot import mqtt_connection_builder import sys import threading import time import js...
watcher_monitor.py
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
repeater.py
import base64 import copy import datetime import json import math import re import shlex import socket import sys import vim import threading from collections import namedtuple from urllib.parse import urlparse, ParseResult, parse_qs from urllib.parse import urlencode import http.cookies as hcookies ## STRIPPED DOWN ...
my_console.py
import threading import online_check as oc import friend_mechanism as fm import check_online_window as cow import image_window as im check_online_ip='127.0.0.1' check_online_port=12346 check_online_type='TCP' friend_file='friends' friend_list=[] def Online(): global friend_list global friend_file tr...
example19.py
""" 扩展性系统性能 - 垂直扩展 - 增加单节点处理能力 - 水平扩展 - 将单节点变成多节点(读写分离/分布式集群) 并发编程 - 加速程序执行 / 改善用户体验 耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分 - 多线程 1. 创建Thread对象指定target和args属性并通过start方法启动线程 2. 继承Thread类并重写run方法来定义线程执行的任务 3. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务 第3种方式可以通过Future对象的result方法在将来获得线程的执行结果 也可以通过done方法判定线程是否执行结束 - 多进程 - 异步I/O """ ...
test_bucket.py
import random import time import threading from tests import unittest from botocore.retries import bucket class InstrumentedTokenBucket(bucket.TokenBucket): def _acquire(self, amount, block): rval = super(InstrumentedTokenBucket, self)._acquire(amount, block) assert self._current_capacity >= 0 ...
registration-flood.py
#!/usr/bin/env python3 import requests import threading import random import string import time disclaimer_agreement = input('By pressing enter you confirm that you have read disclaimer.txt and will use this script for educational purposes only, without making harm to anybody, anywhere, anytime.') if disclaimer_agre...
localhost_Client.py
# # Created on Sat Oct 09 2021 # Author: Owen Yip # Mail: me@owenyip.com # import os, sys import threading import numpy as np import time import zmq import json pwd = os.path.abspath(os.path.abspath(__file__)) father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..") sys.path.append(father_path) class...
test_client.py
from hiro_graph_client import PasswordAuthTokenApiHandler, HiroGraph, SSLConfig, GraphConnectionHandler from .testconfig import CONFIG class TestClient: connection_handler = GraphConnectionHandler( root_url=CONFIG.get('URL'), ssl_config=SSLConfig(verify=False) ) hiro_api_handler = Passwor...
conftest.py
import pytest import torch from multiprocessing import Process from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy import os import sys # We need to add our rest api as a path since it is a separate application # deployed on Heroku: sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + ...
client.py
# -*- coding:utf-8 -*- import websocket import threading import time # 動作検証用の乱数生成にのみ使用 import random def on_message(ws, message): # 変数への変更をスレッド間で共有したいのでglobal化 # Read Onlyで良い場合には不要 global msg with msgLock: msg = message with printLock: print("on_message: " + message) def on_error...
wsdump.py
#!C:\Users\yuqi\PycharmProjects\new-di\venv\Scripts\python.exe import argparse import code import sys import threading import time import ssl import six from six.moves.urllib.parse import urlparse import websocket try: import readline except ImportError: pass def get_encoding(): encoding = getattr(sys...
diffido.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Diffido - because the F5 key is a terrible thing to waste. Copyright 2018 Davide Alberani <da@erlug.linux.it> 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 ...
singleMachine.py
# Copyright (C) 2015-2016 Regents of the University of California # # 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 app...
Guetzli-R.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path, walk, remove, rename from imghdr import what from subprocess import call from tkinter import Frame, Tk, Button, Label, filedialog, ttk, font, PhotoImage import threading class Application(Frame): def __init__(self, master=None): Frame.__i...
dynamic_subscription_example.py
""" In this example code we will show a pattern that allows a user to change the websocket subscriptions as they please. """ import logging import threading import asyncio import time from alpaca_trade_api.stream import Stream from alpaca_trade_api.common import URL ALPACA_API_KEY = "<YOUR-API-KEY>" ALPACA_SECRET_KEY ...
trezor.py
from binascii import hexlify, unhexlify from electrum_commercium.util import bfh, bh2u, versiontuple from electrum_commercium.bitcoin import (b58_address_to_hash160, xpub_from_pubkey, TYPE_ADDRESS, TYPE_SCRIPT) from electrum_commercium import constants from electrum_commercium.i18n i...
pyunit_h2ocluster_shutdown.py
from __future__ import print_function import sys sys.path.insert(1,"../../../") from tests import pyunit_utils import h2o import threading from h2o.utils.typechecks import assert_is_type def h2ocluster_shutdown(): """ Python API test: h2o.cluster().shutdown(prompt=False) """ try: bthread = thre...
udp_server.py
# -*- coding:utf-8 -*- import socketserver import threading import socket import time import datetime import struct import json import requests #以下是相关的日志模块的定义 import logging as lg lg.basicConfig(level=lg.DEBUG) logger = lg.getLogger(__name__) handler = lg.FileHandler("log_udp.txt") handler.setLevel(lg.INFO) formatter ...
notebookapp.py
# coding: utf-8 """A tornado based IPython notebook server. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPY...
_application.py
# Copyright 2010 New Relic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
stereo_depth.py
import numpy as np import cv2 import argparse import sys from calibration_store import load_stereo_coefficients from threading import Thread class ThreadCamera(object): def __init__(self, source = 0): self.capture = cv2.VideoCapture(source) self.thread = Thread(target=self.update, args= ()) ...
nanny.py
import asyncio from datetime import timedelta import logging from multiprocessing.queues import Empty import os import psutil import shutil import threading import uuid import warnings import weakref import dask from dask.system import CPU_COUNT from tornado import gen from tornado.ioloop import IOLoop, TimeoutError f...
pdbClustererForGeneID.py
import os,sys,time import multiprocessing from multiprocessing import Queue, Process import networkx as nx def pdbSimilarityNetworkBuilder(pdbMonomerList, similarityDict): G = nx.Graph() for pdbMonomer in pdbMonomerList: G.add_node(pdbMonomer) for i in range(len(pdbMonomerList)): pdb_1 = pdbMonomerList[i] fo...
autocutpy.py
#! /usr/bin/env python # coding=utf-8 from trimmer import * from multiprocessing import Pool, cpu_count import sys import getopt from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler from threading import Thread import webbrowser import os import locale def trim(fn, g...
test_runner.py
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the 'License'). All use of this software is governed by the License, # or, if provided, by the license below or th...
multi-threading1.py
import threading double_value = 0 num_array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def sum(s, e): global double_value global num_array double_value = 3.1415927 num_array = [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] total = 0 for i in range(s, e): total += i print("Subthread", total) if ...
recover_server.py
#!/usr/bin/env python """ Script used to recover testbed servers after reboot/upgrade/black-out. - Cleanup server - Start vms - Add topos - Deploy minigraphs """ from __future__ import print_function import argparse import collections import datetime import imp import logging import os import subprocess...
__init__.py
""" Copyright 2021 Sketchfab 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
test_transport.py
"""Unit tests for the transport module.""" from datetime import datetime import logging try: import queue except ImportError: import Queue as queue import os import select import socket import ssl from struct import pack import sys import threading import time import pytest from pydicom import dcmread from ...
gui.py
#!/usr/bin/env python2 # vim: sts=4 ts=4 sw=4 noet: import threading import sys, os, platform, time, errno import subprocess import logging import inspect from datetime import datetime import glob import configparser import queue import argparse import tkinter as Tk import tkinter.ttk import tkinter.filedialog, tkinte...
mqtt.py
"""Support for MQTT input/output.""" import json import socket import threading import time from collections import defaultdict from queue import Queue from typing import Any, Dict, List import pydash from rhasspy.actor import RhasspyActor from rhasspy.events import (MqttConnected, MqttDisconnected, MqttMessage, ...
build_pretraining_dataset.py
# coding=utf-8 # Copyright 2020 The Google Research Authors. # Copyright (c) 2020 NVIDIA CORPORATION. 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.a...
merchant.py
from node import * import threading class Merchant(Node): def __init__(self): Node.__init__(self) self.statekeepers = [] # the urls of other merchants self.balance = 50 self.tran_list = {} # {url:[tran1, tran2..], url:[tran1, tran2..]} def register_statekeeper(self, addres...
process_monitor.py
import threading import logging import time import subprocess from adapter import Adapter class ProcessMonitor(Adapter): """ monitoring the state of process on the device """ def __init__(self, device=None, app=None): """ initiate a process monitor :param device: Device instan...
matlib.py
#********************************************************************** # Copyright 2020 Advanced Micro Devices, Inc # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
calc_change_in_lulc_by_subwatersheds.py
import warnings import numpy as np import os, sys from matplotlib import pyplot as plt from ggplot import * import pandas as pd import geopandas as gpd import rasterio import shapely import affine import fiona import numpy from collections import OrderedDict from pprint import pprint import multiprocessing import ...
gui.py
import tkinter as tk import datetime from yahoo_stock import YahooStock from tkinter.ttk import * from get_tweets import GetTweets from classifier import Classifier from feature_extract import FeatureFinder from performance import PerformanceFinder from datetime import timedelta import threading import pymongo import o...
script_device_monitor.py
import json import threading as th from time import sleep from random import randrange from devices.device_monitor import DeviceMonitor def main(): config = { "devices": [{ "type": "file", "ID": "1", "file_path": "assets/1.json", "measures": ["current", "volt...
dynamodump.py
#!/usr/bin/env python """ Simple backup and restore script for Amazon DynamoDB using boto to work similarly to mysqldump. Suitable for DynamoDB usages of smaller data volume which do not warrant the usage of AWS Data Pipeline for backup/restores/empty. dynamodump supports local DynamoDB instances as w...
stdout_writer_solution.py
import random import sys import threading import time lock = threading.Lock() def write(): lock.acquire() sys.stdout.write("%s writing.." % threading.current_thread().name) time.sleep(random.random()) sys.stdout.write("..done\n") lock.release() threads = [] for i in range(50): thread = threa...
system.py
# Copyright 2014-2019 Chris Cummins <chrisc.101@gmail.com>. # # 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...
twisterlib.py
#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.fu...
batchprocess.py
import os.path as op import re import cv2 import numpy as np import pandas as pd import imgstore from imgstore import new_for_filename, new_for_format from imgstore.util import ensure_color from stitchup import Stitcher, StoreAligner, new_window import datetime, glob import os, sys import yaml c...
scanner.py
import optparse import socket import threading screenLock = threading.Semaphore(value=1) def connScan(tgtHost, tgtPort): try: connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connSkt.connect((tgtHost, tgtPort)) connSkt.send('SomeText\r\n') results = connSkt.recv(100) ...
manager.py
from dataclasses import dataclass import logging import threading import time import traceback from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Set, Tuple from concurrent.futures.thread import ThreadPoolExecutor from blspy import G1Element from chiapos import DiskProver from hddcoin.co...
test_util.py
# Copyright 2015 The TensorFlow Authors. 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 required by applica...
No_hop_host.py
from scapy.all import sendp, send, srp1, sniff from scapy.all import Packet, hexdump from scapy.all import Ether, BitEnumField, BitField, IP, ICMP from scapy.all import bind_layers import os import json import time import socket import sys import threading max_id=32 class No_hop(Packet): name = "No_hop" field...
application.py
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from sqlalchemy_utils.functions import database_exists from flask_cors import CORS from threading import Thread db = SQLAlchemy() def create_app(**config_overrides): app = Flask(__name__) ...
App.py
from threading import Thread from typing import Callable, Any from app.entities.Entity import Entity from app.systems.System import System class App: configuration = {} providers = [] services = {} systems = [] entities = {} def add_entity(self, function: Callable[[Any], Entity]) -> None: ...
core.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """PY4WEB - a web framework for rapid development of efficient database driven web applications""" # Standard modules import asyncio import cgitb import code import copy import datetime import enum import functools import http.client import http.cookies import importlib.ma...
fs-ty.py
import multiprocessing import sys import os import signal import dakota.interfacing as di import subprocess import glob sys.path.append('../../../scripts') import input as inp import output as oup import external_cym cycdir = '../../../cyclus-files/synergistic/fs-ty/' # ---------------------------- # Parse Dakota par...