source
stringlengths
3
86
python
stringlengths
75
1.04M
evaler.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import threading, sys, logging from collections.abc import Iterator from .lv_types import EventData # pylint: disable=unused-wildcard-import # pylint: disable=wildcard-import # pylint: disable=unused-import from functools import * from itertools...
human_controller.py
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist, Pose import sys, select, os import math from gazebo_msgs.msg import ModelStates, ModelState, LinkState import time import threading import numpy as np class HumanController(): """Human navigation based on social forces model""" def __init_...
conftest.py
"""pytest fixtures for kubespawner""" import base64 import inspect import io import logging import os import sys import tarfile import time from distutils.version import LooseVersion as V from functools import partial from threading import Thread import kubernetes import pytest from jupyterhub.app import JupyterHub fr...
gpu_usage.py
################################################################################ # Copyright (c) 2021 ContinualAI. # # Copyrights licensed under the MIT License. # # See the accompanying LICENSE file for terms. ...
test_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 unittest import time import uuid from unittest import mock from parlai.mturk.core.socket_manager import Packet, S...
HydrusPaths.py
import os import psutil import re import send2trash import shlex import shutil import stat import subprocess import threading import traceback from hydrus.core import HydrusConstants as HC from hydrus.core import HydrusData from hydrus.core import HydrusGlobals as HG from hydrus.core import HydrusThreading def Append...
DLProcessor.py
import socket, ssl import threading import time from .DLInfos import Target import logging import traceback import sys if sys.version_info <= (2, 7): from urllib import splitvalue, splitquery, urlencode elif sys.version_info >= (3, 0): from urllib.parse import splitvalue, splitquery, urlencode logger = l...
SatadishaModule_final_trie.py
# coding: utf-8 # In[298]: import sys import re import string import csv import random import time #import binascii #import shlex import numpy as np import pandas as pd from itertools import groupby from operator import itemgetter from collections import Iterable, OrderedDict from nltk.tokenize import sent_tokenize...
rfswitch.py
"""rf433 device proxy code.""" import collections import logging import threading import Queue import rcswitch from pi import proxy class RFSwitch(proxy.Proxy): """433mhz RF Switch proxy implementation.""" def __init__(self, pin, repeats=5): self._switch = rcswitch.RCSwitch() self._switch.enableTransm...
record.py
# coding: utf-8 import glob import os import shlex import subprocess import threading import time import traceback import mss from PIL import Image from base.config.config import Config from base.logs.log import Log4Kissenium from base.tools.platform import Platform from base.tools.sm_tools import SmallTools class...
server_socket.py
from socket import gethostbyname, gethostname, SHUT_WR, socket, SOL_SOCKET, SO_REUSEADDR, AF_INET, SOCK_STREAM from threading import Thread import sys class ServerSocket: """ A Class to represent Server Socket. """ def __init__(self, port: int,db,model) -> None: # Creating an INET , STREAMing...
multiprocess_iterator.py
from __future__ import division from collections import namedtuple import multiprocessing from multiprocessing import sharedctypes import signal import sys import threading import warnings import numpy import six from chainer.dataset import iterator _response_time = 1. _short_time = 0.001 _PrefetchState = namedtupl...
video_recorder.py
# 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, software # d...
twitch.py
import os import json import webbrowser from threading import Thread import time from PyQt5.QtWidgets import QFileDialog, QTextEdit, QHBoxLayout, QFormLayout, QHeaderView, QTabWidget, QCheckBox, QGridLayout, QComboBox, QLineEdit, QLabel, QApplication, QWidget, QPushButton, QVBoxLayout, QTableWidget, QTableWidgetItem f...
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import...
ibuddy_usbapi.py
""" USBAPI - a simple API for driving the USB attached iBuddy USAGE To use this you need to add pywinusb to your Python installation - https://pypi.python.org/pypi/pywinusb/ Then you can drive this from the Python console as follows: >>> import usbapi as usb >>> devices = usb.usbapi().getDevices() That gets you an...
DataGen_Transformer_split_IDMap.py
import csv import os import sys import shutil import time import numpy as np import scipy.io as sio import yaml import argparse from easydict import EasyDict from os.path import dirname, realpath, pardir from hashids import Hashids import hashlib sys.path.append(os.path.join(dirname(realpath(__file__)), pardir)) imp...
websocket_client.py
import json import logging import socket import ssl import sys import traceback from datetime import datetime from threading import Lock, Thread from time import sleep from typing import Optional import websocket from howtrader.trader.utility import get_file_logger class WebsocketClient: """ Websocket API ...
test_ssl.py
import pytest import threading import socket as stdlib_socket import ssl as stdlib_ssl from contextlib import contextmanager from functools import partial from OpenSSL import SSL import trustme from async_generator import async_generator, yield_, asynccontextmanager import trio from .. import _core from .._highlevel...
event.py
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2012-2013 by the SaltStack Team, see AUTHORS for more details :license: Apache 2.0, see LICENSE for more details. tests.integration.modules.event ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' # Import python ...
zeromq.py
# -*- coding: utf-8 -*- """ Zeromq transport classes """ # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy import errno import hashlib import logging import os import signal import socket import sys import threading import weakref from random import randint # I...
feature_shutdown.py
#!/usr/bin/env python3 # Copyright (c) 2018-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BGLd shutdown.""" from test_framework.test_framework import BGLTestFramework from test_framework...
toster.py
# This file contains simple python module # for communication with the server from threading import Thread, RLock import sys import json __infoCallbacks = [] __requestCallbacks = [] __communicationThread = None __localLock = RLock() def registerInfoCallback(cb): __localLock.acquire() __infoCallbacks.append...
itachi.py
# -*- coding: utf-8 -*- import LINETCR from LINETCR.lib.curve.ttypes import * from datetime import datetime import io,os,re,ast,six,sys,glob,json,time,timeit,codecs,random,shutil,urllib,urllib2,urllib3,goslate,html5lib,requests,threading,wikipedia,subprocess,googletrans ,pytz from gtts import gTTS from random import...
cls_oaicitest.py
#/* # * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more # * contributor license agreements. See the NOTICE file distributed with # * this work for additional information regarding copyright ownership. # * The OpenAirInterface Software Alliance licenses this file to You under # * the OAI Publ...
msee_tests.py
import sys import ptf from ptf.base_tests import BaseTest import ptf.testutils as testutils from ptf.testutils import simple_arp_packet import struct from threading import Thread from pprint import pprint sys.path.append('/usr/lib/python2.7/site-packages') from thrift import Thrift from thrift.transport import TSocke...
test_server.py
import os from multiprocessing.managers import DictProxy from pathlib import Path from unittest.mock import Mock, ANY import requests import time import uuid import urllib.parse from typing import List, Text, Type, Generator, NoReturn, Dict, Optional from contextlib import ExitStack from _pytest import pathlib from ...
process_replay.py
#!/usr/bin/env python3 import importlib import os import sys import threading import time from collections import namedtuple import capnp from tqdm import tqdm import cereal.messaging as messaging from cereal import car, log from cereal.services import service_list from common.params import Params from selfdrive.car....
actor_definition.py
import contextlib import logging import os import pkgutil import sys from io import UnsupportedOperation from multiprocessing import Process, Queue import leapp.libraries.actor # noqa # pylint: disable=unused-import from leapp.actors import get_actor_metadata, get_actors from leapp.exceptions import (ActorInspectionF...
run.py
# -*- coding: utf-8 -*- # 总调度器 + 多线程控制器 from do.house_selector import HouseSelector from do.page_extractor import PageExtractor from do.price_stater import PriceStater from util.config import ConfigParser from constant.logger import * import time class Do(HouseSelector, PageExtractor, PriceStater): @staticmetho...
fantome_opera_serveur.py
# coding=utf-8 from random import shuffle,randrange from time import sleep from threading import Thread import dummy0, dummy1 latence = 0.01 permanents, deux, avant, apres = {'rose'}, {'rouge','gris','bleu'}, {'violet','marron'}, {'noir','blanc'} couleurs = avant | permanents | apres | deux passages = [{1,4},{0,2},{1,...
thread.py
import threading import time import random # base thread class MyThread(threading.Thread): def run(self): # task implementation print("in my thread") thread = MyThread() thread.run() # base thread without lock def show_number_without_lock(number): wait_time = random.uniform(0, 0.5) ti...
download_from_google_storage.py
#!/usr/bin/env python # Copyright (c) 2012 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. """Download files from Google Storage based on SHA1 sums.""" import hashlib import optparse import os import Queue import re impo...
test_client.py
# test_client.py -- Compatibilty tests for git client. # Copyright (C) 2010 Google, Inc. # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or ...
tg_rfc2544_trex.py
# Copyright (c) 2016-2017 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 applicable law or agreed...
installwizard.py
import os import sys import threading import traceback from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from electrum import Wallet, WalletStorage from electrum.util import UserCancelled, InvalidPassword from electrum.base_wizard import BaseWizard from electrum.i18n import _ from ....
dataengine_install_libs.py
#!/usr/bin/python # ***************************************************************************** # # 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 A...
pyramidhelpers.py
import logging from multiprocessing import Process from wsgiref.simple_server import make_server from hncddpylibs.pipeline import S3PipelineService from pyramid.config import Configurator log = logging.getLogger(__file__) def setup_web_server(processor, port, bucket, service_name): def index(request): l...
ue_mac.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 threading from typing import List from ryu.controller import ofp_event from ryu.controller.handler import M...
netapi.py
# encoding: utf-8 ''' The main entry point for salt-api ''' # Import python libs import logging import multiprocessing import signal import os # Import salt-api libs import salt.loader logger = logging.getLogger(__name__) class NetapiClient(object): ''' Start each netapi module that is configured to run ...
sdk_worker.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
database.py
#!/usr/bin/env python3 """Connectivity modules for various NoSQL databases.""" __author__ = 'Philipp Engel' __copyright__ = 'Copyright (c) 2019, Hochschule Neubrandenburg' __license__ = 'BSD-2-Clause' import logging import threading import time from typing import Any, Dict, Union try: import couchdb except Imp...
kafkaConsumer_Firebase.py
import os import json from time import sleep import signal import threading import uuid from kafka import KafkaConsumer from cryptography.fernet import Fernet import firebase_admin from firebase_admin import credentials from firebase_admin import firestore def read_from_kafka(topic_name, kafka_addr, f, db, closing...
ThreadingTest.py
########################################################################## # # Copyright (c) 2010-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
covaidapp.py
# import the necessary packages from __future__ import print_function from PIL import Image from PIL import ImageTk from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.models import load_model import numpy as np import tensorflow as tf import tkinter as tki import threading import dateti...
dataloader.py
import os import torch from torch.autograd import Variable import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image, ImageDraw from SPPE.src.utils.img import load_image, cropBox, im_to_torch from opt import opt from yolo.preprocess import prep_image, prep_frame, inp_to_i...
plant_guard.py
import RPi.GPIO as GPIO import time from threading import Lock, Thread from pathlib import Path lock = Lock() keyboardListening = False keyboardDir = 0 movementTerminated = False rikt = [] PUMP_PIN = 5 PUMP_REV_PIN = 6 def init(exitOnLoadFailure): GPIO.setmode(GPIO.BCM) initPump() initStepper(exitOnLoadFailure...
virustotal.py
#!/usr/bin/env python3 __author__ = "Gawen Arab" __copyright__ = "Copyright 2012, Gawen Arab" __credits__ = ["Gawen Arab"] __license__ = "MIT" __version__ = "1.0.3-python3" __maintainer__ = "Gawen Arab" __email__ = "g@wenarab.com" __status__ = "Production" # Snippet from http://code.activestate.com/recipes/146306/ fr...
uDNS.py
# coding=utf-8 # # 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, software ...
helpers.py
"""Helper functions/classes for unit tests.""" from __future__ import division import copy from contextlib import contextmanager from queue import Queue import socket from threading import Thread from time import sleep from typing import Dict, Generator, List, Pattern, Union from flashfocus.client import ClientMonito...
image_queue.py
from threading import Thread, Event from contextlib import contextmanager from queue import Queue import numpy as np import time def _start(queue, stop_event): """ Thread target function. Starts the ImageQueue._populate function which runs indefinitely until stop_event is set. Args: queue: ...
backend_jbe.py
"""Construct a backend by using the Stanford Portable Library JAR. This module handles the initialization of and connection to the backend JAR, as well as all interprocess communications. This specific backend should not be directly referenced by any client applications. """ from __future__ import print_function __P...
interface.py
# Copyright (c) 2016 Ansible by Red Hat, Inc. # # 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 Licen...
server.py
'''https://www.youtube.com/watch?v=3QiPPX-KeSc''' import socket import threading SERVER = socket.gethostbyname(socket.gethostname()) # automatically gets the server IP addr equi to SERVER = "192.168.20.7" # print("Server ip address is: ", SERVER) # print("Server name is: ", socket.gethostname()) # To connect from out...
pairs2vocab.py
import argparse import os import ioutils from multiprocessing import Process, Queue from Queue import Empty from representations.matrix_serializer import save_count_vocabulary import six import sys def worker(proc_num, queue, out_dir, in_dir): while True: try: year = queue.get(block=False) ...
script.py
from __future__ import absolute_import import os, traceback, threading, shlex from . import controller class ScriptError(Exception): pass class ScriptContext: def __init__(self, master): self._master = master def log(self, message, level="info"): """ Logs an event. ...
main_server.py
from pickle import NONE import socketserver import socket import threading import tkinter import zmq import base64 import cv2 class MyHandler(socketserver.BaseRequestHandler): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) users = {} print((([ip for ip in socket.gethostbyname_ex(socket.gethostnam...
read_only_vertex_bench.py
#! /usr/bin/env python # # =============================================================== # Description: Read-only multi-client benchmark which only # reads 1 vertex per query. # # Created: 2014-03-21 13:39:06 # # Author: Ayush Dubey, dubey@cs.cornell.edu # # Copyright (C) 20...
command.py
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import enum import json import logging import os import re import resource import signal import subprocess import threading from ab...
example_respmod_500_error.py
# -*- coding: utf8 -*- import time import threading from icapserver import * set_logger('debug') class ExampleICAPHandler(BaseICAPRequestHandler): def example_OPTIONS(self): self.set_icap_response(200) self.set_icap_header('Methods', 'RESPMOD, REQMOD') self.set_icap_header('Service', 'ICAP Server' + ' ' + s...
actr.py
import json import threading import socket import time import os import sys current_connection = None class request(): def __init__(self,id): self.id = id self.lock = threading.Lock() self.cv = threading.Condition(self.lock) self.complete = False def notify_res...
utils.py
import re import queue import logging import threading logger = logging.getLogger(__name__) # S3 multi-part upload parts must be larger than 5mb KB = 1024 MB = KB**2 GB = KB**3 TB = KB**4 MIN_S3_SIZE = 5 * MB def _threads(num_threads, data, callback, *args, **kwargs): q = queue.Queue() item_list = [] ...
views.py
from rest_framework import pagination from rest_framework.response import Response from multiprocessing import Process from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.core.paginator import Paginator from rest_framework.parsers import JSONParser impor...
data_reader_Audio_RIRs.py
import copy import fnmatch import os import random import re import threading import math import librosa import numpy as np import tensorflow as tf import json import pickle from numpy.random import permutation from numpy.random import randint import numpy as np import pandas as pd from scipy import signal import sci...
command.py
import concurrent.futures import logging import os import queue import re import threading from pathlib import Path from typing import Optional, Tuple import boto3 import botocore from botocore.endpoint import MAX_POOL_CONNECTIONS from botocore.exceptions import NoCredentialsError from .exceptions import DirectoryDoe...
engine.py
""" Main BZT classes Copyright 2015 BlazeMeter 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...
generate-dataset-canny.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author : Hongzhuo Liang # E-mail : liang@informatik.uni-hamburg.de # Description: # Date : 20/05/2018 2:45 PM # File Name : generate-dataset-canny.py import numpy as np import sys import pickle from dexnet.grasping.quality import PointGraspMetrics3D from de...
poisson_tests.py
import math, sys, threading, time, requests, random, uuid, json from time import sleep from dataclasses import dataclass @dataclass class ConnectivityServiceData: start_TS: int = -1 inter_arrival_time: float = -0.1 end_TS: int = -1 type: str = '' result: str = '' uuid: str = '' ber: bool = ...
simulation_3.py
''' Created on Oct 12, 2016 @author: mwittie ''' import network_3 import link_3 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__ == '__main__': ...
gui.py
import random import threading import tkinter import tkinter.scrolledtext import collections from operator import attrgetter from operator import itemgetter from time import sleep from PluginBot import PluginBot from PluginBot import getMessage from PluginBot import BYTE def rgb(red, green, blue): return "#%02x%02x...
clientGUI.py
#!/usr/bin/env python3 """Script for Tkinter GUI chat client.""" from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import tkinter def receive(): """Handles receiving of messages.""" while True: try: msg = client_socket.recv(BUFSIZ).decode("utf8") msg_...
bot.py
import asyncio import dataclasses import datetime import logging import math import multiprocessing import os import random import signal import time import traceback import typing import discord import jsonpickle import openai from discord import state as discord_state DISCORD_TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXX.XXXXX...
test_threaded_import.py
# This is a variant of the very old (early 90's) file # Demo/threads/bug.py. It simply provokes a number of threads into # trying to import the same module "at the same time". # There are no pleasant failure modes -- most likely is that Python # complains several times about module random having no attribute # randran...
__init__.py
# -*- coding: utf-8 -*- # Copyright 2015 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...
binaries.py
# Lint-as: python3 """Utilities for locating and invoking compiler tool binaries.""" # Copyright 2020 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception import importlib...
tcp_server_demo1.py
# -*- coding: utf-8 -*- # @Time : 2018/8/1 上午10:58 # @Author : yidxue import socket import threading import time def tcplink(sock, addr): print('Accept new connection from %s:%s...' % addr) sock.send('Welcome!') while True: data = sock.recv(1024) time.sleep(5) if data == 'exit'...
pranjan77ContigFilterServer.py
#!/usr/bin/env python from wsgiref.simple_server import make_server import sys import json import traceback import datetime from multiprocessing import Process from getopt import getopt, GetoptError from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\ JSONRPCError, ServerError, InvalidRequestE...
view_tester.py
# Copyright 2017-2022 TensorHub, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
PiVideoStream.py
# import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera from threading import Thread import cv2 class PiVideoStream: def __init__(self, resolution=(320, 240), framerate=32): # initialize the camera and stream self.camera = PiCamera() self.camera.resolution = resoluti...
unittableview.py
import vdomr as vd import time import multiprocessing import sys from .stdoutsender import StdoutSender import mtlogging import numpy as np import spikeforest_analysis as sa from spikeforest import EfficientAccessRecordingExtractor import json class UnitTableView(vd.Component): def __init__(self, context): ...
main_console.py
import threading import time # global variables hero_health = 40 orc_health = 7 dragon_health = 20 def thread_orc(): global hero_health global orc_health while orc_health > 0 and hero_health > 0: time.sleep(1.5) hero_health = hero_health - 1 print("Orc attacked... Hero health: ", ...
test.py
# coding=utf-8 import socket # socket模块 import json import random import numpy as np from collections import deque from keras.models import Sequential, Model from keras.layers import Input, Dense, Conv2D, Flatten, concatenate from keras.optimizers import Adam from math import floor, sqrt import tensorflow as tf import...
test_stream_xep_0059.py
import threading from sleekxmpp.test import * from sleekxmpp.xmlstream import register_stanza_plugin from sleekxmpp.plugins.xep_0030 import DiscoItems from sleekxmpp.plugins.xep_0059 import ResultIterator, Set class TestStreamSet(SleekTest): def setUp(self): register_stanza_plugin(DiscoItems, Set) ...
test_browser.py
# coding=utf-8 # Copyright 2013 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. import argparse import json import multiprocessing imp...
timo.py
# -*- coding: utf-8 -*- import os,sys from urllib.request import Request,urlopen import tinify import threading import time import base64 from PIL import Image import shutil import json keys = ["yourkey1","yourkey2","yourkey3"] suffix = ["png","jpg","JPG","JEPG","jepg","PNG"] suffixMp3 = ["mp3","MP3"] global timo_h...
email.py
# from threading import Thread # from flask import render_template # from flask_mail import Message # from app import app, mail # def send_async_email(app, msg): # with app.app_context(): # mail.send(msg) # def send_email(subject, sender, recipients, text_body, html_body): # msg = Message(subject, s...
03.py
import time import threading def test(): time.sleep(10) for i in range(1, 10): print(i) thread1 = threading.Thread(target=test, daemon=False) # thread1 = threading.Thread(target=test, daemon=True) thread1.start() print('主线程完成了')
datasets.py
# Dataset utils and dataloaders import glob import logging import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread import cv2 import numpy as np import torch import torch.nn.functional ...
audio.py
from pydub import AudioSegment import os import sys import csv import threading, queue import time from log import Log from error import Error import pygame class Audio(Log, Error): ''' The Audio object takes the number of handbells and their tuning from the current ReBel configuration and compares them...
pronterface_serial.py
from serial.tools import list_ports # -------------------------------------------------------------- # Printer connection handling # -------------------------------------------------------------- def connect_to_printer(self, port, baud, dtr): try: self.p.connect(port, baud, dt...
test_threading.py
""" Tests for the threading module. """ import test.support from test.support import (verbose, import_module, cpython_only, requires_type_collecting) from test.support.script_helper import assert_python_ok, assert_python_failure import random import sys import _thread import threading import...
ThreadLocal.py
''' ThreadLocal 每个线程都有自己的数据,使用局部变量,函数调用时麻烦? 总结: 一个ThreadLocal虽然是全局变量,但每个线程都只能读写自己线程内 的独立副本,互不干扰,解决在参数在一个线程中,各个函数间的传递 多任务处理方案: 多进程 多线程 异步IO编程模型(事件驱动编程) 单线程的异步编程:协程 任务分为: CPU 密集型:涉及大量计算,音视频处理 ---> 最好用C语言或多进程处理 IO 密集型:涉及网络,磁盘IO ---> 多线程 ''' ...
model.py
from __future__ import absolute_import from __future__ import print_function import copy import random from itertools import chain, product from multiprocessing import Process from flask import Flask, request, jsonify from flask.ext.cors import CORS import numpy as np from . import scoring from .dataloader.goboard imp...
sample_bootstrap.py
import sys, time from threading import Thread sys.path.insert(0, './../') import PoP import myGetMVP, importGameRes, myGetRating # function written by the user # the nodeID config is already generated, please refer to sample_setup.py nodeID, matchID = "Alice", 1 myPoP = PoP.handler(nodeID=nodeID, winnerFunc=myGetMVP.g...
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import configargparse import cv2 as cv from gestures.tello_gesture_controller import TelloGestureController from gestures.swarm_gesture_controller import SwarmGestureController from utils import CvFpsCalc from djitellopy import Tello from djitellopy import TelloSwarm fro...
database_screen.py
import pathlib import threading import traceback import json from colorama import Style, Fore from cryptography.fernet import InvalidToken, Fernet from YeetsMenu.menu import Menu from YeetsMenu.option import Option from pw_manager.utils import utils, constants, decorators, errors from pw_manager.db import Database f...
detector_utils.py
# Utilities for object detector. import numpy as np import sys import tensorflow as tf import os from threading import Thread from datetime import datetime import cv2 from utils import label_map_util from collections import defaultdict detection_graph = tf.Graph() sys.path.append("..") # score threshold for showing...
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...
ai_flow_client.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...
common.py
"""Test the helper method for writing tests.""" import asyncio from datetime import timedelta import functools as ft import os import sys from unittest.mock import patch, MagicMock, Mock from io import StringIO import logging import threading from contextlib import contextmanager from homeassistant import core as ha, ...