source
stringlengths
3
86
python
stringlengths
75
1.04M
coordinator_example.py
import tensorflow.compat.v1 as tf import numpy as np import threading import time tf.disable_v2_behavior() def thread_op(coordinator, thread_id): while coordinator.should_stop() == False: if np.random.rand() < 0.1: print("Stopping from thread_id: %d \n" % thread_id) coordinator.requ...
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...
model.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import os os.system( "pip install --extra-index-url https://developer.download.nvidia.com/compute/redist/cuda/10.0 nvidia-dali && pip3 install torch torchvision") import threading import random import tensorflow as tf import torch import ...
runner.py
""" Convenience functions for creating a context and evaluating nodes for a range of dates and collecting the results. """ from .context import MDFContext, NodeOrBuilderTimer, _profiling_is_enabled from .nodes import MDFNode from datetime import datetime import numpy as np import pandas as pa import logging import insp...
LHconsole.py
import threading from win32com.shell import shell, shellcon from threading import Thread from queue import Queue, Empty import sys import time import subprocess class LHconsole: def __init__(self, file_name=False): #steamPath = "D:\\Steam" #lh_path = steamPath + "\\steamapps\\common\\SteamVR\\too...
gui.py
import json import threading from os import mkdir, path, startfile from sys import exit from tkinter import filedialog, messagebox, IntVar, ttk from winreg import ConnectRegistry, EnumValue, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, OpenKey from ttkthemes import ThemedTk from env import * from update import update def...
test_api.py
""" mbed SDK Copyright (c) 2011-2014 ARM 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 License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
callbacks_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
serial_device.py
import serial import sys from threading import Thread class SerialDevice: def __init__(self, portname='', baudrate=0, stopbits=1, listen_callback=None): self.portname = portname self.baudrate = baudrate self.stopbits = stopbits self.timeout = None self.listen_callback = None...
CountDown.py
from tkinter import Tk, Button, Label, DISABLED, NORMAL from time import sleep from winsound import Beep from threading import Thread class CountDown: def __init__(self): self.stop_thread = False self.hup = None self.hdo = None self.mup = None self.mdo = None self....
search.py
# -*- coding: utf-8 -*- def __auth_service(core, service_name, request): service = core.services[service_name] response = core.request.execute(core, request) if response.status_code == 200 and response.text: service.parse_auth_response(core, service_name, response.text) def __query_service(core, s...
gw_grpc_client.py
# Copyright 2022. ThingsBoard # # 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 ...
mpi_worker.py
import psana from psmon.plots import Image import matplotlib.pyplot as plt from matplotlib.colors import Normalize from psmon import publish import numpy as np import os import logging import requests import socket import argparse import sys import time import inspect from threading import Thread, Lock import zmq from ...
track.py
# Written by Bram Cohen # see LICENSE.txt for license information from BitTornado.parseargs import parseargs, formatDefinitions from BitTornado.RawServer import RawServer, autodetect_socket_style from BitTornado.HTTPHandler import HTTPHandler, months from BitTornado.parsedir import parsedir from NatCheck import...
test_ftplib.py
"""Test script for ftplib module.""" # Modified by Giampaolo Rodola' to test FTP class, IPv6 and TLS # environment import ftplib import asyncore import asynchat import socket import StringIO import errno import os try: import ssl except ImportError: ssl = None from unittest import TestCase, SkipTest, skipUnl...
player.py
import model.logger import os import threading import subprocess def dele(fpath): """ 删除文件 :param fpath: 文件路径 :return: 无 """ if os.path.exists(fpath): os.remove(fpath) def doPlay(file,dell): cmd = ["play", str(file)] model.logger.moduleLoggerMain.info("Executing %s", " ".join(c...
colors.py
from termcolor import colored, cprint import colorama colorama.init() import logger_config import logging logger = logging.getLogger('2047') import threading # _pq = [] # _pqc = threading.Condition() def qprint(*a,**kw): to_print = ' '.join((str(i) for i in a)) logger.info(to_print) # with _pqc: #...
serverAndClient.py
from threading import Thread, Lock, Event import socket import time from lru import LRU class SocketCommunicator(): def __init__(self, maxUnacceptConnections=5): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('', 10000) self.sock.bind(server_address) ...
keep_alive.py
from flask import Flask from threading import Thread import os app = Flask('') @app.route('/') def home(): return f"I'm online don't worry about me" def run(): app.run(host='0.0.0.0',port=8082) def keep_alive(): t = Thread(target=run) t.start()
gnupg.py
""" A wrapper for the 'gpg' command:: Portions of this module are derived from A.M. Kuchling's well-designed GPG.py, using Richard Jones' updated version 1.3, which can be found in the pycrypto CVS repository on Sourceforge: http://pycrypto.cvs.sourceforge.net/viewvc/pycrypto/gpg/GPG.py This module is *not* forward-...
async-with-threads.py
# -*- coding: utf-8 -*- import asyncio import threading import os import sys root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 async def test(loop): exchange = ccxt.bittrex({ 'asyncio_loo...
new_controller.py
""" Training a linear controller on latent + recurrent state with CMAES. This is a bit complex. num_workers slave threads are launched to process a queue filled with parameters to be evaluated. Remember best is only logged every three epochs """ import argparse import sys from os.path import join, exists from os impo...
primes_queue.py
import math import time import multiprocessing import argparse FLAG_ALL_DONE = b"WORK_FINISHED" FLAG_WORKER_FINISHED_PROCESSING = b"WORKER_FINISHED_PROCESSING" def check_prime(possible_primes_queue, definite_primes_queue): while True: n = possible_primes_queue.get() if n == FLAG_ALL_DONE: ...
LightBoxHost.py
#!/usr/bin/env python3 from datetime import datetime, timedelta, time #Timestamps from multiprocessing import Process, log_to_stderr, set_start_method #Multiprocessing functions for handling ReminderHost import json #Json Serialisat...
rc_driver.py
__author__ = 'zhengwang' import threading import SocketServer import serial import cv2 import numpy as np import math # distance data measured by ultrasonic sensor sensor_data = " " class NeuralNetwork(object): def __init__(self): self.model = cv2.ANN_MLP() def create(self): layer_size = n...
service_streamer.py
# coding=utf-8 # Created by Meteorix at 2019/7/13 import logging import multiprocessing import os import threading import time import uuid import weakref import pickle from queue import Queue, Empty from typing import List from redis import Redis from .managed_model import ManagedModel TIMEOUT = 1 TIME_SLEEP = 0.001...
downloadclient.py
# -*- coding: utf-8 -*- # Copyright 2018-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
log_battery.py
# log_battery.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Wed, Sep 1, 2021 5:05:45 PM """Example to continuously read the battery (with no Wifi connection)""" import csv import time import logging import argparse import threading fro...
consumerAndProducer.py
""" Problema productor-consumidor Programa que ejecuta la el proceso de productor-consumidor Las labores de cada una son las siguientes: productor: generar un producto, almacenarlo y comenzar nuevamente; El productor no debe añadir más productos que la capacidad del buffer consumidor: toma simultaneamente productos un...
processing_ping.py
#!/usr/bin/env python from processing import Process, Queue, Pool import time import subprocess from IPy import IP import sys q = Queue() ping_out_queue = Queue() snmp_out_queue = Queue() ips = IP("10.0.1.0/24") num_ping_workers = 10 num_snmp_workers = 10 def ping(i,q,out=out_queue): while True: if q.empt...
test_classify_async_multinet.py
''' Copyright 2019 Xilinx 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 writing, software di...
Home.py
"""Home.py ETP est déterminé aléatoirement entre 0, 1 et 2 : 0 -> toujours donner l'énergie (communiste) 1 -> toujours vendre au marché (capitaliste) 2 -> essaye de donner l'énergie, sinon il la vend au marché (libéral) """ from multiprocessing import Process, Value from sysv_ipc import IPC_CREAT, Message...
impinj_r700.py
from interrogator import * import threading import json import sys from httplib2 import Http from sllurp import llrp from twisted.internet import reactor import os import queue from time import sleep import collections import random import socket import math import numpy as np from datetime import datetime #added impo...
controller_worker.py
# Copyright 2019, 2020 SAP SE # Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 # # Unl...
example_ticker_and_miniticker.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # File: example_ticker_and_miniticker.py # # Part of ‘UNICORN Binance WebSocket API’ # Project website: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api # Documentation: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api # PyPI: htt...
views.py
import json import logging import os import workflow_manager from workflow_manager_analysis import AnalysisWorkflowManager from threading import Thread from django import forms from django.http import HttpResponse, QueryDict, JsonResponse from django.views.decorators.http import require_http_methods, require_POST, req...
classification.py
# coding: utf-8 # Copyright (c) HP-NTU Digital Manufacturing Corporate Lab, Nanyang Technological University, Singapore. # # This source code is licensed under the Apache-2.0 license found in the # LICENSE file in the root directory of this source tree. import argparse import csv import os import tensorflow as tf imp...
command_execution_win.py
# -*- coding: utf-8 -*- """ Module for command execution function call_command() on Windows. Copyright: 2022 by Clemens Rabe <clemens.rabe@clemensrabe.de> All rights reserved. This file is part of gitcache (https://github.com/seeraven/gitcache) and is released under the "BSD 3-Clause License". Please...
musicPlayer.py
#!/usr/bin/env python import sys, inspect, cgi, os, subprocess, pipes, json, select, time, threading from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from mutagen.easyid3 import EasyID3 from urlparse import parse_qs from threading import Thread # SETTINGS serverPort = 40000 baseDir = os.path.dirname(os.pa...
__init__.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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 3 of the License, or # (at your option) an...
AngleMeterAlpha.py
#Connections #MPU6050 - Raspberry pi #VCC - 5V (2 or 4 Board) #GND - GND (6 - Board) #SCL - SCL (5 - Board) #SDA - SDA (3 - Board) from Kalman import KalmanAngle import smbus2 #import SMBus module of I2C import time import math import threading class AngleMeterAlpha: #Read the gyro and acceleromater values fro...
talan_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...
transfer.py
from Ipv6_turn.server import Service import socket from threading import Thread import json import time from datetime import datetime class Transfer: def __init__(self,address=('127.0.0.1',9080)): self.user_info ={} #self.user_info={'000000':{'passward':'sdlab123','service':None,'heart_ad...
museServer.py
import argparse import math import time import threading import os from pythonosc import dispatcher from pythonosc import osc_server def initArrays(): global alphaArray, betaArray, deltaArray, thetaArray global timesCalled, lastSubmit timesCalled = 0 alphaArray = [] betaArray = [] thetaArray = [] deltaA...
detector_utils.py
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 bounding boxes. _s...
main_window.py
import re import os import sys import time import datetime import traceback from decimal import Decimal import threading import electrum from electrum.bitcoin import TYPE_ADDRESS from electrum import WalletStorage, Wallet from electrum_gui.kivy.i18n import _ from electrum.paymentrequest import InvoiceStore from electr...
word2vec.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
saga.py
############################################################################### # # Copyright 2009-2013, Universitat Pompeu Fabra # # This file is part of Wok. # # Wok 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...
trio.py
import threading from contextlib import suppress from functools import partial import outcome import trio from trio import Cancelled, RunFinishedError from .base import AsyncEngine, ThreadWorker from .exc import AlreadyQuit _STOP = object() class TrioThreadWorker(ThreadWorker): def __init__(self, *, branch_fro...
search_worker.py
"""Search worker """ import queue import sys import threading from threading import Thread from anubis.scanners.crt import search_crtsh from anubis.scanners.dnsdumpster import search_dnsdumpster from anubis.scanners.hackertarget import subdomain_hackertarget from anubis.scanners.netcraft import search_netcraft from a...
test_generator.py
import multiprocessing import time from multiprocessing import Queue import numpy as np import os from keras import Input, Model from keras.layers import Dense, Conv2D, MaxPooling2D, concatenate, Flatten from keras_vggface.vggface import VGGFace from skimage.feature import hog from skimage.metrics import structural_si...
decorators.py
import time import collections from functools import wraps, partial from traceback import format_tb from db.basic import db_session from logger import ( parser, crawler, storage, other) from utils import KThread from exceptions import Timeout # 封装了一个处理函数异常的装饰器 def timeout_decorator(func): @wraps(func) def...
server.py
#!/usr/bin/env python """ ComicStreamer main server classes """ """ Copyright 2012-2014 Anthony Beville 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....
beam_worker_pool_service.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...
rat.py
#!/usr/bin/env python3 ''' A peer to peer chat client. Refer to the README for dessign goals and usage. ''' from threading import Thread import time import bot import crypto import name import pack import prompt import port import sock def get_conf(path: str='../conf.ini', c: list=[]): ''' Use like: ...
00.py
import threading import socket def handler_client(service_socket): client_socket, ip_port = service_socket.accept() print("客户端IP和端口", ip_port) def tansmit_data(): receive_data = client_socket.recv() receive_content = receive_data.decode("gbk") send_content = input("请回复:") send_d...
variable_scope_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
NarrativeIndexerImpl.py
# -*- coding: utf-8 -*- #BEGIN_HEADER from threading import Thread from confluent_kafka import Consumer, KafkaError from Utils.IndexerUtils import IndexerUtils import json #END_HEADER class NarrativeIndexer: ''' Module Name: NarrativeIndexer Module Description: A KBase module: NarrativeIndexer ...
state.py
""" This handler listens for state change events and if they match a monitoring configuration creates an event. It also posts state changes to the DartAPI to update the central data store. """ from . import BaseHandler from ..configurations import ConfigurationsManager from dart.common.supervisor import SupervisorClie...
connection.py
# Copyright DataStax, 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 writing, softwa...
CustomSocket.py
from __future__ import print_function import numpy as np import os, sys import random, socket from threading import Thread import time # import cv2 ## Global Static Variables INITIAL_MESSAGE = 'Handshake' class Server(): def __init__(self, tcp_ip = 'localhost', tcp_port = 5000, max_clients = 1, buffer_size = 1024): ...
core.py
from __future__ import absolute_import, division, print_function from collections import deque from datetime import timedelta import functools import logging import six import sys import threading from time import time import weakref import toolz from tornado import gen from tornado.locks import Condition from tornad...
websockets.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restrictio...
test_functools.py
import abc import collections import copy from itertools import permutations import pickle from random import choice import sys from test import support import unittest from weakref import proxy try: import threading except ImportError: threading = None import functools py_functools = support.import_fresh_mod...
mapManager.py
import os #from multiprocessing import Process, Queue from threading import Thread from Queue import Queue from buffalo import utils class MapManager: """ Manages chunks and map loading """ BASE_PATH = ["maps"] # BASE_PATH is a list version of the base path in # which M...
idsWrapper.py
""" IdsWrapper IDS camera DLL wrapper """ from simplesensor.shared.threadsafeLogger import ThreadsafeLogger from platform import architecture from threading import Thread from .idsConsts import * from ctypes import * import numpy as np import time class IdsWrapper(object): def __init__(self, loggingQueue, moduleC...
thread_loacl.py
import threading # 创建全局ThreadLocal对象: local_school = threading.local() def process_student(): # 获取当前线程关联的student: std = local_school.student print('Hello, %s (in %s)' % (std, threading.current_thread().name)) def process_thread(name): # 绑定ThreadLocal的student: local_school.student = name pro...
bot.py
import time import re from slack import WebClient import json import inspect import os import traceback import threading import tempfile import subprocess with open('config.json') as f: config = json.load(f) SLACK_BOT_TOKEN = os.environ['SLACK_BOT_TOKEN'] or config['SLACK_BOT_TOKEN'] # instantiate Slack client s...
test_stdout.py
import multiprocessing import os import random import string import sys import tempfile import time import pytest from dagster import ( DagsterEventType, InputDefinition, ModeDefinition, execute_pipeline, fs_io_manager, pipeline, reconstructable, resource, solid, ) from dagster.cor...
onnxruntime_test_python.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -*- coding: UTF-8 -*- import unittest import os import numpy as np import onnxruntime as onnxrt import threading class TestInferenceSession(unittest.TestCase): def get_name(self, name): if os.path.exists(name)...
mirage.py
import logging try: from Queue import Empty except: from queue import Empty # from redis import StrictRedis from time import time, sleep from threading import Thread from collections import defaultdict # @modified 20190522 - Task #3034: Reduce multiprocessing Manager list usage # Use Redis sets in place of Mana...
s3.py
""" Object Store plugin for the Amazon Simple Storage Service (S3) """ import logging import multiprocessing import os import shutil import subprocess import threading import time from datetime import datetime try: # Imports are done this way to allow objectstore code to be used outside of Galaxy. import boto ...
multi_process_executor.py
# # Copyright 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 i...
multisearcher.py
#!/usr/bin/env python2.7 # -*- encoding: utf8 -*- # Multi searcher by Nas @proclnas <proclnas@gmail.com> # # The MultiSearcher is an open source scan which uses some engines # to find web sites with the use of keywords and phrases. # # Current engines: # [ask, bing, rambler.ru] # # Made to be simple and fast, so this i...
keepkey.py
from binascii import hexlify, unhexlify import traceback import sys from electrum_dongri.util import bfh, bh2u, UserCancelled from electrum_dongri.bitcoin import (b58_address_to_hash160, xpub_from_pubkey, TYPE_ADDRESS, TYPE_SCRIPT, is_segwit_address) from ele...
store.py
import json import logging import os import threading import time import uuid as uuid_builder from copy import deepcopy from os import mkdir, path, unlink from threading import Lock from changedetectionio.notification import ( default_notification_body, default_notification_format, default_notification_tit...
RFCOMM.py
import os import serial import time import json from threading import Thread from lib_oled96 import ssd1306 from smbus import SMBus from PIL import ImageFont def startRFCOMM(): try: ser = serial.Serial("/dev/rfcomm0") if ser.isOpen(): f = open("/home/pi/Downloads/test.txt","a") ...
launch.py
import threading import subprocess def run_script(s): subprocess.run(["python", s], check=True) threading.Thread(target=run_script, args=("server.py",)).start() threading.Thread(target=run_script, args=("shepherd.py",)).start() threading.Thread(target=run_script, args=("ydl.py",)).start()
__init__.py
# -*- coding: utf-8 -*- import time import pafy import audioop import logging import threading as th import subprocess as sp from mumbleroni.core.module.abstract_module import AbstractModule from pymumble.pymumble_py3 import Mumble from bs4 import BeautifulSoup _logger = logging.getLogger(__name__) class YoutubeMu...
train_faster_rcnn_alt_opt.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Train a Faster R-CNN network using alternat...
test_compiled_router.py
from threading import Barrier, Thread from time import sleep from unittest.mock import MagicMock import pytest from falcon.routing import CompiledRouter def test_find_src(monkeypatch): called = False find = CompiledRouter.find def mock(*args): nonlocal called called = True find(...
super-waffle.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import socket import threading import queue import time import struct import uuid import numpy import schedule import hurst import matplotlib.pyplot as pyplot from matplotlib.table import table from keras.models import Model from keras.layers import...
socket_client.py
import socket import errno from threading import Thread HEADER_LENGTH = 10 client_socket = None # Connects to the server def connect(ip, port, my_username, error_callback): global client_socket # Create a socket # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_B...
test_remote_account.py
# Copyright 2015 Confluent 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 writing, s...
Value_test.py
import time from multiprocessing import Process, Value def func(val): """多进程修改共享的数据, Output: 1. 80 2. 86 3. 79 不是进程安全的 Arguments: val {[type]} -- [description] """ for i in range(10): time.sleep(0.1) val.value += 1 if __name__ == '__main__': v = Value...
test_required_confirmations.py
import threading import time import pytest import brownie def send_and_wait_for_tx(): tx = brownie.accounts[0].transfer( brownie.accounts[1], "0.1 ether", required_confs=0, silent=True ) tx.wait(2) assert tx.confirmations >= 2 assert tx.status == 1 @pytest.fixture def block_time_networ...
RandNetPic.py
import sublime, sublime_plugin import re import random import threading from . import ShowImageInSublime import re, os, shutil from . import RandNetPicHelper from . import RandNetPicGamerSky from . import RandNetPicZbjuran class RandomPicLoader(): def __init__(self): self.loader = [] # self.loader....
geneticalgorithm_descend.py
# # # Copyright (C) University of Melbourne 2012 # # # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, ...
client.py
import socket #import socket module #import time import threading import cv2 import base64 import numpy as np def receiveData(client): while(True): data = client.recv(1024).decode() #print(data) try: frame = data img = base64.b64decode(frame) npimg = np.fromstring(img, dtype=np.uint8) source = ...
test_sys.py
import unittest, test.support from test.support.script_helper import assert_python_ok, assert_python_failure import sys, io, os import cosmo import struct import subprocess import textwrap import warnings import operator import codecs import gc import sysconfig import platform import locale # count the number of test ...
misc.py
""" Misc module contains stateless functions that could be used during pytest execution, or outside during setup/teardown of the integration tests environment. """ import contextlib import logging import errno import multiprocessing import os import re import shutil import stat import subprocess import sys import tempf...
screens.py
import asyncio from weakref import ref from decimal import Decimal import re import threading import traceback, sys from typing import TYPE_CHECKING, List from kivy.app import App from kivy.cache import Cache from kivy.clock import Clock from kivy.compat import string_types from kivy.properties import (ObjectProperty,...
sanity_check.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...
java.py
import os import atexit import shutil import tempfile from contextlib import contextmanager import threading import onir logger = onir.log.easy() class _JavaInterface: def __init__(self): self._autoclass = None self._defs = {} self._cache = {} self._jars = [] self._log_lis...
ui.py
import datetime import threading from json import (load as jsonload, dump as jsondump) import PySimpleGUI as sg from apscheduler.schedulers.background import BlockingScheduler from szu_autoconnect.core.auto import Connector SETTINGS_FILE = 'settings.cfg' DEFAULT_SETTINGS = { 'username': '', 'password': '', ...
master_server.py
#!/usr/bin/env python # # Copyright 2013 Tanel Alumae """ Reads speech data via websocket requests, sends it to Redis, waits for results from Redis and forwards to client via websocket """ import sys import logging import json import codecs import os.path import uuid import time import threading import functools from ...
node_provider.py
import random import copy import threading from collections import defaultdict import logging import boto3 import botocore from botocore.config import Config from ray.autoscaler.node_provider import NodeProvider from ray.autoscaler.tags import TAG_RAY_CLUSTER_NAME, TAG_RAY_NODE_NAME, \ TAG_RAY_LAUNCH_CONFIG, TAG_...
LockTest.py
# coding=utf-8 import threading __author__ = 'xubinggui' # 假定这是你的银行存款: balance = 0 lock = threading.Lock() def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(100000): lock.acquire() try: change...
prepare_data.py
import os __file__ = os.path.realpath(__file__) os.chdir(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import sys sys.path.insert(0, os.getcwd()) from core.tokenizer import tokenize # Prepare all files def prepare(): global vocab, written_lines # Files to be prepared files = ...
map_minas_kafka.py
import json import time import os import sys import multiprocessing as mp import numpy as np from numpy import linalg as LA from tornado.ioloop import IOLoop from tornado import gen from kafka import KafkaConsumer from kafka import KafkaProducer import kafka as kafkaPy from minas.map_minas_support import * def _kaf...