source
stringlengths
3
86
python
stringlengths
75
1.04M
regen.py
#!/usr/bin/env python3 import os import time import multiprocessing from tqdm import tqdm import argparse # run DM procs os.environ["USE_WEBCAM"] = "1" import cereal.messaging as messaging from cereal.services import service_list from cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: d...
dp_utils.py
"""Utils for new predict method in pytorch DataParallel.""" import threading from itertools import chain from typing import List from typing import Optional import torch import torch.nn as nn from torch._utils import ExceptionWrapper from torch.cuda._utils import _get_device_index def get_a_var(obj): # noqa: D10...
lambda_executors.py
import base64 import contextlib import dataclasses import glob import json import logging import os import re import shlex import subprocess import sys import threading import time import traceback import uuid from multiprocessing import Process, Queue from typing import Any, Callable, Dict, List, Optional, Tuple, Unio...
shell.py
"""Common Shell Utilities.""" import os from subprocess import Popen, PIPE from multiprocessing import Process from threading import Thread from ..core.meta import MetaMixin from ..core.exc import FrameworkError def cmd(command, capture=True, *args, **kwargs): """ Wrapper around ``exec_cmd`` and ``exec_cmd2`...
run-tests.py
#!/usr/bin/env python3 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "L...
interface.py
from PyQt5 import QtCore, QtGui, QtWidgets, uic import sys import cv2 import numpy as np import threading import time import queue from playback import Player # Cam Params cam_running = False capture_thread = None q = queue.Queue() # Playback Params video_running = False video_thread = None vid = queue.Queue() # in...
spinner.py
import sys, time, threading #twirl_sequence = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|" #twirl_sequence = "v<^>" *4 + "^<v>" *4 #twirl_sequence = "dqpb" *4 + "pqdb" *4 #twirl_sequence = ".oO°Oo." #twirl_sequence = "░▒▓" twirl_sequence = "▙▛▜▟" #twirl_sequence = "1234" def spin_cursor(): while True: for c...
thread_new.py
import functools import time from threading import Thread def thread_new(key: str= '', daemon=True): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): t = Thread( target=lambda: func(*args, **kwargs), daemon=daemon ) ...
pyfinex.py
import websocket import threading import time from time import sleep import json import hmac import hashlib # API JSON KEYS KEY_CHANNEL_NAME = "channel" KEY_CHANNEL_ID = "chanId" KEY_EVENT = "event" # COMMON API JSON VALUES EVENT_SUBSCRIBED = "subscribed" # USEFUL STRINGS BFX_WEBSOCKET_ADDRESS = "wss://api2.bitfi...
check3.py
import asyncio from threading import Thread import os import math from multiprocessing import Process import argparse import datetime import time from telethon.tl.functions.contacts import ImportContactsRequest from telethon.tl.types import InputPhoneContact import config from save_util import save_user_info from sql...
email.py
# coding:utf8 from threading import Thread from flask import current_app, render_template from flask_mail import Message from . import mail def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): app = current_app._get_current_object()...
data_store_test.py
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """These are basic tests for the data store abstraction. Implementations should be able to pass these tests to be conformant. """ from __future__ import division import csv import functools import hashlib import inspect import logging import operator impor...
slp_graph_search.py
""" SLP Graph Search Client Performs a background search and batch download of graph transactions from gs++ server. For more information about the gs++ server see: https://github.com/blockparty-sh/cpp_slp_graph_search This class is currently only used by slp_validator_0x01.py. The NFT1 validator has not yet been att...
keyboard.py
from threading import Thread from time import time from pynput.keyboard import Listener from . import BaseModule class KeyboardModule(BaseModule): def __init__(self): super().__init__(name='keyboard', source=101) # Создаем поток для трекинга нажатий на клавиатуру # передаем в функцию ма...
tcp.py
# -*- coding: utf-8 -*- ''' TCP transport classes Wire protocol: "len(payload) msgpack({'head': SOMEHEADER, 'body': SOMEBODY})" ''' # Import Python Libs from __future__ import absolute_import import logging import msgpack import socket import os import weakref import time import traceback import errno # Import Salt...
test_io.py
"""Unit tests for the io module.""" # Tests of io are scattered over the test suite: # * test_bufio - tests file buffering # * test_memoryio - tests BytesIO and StringIO # * test_fileio - tests FileIO # * test_file - tests the file interface # * test_io - tests everything else in the io module # * test_univnewlines - ...
OS.py
from tkinter import * from tkinter.ttk import * import shutil import os import subprocess from functools import partial from threading import * import time import string from math import * def io(): def readthread(): print("Reading!!") time.sleep(10) def writethread(): print("Writing!!...
pixels.py
import apa102 as apa102 import time import threading try: import queue as Queue except ImportError: import Queue as Queue class Pixels: PIXELS_N = 3 def __init__(self): self.basis = [0] * 3 * self.PIXELS_N self.basis[0] = 1 self.basis[4] = 1 self.basis[8] = 2 self.colors = [0] * 3 * self.PIXELS_N se...
KinesisStreamHandler.py
__author__ = 'Omri Eival' from logging import StreamHandler from io import BufferedIOBase, BytesIO from boto3 import client from aws_logging_handlers.validation import is_string_func, is_non_empty_string, is_positive_int, empty_str_err, \ bad_integer_err, ValidationRule from aws_logging_handlers.tasks import Task,...
proxy.py
import socket from threading import Thread #Class for HTTP requests class Request: def __init__(self, orig: bytes): self.original = orig self.headers = {} self.bytes = b'' self.meta = '' self.host = None self.port = None @classmethod #Converts byte sequenc...
publisher.py
from iamzero.logging import configure_root_logger from iamzero.config import Config from iamzero.identity import Identity from typing import Any, List, Tuple from iamzero.event import Event from abc import ABC, abstractmethod import queue from urllib.parse import urljoin import gzip import io import json import thread...
communicate.py
import struct import serial from serial import * import sys import glob import time import threading import time from tkinter import * from PIL import Image, ImageTk, ImageColor from tkinter.ttk import Combobox from math import sin WIDTH = 600 HEIGHT = 800 QRCODEX = 200 QRCODEY = 200 QRCODESZ = 200 availableP...
state.py
import threading import json import time import re from talon import Context, ui from user.emacs.utils import rpc from user.utils.key_value_store import KeyValueStore VOICEMACS_TITLE_PREFIX = "voicemacs:" DATA_PENDING_KEY = "data" TITLE_CHECK_PAUSE = 0.002 emacs_state = KeyValueStore() # TODO: Yuck. Extract thi...
client.py
import socket import threading as thr import PySimpleGUI as sg import rsa from rsa import PublicKey HOST = 'server.srikar.tech' # change the host PORT = 55543 publicKey, privateKey = rsa.newkeys(2048) publicKeys = [] caesar_Key = 69 header_Size = 10 def caesar_Encrypt(string,s): result = "" for c in string: if c.is...
schedulers.py
# Copyright 2020; Raja Tomar # See license for more details import logging import threading import weakref from requests import ConnectionError from six import PY3 from six import string_types from six.moves.urllib.parse import urlparse from .elements import VoidResource from .elements import CSSResource from .elemen...
ajaxterm.py
#!/usr/bin/env python """ Ajaxterm """ import array,cgi,fcntl,glob,mimetypes,optparse,os,pty,random,re,signal,select,sys,threading,time,termios,struct,pwd os.chdir(os.path.normpath(os.path.dirname(__file__))) # Optional: Add QWeb in sys path sys.path[0:0]=glob.glob('../../python') import qweb import string, subproc...
keylog.py
def keylog(task_id): global responses global stopping_functions def get_active_window_title(): root = subprocess.Popen(['xprop', '-root', '_NET_ACTIVE_WINDOW'], stdout=subprocess.PIPE) stdout, stderr = root.communicate() m = re.search(b'^_NET_ACTIVE_WINDOW.* ([\w]+)$', stdout) ...
test.py
import os import time import multiprocessing as mp from multiprocessing.managers import BaseManager class ctrl(object): def __init__(self): print('init') def test(self): print('test') def do_step(self, x, t): time.sleep(t) print(os.getpid(), x) def ctrl_worker(ctrl, x, t): ...
train_faster_rcnn_alt_opt.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Train a Faster R-CNN network using alternat...
cronjobs.py
#!/usr/bin/env python """Cron management classes.""" import random import threading import time import logging from grr.lib import access_control from grr.lib import aff4 from grr.lib import config_lib from grr.lib import data_store from grr.lib import flow from grr.lib import master from grr.lib import queue_manag...
26_2_multithread_synchronization_rlock.py
from threading import Thread from threading import RLock import time start = time.time() num = 0 ################################# #为了保证数据的一致性 # #创建threading属性RLock的实例对象# ################################# rlock = RLock() def do_sth(): global num for i in range(1000000): """ # 上锁 ...
example_train.py
# -*- coding: utf-8 -*- """ Created on Sun Jul 14 16:14:07 2019 @author: truthless """ import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) import numpy as np import torch from torch import multiprocessing as mp from convlab2.dialog_agent.agent import PipelineAgen...
runweb.py
"""This file is for dev server only. DO NOT USE FOR PROD """ from gevent import monkey monkey.patch_all() from lib.patch import patch_all patch_all() import multiprocessing import os import shlex import sys import subprocess import gevent.pywsgi import gevent.socket from app.server import flask_app def main...
eea_runtime_pywasm3.py
# # This module contains an example pywasm3 runtime. # https://github.com/wasm3/pywasm3 # import json import os import threading import time import wasm3 import eea_api import eea_utils import eea_registered_functions # Initialize an instance of the EEA. def init(device_id, eea_queue, mqtt_queue, persisted_bundl...
exposition.py
import base64 from contextlib import closing from http.server import BaseHTTPRequestHandler import os import socket from socketserver import ThreadingMixIn import sys import threading from urllib.error import HTTPError from urllib.parse import parse_qs, quote_plus, urlparse from urllib.request import ( build_opener...
trainer.py
# Lint as: python3 # Copyright 2018 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 ...
react_touch.py
#http://doc.aldebaran.com/2-5/naoqi/core/almemory-api.html #http://doc.aldebaran.com/2-5/naoqi/sensors/altouch-api.html #http://doc.aldebaran.com/2-5/dev/libqi/api/python/signal.html #http://doc.aldebaran.com/2-5/family/pepper_technical/pepper_dcm/actuator_sensor_names.html import qi import argparse import sys import ...
keep_alive.py
from flask import Flask from threading import Thread app = Flask('') @app.route('/') def main(): return "Add KOOLIOMAN to your server, today!" def run(): app.run(host="0.0.0.0", port=8080) def keep_alive(): server = Thread(target=run) server.start()
kube.py
""" Script to start a production server on Kubernetes. This script can serve as the mainApplicationFile for the SparkApplication custom resource of the spark-operator """ import logging import os import threading from logging.config import dictConfig from openeo_driver.server import run_gunicorn from openeo_driver.vi...
test_thread.py
import sys import cffi cfile_name = sys.argv[1] ffibuilder = cffi.FFI() # the API exported by the python code ffibuilder.embedding_api(""" void py_tick(const char *line); const char *py_get_output(void); void py_init(void); """) # declare things that the python code wants to use # wrappers are generated...
test_memcached_backend.py
import os import ssl from threading import Thread import time from unittest import mock from unittest import TestCase import weakref import pytest from dogpile.cache import make_region from dogpile.cache.backends.memcached import GenericMemcachedBackend from dogpile.cache.backends.memcached import MemcachedBackend fr...
controller.py
import tkinter as tki from tkinter import Toplevel, Scale import threading import datetime import os import time import platform class TelloUI(object): """ Wrapper class to enable the GUI. """ def __init__(self, tello): """ Initializes all the element of the GUI, supported by Tkinter ...
test_ssl.py
# Test the support for SSL and sockets import sys import unittest from test import test_support import asyncore import socket import select import time import gc import os import errno import pprint import urllib, urlparse import traceback import weakref import functools import platform from BaseHTTPServer import HTT...
AuthMatrix.py
# Copyright (c) 2016 Mick Ayzenberg - Security Innovation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify...
server.py
import asyncio import multiprocessing import os import sys import traceback from collections import deque from functools import partial from inspect import isawaitable from signal import SIG_IGN, SIGINT, SIGTERM, Signals from signal import signal as signal_func from socket import SO_REUSEADDR, SOL_SOCKET, socket from ...
5min_alert_host_network_rx.py
''' Test about monitor trigger on host network rx in five minutes @author: Songtao,Haochen ''' import os import test_stub import random import threading import time import zstacklib.utils.ssh as ssh import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_operations as res_ops imp...
e3dcwebgui.py
import logging logger = logging.getLogger(__name__) import hashlib import math import struct import threading import traceback from e3dc._rscp_utils import RSCPUtils from e3dc.e3dc import E3DC from e3dc.rscp_helper import rscp_helper try: import thread except ImportError: import _thread as thread import ti...
util.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Various low-level utilities. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime import json import math import os import re import select import si...
test.py
import logging import time import os import pytest from helpers.cluster import ClickHouseCluster, get_instances_dir from helpers.utility import generate_values, replace_config, SafeThread SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CONFIG_PATH = os.path.join( SCRIPT_DIR, "./{}/node/configs/confi...
__init__.py
""" Create ssh executor system """ import base64 import binascii import copy import datetime import getpass import hashlib import logging import multiprocessing import os import queue import re import subprocess import sys import tarfile import tempfile import time import uuid import salt.client.ssh.shell import salt...
py_utils.py
# Lint as: python3 # Copyright 2018 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 ...
proxy.py
#!/usr/bin/env python3 from argparse import ArgumentParser import binascii import logging import socket import ssl import threading logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def send_message(dns, query, ca_path): server = (dns, 853) sock = socket.socket(socket.AF_INET, so...
conftest.py
import faulthandler import io import logging.handlers import multiprocessing as mp import os import signal import sys import threading from collections import namedtuple from os import getenv from pathlib import Path from random import randint from zipfile import ZipFile import pytest TEST_DATA = "data" TEST_PYBIO_ZI...
multiprocessing_env.py
#This code is from openai baseline #https://github.com/openai/baselines/tree/master/baselines/common/vec_env import numpy as np from multiprocessing import Process, Pipe def worker(remote, parent_remote, env_fn_wrapper): parent_remote.close() env = env_fn_wrapper.x() while True: cmd, data = remote...
slp_dagging.py
""" Breadth-first DAG digger for colored coins. We do a breadth-first DAG traversal starting with the transaction-of-interest at the source, and digging into ancestors layer by layer. Along the way we prune off some connections, invalidate+disconnect branches, etc., so our 'search DAG' is a subset of the transaction D...
test_win32file.py
import unittest from pywin32_testutil import str2bytes, TestSkipped, testmain import win32api, win32file, win32pipe, pywintypes, winerror, win32event import win32con, ntsecuritycon import sys import os import tempfile import threading import time import shutil import socket import datetime import random import win32tim...
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
backend_spotify.py
""" https://github.com/drshrey/spotify-flask-auth-example https://github.com/plamere/spotipy/issues/194 https://spotipy.readthedocs.io/en/latest/ https://developer.spotify.com/dashboard/ https://developer.spotify.com/documentation/general/guides/scopes/ https://developer.spotify.com/documentation/web-api/reference/...
macdirectorywatcher.py
import threading import AppKit import FSEvents class DirectoryWatcher: DIE = 'DIE' def __init__(self, directory, onFileChange, onResetAll): self.__directory = directory self.__onFileChange = onFileChange self.__onResetAll = onResetAll self.__started = threading.Event() ...
utils.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
tnaRun.py
from runGame import * BOOTSRAP_FILE = "game1" AGENTS = "temporaryName,TUC_TAC" AGENT_INFO = {"temporaryName": ["brokers/temporaryName", "temporaryName-1.7.0.jar"], "TUC_TAC": ["brokers/TUC_TAC", "TUC_TAC_2020.jar"]} #AGENTS = "TUC_TAC" #AGENT_INFO = {"TUC_TAC": ["brokers/TUC_TAC", "TUC_TAC...
main_engine.py
import importlib import os import pathlib import signal import sys import threading import time from collections import OrderedDict from threading import Thread, Lock #import easytrader from logbook import Logger, StreamHandler from .event_engine import EventEngine from .log_handler.default_handler import DefaultLogH...
shm_multiproc.py
import ctypes import numpy as np from multiprocessing import Pipe, Process from multiprocessing.sharedctypes import RawArray from . import Env, Space START, STEP, RESET, STOP, DONE = range(5) class ShmProcEnv(Env): def __init__(self, env, idx, shm): super().__init__(env.id) self._env, self.idx, s...
dataset.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-05-09 20:27 import math import os import random import tempfile import warnings from abc import ABC, abstractmethod from copy import copy from logging import Logger from typing import Union, List, Callable, Iterable, Dict import torch import torch.multiprocessing as...
assemble.py
# # Copyright (c) 2009-2021 steelpy # # Python stdlib imports from itertools import chain import math as math import pickle import time from typing import Dict, List, Tuple # , ClassVar, Iterable, Union #from multiprocessing import Process, Manager # package imports from steelpy.trave3D.processor.operations import ze...
server.py
#!/usr/bin/env python3 import argparse import http.server import json import logging import os import shutil import signal import socketserver import threading import webbrowser try: import setproctitle setproctitle.setproctitle('pmserver') except Exception: pass # Set up logger logging.basicConfig( ...
test_numpy.py
from __future__ import division, absolute_import, print_function import queue import threading import numpy as np import pytest from numpy.random import random from numpy.testing import ( assert_array_almost_equal, assert_array_equal, assert_raises, ) import scipy.fft as fft def fft1(x): L = len(x...
task.py
import atexit import os import signal import sys import threading import time from argparse import ArgumentParser from collections import OrderedDict, Callable import psutil import six from .backend_api.services import tasks, projects from .backend_interface import TaskStatusEnum from .backend_interface.model import ...
main.py
from queue import Queue import requests import random from typing import List import queue import threading import string import logging import time class NitroGen: def __init__( self, numberOfCodes: int, nitroType: str, numberOfThreads: int ) -> None: logging.basicConfig(format="%(message)s",...
server.py
import base64 import contextlib import hashlib import io import os import logging import queue import select import socket import struct import subprocess import sys import threading import time from enum import Enum from http.server import BaseHTTPRequestHandler from itertools import cycle from .proto import message...
globalVariables.py
from apiKeys import * import random from playsound import playsound import threading import os import time # Variables - Tunable params VOICE_GENDER = "female" VOICE_RATE = 165 # Microphone Tunable params CAL_DURATION = 1 # Seconds PAUSE_THRESH = 0.8 # Seconds DAMPING_RATIO = 0.7 # Def...
combi_source.py
import requests import time import base64 import ecdsa def wallet(): response = None while response not in ["1", "2", "3","4"]: response = input("""What do you want to do? 1. Generate new wallet 2. Send coins to another wallet 3. Check transactions 4. Quit\n""") i...
unity_server.py
import cv2 import numpy as np from simple_websocket_server import WebSocketServer, WebSocket import logging from ROAR.utilities_module.vehicle_models import VehicleControl import threading frame = None throttle = 0 steering = 0 class SimpleUnityWebsocketServer(WebSocket): def handle(self): global frame, ...
Rerequester.py
# Written by Bram Cohen # modified for multitracker operation by John Hoffman # see LICENSE.txt for license information from OCSBttrack.zurllib import urlopen, quote from urlparse import urlparse, urlunparse from socket import gethostbyname from btformats import check_peers from OCSBttrack.bencode import bdecode from ...
run_benchmarks.py
#!/usr/bin/env python # Copyright 2012 Cloudera 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 ag...
download_bucket.py
# Copyright 2018 Amazon Research Cambridge # # 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...
rdd.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
SensorThreads.py
from Sensors import IMU from Sensors import UltrasonicSensor as us #from Communication import ArduinoCommunication as ac import threading import time #Declare Gloabal Variables _distance = 0 _imu_gyro_x = 0 _imu_gyro_y = 0 _imu_gyro_z = 0 _speed = 0 class SensorThread(): def __init__(self): self.imu = IMU...
test_logging.py
# Copyright 2001-2017 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permissio...
magnet_to_torrent_aria2c.py
#!usr/bin/python # encoding=utf8 import subprocess from threading import Thread from .database import RedisClient SAVE_PATH = ".\\torrents" STOP_TIMEOUT = 60 MAX_CONCURRENT = 16 MAX_MAGNETS = 256 CMD = ( "aria2c -d {save_path} " "--bt-metadata-only=true " "--bt-save-metadata=true " "--listen-port=68...
dev_one_stream.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # File: dev_one_stream.py # # Part of ‘UnicornFy’ # Project website: https://www.lucit.tech/unicorn-fy.html # Github: https://github.com/LUCIT-Systems-and-Development/unicorn-fy # Documentation: https://unicorn-fy.docs.lucit.tech/ # PyPI: https://pypi.org/project/unicorn...
dl_ani24.py
from ._utils import * baseURL = 'https://ani24do.com' async def GetOneVideoURL(aniLink, loop): soup = await GetSoup(aniLink, referer=aniLink, loop=loop) epiTitle = soup.find('div', {'class':'view_info_box'}).find_all('div')[0].text bigTitle = ' '.join(epiTitle.split(' ')[0:-1]) epiIDs = aniLink.s...
test_semaphore.py
import unittest from typing import Callable from threading import Thread from homeworks.homework_6.task_1.semaphore import Semaphore def run_threads(target: Callable, threads_quantity: int): """ Runs given number of threads perfoming giving function. """ threads = [Thread(target=target) for i in rang...
workerresource.py
import collections import dataclasses import gc import multiprocessing import os from multiprocessing import Lock, Pipe, Pool, Process, Value from typing import Any, Callable, Dict, Iterable, List, NewType, Tuple, Union from .exceptions import (UserFuncRaisedException, WorkerDiedError, WorkerI...
SaniTrendCloud.py
#test import platform import json from pycomm3.exceptions import CommError import threading import time from datetime import datetime from requests.models import HTTPError import requests import os from ftplib import FTP import shutil import psutil # Overall Configuration Class to import that has # auxillary function...
utils.py
# Copyright 2020 - 2021 MONAI Consortium # 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 wri...
core_test.py
# Copyright 2017 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...
QTMainView.py
# -*- coding: utf-8 -*- from PySide import QtCore, QtGui from PySide.QtGui import * import requests, json, os import threading from Uploader import rec, selectFile, sendAudioMessage import QTLogin # rec('record.mp3', rate=20000) # selectFile('record.mp3') # sendAudioMessage(31) class MainView(object): def setupUi(...
mysql_test.py
#!/usr/bin/env python import logging import os import random import string import threading import unittest # TODO(hanuszczak): This should be imported conditionally. import MySQLdb import unittest from grr.server.grr_response_server import db_test_mixin from grr.server.grr_response_server import db_utils from grr.se...
PlexConnect.py
#!/usr/bin/env python """ PlexConnect Sources: inter-process-communication (queue): http://pymotw.com/2/multiprocessing/communication.html """ import sys, time from os import sep import socket from multiprocessing import Process, Pipe import signal, errno from Version import __VERSION__ import DNSServer, WebServer...
multi_launcher.py
""" This module contains methods for launching several Rockets in a parallel environment """ import os import threading import time from multiprocessing import Manager, Process from fireworks.core.rocket_launcher import rapidfire from fireworks.fw_config import ( DS_PASSWORD, PING_TIME_SECS, RAPIDFIRE_SLE...
maalserver.py
#!/usr/bin/env python3 import asyncore import datetime import smtpd import threading import time from flask import Flask, render_template from pymongo import MongoClient # Global and configs SMTP_IP = "127.0.0.1" SMTP_PORT = 25 FLASK_SERVER = "localhost:8000" MONGO_DB = "maal-database" MONGO_SERVER = "localhost" mo...
test_launcher.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Copyright 2017-2020 Baidu 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...
game.py
import os.path import pickle import threading import time import pygame from pygame.locals import KEYDOWN from clientmedia import voice, play_sequence import clientgame from clientgameorder import update_orders_list import definitions import config from constants import METASERVER_URL, PROFILE from definitions import...
displacy.py
# coding: utf8 import plac import threading import time import webbrowser from spacy import displacy from sudachipy.tokenizer import Tokenizer as OriginalTokenizer from . import * from .bccwj_ud_corpus import convert_files from .corpus import * from .parse_tree import correct_dep from .sudachi_tokenizer import SUDACHI_...
test_tracer.py
# -*- coding: utf-8 -*- """ tests for Tracer and utilities. """ import contextlib import multiprocessing import os from os import getpid import threading from unittest.case import SkipTest import warnings import mock import pytest import six import ddtrace from ddtrace.constants import ENV_KEY from ddtrace.constants ...
15-3_detect_fire.py
#!/usr/bin/env python #-*- coding: utf-8 -*- #불을 발견하고 이에 따라 비행을 제어하는 코드. import rospy, sys, cv2, os, datetime, time, threading from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from geometry_msgs.msg import Twist class DetectFire: def __init__(self): ...
observer.py
import logging import threading from typing import Any from typing import Dict from typing import List from typing import Callable obs_log = logging.getLogger(__name__) obs_log.addHandler(logging.NullHandler()) default_subscriber = [ lambda event_name, data: obs_log.debug( f"Default Observer: event_name...
napari_frontend.py
from pycromanager import start_headless from pycromanager import Acquisition, multi_d_acquisition_events from napari.qt.threading import thread_worker import threading import napari import numpy as np import time # Optional: start pycro-manager in headless mode mm_app_path = '/Applications/Micro-Manager-2.0.0-gamma1' ...
base_camera.py
import time import threading try: from greenlet import getcurrent as get_ident except ImportError: try: from thread import get_ident except ImportError: from _thread import get_ident class CameraEvent(object): """An Event-like class that signals all active clients when a new frame is ...