source
stringlengths
3
86
python
stringlengths
75
1.04M
dmlc_mpi.py
#!/usr/bin/env python """ DMLC submission script, MPI version """ import argparse import sys import os import subprocess import tracker from threading import Thread parser = argparse.ArgumentParser(description='DMLC script to submit dmlc job using MPI') parser.add_argument('-n', '--nworker', required=True, type=int, ...
fractureP_S.py
import os import subprocess import sys import threading import shutil import numpy as np from PyQt5 import QtWidgets from PyQt5.QtWidgets import QMessageBox from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCan...
trapd.py
''' Created on Nov. 06, 2014 @author: yunli ''' from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.dgram import udp from pyasn1.codec.ber import decoder from pysnmp.proto import api from threading import Thread, Event import logging import util import signal import sys import...
build.py
import sys import threading from colorama import Fore, Style,init from utils import * def animate(message): for c in itertools.cycle(['|', '/', '-', '\\']): if done: break print("\r"+Style.BRIGHT+Fore.GREEN+message+c+Fore.RESET, end="") time.sleep(0.1) def build(direc, port1, i...
multiprocessing_train.py
#!/usr/bin/env python3 -u import os import random import signal import torch from fairseq import distributed_utils, options from train import main as single_process_main def main(args): # Set distributed training parameters for a single node. if not args.distributed_world_size: args.distributed_wor...
server.py
import asyncio import json import re from itertools import cycle from threading import Thread from time import sleep import serial from aiohttp import web from scipy import signal class Sensor: # Serial message patterns. re_patterns = [ r'(RPY) - Roll: (-?\d+) \| Pitch: (-?\d+) \| Yaw: (-?\d+)', ...
getsonar.py
#http://doc.aldebaran.com/2-5/naoqi/core/almemory-api.html #http://doc.aldebaran.com/2-5/family/pepper_technical/pepper_dcm/actuator_sensor_names.html#ju-sonars import qi import argparse import sys import time import threading sonarValueList = ["Device/SubDeviceList/Platform/Front/Sonar/Sensor/Value", ...
pysms.py
from threading import Thread from multiprocessing import Pool from datetime import datetime def join_threads(threads): for t in threads: t.join() class ApiRequestError(Exception): def __init__(self, message): super().__init__(message) class DeviceManager(): def __init__(self, identifier):...
socket_handler.py
import threading import websocket import json import logging logging.basicConfig() class SocketHandler(threading.Thread): def __init__(self, host, send_q, recv_q, debug=False, sentinel=None): super(SocketHandler, self).__init__() self.debug = debug self.send_q = send_q self.recv_q = recv_q self._...
__main__.py
""" A security camera on computer using webcam. """ from datetime import datetime from multiprocessing import Process, cpu_count import os import security_webcam as sw def main(): """ Main Loop """ args = sw.parse_inputs() print(f"Settings >>> top fps: {args.fps}, recording length: {args.max_len} m...
infer_tb.py
# # -*- coding: utf-8 -*- # # Copyright (c) 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
cca.py
#!/usr/bin/env python3 ''' A driver script for CCA container image Copyright 2021 Codinuum Software Lab <https://codinuum.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http...
lambda_executors.py
import base64 import contextlib import glob import json import logging import os import re 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, Union from localstack import config...
run_multi_q3.py
import os from multiprocessing import Process, Lock import re base_folder = 'code/data' data_folder = 'data' exp_names = ['rec_hist_60_delta_3','rec_hist_60_delta_5','rec_hist_60_delta_10'] system_code = ['cd code && python3 train_policy.py pm --exp_name q3_%s -e 3 --history 60 --discount 0.90 -lr 5e-4 -n 100 --r...
test_controller.py
from threading import Thread, Event from unittest.mock import Mock import queue import pytest from mitmproxy.exceptions import Kill, ControlException from mitmproxy import controller from mitmproxy import master from mitmproxy import proxy from mitmproxy.test import taddons class TMsg: pass class TestMaster: ...
ntp.py
#!/usr/bin/env python3 #MIT License # #Copyright (c) 2021 Sloobot # #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, m...
osa_utils.py
#!/usr/bin/python3 """ (C) Copyright 2020-2022 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ import ctypes import queue import time import threading import re from avocado import fail_on from ior_test_base import IorTestBase from mdtest_test_base import MdtestBase from exception_utils import...
mul_f.py
from __future__ import print_function import argparse import os import cv2 import time import mxnet as mx import numpy as np from rcnn.config import config from rcnn.symbol import get_vggm_test, get_vggm_rpn_test from rcnn.symbol import get_vgg_test, get_vgg_rpn_test from rcnn.symbol import get_resnet_test from rcnn.io...
worlds.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 parlai.mturk.core.worlds import MTurkOnboardWorld, MTurkTaskWorld import threading class AskerOnboardingWorld(MTur...
coderunner.py
# -*- coding: utf-8 -*- import os import re import subprocess import syslog import threading import Queue from filewatcher import componentprop _runner_queue = {} _task_queue_assignment = re.compile('^\(([A-Za-z0-9-]+)\)\s*([^\s].+)$') _command_carry_variable_macro = re.compile('^%([A-Za-z0-9_-]+)%$') def _subp...
tasks.py
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # Python from collections import OrderedDict, namedtuple import errno import functools import importlib import json import logging import os import shutil import stat import tempfile import time import traceback from distutils.dir_util ...
tcp-server.py
# Basic socket tcp server import socket import sys import threading def main(host='localhost', port=2300): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: print(host, port) s.bind((host, int(port))) s.listen(10) while 1: client, addr = s.accept() print('Connection from {}'.format(addr)) ...
subproc.py
""" ttt.subproc ~~~~~~~~~~~~ This module provides additional functions for subprocess execution built on top of the existing subprocess module. :copyright: (c) yerejm """ import os import subprocess import sys import threading from six.moves import queue def execute(*args, **kwargs): """Wrapper around subproce...
remote_executor.py
# Copyright 2019, The TensorFlow Federated 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 o...
mpfps.py
import multiprocessing import logging import time import sys import numpy as np import threading from lib.mpvariable import MPVariable import types PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY2: import copy_reg elif PY3: import copyreg as copy_reg def _pickle_method(m): if m.im_self ...
test___init__.py
'''cping.protocols tests''' import threading import time import unittest import cping.protocols # pylint: disable=protected-access class TestHost(unittest.TestCase): '''cping.protocols.Host tests.''' def test_add_result(self): '''Add a result.''' host = cping.protocols.Ping()('localhost') ...
web_gui.py
import threading import time import cv2 as cv import numpy as np from datetime import date from flask import Flask from flask import render_template from flask import Response from .utils import visualization_utils as vis_util from tools.objects_post_process import extract_violating_objects from tools.environment_scor...
test_gluon_model_zoo.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 u...
bind_amqp.py
from galaxy.util import asbool, mask_password_from_url from pulsar.client import amqp_exchange_factory from pulsar import manager_endpoint_util import functools import threading import logging log = logging.getLogger(__name__) TYPED_PARAMS = { "amqp_consumer_timeout": lambda val: None if str(val) == "None" else ...
test_transactions.py
import queue import threading import pytest import sheraf.transactions import tests import ZODB.POSException from tests.utils import conflict def test_initial_value(): _queue = queue.Queue() def run(q): q.put(sheraf.Database.current_connection()) thread = threading.Thread(target=run, args=(_que...
core.py
""" libraries needed machine: for uart usage uio: packet buffer struct: serlization _TopicInfo: for topic negotiation already provided in rosserial_msgs """ import machine as m import uio import ustruct as struct from time import sleep, sleep_ms, sleep_us from rosserial_msgs import TopicInfo import sys import o...
concurrent_helper.py
""" A private module that implements concurrency-friendly versions of queues, dictionaries and counters. Author: JMJ """ import collections import logging import time import threading import sched _NO_DEFAULT = object() # To check if an optional parameter was specified in selected method calls _logger = logging.getL...
dgm.py
from threading import Thread from BucketLib.BucketOperations import BucketHelper from basetestcase import ClusterSetup from cb_tools.cbstats import Cbstats from couchbase_helper.documentgenerator import doc_generator from remote.remote_util import RemoteMachineShellConnection from table_view import TableView class ...
test_blitter.py
#%% #%load_ext autoreload #%autoreload 2 import multiprocessing as mp import numpy as np import os import sys import pytest from time import sleep from types import SimpleNamespace as SN from utils.memory_tracker.blitter import Blitter #%% refresh = 3 history = 12 dataEvents = 1000 history / refresh def reader(que...
proxy2.py
# -*- coding: utf-8 -*- # # # This code originated from the project https://github.com/inaz2/proxy2 but has since # been modified extensively. # # import base64 import re import socket import ssl import threading import urllib.parse from http.client import HTTPConnection, HTTPSConnection from http.server import BaseH...
quanjingwang.py
# -*- coding:utf-8 -*- # 多线程,自动创建文件夹,每个页面单独存储一个文件夹 import os import queue import re import threading import time import requests from bs4 import BeautifulSoup string = 'https://www.quanjing.com/category/1286521/' url_queue = queue.Queue() pipei = re.compile('lowsrc="(.*?)" m=') # def get_url(page): for i in r...
train.py
# Copyright (c) 2018 PaddlePaddle 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 app...
logger.py
import sys import logging.handlers import platform import threading import traceback from . import compat from . import handlers try: import notifiers.logging _has_notifiers = True except (ImportError, ModuleNotFoundError): _has_notifiers = False # register module-level functions for all supported notifiers def _c...
test_seeker.py
# Copyright 2019 Ram Rachum and collaborators. # This program is distributed under the MIT license. import io import textwrap import threading import time import sys from executor.seeker.utils import truncate import pytest from executor import seeker from executor.seeker.variables import needs_parentheses from .util...
__init__.py
"""DNS proxy package.""" from dnsproxy.website import WebServer from dnsproxy.server import Server from dnsproxy.config import Config from threading import Thread from sys import argv import logging logger = logging.getLogger('dnsproxy') logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)-15s %(...
utils.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import ipaddress import re import socket from datetime import timedelta from threading import Event, Thread from ...
client.py
## ## Copyright (C) 2017, Amit Aides, all rights reserved. ## ## This file is part of Camera Network ## (see https://bitbucket.org/amitibo/cameranetwork_git). ## ## Redistribution and use in source and binary forms, with or without modification, ## are permitted provided that the following conditions are met: ## ## 1) ...
test_html.py
from __future__ import print_function import os import re import threading from functools import partial import pytest import numpy as np from numpy.random import rand from pandas import (DataFrame, MultiIndex, read_csv, Timestamp, Index, date_range, Series) from pandas.compat import (map, zip,...
main.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import re import subprocess import struct import sys import blessed import random import SimpleHTTPServer import SocketServer import multiprocessing from Crypto.Cipher import AES import base64 import string import glob import readli...
transaction.py
#!/usr/bin/python3 import functools import sys import threading import time from collections import OrderedDict from hashlib import sha1 from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import black import requests from eth_abi import decode_abi from hexbytes imp...
wrapper.py
import socket from threading import Thread def echo(name:str, client_id:int, data:str)->list: """ Basic callback function that echos everything """ return data class HRTPServer(object): """ Server object """ def __init__(self, ip="0.0.0.0", port=8088, callback=None): self.ip = ip ...
VideoServer.py
#Embedded file name: ACEStream\Video\VideoServer.pyo import sys import time import socket import BaseHTTPServer from SocketServer import ThreadingMixIn from threading import RLock, Thread, currentThread from traceback import print_stack, print_exc import string from cStringIO import StringIO import os from ACEStream.Gl...
build_environment.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) """ This module contains all routines related to setting up the package build environment. All of this is set up by packa...
multi_fake_ap.py
import os import sys os.system("clear") import pyfiglet print (chr(27)+"[36m") banner = pyfiglet.figlet_format("Multi Fake AP ") print (banner) print (" Author : Rahat Khan Tusar(RKT)") print (" Github : https;//github.com/r3k4t") from scapy.all import * from threading import Thread from faker imp...
jndiRep.py
#!/usr/bin/env python from shutil import get_terminal_size from time import time, ctime import subprocess import threading import requests import argparse import base64 import json import sys import re import os paths = [] findings = [] WIDTH = get_terminal_size().columns RED = "\x1b[31m" GREEN = "\x1b[32m" CYAN = "\x...
fire_cli.py
import sys import threading import uuid from io import StringIO import fire from dukepy.fire.fire_root import Root from dukepy.traces import print_exception_traces from dukepy.fire.fire_command import FireCommand fire_threads = [] def db_fire_cmd(cmd, source): def act(): try: req = FireComm...
test_subprocess.py
import unittest from unittest import mock from test import support import subprocess import sys import platform import signal import io import os import errno import tempfile import time import selectors import sysconfig import select import shutil import gc import textwrap try: import ctypes except ImportError: ...
timing_test.py
import odrive import time import math import threading thread_active = True serial_a = "208239904D4D" #String containing front ODrive's serial number in hex format all capitals serial_b = "206039994D4D" #String containing back ODrive's serial number in hex format all capitals odrv = odrive.find_any(serial...
server.py
import os import sys import socket import threading import json import click SIZE = 1024 FORMAT = "utf-8" SERVER_DATA_PATH = "./" peer_table = {} filesize_table = {} md5_table = {} cond = threading.Condition() def clientHandler(conn, addr): global peer_table global cond full_addr = addr[0] + ":" + str(ad...
app.py
############################################################################# # Copyright (c) 2018, Voilà Contributors # # Copyright (c) 2018, QuantStack # # # # Distri...
iot-hub-client-dual.py
import json import random import re import sys import threading import time from azure.iot.device import IoTHubDeviceClient, Message AUX_CONNECTION_STRING = sys.argv[1] DEVICE_NAME=AUX_CONNECTION_STRING.split(";")[1].split("=")[1] AUX_BASE_HEART_RATE = 65 AUX_BASE_BODY_TEMPERATURE = 37.0 AUX_MAXIMU...
release.py
#!/usr/bin/python import re import sys import os import os.path import subprocess import shutil import tempfile from datetime import * from multiprocessing import Process from utils import * try: from xml.etree.ElementTree import ElementTree except: prettyprint(''' Welcome to the Infinispan Release Script....
main.py
from utils import * from process import * from server import run_server import multiprocessing,requests p = multiprocessing.Process(target=run_server, args=()) p.daemon = True path_volume= abspath(__file__)+"_data/" keyword= "ok assistant" list_stop= get_tree_by_tag("start>stop")['keywords'] volumes={str(path_volume)...
test_process.py
import multiprocessing as mp from jitcache import Cache import time cache = Cache() @cache.memoize def slow_fn(input_1, input_2): print("Slow Function Called") time.sleep(1) return input_1 * input_2 def test_process(): kwarg_dict = {"input_1": 10, "input_2": 4} n_processes = 10 process_l...
game.py
import copy import math import os import re import threading from datetime import datetime from typing import Dict, List, Optional, Union from kivy.clock import Clock from katrain.core.constants import ( ANALYSIS_FORMAT_VERSION, OUTPUT_DEBUG, OUTPUT_INFO, PLAYER_AI, PLAYER_HUMAN, PROGRAM_NAME,...
threading_accept_die.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 17 13:07:14 2018 @author: tensorflow-cuda """ import threading def print_cube(num): """ function to print cube of given num """ print("Cube: {}".format(num * num * num)) def print_square(num): """ function to print squa...
request_example.py
import multiprocessing import requests import sys import threading from timeit import Timer import warnings def request_item(item_id): print("Thread {} starts ...".format(threading.currentThread().getName())) try: r = requests.get("http://hn.algolia.com/api/v1/items/{}".format(item_id)) e...
ruleBackend.py
import time import paho.mqtt.client as mqtt import signal import sys import threading topics=[] publisher=None subscriber=None connected=None def disconnecthandler(mqc,userdata,rc): print("Disconnected from broker") global connected connected = False def init(host,port,user=None,password=None): globa...
test_threading_local.py
import sys import unittest from doctest import DocTestSuite from test import support from test.support import threading_helper import weakref import gc # Modules under test import _thread import threading import _threading_local class Weak(object): pass def target(local, weaklist): weak = Weak() local.w...
it_multiprocess.py
import re import unittest from time import sleep from multiprocessing import Process from urllib import request from sanic import Sanic from sanic.response import json from sanic_prometheus import monitor, SanicPrometheusError TEST_PORT = 54424 def launch_server(): app = Sanic('test_mp') @app.route('/te...
monitoring_app_external_broker.py
import time import wx import cStringIO from kafka import KafkaConsumer import threading import Queue from datetime import datetime #import simplejson import pickle local_consumer1 = KafkaConsumer('PhayaThai-1', bootstrap_servers = ['192.168.1.7:9092'], group_id = 'view1', consumer_timeout_ms = 300) local_consumer2 = ...
cryoDaqInit.py
#!/usr/bin/env python3 #----------------------------------------------------------------------------- # Title : cryo DAQ top module (based on ePix HR readout) #----------------------------------------------------------------------------- # File : cryoDAQ.py evolved from evalBoard.py # Created : 2018-06-12...
web_server_2.py
#!/usr/bin/python3 # file: multiprocess_web_server.py # Created by Guang at 19-7-19 # description: # *-* coding:utf8 *-* import multiprocessing import socket import re import time import sys sys.path.insert(0, "../../") from mini_web.framework import mini_frame_2 class WSGIServer(object): def __init__(self, i...
atrace_agent.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import py_utils import re import sys import threading import zlib from devil.android import device_utils from devil.android.sdk import versi...
ready_loop.py
# Called when the bot is ready to be used import asyncio import datetime import sqlite3 import threading import time import discord from Data.Const_variables.import_const import Login, Ids from Script.import_emojis import Emojis from Script.import_functions import int_to_str async def ready_loop(self): if self...
tests.py
import os import shutil import sys import tempfile import threading import time import unittest from datetime import datetime, timedelta from io import StringIO from pathlib import Path from urllib.request import urlopen from django.core.cache import cache from django.core.exceptions import SuspiciousFileOperation fro...
youtube.py
import re import threading import traceback import pykka import requests import youtube_dl from cachetools import LRUCache, cached from mopidy.models import Image from mopidy_youtube import logger from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry api_enabled = False # ...
iotserver.py
from iotcommon import IotUDPHandler from iotcommon import UdpPacket import datetime import iotcommon import SocketServer import binascii import logging import time import threading import os import socket import ssl import sys import json class IotSession: TYPE_UDP = 'udp' TYPE_SSL = 'ssl' def __init__(sel...
aws_upload.py
import boto3 session = boto3.Session( aws_access_key_id='<Your access key>', aws_secret_access_key='<Your secret Key>') s3 = session.resource('s3') import threading from os import listdir from typing import List #TODO: Constans to be filled by developer AWS_BUCKET_NAME = "" AWS_DESTINATION_FOLDER_NAME = "" LOCAL_SOUR...
notify_mtr_older.py
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ import base64 import hashlib import hmac import os import re import threading import time import urllib.parse import requests try: import json5 as json except ModuleNotFoundError: import json try: from utils_env import get_file_path except ModuleNotFoundError:...
_channel.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...
extraicnpj.py
# -*- coding: utf-8 -*- import sys import io from FilaDeLinhas import FilaDeLinhas import threading from GravaCnpj import GravacaoPgCopy def trata(texto): ok = texto ok = ok.replace(';',' ') ok = ok.replace('"',' ') ok = ok.replace('\0','') ok = ok.replace('\\','/') ok = ok.strip() while ' ' in ok: ...
keepkey.py
from binascii import hexlify, unhexlify import traceback import sys from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING from electrum_onion.util import bfh, bh2u, UserCancelled, UserFacingException from electrum_onion.bip32 import BIP32Node from electrum_onion import constants from el...
engine.py
""" """ import logging from logging import Logger import smtplib import os from abc import ABC from datetime import datetime from email.message import EmailMessage from queue import Empty, Queue from threading import Thread from typing import Any, Sequence, Type, Dict, List, Optional from vnpy.event import Event, Eve...
serve.py
# !/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import signal import uuid from queue import Queue from threading import Thread import bottle from tqdm import tqdm from common import logger from common import tf from common.config import get_config_from_args from common.util import batch from tasks imp...
zeromq.py
# -*- coding: utf-8 -*- ''' Zeromq transport classes ''' # Import Python Libs from __future__ import absolute_import import os import sys import copy import errno import signal import hashlib import logging import weakref from random import randint # Import Salt Libs import salt.auth import salt.crypt import salt.uti...
authentication.py
""" Spotify Terminal authenticates with Spotify by directing your browser to the locally hosted authentication link. """ import json import os import requests import struct import urllib import webbrowser from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from threading import Thread import common logger ...
wittypi.py
import time import queue from multiprocessing import Process, Queue, Event from py_wittypi_device import WittyPiDevice class VoltageMonitor: def __init__(self,config): self.median_values = config['Voltage'].getint('median_values') self.median_dt = config['Voltage'].getfloat('median_dt') ...
common.py
# common.py # Tom Taylor / Version Control # 2021 from os import environ from threading import Thread from playsound import playsound from twitchio.ext import commands # CONFIG ------------------------------ bot = commands.Bot( irc_token=environ['TMI_TOKEN'], client_id=environ['CLIENT_ID'], ni...
b.py
import threading def thread_job(): print("This is an added Thread, number is %s" % threading.current_thread()) def main(): added_thread = threading.Thread(target=thread_job) # # 查看进程中还有几个线程在运行 # print(threading.active_count()) # # 返回一个包含正在运行的线程的list # print(threading.enumerate()) # # 当前执...
util.py
"""Utilities for working with mulled abstractions outside the mulled package.""" import collections import hashlib import logging import re import sys import tarfile import threading from io import BytesIO import packaging.version import requests log = logging.getLogger(__name__) QUAY_REPOSITORY_API_ENDPOINT = 'htt...
microservice.py
import argparse import os import importlib import json import time import logging import multiprocessing as mp import threading import sys from typing import Dict, Callable from distutils.util import strtobool from seldon_core import persistence, __version__, wrapper as seldon_microservice from seldon_core.metrics im...
web_test.py
import asyncio try: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except: print("Warning: Unable to initialize uvloop") from pyice import web_async from pyice import web import threading import time server = web.Server(web.ServerConfig().set_num_executors(3).set_listen_addr("127.0...
utils.py
"""App utilities. """ import json import logging import sys import threading import time import traceback from configs.general_configs import PRINT_THREAD from ..azure_app_insight.utils import get_app_insight_logger from ..azure_parts.models import Part from ..azure_parts.utils import batch_upload_parts_to_customvis...
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 ...
interaction_console.py
import threading import archr from PySide2.QtWidgets import QMainWindow, QMessageBox, QVBoxLayout from PySide2.QtCore import Qt from qtterm import TerminalWidget from angrmanagement.plugins import BasePlugin from angrmanagement.ui.views import BaseView from angrmanagement.ui.views.interaction_view import ( SavedI...
iterators.py
import multiprocessing import sys import queue import threading import traceback from typing import TypeVar, Iterable, Iterator, List, Callable T = TypeVar('T') __all__ = ['ThreadedIterator', 'MultiWorkerCallableIterator', 'BufferedIterator', 'DoubleBufferedIterator'] class ThreadedIterator(Iterator[T...
test_operator_gpu.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 u...
proxy_crawler.py
#! /usr/bin/python3 # rootVIII | proxy_crawler.py from sys import exit from threading import Thread from crawler.crawl import ProxyCrawler, HeadlessProxyCrawler from crawler.arguments import ArgParser def main(): while True: if not args.headless: bot = ProxyCrawler(args.url, args.keyword) ...
client.py
import socket, threading, traceback, queue, json from datetime import datetime from chatapp.shared import message class TCP_Nonblocking_Client: def __init__(self, host, port, username, password, verbose_output=True): self.host = host self.port = port self.sock = None self.format = 'utf-8' s...
history.py
# Copyright 2021 HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. # # 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/LICE...
mopidy.py
import json import re import threading from platypush.backend import Backend from platypush.message.event.music import MusicPlayEvent, MusicPauseEvent, \ MusicStopEvent, NewPlayingTrackEvent, PlaylistChangeEvent, VolumeChangeEvent, \ PlaybackConsumeModeChangeEvent, PlaybackSingleModeChangeEvent, \ Playback...
send data to feed with paho-mqtt publish.py
# Import standard python modules import threading import time import os import sys # Import paho MQTT client. import paho.mqtt.client as mqtt # "global" Vars if(len(sys.argv)!=4): sys.stderr.write('Usage: "{0}" $AdafruitIOUsername $AdafruitIOKey $AdafruitIOFeedKey\n'.format(sys.argv[0])) os._exit(1) AdafruitIOFe...
nssc_web_interface.py
import os from flask import Flask, render_template, request, redirect from ament_index_python.packages import get_package_share_directory import rclpy from rclpy.node import Node from std_msgs.msg import String from nssc_interface.msg import ColorFilterParams, CameraSettings import threading from dataclasses import dat...
test_motor_change_stream.py
# Copyright 2017-present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...