source
stringlengths
3
86
python
stringlengths
75
1.04M
community_asist_app.py
import sys import threading from util.application_util.gaze_data_receiver import GazeDataReceiver from util.application_util.Drawer import Drawer from PyQt5.QtWidgets import * from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QPainter, QFont from PyQt5.QtCore import Qt, QRect from util.application_util...
main.py
# -*- coding: utf-8 -*- # @Time : 2021/1/1 下午4:50 # @Author : JakeShihao Luo # @Email : jakeshihaoluo@gmail.com # @File : main.py # @Software: PyCharm from scanner import * from tello_node import * import multiprocessing import numpy as np import copy def scheduler(tello_node, permission_flag): print('s...
email.py
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() msg = Mess...
Genetics.py
import multiprocessing import pickle import sys from abc import ABC, abstractmethod from random import randint, choices, choice # for macOS only from typing import Dict, Union, Any, List if sys.platform == 'darwin': multiprocessing.set_start_method('fork') from multiprocessing import Process, Manager import clic...
cli.py
# -*- coding: utf-8 -*- from __future__ import print_function import click import copy from functools import wraps import glob import io import json import logging import netrc import os import random import re import requests import shlex import signal import socket import stat import subprocess import sys import tex...
test_search_20.py
import pytest from time import sleep from base.client_base import TestcaseBase from utils.util_log import test_log as log from common import common_func as cf from common import common_type as ct from common.common_type import CaseLabel, CheckTasks from utils.utils import * from common.constants import * prefix = "se...
watcher.py
from __future__ import absolute_import import sys import os from wandb import util # Ensure we don't have the wandb directory in the path to avoid importing our tensorboard # module. This should only happen when wandb is installed with pip -e or pip install ...#egg=wandb for path in sys.path: if path.endswith(os.p...
grpc_server.py
# Copyright 2020 Broadband Forum # # 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 writi...
genLR_SRmapping.py
#!/usr/bin/python import sys import os import datetime import string import commands import threading import random def log_print(print_str): os.system("echo '" + str(print_str) + "'") def log_command(print_str): os.system("echo " + str(print_str)) os.system(str(print_str)) ###########################...
socket_manager.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. import errno import logging import json import threading import time from typing import Dict, Union from queue import P...
subchapter_03_queue_basic.py
import tensorflow as tf sess = tf.InteractiveSession() queue1 = tf.FIFOQueue(capacity=10, dtypes=[tf.string]) #todo Queue Data 삽입 enque_op = queue1.enqueue(['F']) print(sess.run(queue1.size())) enque_op.run() print(sess.run(queue1.size())) enque_op = queue1.enqueue(['I']) enque_op.run() enque_op = queue1.enqueue(['...
llvdrvterm.py
#!/usr/bin/env python # # llvdrvterm.py # a hacked version of miniterm.py, including vampire mass storage interface # Modified version by Scott Lawrence <yorgle@gmail.com> # # Version / Changelog: # # v0.02 - 2021-01-18 - Added -a --autoport for doing the autoport search internally # # v0.01 - 2020-11-24 - Initi...
athenad.py
#!/usr/bin/env python3 import base64 import hashlib import io import json import os import sys import queue import random import select import socket import threading import time from collections import namedtuple from functools import partial from typing import Any import requests from jsonrpc import JSONRPCResponseM...
portscan.py
#!/usr/bin/env python3 import socket import threading R = '\033[31m' # red G = '\033[32m' # green C = '\033[36m' # cyan W = '\033[0m' # white Y = '\033[33m' # yellow def ps(ip, output, data): threads = [] result = {} print('\n' + Y + '[!]' + Y + ' Starting Port Scan...' + W + '\n') print(G + '[+]' + C + ' Test...
GUI_v1.py
#FaceOff Deepfake Detector GUI #Lead Developer: Gabriel Schmitt #Contributions by: Margo Sikes, Caleb Graham from tkinter import * from tkinter import ttk from tkinter import filedialog from tkinter import messagebox from tkinter.ttk import Progressbar from os import path import itertools import os impor...
adb_enhanced.py
#!/usr/bin/env python3 import re import signal import subprocess import sys import tempfile import threading import time import os import random from functools import wraps, partial from urllib.parse import urlparse from enum import Enum import psutil # asyncio was introduced in version 3.5 if sys.version_info >= (3,...
remind.py
# coding=utf-8 """ remind.py - Sopel Reminder Module Copyright 2011, Sean B. Palmer, inamidst.com Licensed under the Eiffel Forum License 2. https://sopel.chat """ from __future__ import unicode_literals, absolute_import, print_function, division import os import re import time import threading import collections imp...
__init__.py
#!/usr/bin/python3 -OO # Copyright 2007-2021 The SABnzbd-Team <team@sabnzbd.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
backend.py
# -*- coding: utf-8 -*- # This code is based on AjaxTerm/Web-Shell which included a fairly complete # vt100 implementation as well as a stable process multiplexer. # I made some small fixes, improved some small parts and added a Session class # which can be used by the widget. # License: GPL2 import sys import os impor...
master.py
# -*- coding: utf-8 -*- """ This module contains all of the routines needed to set up a master server, this involves preparing the three listeners and the workers needed by the master. """ # Import python libs from __future__ import absolute_import, print_function, unicode_literals, with_statement import collections ...
data_flow.py
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import numpy as np import threading try: # Python 2 import Queue as queue except Exception: # Python 3 import queue import tensorflow as tf from . import utils class DataFlow(object): """ Data Flow. Bas...
main.py
import atexit import os import re import sys import threading import time import traceback import yaml import requests import datetime @atexit.register def _end(): end_time = time.time() print(to_log("INFO", "执行结束", "执行耗时{:.3f}s".format(end_time - start_time))) def get_shopid(): """ 获取 shopid, 如果网...
test_state.py
# -*- coding: utf-8 -*- ''' Tests for the state runner ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import errno import logging import os import shutil import signal import tempfile import time import textwrap import threading from salt.ext.six.moves import queue #...
snapraid-runner.py
#!/usr/bin/env python3 import argparse import configparser import logging import logging.handlers import os.path import subprocess import sys import threading import time import traceback from collections import Counter, defaultdict from io import StringIO # Global variables config = None email_log = None def tee_lo...
process_data.py
import argparse import glob import math import tarfile import tempfile from datetime import datetime, timedelta from os import remove from os import sep as os_path_sep from os.path import isdir, join, exists, splitext, relpath parser = argparse.ArgumentParser( description="This program processes imdb-wiki face dat...
MagicBox.py
from time import sleep import serial from threading import Thread from utils.start_software import start_software from utils.volume import set_volume class MagicBox: _raw_pins = {'A0': 0, 'A1': 0, 'D0': 0, 'D1': 0, 'D2': 0, 'D1...
thread.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @title: # @author: luowen<loovien@163.com> # @website: https://loovien.github.com # @time: 9/5/2020 1:34 AM import threading from queue import Queue from os import path q = Queue(100) def work(): while True: item = q.get() print("work {} finished"...
widgets.py
############################################################################### # Copyright (c) 2019, 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...
startup.py
from InquirerPy.utils import color_print import sys, psutil, time, cursor, valclient, ctypes, traceback, os, subprocess from .utilities.killable_thread import Thread from .utilities.config.app_config import Config from .utilities.config.modify_config import Config_Editor from .utilities.processes import Processes from...
main.py
from configs.config_phaser import parse def run_metalight(): from algs.MetaLight.metalight_train import main args = parse() print('start execute...') args.algorithm = 'MetaLight' args.project = 'MetaLight_XXGX' main(args) def run_frapplus(): from algs.FRAPPLUS.frapplus_train import main ...
isp_qemu.py
import socket import select import threading import time import sys import subprocess import os import logging import isp_utils import shutil import multiprocessing # set timeout seconds timeout_seconds = 3600 uart_log_file = "uart.log" status_log_file = "pex.log" process_exit = False qemu_base_cmd = "qemu-system-ri...
PCHandler.py
import socket import time import threading from Queue import Queue import sys import traceback import multiprocessing import logging class PCHandler(multiprocessing.Process): m = multiprocessing.Manager() threadLock = threading.Lock() queueHandler = m.Queue() def __init__(self, h...
CustomCloud.py
# CustomCloud.py - Hologram Python SDK Custom Cloud interface # # Author: Hologram <support@hologram.io> # # Copyright 2016 - Hologram (Konekt, Inc.) # # # LICENSE: Distributed under the terms of the MIT License from collections import deque import socket import sys import threading import time from Hologram.Cloud imp...
client.py
# Gaurang Gupta - 2018A7PS0225H # Rushabh Musthyala - 2018A7PS0433H # Mihir Bansal - 2018A7PS0215H # Aditya Jhaveri Alok - 2018A7PS0209H # Dev Gupta - 2017B3A71082H from connection import Connection from packet import Packet import base64 import threading import time import random import json import os class Cl...
thread_buffer.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...
audio.py
import struct import time import wave from datetime import datetime, timedelta from threading import Thread, Lock from .conn import ClientConnection from .protocol_encoder import OutputAudio MIN_WAIT = 0.033 class AudioManager: """ This class takes care of reading audio files and generating the OutputAudio ...
exploit_launcher.py
import requests import imp import os import re import datetime import sys import threading import subprocess from CustomUtils import * VERBOSE = False # Carica modulo per database database = imp.load_source('*', 'CTF-Flag-Submitter/database.py') DB = database.connect_to_db( 'instance/InsHack@ti.sqlite' ) BASE_PATH =...
main_pololu.py
#version 0.0.1——>0.0.2 from math import sqrt import math from numpy.lib.function_base import delete from pololu_imageproc import imageproc from pololu_xbee import Xbee_app from tkinter import * from digi.xbee.devices import XBeeDevice import pyrealsense2 as rs import numpy as np import cv2 import PIL.Image...
ChildRobotInteractionFSM.py
import time import json #from transitions import Machine from transitions.extensions import HierarchicalMachine as Machine from ..RobotBehaviorList.RobotBehaviorList import RobotBehaviors from ..RobotBehaviorList.RobotBehaviorList import RobotRoles from ..RobotBehaviorList.RobotBehaviorList import RobotRolesBehavior...
dask.py
# pylint: disable=too-many-arguments, too-many-locals, no-name-in-module # pylint: disable=missing-class-docstring, invalid-name # pylint: disable=too-many-lines, fixme # pylint: disable=too-few-public-methods # pylint: disable=import-error """Dask extensions for distributed training. See https://xgboost.readthedocs.io...
rbts_genome_to_genetableServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from json...
client4STA.py
############# options setting #################### import sys, getopt, os from get_host_ip import get_host_ip from validate_port import validate_port opts, args = getopt.getopt(sys.argv[1:], 'hp:s:k:') socket_host = '' socket_port = 4000 server_host = None server_port = None port = None for op, value in opts: if...
main.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT <<<<<<< HEAD import time ======= import time,threading >>>>>>> f85633c86d99f9bef1ec0634728cbf7cdbfc08f9 class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWind...
flask_embed.py
from flask import Flask, render_template from bokeh.application import Application from bokeh.application.handlers import FunctionHandler from bokeh.embed import server_document from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.plotting import figure from bokeh.server.server...
test_window_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...
test_core.py
""" test.test_core ~~~~~~~~~~~~~~ Provides tests to verify that Home Assistant core works. """ # pylint: disable=protected-access,too-many-public-methods # pylint: disable=too-few-public-methods import os import unittest import time import threading from datetime import datetime import homeassistant as ha class Tes...
__init__.py
"""Easy to use python subprocess interface.""" from easyprocess.unicodeutil import split_command, unidecode, uniencode import logging import os.path import platform import signal import subprocess import tempfile import threading import time from easyprocess.about import __version__ log = logging.getLogger(__name__)...
vegeta_stress.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import infra.network import infra.e2e_args import subprocess import threading import time import generate_vegeta_targets as TargetGenerator from loguru import logger as LOG VEGETA_BIN = "/opt/vegeta/vegeta" def print...
client.py
""" ---Adaptive Cruise Control - Client--- Adaptive Cruise Control using Monocular depth estimation. """ """ Si occupa della gestione della rete: - Receive: accelerazione, velocità, ACK. - Send: immagini raw, sensori, configurazioni (listeners, camera config, parametri flow, parametri monoculare) UDP: invio/ricezione ...
fantasygold_transaction_receipt_origin_contract_address.py
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.address import * import threading def waitforlogs(node, contract_address): logs = node.cli.waitforlo...
one.py
from threading import* #print(threading.current_thread().getName()) # def display(): # for i in range(1,11): # print("child") # t = Thread(target=display) # t.start() # for i in range(1,11): # print("main thred") # class MyThread(Thread): # def run(self): # for i in range(10): # ...
run.py
__author__ = 'tinglev' import logging import threading from flask import Flask, request, abort from modules.event_system import event_system from modules.subscribers.slack import (slack_deployment, slack_error, slack_recommendation) from modules.subscribers.detectify import detec...
main.py
from github_webhook import Webhook from flask import Flask, make_response, request from json import JSONDecodeError from protected_repo import ProtectedRepository from threading import Thread from mail import Email, FakeEmail import json import os basepath = os.path.dirname(__file__) CONFIG_FILE = "config.json" def l...
client.pyw
#!/usr/bin/env python3 # Hydrus is released under WTFPL # You just DO WHAT THE FUCK YOU WANT TO. # https://github.com/sirkris/WTFPL/blob/master/WTFPL.md try: import locale try: locale.setlocale( locale.LC_ALL, '' ) except: pass import os import argparse import traceback ...
main.py
# built using example code from pytorch getting started with examples documentation http://pytorch.org/tutorials/beginner/pytorch_with_examples.html # -*- coding: utf-8 -*- import argparse import numpy as np import time np.random.RandomState(0) import matplotlib as mpl mpl.use("Agg") import matplotlib.pyplot as plt plt...
client.py
# Library imports import pyaudio import socket import sys import threading # Socket consts SERVER_IP = sys.argv[1] SERVER_PORT = int(sys.argv[2]) CHANNEL_ID = sys.argv[3].encode() # Audio consts CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 # Mic input daemon def mic_input(sock, istream): try: ...
main.py
#!/usr/bin/env python3 import operator import sys import time from collections import defaultdict, namedtuple from queue import Empty, Queue from threading import Event, Thread Vec2D = namedtuple("Vec2D", ["x", "y"]) class Memory(list): def __getitem__(self, index): if index >= len(self): se...
stt.py
# # The file is from https://github.com/googleapis/python-speech/blob/master/samples/microphone/transcribe_streaming_infinite.py # account.json should be in the same folder with this file # #!/usr/bin/env python # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you ma...
__init__.py
#!/usr/bin/python3 # @todo logging # @todo extra options for url like , verify=False etc. # @todo enable https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl as option? # @todo option for interval day/6 hour/etc # @todo on change detected, config for calling some API # @todo make tables responsive! # @todo fe...
scanner.py
import socket import threading from os import system total=0 th1=0 th2=0 th3=0 th4=0 rg=254 ipadd=[] system("clear") print("+++++++++++++++++++++++++++++++++++++++++++++++++") print("\n") print(" RANGE SCANNER 0.1 \n") print(" Made by:- Sarthak Saini") print("++++++++++++++++++...
connection.py
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
e2eTest.py
#!/usr/bin/env python import argparse import tempfile import subprocess import json from time import sleep import threading import os import sys from tempfile import NamedTemporaryFile import requests from requests_oauthlib import OAuth1 client_key = 'mock-key' client_secret = 'mock-secret' oauth = OAuth1(client_key...
__init__.py
from __future__ import print_function from six.moves import input import argparse from contextlib import contextmanager import threading import subprocess try: from subprocess import DEVNULL except ImportError: import os DEVNULL = open(os.devnull, 'wb') from . import networksetup def signal_on_error(pro...
_channel_test.py
# Copyright 2016 gRPC authors. # # 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 writing...
arpspoof.py
from tkinter import* from tkinter import messagebox import threading from scapy.all import ARP,Ether,sendp bools = False tk = Tk() tk.title('arp多人') tk.geometry('300x160+420+200') #-------------------------------- def ip_hz(): ips = [] for i in range(2,252): ips.append(i) retu...
ffmpegmux.py
import logging import subprocess import sys import threading from shutil import which from streamlink import StreamError from streamlink.compat import devnull from streamlink.stream.stream import Stream, StreamIO from streamlink.utils import NamedPipe log = logging.getLogger(__name__) class MuxedStream(Stream): ...
eventloopscheduler.py
import logging import threading from threading import Timer from rx.concurrency import ScheduledItem from rx.disposables import Disposable from rx.internal.exceptions import DisposedException from rx.internal.priorityqueue import PriorityQueue from .scheduler import Scheduler log = logging.getLogger('Rx') class Ev...
map_reduce.py
r""" Parallel computations using RecursivelyEnumeratedSet and Map-Reduce There exists an efficient way to distribute computations when you have a set `S` of objects defined by :func:`RecursivelyEnumeratedSet` (see :mod:`sage.sets.recursively_enumerated_set` for more details) over which you would like to perform the fo...
test_locks.py
import queue from threading import Thread import django import pytest from django.db import OperationalError, connection, connections from django.db.transaction import TransactionManagementError, atomic from django.test import TestCase, TransactionTestCase from django_mysql.exceptions import TimeoutError from django_...
tlxml.py
import requests from lxml import etree import threading from queue import Queue class QiubaiSpdier: def __init__(self): self.url_temp = "http://www.qiushibaike.com/8hr/page/{}/" self.headers = {"User-Agent": ""} self.url_queue = Queue() self.html_str_queue = Queue() self.co...
test.py
import urllib2 import getpass import os import sys import re import threading import keyring from time import sleep from poster import encode from poster import streaminghttp def wait(arg1 , stop_event): while (not stop_event.is_set()): sys.stdout.write('.') sys.stdout.flush() stop_event.w...
redis_dryer2.py
def dryer(): import redis import os import time conn = redis.Redis() pid = os.getpid() timeout = 20 print('Dryer process %s is starting' % pid) while True: msg = conn.blpop('dishes', timeout) if not msg: break val = msg[1].decode('utf-8') if v...
_execution_utils.py
import threading import AutoPypline.auto_pipeline as auto def parallel_executor(flows, graph): """ Parallel execution of each flow in flows :param flows: Type: list List of flows to be executed (generated by flow_generator) :param graph: Type: Dict Graph Data Structure ...
conv_to.py
# !/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Jorge de la Peña García Email: jpena@ucam.edu Description: Convert molecule folders between sdf, pdb, pdbqt and mol2 formats """ import argparse import os from glob import glob from os.path import join, splitext import subprocess import sys TIME_LIM...
process_test.py
import unittest import aioprocessing.mp as multiprocessing import aioprocessing from ._base_test import BaseTest, _GenMixin def f(q, a, b): q.put((a, b)) def dummy(): pass class GenAioProcessTest(BaseTest, _GenMixin): def setUp(self): self.Obj = aioprocessing.AioProcess self.inst = se...
helpers.py
# -*- coding: utf-8 -*- ''' :copyright: Copyright 2013-2017 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.support.helpers ~~~~~~~~~~~~~~~~~~~~~ Test support helpers ''' # pylint: disable=repr-flag-used-in-string,wrong-import-order ...
__init__.py
import threading import time from .skype_chatbot import * class SkypeBot: def __init__(self, client_id, client_secret): def get_token(): global token payload = "grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret + \ ...
bhnet.py
#!/opt/local/bin/python2.7 import sys import socket import getopt import threading import subprocess # define some global variables listen = False command = False upload = False execute = "" target = "" upload_destination = "" port = 0 # this r...
threading_simple.py
import threading def worker(): """thread worker function""" print('Worker') threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start()
main.py
import json import threading from datetime import datetime from hashlib import sha1 from os import listdir, mkdir, path, remove from shutil import copyfile from sys import exit from tkinter import messagebox from env import * from gui import find_game_path, UPKManager def checksum(file_name): hash_obj = sha1() ...
testsuite.py
# Copyright (c) 2009 testtools developers. See LICENSE for details. """Test suites and related things.""" __metaclass__ = type __all__ = [ 'ConcurrentTestSuite', 'iterate_tests', ] try: from Queue import Queue except ImportError: from queue import Queue import threading import unittest import testtool...
FD_BS_circle.py
import cv2 from tkinter import Tk from tkinter.filedialog import askopenfilename import numpy as np import imutils import threading def main(): cap = cv2.VideoCapture(vid_path) status1, previous_frame = cap.read() total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) copy_frame ...
serve.py
# -*- coding: utf-8 -*- import argparse import json import os import signal import socket import sys import threading import time import traceback import urllib2 import uuid from collections import defaultdict from multiprocessing import Process, Event from .. import localpaths import sslutils from wptserve import se...
audio.py
# import time # import argparse # # parser = argparse.ArgumentParser() # parser.add_argument('-t', dest='speak_str', action='store') # args = parser.parse_args() # # speak_str = args.speak_str # # # 这个函数可能会放到其他线程里去,可以要放入队列中 # print('现在音响正在发音...内容是:{}'.format(speak_str)) # time.sleep(2) from queue import Queue import t...
conftest.py
# vim: smarttab tabstop=4 shiftwidth=4 expandtab softtabstop=4 filetype=python # vim: set syntax=python: import pytest import Queue import subprocess import sys import threading import time EMPTY_A_BOOTSTRAP = "setup/docker-compose-site-empty-a-bootstrap.yml" SHARED_A_B_BOOTSTRAP = "setup/docker-compose-site-...
lock.py
# -*- coding:utf-8 -*- import threading # 定义获取列表值的函数,参数为索引值. def get_value(index): # 定义列表 data_list = [1,3,5,7,9] # 上锁 lock.acquire() # 输出内容 if index >= len(data_list): print("{}下标越界".format(index)) # 释放锁 lock.release() return print(data_list[index]) ...
test_client.py
#!/usr/bin/env python # Copyright 2012 James McCauley # # 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 la...
test_locking.py
from datetime import datetime, timedelta from utils.concurency import UserLock from threading import Thread from multiprocessing.process import Process from time import sleep from timeit import default_timer def test_user_lock(): hold_user_lock(5) run_threads([Thread(target=hold_user_lock, args=[i]) for i in r...
run.py
#! /usr/bin/env python import argparse import base64 import codecs import collections import logging import json import os import stat import pipes import re import signal import sys import threading import time from io import StringIO import pexpect import psutil logger = logging.getLogger('awx.main.utils.expect')...
services.py
import socket import os import threading # 处理客户端请求下载文件的操作(从主线程提出来的代码) def deal_client_request(ip_port, service_client_socket): # 连接成功后,输出“客户端连接成功”和客户端的ip和端口 print("客户端连接成功", ip_port) # 接收客户端的请求信息 file_name = service_client_socket.recv(1024) # 解码 file_name_data = file_name.decode("utf-8") #...
test_config.py
import asyncio import copy import pytest import random import yaml from pipscoin.util.config import create_default_pipscoin_config, initial_config_file, load_config, save_config from pipscoin.util.path import mkdir from multiprocessing import Pool from pathlib import Path from threading import Thread from time import ...
pull_players.py
"""Retrieves account ids from Valve's DOTA2 API through GetMatchHistoryBySequenceNum. This module retrieves account ids by retrieving matches from GetMatchHistoryBySequenceNum and then retrieving players from the retrieved matches. The account_ids are put into a database. """ import urllib.parse import json import t...
test_execute.py
# coding: utf-8 import collections.abc as collections_abc from contextlib import contextmanager from contextlib import nullcontext import copy from io import StringIO import re import threading from unittest import mock from unittest.mock import call from unittest.mock import Mock from unittest.mock import patch impor...
log_human_activities.py
import asyncio import logging import threading import os from time import sleep from getmac import get_mac_address as gma from tornado.platform.asyncio import AnyThreadEventLoopPolicy from angrmanagement.config import Conf import angrmanagement.ui.views as Views from ..base_plugin import BasePlugin l = logging.getLog...
dbus_exporter.py
from . import interfaces import decorator import dbus.service import dbus.mainloop.glib import dbus.exceptions import inspect import threading import signal import tuned.logs import tuned.consts as consts from tuned.utils.polkit import polkit from gi.repository import GLib log = tuned.logs.get() class DBusExporter(in...
check_reactive.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2020 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ma...
test_debugger.py
# coding: utf-8 ''' The idea is that we record the commands sent to the debugger and reproduce them from this script (so, this works as the client, which spawns the debugger as a separate process and communicates to it as if it was run from the outside) Note that it's a python script but it'll spawn a ...
base_comm_actor.py
import threading from abc import ABC, abstractmethod from typing import Any class BaseCommActor(ABC): def __init__(self, cfg): self._cfg = cfg self._active_flag = False # Note: the following variable will be set by the outside caller self._logger = None self._actor_uid = N...
benchmark_utils.py
# This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp # Copyright by the AllenNLP authors. """ Utilities for working with the local dataset cache. """ import copy import csv import linecache import os import platform import sys from abc import ABC, abstractmethod from collections impo...
dmock.py
from telnetsrv.threaded import TelnetHandler, command import SocketServer import os class TelnetServer(SocketServer.ThreadingTCPServer): allow_reuse_address = True class DeviceHandler(TelnetHandler): """Generic device handler""" # Dictionary to alter the command output provided in the text file. Useful...