source
stringlengths
3
86
python
stringlengths
75
1.04M
testing.py
""" Testing utilities. """ import os import re import threading import functools from tempfile import NamedTemporaryFile import numpy as np from numpy import testing from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_array_less, assert_array_almost_equal_nulp, ...
A3C.py
import multiprocessing # 多线程模块 import threading # 线程模块 import queue import tensorflow as tf import numpy as np import gym import os import shutil # 拷贝文件用 import matplotlib.pyplot as plt from FeudalBatchProcessor import FeudalBatchProcessor import policy_utils from LSTMmodel import SingleStepLSTM Game = 'CartPole-v0...
engine.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/04/15 22:55 # @Author : Xu # @Site : https://xuccc.github.io/ import time import schedule import signal from threading import Thread from colorama import Fore from typing import Dict from core.log import Log from core.db import init_database from cor...
ThreadShare.py
# References # https://www.geeksforgeeks.org/time-perf_counter-function-in-python/ # https://docs.python.org/3/library/threading.html # https://realpython.com/intro-to-python-threading/ import threading # Python program to show time by perf_counter() myvar = 1 # var under observation def thread_function(name): ...
controller.py
import os import re import traceback from datetime import datetime from math import floor from pathlib import Path from threading import Thread from typing import List, Set, Type, Tuple, Optional from bauh.api.abstract.controller import SearchResult, SoftwareManager, ApplicationContext, UpgradeRequirements, \ Upgr...
install.py
import enum from os import PathLike import gdown import click from pathlib import Path from dotenv import dotenv_values from pydrive import auth from pydrive.files import ApiRequestError import questionary as que import threading from pydrive.drive import GoogleDrive from pydrive.auth import GoogleAuth from yesc.utils ...
lldb.py
from __future__ import annotations from ..typecheck import * from ..import core from ..import ui from ..debugger import dap from ..views.input_list_view import InputListView from ..import commands from ..import settings from .import util import re import threading import socket class LLDBTransport(dap.SocketTran...
replay_actions.py
#!/usr/bin/python # Copyright 2017 Google Inc. 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 ...
test_cuda.py
# Owner(s): ["module: cuda"] from itertools import repeat, chain, product from typing import NamedTuple import collections import contextlib import ctypes import gc import io import pickle import queue import sys import tempfile import threading import unittest import torch import torch.cuda import torch.cuda.comm as...
user.py
#!/usr/bin/env python2.7 import argparse # new in Python2.7 import os import time import string import atexit import threading import logging import sys from yapsy.PluginManager import PluginManager # Load the plugins from the plugin directory. manager = PluginManager() manager.setPluginPlaces(["plugins"]) manager.c...
http_server_test.py
# Copyright 2017 Google Inc. 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 applicable law or a...
async_checkpoint.py
# 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 required by applica...
spunky.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Spunky Bot - An automated game server bot http://www.spunkybot.de Author: Alexander Kress This program is released under the MIT License. See LICENSE for more details. ## About ## Spunky Bot is a lightweight game server administration bot and RCON tool, inspired by t...
__init__.py
#!/usr/bin/env python # encoding: utf-8 # Copyright (c) 2016-2017, Stadt Karlsruhe (www.karlsruhe.de) # # 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...
tests.py
# Unit tests for cache framework # Uses whatever cache backend is set in the test settings file. import copy import io import os import pickle import re import shutil import tempfile import threading import time import unittest from pathlib import Path from unittest import mock from django.conf import settings from dj...
txn_processor.py
from typing import Dict, List from threading import Thread, get_ident from time import sleep from occ.typings.transaction import Transaction from occ.database import Database, DatabaseCacheExecutorWrapper from utils.mutex import Mutex class TxnProcessor: def __init__(self, db: 'SerialDatabase') -> None: self.db...
plugin.py
# Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO # 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 ...
test_program_for_PhidgetsAdvancedServo8MotorRCC0004_ReubenPython2and3Class.py
# -*- coding: utf-8 -*- ''' Reuben Brewer, Ph.D. reuben.brewer@gmail.com, www.reubotics.com Apache 2 License Software Revision F, 03/13/2022 Verified working on: Python 2.7, 3.8 for Windows 8.1, 10 64-bit and Raspberry Pi Buster (no Mac testing yet). ''' __author__ = 'reuben.brewer' from PhidgetsAdv...
key_poll.py
#!/usr/bin/python3 import os from select import select from threading import Thread from evdev import InputDevice, ecodes from logger import ebf_logger LOGGER = ebf_logger(__name__) keyInputPath = r"/dev/input/by-path/platform-gpio-keys-event" onOffInputPath = r"/dev/input/by-path/platform-20cc000.snvs:snvs-powerkey...
rabbit_queue.py
# -*- coding: utf-8 -*- import time import threading import pika from studio.storage.storage_setup import get_storage_verbose_level from studio.util import logs class RMQueue: """This publisher will handle failures and closures and will attempt to restart things delivery confirmations are used to track ...
lin_recon_payload.py
import socket, os, pickle, ctypes, pyaudio, wave, pyxhook, alsaaudio, subprocess, re, webbrowser, cv2 from threading import Thread from platform import platform from getpass import getuser from time import sleep from datetime import datetime from mss import mss port = !!!!! ip_addr = @@@@@ lkey = ##### End = $$$$$ ske...
test_dht_node.py
import asyncio import heapq import multiprocessing as mp import random import signal from itertools import product from typing import List, Sequence, Tuple import numpy as np import pytest from multiaddr import Multiaddr import hivemind from hivemind import get_dht_time from hivemind.dht.node import DHTID, DHTNode fr...
snapraid-runner.py
#!/usr/bin/env python3 # -*- coding: utf8 -*- from __future__ import division import argparse import logging import logging.handlers import os.path import subprocess import sys import threading import time import traceback from collections import Counter, defaultdict if sys.version_info[0] > 2: import configparse...
emailbot.py
#Standard library modules import sys import threading import re import time import datetime import traceback #Additional modules import euphoria as eu from emailbot.euphutils import EuphUtils #Project modules import emailbot.mailer as mailer import emailbot.logger as logger import emailbot.longmessage_room as longme...
task_launcher.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # TODO(#99) do we standardize some kinds of data loader formats? perhaps # one that loads from files, and then an arbit...
store_gc_service_test.py
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import threading import time from pants.pantsd.service.store_gc_service import StoreGCService from pants.testutil.rule_runner import RuleRunner def test_run() -> None: interval_secs...
eeg.py
""" Abstraction for the various supported EEG devices. 1. Determine which backend to use for the board. 2. """ import sys import time import logging from time import sleep from multiprocessing import Process import numpy as np import pandas as pd from brainflow import BoardShim, BoardIds, BrainFlowInputPar...
test_mcrouter_basic.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from threading import Thread import time from mcrouter.test.MCProcess import McrouterClient, Memcached, Mcrouter from...
process_replay.py
#!/usr/bin/env python3 import importlib import os import sys import threading import time import signal from collections import namedtuple import capnp import cereal.messaging as messaging from cereal import car, log from cereal.services import service_list from common.params import Params from common.timeout import ...
plugin.py
import requests.exceptions import time from collections import defaultdict from aqt import mw from aqt.utils import showInfo, askUser, showWarning from aqt.qt import * from anki.utils import splitFields, ids2str from .duolingo_dialog import duolingo_dialog from .duolingo import Duolingo, LoginFailedException from .d...
control_manager.py
""" "Joint" control model capable of merging data from several driving modes. """ from multiprocessing import Process from .model import ControlModel from .converter import Converter from ..enums import DrivingMode from ..constants.control import CONTROL_MANAGER_NAME, CONTROL_MANUAL_NAME, CONTROL_AUTONOMOUS_NAME, CONTR...
catalog_collections.py
"""Catalog collections within the execution environment.""" import argparse import hashlib import json import multiprocessing import os import re import subprocess import sys from collections import Counter from collections import OrderedDict from datetime import datetime from glob import glob from json.decoder import...
treasury.py
import logging import threading import time from brownie import ZERO_ADDRESS, Contract, chain, web3 from brownie.network.event import EventLookupError from eth_abi import encode_single from eth_utils import encode_hex from joblib import Parallel, delayed from yearn.constants import (ERC20_TRANSFER_EVENT_HASH, ...
main.py
from redash.app import create_app from redash.utils import rq, data_sources, users from multiprocessing import Pool, freeze_support, Process,current_process import os import psutil import sys import getopt import dotenv from functools import partial import requests import time app = create_app() def run_process(proces...
espresso-mpc.py
#!/usr/bin/python def he_control_loop(dummy, state): from time import sleep from datetime import datetime, timedelta import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(conf.he_pin, GPIO.OUT) GPIO.output(conf.he_pin,0) try: while True: control_signal = state['control_signal'] # P...
decorators.py
import threading import time """ Файл для написания декораторов приложения """ def thread(func): """Декоратор для запуска функции в отдельном потоке""" def wrapper(*args, **kwargs): ch1 = threading.Thread(target=func, args=args, kwargs=kwargs) ch1.start() return wrapper def pause(t=1): ...
custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
dx_skel.py
#!/usr/bin/env python # Corey Brune - Feb 2017 #Description: # This is a skeleton script which has all of the common functionality. # The developer will only need to add the necessary arguments and functions # then make the function calls in main_workflow(). #Requirements #pip install docopt delphixpy.v1_8_0 #The belo...
related.py
import json import threading import time import queue from requests.exceptions import HTTPError, ReadTimeout import random from playstoreapi.googleplay import GooglePlayAPI, LoginError from gplaycrawler.utils import get_logger # def details(packageName): # d = api.details(packageName) # filename = packageNa...
postgresql.py
import json import datetime, time import itertools import psycopg2 import decimal import os import multiprocessing from multiprocessing import Queue from common import util import queue import threading from threading import Thread class IDEBenchDriver: def init(self, options, schema, driver_arg): self.ti...
test_functools.py
import abc import builtins import collections import copy from itertools import permutations import pickle from random import choice import sys from test import support import time import unittest from weakref import proxy import contextlib try: import threading except ImportError: threading = None import func...
test_disk_general.py
#!/usr/bin/python # -*- coding: utf-8 -*- # DATE: 2022/1/19 # Author: clarkmonkey@163.com import os import sqlite3.dbapi2 as sqlite3 import threading import time from typing import NoReturn import pytest from cache3 import SimpleDiskCache from cache3.disk import SessionDescriptor # api >>> SessionDescriptor.__set_...
serverside.py
#!/usr/bin/env python3 import socket import sqlite3 import threading import time import traceback from datetime import datetime from constants import * lock = threading.Lock() data_from_db = {} # : dict[int, tuple[bool, bytes]] data_to_db = {} # : dict[int, tuple[bool, bytes]] next_chunk_ids = {} # : dict[int, in...
imagestream.py
from datetime import datetime from threading import Thread from queue import Queue from collections import deque # from asyncio import Lock from threading import Lock import time import cv2 class ImageStream: """ Maintains a queue of the N most recent frames from a live video stream. Older frames are disc...
test.py
# -*- coding: utf-8 -*- import redis import unittest from hotels import hotels import random import time from RLTest import Env from includes import * def testAdd(env): if env.is_cluster(): raise unittest.SkipTest() r = env env.assertOk(r.execute_command( 'ft.create', 'idx', 'schema', 'ti...
5min_alert_host_disk_read_bandth.py
''' Test about monitor trigger on host disk reading bandwidth in five minutes @author: Songtao,Haochen ''' import os import test_stub import random import time import threading import zstacklib.utils.ssh as ssh import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource...
client.py
__author__ = 'tanel' import argparse from ws4py.client.threadedclient import WebSocketClient import time import threading import sys import urllib import queue as Queue #from multiprocessing import Queue import json import time import os def rate_limited(maxPerSecond): minInterval = 1.0 / float(maxPerSecond) ...
_testing.py
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import operator import os from shutil import rmtree import string import tempfile from typing import Any, Callable, ContextManager, List, Optional, Type, Union, cast imp...
standalone_test.py
"""Tests for acme.standalone.""" import os import shutil import socket import threading import tempfile import unittest from six.moves import http_client # pylint: disable=import-error from six.moves import queue # pylint: disable=import-error from six.moves import socketserver # type: ignore # pylint: disable=imp...
test_flatmap_runner.py
# Copyright 2021 Zilliz. 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 applicable law or agree...
dos-server.py
import SocketServer import os import socket import struct import threading import time import sys ## Class from ## https://stackoverflow.com/questions/1312331/using-a-global-dictionary-with-threads-in-python class ThreadSafeDict(dict) : def __init__(self, * p_arg, ** n_arg) : dict.__init__(self, * p_arg, ...
remote_agent_buffer.py
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # 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 us...
musicdata_lms.py
#!/usr/bin/python # coding: UTF-8 # musicdata service to read from LMS # Written by: Ron Ritchey import json, threading, logging, queue, time, sys, urllib.request, urllib.parse, urllib.error, pylms, getopt, telnetlib, urllib.parse from pylms import server from . import musicdata class musicdata_lms(musicdata.musicd...
tests.py
#-*- coding:utf-8 -*- import unittest from contextlib import contextmanager from datetime import datetime from time import sleep import mock from pytest import fail from tornado import gen from tornado import testing from pybreaker import * class CircuitBreakerStorageBasedTestCase(object): """ Mix in to te...
musca.py
import threading import time from threading import Lock from astropy import units as u from panoptes.utils import error, get_quantity_value from panoptes.utils.time import CountdownTimer from panoptes.pocs.dome.abstract_serial_dome import AbstractSerialDome class Protocol: # device names SHUTTER = 'Shutter'...
__init__.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2021, Nigel Small # # 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 # # Unle...
rhcnode_record_desktop.py
#!/usr/bin/env python3 # Copyright (c) 2019, The Personal Robotics Lab, The MuSHR Team, The Contributors of MuSHR # License: BSD 3-Clause. See LICENSE.md file in root directory. import cProfile import os import signal import threading import random import numpy as np import rospy from ackermann_msgs.msg import Acker...
stats.py
#!/usr/bin/env python3 # coding=utf-8 # SysRq ScadsStats. Finding active users on VK walls. # Copyright (C) 2015-2016 Matvey Vyalkov # # This file is part of SysRq VK Stats. # # SysRq VK Stats is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
dump.py
import os,threading semester="F19" semester_full="Fall2019" useragent='"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"' baseLecURL="http://www.cse.buffalo.edu/~lusu/cse4589/"+semester_full+"/ClassNotes/" baseHWURL="http://www.cse.buffalo.edu/~lusu/cs...
miniterm.py
#!/Users/vcrizpy/Desktop/dapps/ethnewdelhi/m2m-vtol/demo_remote_server/m2m/bin/python3 # # Very simple serial terminal # # This file is part of pySerial. https://github.com/pyserial/pyserial # (C)2002-2015 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause import codecs import os import sys ...
try_stream.py
import sys import os import time import threading import zmq import numpy as np from pi_client import ClientStreamer from message_receiver import MessageReceiver connection_flag = False messaging_socket = zmq.Context().socket(zmq.SUB) messaging_socket.bind('tcp://*:5051') #messaging_socket.bind('tcp://18.214.123.134:...
client.py
"""VRKnock WebSocket Client""" import _thread from asyncio.locks import Event import threading import time import websocket import asyncio import json from custom_components.vrknock_client.const import VERSION PORT = 16945 class VRKnockClient: def __init__(self, host: str, code: str, mode: str = "direct") -> No...
resultdump.py
import os import json import time import logging from glob import glob from threading import Thread from threading import RLock from queue import Queue from queue import Empty from datetime import datetime from datetime import timedelta from enum import Enum from sbws.globals import RESULT_VERSION, fail_hard from sbws....
_dask.py
""" Dask Distributed Tools - dask_compute_stream """ import queue import threading from random import randint from typing import Any, Iterable import dask.bag import structlog import toolz from dask.distributed import Client from datacube_alchemist.settings import AlchemistSettings _LOG = structlog.get_logger() ...
test_writer_service.py
import threading from threading import Thread from unittest.mock import MagicMock import pytest from datastore.shared.di import injector from datastore.shared.services import EnvironmentService, ReadDatabase from datastore.writer.core import ( Database, Messaging, OccLocker, RequestCreateEvent, Re...
apmserver.py
from datetime import datetime, timedelta import json import os import re import shutil import subprocess import sys import threading import time import unittest from urllib.parse import urlparse from elasticsearch import Elasticsearch, NotFoundError import requests import libbeat_paths from beat.beat import INTEGRATI...
hn_async2.py
import asyncio import aiohttp from tqdm import tqdm import json import sqlite3 import queue import threading DB_NAME = "hn2.db3" def create_db(db_name): with sqlite3.connect(db_name) as db: db.execute( "CREATE TABLE IF NOT EXISTS hn_items(id int PRIMARY KEY, item_json text)" ) ...
syslog_streamer.py
import time import signal import socket import multiprocessing MESSAGE = ( b'158 <46>1 2013-04-02T14:12:04.873490-05:00 tohru rsyslogd - - - ' b'[origin software="rsyslogd" swVersion="7.2.5" x-pid="12662" x-info=' b'"http://www.rsyslog.com"] start') TEST_DURATION = 60 OUTPUT = str('Sent {} messages in {}...
wtiproj03_client.py
import wti03_ETL import requests import json import threading import time def fuction(): r = requests.get('http://localhost:8888/ratings') wti03_ETL.print_request(r) r = requests.post('http://localhost:8888/rating', json.dumps({ "userID": 75, "movieID": 110, "rating": 4, "...
brain.py
""" Brain class - high level behavior and emotion engine. """ from typing import Optional from threading import Thread from queue import Queue, Empty import time from . import logger, logger_reaction, logger_behavior from . import client from . import event from . import emotions from . import behavior from . impor...
datasets.py
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Dataloaders and dataset utils """ import glob import hashlib import json import logging import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool, Pool from pathlib import Path from threading import Thread ...
webApp.py
import Queue import threading import os import urllib2 threads = 10 target = "http://xperblueray.com" directory = "/usr/blueray/Downloads/pytest" filters = [".jpg",".gif","png",".css"] os.chdir(directory) web_paths = Queue.Queue() for r,d,f in os.walk("."): for files in f: remote_path = "%s/%s" ...
websockets.py
#!/usr/bin/env python3 # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # 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 withou...
destination.py
#!/usr/bin/env python import hashlib # used for generating md5 Checksums import socket # for python Socket API import struct # used in decoding and encoding messages import threading # used for multithreaded structure import time # used to generate timestamps # Destination node ## Notice that, RDT protocol impleme...
datasets.py
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Dataloaders and dataset utils """ import glob import hashlib import json import logging import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool, Pool from pathlib import Path from threading import Thread ...
lenovo_fix.py
#!/usr/bin/env python3 from __future__ import print_function import argparse import configparser import glob import gzip import os import re import struct import subprocess import sys from collections import defaultdict from datetime import datetime from errno import EACCES, EPERM from multiprocessing import cpu_count...
simulation_3.py
''' Created on Oct 12, 2016 @author: mwittie ''' import network_3 as network import link_3 as link import threading from time import sleep ##configuration parameters router_queue_size = 0 #0 means unlimited simulation_time = 1 #give the network sufficient time to transfer all packets before quitting if __name__ == '...
test_transaction.py
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license import time import pytest import dns.name import dns.rdataclass import dns.rdatatype import dns.rdataset import dns.rrset import dns.transaction import dns.versioned import dns.zone class DB(dns.transaction.TransactionManager): def __i...
timed_subprocess.py
""" For running command line executables with a timeout """ import shlex import subprocess import threading import salt.exceptions import salt.utils.data class TimedProc: """ Create a TimedProc object, calls subprocess.Popen with passed args and **kwargs """ def __init__(self, args, **kwargs): ...
Misc.py
## @file # Common routines used by all tools # # Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR> # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the lic...
presence.py
import subprocess import RPi.GPIO as GPIO import csv import datetime from time import sleep from threading import Thread # Edit these for how many people/devices you want to track occupant = ["NOME"] # MAC addresses for our phones address = ["00:00:00:00:00:00"] #GPIO pin that we use pin = 14 # Sleep once right wh...
tpu_estimator.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...
motor_controller.py
import tkinter import serial from threading import Thread, Condition import sys import glob class SliderGUIWindow: def __init__(self, serial_port): self.root = tkinter.Tk() self.root.protocol("WM_DELETE_WINDOW", self.closeRequested) self.slider_value = tkinter.DoubleVar() self.scale = tkinter.Scale(self.root...
01_static_web_server.py
# coding:utf-8 import socket from multiprocessing import Process HTML_ROOT_DIR = "" def handle_client(client_socket): """处理客户端请求""" # 获取客户端请求数据 request_data = client_socket.recv(1024) print("request data:", request_data) # 构造响应数据 response_start_line = "HTTP/1.1 200 OK\r\n" response_hea...
result.py
import subprocess import sys import time import traceback from queue import Queue from sultan.core import Base from sultan.echo import Echo from threading import Thread class Result(Base): """ Class that encompasses the result of a POpen command. """ def __init__(self, process, commands, context, st...
simple.py
import threading import requests import os import time import json import PySimpleGUI as sg TIMEOUT = 5.0 class ListItem: def __init__(self, id, name): self.id = id self.name = name def __str__(self): return f'{self.name}' class PluginImpl: def __init__(self, player=None): ...
bf.py
#!/usr/bin/env python3 import multiprocessing as mp import os import queue import shutil import sys import tempfile import time from pwn import * def usage(err=None): if err is not None: log.failure(f"error: {err}") log.failure("usage: bf.py <heapedit> <ld.so> <libc6.so> <flag file>") sys.exit(0...
server.py
from http.server import HTTPServer, BaseHTTPRequestHandler, SimpleHTTPRequestHandler from multiprocessing import Process, Queue, Event class Server: def __init__(self): self.serial_queue = Queue() self.process = Process(target=self.run) self.process.start() def run(self): self....
base_dataloader.py
############################################################################################## ############################################################################################## ## ## ## ## ## ##### ### ...
pipe.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from multiprocessing import Pipe, Process import os, time, random def son_process(x, from_pipe,to_pipe,block=False): _out_from_pipe, _in_from_pipe = from_pipe _out_to_pipe, _in_to_pipe = to_pipe _in_from_pipe.close() _out_to_pipe.close() while True: ...
multi_by_process.py
''' 使用multiprocessing模块创建多进程 ''' import os from multiprocessing import Process # 子进程要执行的代码 def run_proc(name): print('Child process %s (%s) Running...' % (name, os.getpid())) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) for i in range(5): p = Process(target=run_proc, args=(s...
monitor.py
import os import sys import time import signal import threading import atexit import Queue _interval = 1.0 _times = {} _files = [] _running = False _queue = Queue.Queue() _lock = threading.Lock() def _restart(path): _queue.put(True) prefix = 'monitor (pid=%d):' % os.getpid() print >> sys.stderr, '%s Chan...
installwizard.py
from functools import partial import threading from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import ObjectProperty, StringProperty, OptionProperty from kivy.core.window import Window from kivy.uix.button import Button from kivy.utils import platform from kivy...
msg.py
from utlis.rank import setrank ,isrank ,remrank ,setsudos ,remsudos ,setsudo,IDrank,GPranks from utlis.send import send_msg, BYusers, sendM,Glang,GetLink from handlers.delete import delete from utlis.tg import Bot, Ckuser from handlers.ranks import ranks from handlers.locks import locks from handlers.gpcmd import...
lib_thread.py
""" Version using threading """ import threading import logging from check_pipx_oudates.lib import get_top_lvl_pkgs, check_pkg logging.basicConfig( level=logging.INFO, format='%(levelname)s:%(asctime)s:%(message)s' ) def thread_A(pkg: str): """ Wrap into thread. """ logging.debug(f'thread start...
my_keyboard.py
# Driver control input from keyboard from threading import Thread from typing import Tuple import pygame from src.l2race_utils import my_logger from src.globals import * from tkinter import * logger = my_logger(__name__) from src.car_command import car_command from src.user_input import user_input def show_help(): ...
Simulation.py
# Copyright 2017 Battelle Energy Alliance, LLC # # 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 t...
state_model_vec.py
import multiprocessing as mp from baselines.her.metric_diversification import MetricDiversifier from baselines.common.vec_env import CloudpickleWrapper import numpy as np def make_state_model_vec(k_vec, vis, vis_coords, load_path, log_path, random_cover, load_prob, phase_length, dilute_at_goal): def make_thunk(k)...
keyboard_mouse_shortcut_monitor.py
import win32api import win32con from threading import Timer from pywinauto.win32_hooks import Hook from pywinauto.win32_hooks import KeyboardEvent from pywinauto.win32_hooks import MouseEvent import threading import time def on_timer(): """Callback by timer out""" win32api.PostThreadMessage(ma...
peer2backup.py
#!/usr/bin/env python3 # -*- coding: utf_8 -*- # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # FIFO queue server for peer2backup # JSON HTTP server for enqueue # spawning process server for dequeue import sys import os import threading import multiprocessing import queue import json # add ./libs/ to module ...