source
stringlengths
3
86
python
stringlengths
75
1.04M
glue.py
import boto3 import logging from time import sleep from multiprocessing import Process from botocore.errorfactory import ClientError def get_crawler_state(glue_client, crawler_name): response = glue_client.get_crawler( Name=crawler_name ) return response['Crawler']['State'] def crawl_after_job...
px.py
"Px is an HTTP proxy server to automatically authenticate through an NTLM proxy" from __future__ import print_function __version__ = "0.5.1" import base64 import ctypes import ctypes.wintypes import multiprocessing import os import select import signal import socket import sys import threading import time import tra...
test_concurrent_futures.py
import test.support # Skip tests if _multiprocessing wasn't built. test.support.import_module('_multiprocessing') # Skip tests if sem_open implementation is broken. test.support.import_module('multiprocessing.synchronize') # import threading after _multiprocessing to raise a more revelant error # message: "No module n...
athenad.py
#!/usr/bin/env python3 import base64 import hashlib import io import json import os import sys import queue import random import select import socket import threading import time from collections import namedtuple from functools import partial from typing import Any import requests from jsonrpc import JSONRPCResponseM...
rgb-depth-encoding-sync.py
#!/usr/bin/env python3 import cv2 import sys import time import depthai as dai import numpy as np from pathlib import Path from datetime import datetime from argument_parser import argument_parser from colormaps import apply_colormap from time import monotonic from pairing_system import PairingSystem from multipro...
send_email.py
import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import time import urllib from threading import Thread def send_email(sender_email, password, receiver_email, route='https://www.google.com/'): t = time.localtime() timestamp = time.strftime("%A %B %d %Y %I:%M %...
proxy_flip1.py
#!/usr/bin/env python2 import traceback import random import socket import argparse import threading import signal import sys from contextlib import contextmanager running = True verbose = True CLIENT2SERVER = 1 SERVER2CLIENT = 2 def mitm(buff, direction): #hb = "".join("{:02x}".format(ord(c)) for c in buff) hb ...
servers_test.py
# Copyright 2019 The Oppia 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 applicable ...
mhm2.py
#!/usr/bin/env python # HipMer v 2.0, Copyright (c) 2020, The Regents of the University of California, # through Lawrence Berkeley National Laboratory (subject to receipt of any required # approvals from the U.S. Dept. of Energy). All rights reserved." # Redistribution and use in source and binary forms, with or...
checker.py
import logging import threading import time logger = logging.getLogger(__name__) class Checker: """ Checker class that calls the periodic callback. If you want to force-check within the next second set checker.last_check to 0. """ def __init__(self, callback, period=600): """Checker ...
feeder.py
from sklearn.model_selection import train_test_split import tensorflow as tf import numpy as np import threading import time import os from tqdm import tqdm from pathlib import Path _batches_per_group = 8 from breaker_audio.component_cmn.synthesizer.utils.text import text_to_sequence from breaker_audio.component_cmn....
test_managers.py
import fiber import time import pytest import docker from fiber.managers import AsyncManager @pytest.fixture(scope="module") def client(): return docker.from_env() def f(ns, ls, di): ns.x += 1 ns.y[0] += 1 ns_z = ns.z ns_z[0] += 1 ns.z = ns_z ls[0] += 1 ls[1][0] += 1 # unmanaged, n...
semaphore.py
import threading import time a = threading.Semaphore() a.acquire() # Semaphore can be acquired as many times as you set it to allow. It # defaults to 1, so if you try to acquire twice in the same thread # you'll wait forever. a.release() # You can release as many times as you want with a semaphore that's not # bound, ...
run.py
# -*- coding: utf-8 -*- import os from discord.ext import commands from discord import Embed, Forbidden, Game from threading import Thread from aiosqlite import connect from asyncio import new_event_loop from traceback import format_exc from all_data.all_data import token, prefix, admin_list all_commands_...
co_operator.py
import asyncio, signal, websockets, json, signal from events import events import threading class GracefulExit(SystemExit): code = 1 def raise_graceful_exit(*args): loop.stop() print("Gracefully shutdown") raise GracefulExit() class Operator: port = None host = None def __init__(self, h...
GUI-hw2.py
import socket import json import datetime as dt import matplotlib.pyplot as plt import matplotlib.animation as animation from collections import deque from multiprocessing import Process, Array import sys import time def sensor_data_receiver(lis_of_sensor_data): HOST = "192.168.50.197" PORT = 65431...
wm_interpreter_YOLO.py
#!/usr/bin/env python import roslib import rospy import smach import smach_ros import actionlib import time import threading from smach_ros import SimpleActionState from std_msgs.msg import String from std_msgs.msg import Float32MultiArray RECOGNIZER_CALLBACK = None RECOGNIZER_CALLBACK2 = None def handleRecognizerMe...
runner.py
# Copyright 2018 Datawire. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
simple_stale_attack.py
import argparse import os import time import traceback from pathlib import Path import threading import fnfqueue from scapy.layers.inet import IP, TCP from scapy.packet import Raw from dhalsim.network_attacks.utilities import launch_arp_poison, restore_arp, \ translate_payload_to_float, translate_float_to_payload...
day-019-acquire_a_thread_lock-3.4.3.py
#!/usr/bin/env python3 import threading, time def takeANap(): time.sleep(5) print('Wake up!') print('Start of program.') threadObj = threading.Thread(target=takeANap) threadObj.start() print('End of program.')
task2.2.2.py
# Material: # Link to the Colab notebook: # https://colab.research.google.com/drive/1s5F1uFqCK1MOG2GHzCWqSWqECDmC3O5h#scrollTo=zPmrTNlSBW-R # You may find the IPYNB/RISE notebook in: # robotic_systems_lab/notebooks/_modeling_and_control_of_manipulators.ipynb # Link to the practice report: # https://docs.google.com/do...
indexes.py
import datetime import Queue from threading import Thread import time from django.test import TestCase from haystack import connections, connection_router from haystack.exceptions import SearchFieldError from haystack import indexes from haystack.utils.loading import UnifiedIndex from core.models import MockModel, AThi...
pssh.py
import paramiko class ssh: shell = None client = None transport = None def __init__(self, address, port, username, password): print("Connecting to server on ip", str(address) + ".") self.client = paramiko.client.SSHClient() self.client.set_missing_host_key_policy(paramiko.Auto...
test_client.py
import asyncio import functools import gc import inspect import logging import os import pickle import random import subprocess import sys import threading import traceback import warnings import weakref import zipfile from collections import deque from contextlib import suppress from functools import partial from oper...
parent_launcher.py
from __future__ import print_function from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * __author__ = 'Administrator' import subprocess import os import threading fr...
main_window.py
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@gitorious # # 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 witho...
navbox.py
#!/usr/bin/python """ ARDrone3 autonomous landing on ARDrone2 box with Orinted Roundel usage: !!! WORK IN PROGRESS !!! ./navbox.py <task> [<metalog> [<F>]] | --test <image|video> [<stopAt index>] """ import sys import math import cv2 import os import numpy as np import inspect BEBOP_ROOT = os.path.rea...
app.py
## Set Initial Variables ## import os # Miscellaneous operating system interface import zmq # Asynchronous messaging framework import time # Time access and conversions import sys # System-specific parameters and functions from matrix_io.proto.malos.v1 import driver_pb2 # MATRIX Protocol Buffer driver library from matr...
cloudd.py
import os import tutils import config as cfg from multiprocessing import Process, cpu_count, Value from threading import Thread import time import cv2 import matplotlib.pyplot as plt class ServiceMonitor(object): def __init__(self, monitor_d): self.monitor_d=monitor_d self.ignored=self.index_existi...
test_bson.py
# -*- coding: utf-8 -*- # # Copyright 2009-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 applicab...
data_store.py
#!/usr/bin/env python """The main data store abstraction. The data store is responsible for storing AFF4 objects permanently. This file defines the basic interface of the data store, but there is no specific implementation. Concrete implementations should extend the DataStore class and provide non-abstract methods. T...
test_dbdict.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Path hack import os, sys sys.path.insert(0, os.path.abspath('..')) from threading import Thread import unittest from tests.test_custom_dict import BaseCustomDictTestCase from requests_cache.backends.storage.dbdict import DbDict, DbPickleDict class DbdictTestCase(BaseCu...
client.py
import weakref, types, collections, struct, time, socket,threading,random,os,logging,traceback,queue,libnacl,select from typing import Sequence, Optional, Tuple from .common import nonce_from_number,pavillion_logger,DEFAULT_PORT,DEFAULT_MCAST_ADDR,ciphers,MAX_RETRIES,preprocessKey from . import common import pavill...
test_lock.py
import unittest import time import threading import uuid import redis from nose.tools import raises from nose.tools import eq_ from retools import global_connection class TestLock(unittest.TestCase): def _makeOne(self): from retools.lock import Lock return Lock def _lockException(self): ...
foo.py
# Python 3.3.3 and 2.7.6 # python fo.py from threading import Thread, Lock # Potentially useful thing: # In Python you "import" a global variable, instead of "export"ing it when you declare it # (This is probably an effort to make you feel bad about typing the word "global") i = 0 Lock = Lock() def incrementing...
builder.py
import os from misc.logos import builder_logo from misc.win_deleter import F_0391 from core.utils import clear from core.colors import * from core.Sessions.sessions import Session from core.Sessions.Connection import * scky_backdoor_code=""" import socket import base64 import time import psutil import subprocess impo...
driver.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2011 Piston Cloud Computing, Inc # Copyright (c) 2012 University Of Minho # (c) Copyright 2013 Hewlett-Pa...
cnn_util.py
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
test_table_count.py
import random import pdb import pytest import logging import itertools from time import sleep from multiprocessing import Process from milvus import IndexType, MetricType from utils import * dim = 128 index_file_size = 10 add_time_interval = 3 tag = "1970-01-01" class TestTableCount: """ params means differen...
views.py
from django.shortcuts import render import os from .models import Project, ProjectEntry, OszScriptGen from .tables import ProjectEntry as ProjectEntry_table from .tables import Plan_Gas_OSZ as Plan_Gas_OSZ_table from .forms import get_Form import threading import subprocess import datetime from Exp_Main.models import R...
local_scheduler_test.py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and 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 abc import json import multiprocessing as mp import os import shutil import signa...
trainer.py
import os import pickle import shutil import time from datetime import datetime from os.path import exists, join, relpath from threading import Thread from typing import List, Union, Optional, Dict, Tuple import pandas as pd import numpy as np import tensorflow as tf from tensorflow.python.training.adadelta import Ada...
test_slave.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for drmaa_futures slave.""" from __future__ import print_function import os import sys import time import pytest import signal import subprocess from contextlib import contextmanager import logging import dill as pickle # Allow e.g. pickling of lambdas # import ...
chiatter.py
#!/usr/bin/env python3 ''' @author: Winter Snowfall @version: 2.50 @date: 06/11/2021 Warning: Built for use with python 3.6+ ''' from prometheus_client import start_http_server, Gauge from modules.chia_stats import chia_stats from modules.truepool_stats import truepool_stats from configparser import ConfigParser from...
default.py
""" Provides the #DefaultTaskManager which operates locally to run tasks in a pool of threads. """ import dataclasses import logging import queue import sys import threading import time import typing as t import uuid import weakref from . import api from .api import ExcInfoType, Runnable, TaskStatus from .util impor...
apps.py
from django.apps import AppConfig from threading import Thread import threading import os import schedule import time from datetime import timedelta, datetime from django.utils import timezone from dateutil.relativedelta import relativedelta class RunThread: @staticmethod def run_threaded(job_func): ...
test_failure.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import pytest import sys import tempfile import threading import time import numpy as np import redis import ray import ray.ray_constants as ray_constants from ray.cluster_utils import C...
cmd_helper.py
# 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. """A wrapper for subprocess to make calling shell commands easier.""" import logging import os import pipes import select import signal import string im...
plotting.py
"""PyVista plotting module.""" import collections.abc import ctypes from functools import wraps import io import logging import os import pathlib import platform import textwrap from threading import Thread import time from typing import Dict import warnings import weakref import numpy as np import scooby import pyvi...
vwsfriend_base.py
import os import sys import re import argparse from datetime import datetime, timedelta, timezone import logging import logging.handlers import time import tempfile import netrc import threading from pyhap.accessory_driver import AccessoryDriver from weconnect import weconnect from weconnect.errors import APICompati...
test_pooling_base.py
# Copyright 2012 10gen, 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, soft...
common.py
import inspect import json import os import random import subprocess import ssl import time import requests import ast import paramiko import rancher import pytest from urllib.parse import urlparse from rancher import ApiError from lib.aws import AmazonWebServices from copy import deepcopy from threading import Lock fr...
api.py
import argparse import logging import json import os import queue import socket import struct import threading import time import bjoern import falcon from falcon_cors import CORS from gamutrf.__init__ import __version__ from gamutrf.birdseye_rssi import BirdsEyeRSSI, RSSI_UDP_ADDR, RSSI_UDP_PORT, MAX_RSSI, FLOAT_SIZ...
pref2.py
from socket import * import time sock = socket(AF_INET, SOCK_STREAM) sock.connect(('localhost', 25000)) n = 0 from threading import Thread def monitor(): global n while True: time.sleep(1) print(n, 'reqs/sec') n = 0 Thread(target=monitor).start() while True: sock.send(b'1') re...
urllib3_tests.py
import threading import mock import urllib3 import opbeat import opbeat.instrumentation.control from opbeat.traces import trace from tests.helpers import get_tempstoreclient from tests.utils.compat import TestCase try: from http import server as SimpleHTTPServer from socketserver import TCPServer except Impo...
cmd.py
# -*- Coding:utf-8 -*- # !/usr/bin/env python3 """ ################################################################################ Command will be execute ################################################################################ """ import os import sys import re import threading from contextlib ...
Client.py
import socket, argparse, signal, time, sys from ipaddress import ip_address from playsound import playsound from threading import Thread from Videofeed import Videofeed class Client: def __init__(self, path, TCP_IP = "127.0.0.1", TCP_PORT = 8080, BUFFER_SIZE = 32768): self.BUFFER_SIZE = BUFFER_SIZE ...
discovery.py
import socket from datetime import datetime import struct, time from threading import Thread from .plug import EcoPlug def normalize_string(x): if type(x) == bytes: return x.rstrip(b' \t\r\n\0') return x class EcoDiscovery(object): UDP_PORT = 8900 def __init__(self, on_add, on_remove): ...
__init__.py
# -*- coding: utf-8 -*- __author__ = 'matth' import threading import traceback import sys import subprocess import time import uuid import logging import json import argparse import shlex import os import jsonrpc try: import queue except ImportError: import Queue as queue import pkgutil from processfamily.thre...
batch_job.py
# This is an implementation of layer executor # design principles # 1. Every *Task* will not be executed immediately, they will be merged into one *job* # 2. Every *Job* is composed of several tasks # 3. Tasks are accumulated by a fixed time interval or fixed account # 4. Job has it's own executor, can be thread...
myemail.py
from threading import Thread import flask from flask_mail import Mail, Message mail = Mail() def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(subject, sender, recipient, text_body, html_body): msg = Message(subject=subject, sender=sender, recipients=[recipient],...
explicit_threading.py
# Copyright 2019, OpenCensus 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 w...
option.py
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import binascii import cookielib import glob import inspect import logging import httplib import os import random import re import socket import string import sys import tempf...
stream.py
from datetime import timedelta from multiprocessing import Process from os import kill, mkfifo, makedirs from os.path import join from signal import SIGINT from tempfile import mkdtemp from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCom...
cc.py
#!/usr/bin/python3 #Coded by Grant ######################################### # Updated version # # -- Grant # ######################################### import requests import socket import socks import time import random import threading import sys import ssl import datetime ...
omni.py
""" Main / Top Level for the OmniAura Synthesizer. author: Omar Barazanji (omar@omniaura.co) Python 3.7.x """ import redis import json import numpy as np import os import ast r = redis.Redis.from_url(url='redis://127.0.0.1:6379/0') import platform OS = 'Windows' if platform.system() == 'Linux': ...
JobBrowserBFF_JSONRPCServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from wsgiref.simple_server import make_server from JobBrowserBFF.jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \ JSO...
rbssh.py
#!/usr/bin/env python # # rbssh.py -- A custom SSH client for use in Review Board. # # This is used as an ssh replacement that can be used across platforms with # a custom .ssh directory. OpenSSH doesn't respect $HOME, instead reading # /etc/passwd directly, which causes problems for us. Using rbssh, we can # work arou...
test_api.py
import tempfile import threading import time from pathlib import Path from aria2p import API, Client, Download from . import ( BUNSENLABS_MAGNET, BUNSENLABS_TORRENT, CONFIGS_DIR, DEBIAN_METALINK, SESSIONS_DIR, TESTS_TMP_DIR, XUBUNTU_MIRRORS, Aria2Server, ) def test_add_magnet_method(...
test_case1.py
#coding=utf-8 import sys sys.path.append("E:/Teacher/Imooc/AppiumPython") import unittest import HTMLTestRunner import threading import multiprocessing from util.server import Server import time from appium import webdriver from business.login_business import LoginBusiness from util.write_user_command import WriteUserC...
__init__.py
# -*- coding: UTF-8 -*- #virtualBuffers/__init__.py #A part of NonVisual Desktop Access (NVDA) #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2007-2017 NV Access Limited, Peter Vágner import time import threading import ctypes import collection...
cli.py
# -*- coding: utf-8 -*- """ flask.cli ~~~~~~~~~ A simple command line application to run flask apps. :copyright: © 2010 by the Pallets team. :license: BSD, see LICENSE for more details. """ from __future__ import print_function import ast import inspect import os import re import ssl import sys ...
test_restart_services.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...
dataloader_iter.py
# Copyright (c) 2020 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 appli...
engine.py
import os import sys import glob import time import logging import threading import collections from importlib.machinery import SourceFileLoader from cantoolz.can import CANSploitMessage class CANSploit: """ Main class implementing the core logic of CANToolz. The class is responsible for parsing the u...
diva_pipeline_v2.py
## demo for diva_pipline ## version: v2 ## last modified 2017.10.06 import time import os import config import diva_parameters from diva_parameters import models, prepipeline, pipeline, pipename,is_parallel from diva_parameters import GPUS, conf, timestamp import pre_process_chunk import merge_inner_chunk import conf...
executor.py
""" Driver of the test execution framework. """ from __future__ import absolute_import import threading from . import fixtures from . import hooks as _hooks from . import job as _job from . import report as _report from . import testcases from .. import config as _config from .. import errors from .. import logging ...
infra.py
#!/usr/bin/env python3 # Ours from peerTry import Peer # Theirs from flask import Flask import requests # Standard import random import re import socket import time from threading import Thread # Globals app = Flask(__name__) INFRA_PORT = 33501 POD_PORT = 33033 POD_HOST = '0.0.0.0' POD_ENDPOINT = '/sensor' HOST_FMT...
01.multiprocessing_pool.py
from multiprocessing import Process, current_process print(f'1 - Iniciando o processo com nome: {current_process().name}') def faz_algo(valor): print(f'valor = {valor}') def main(): pc = Process(target=faz_algo, args=('Passaro', ), name='Processo interno') print(f'2 - Iniciando o processo com nome: {pc...
test_ae.py
"""Tests for the ae module.""" import logging import os import signal import threading import time import pytest from pydicom import read_file from pydicom.dataset import Dataset from pydicom.uid import UID, ImplicitVRLittleEndian from pynetdicom import ( AE, evt, debug_logger, build_context, DE...
omreegalozContigFilterServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import json import os import random as _random import sys import traceback from getopt import getopt, GetoptError from multiprocessing import Process from os import environ from wsgiref.simple_server import make_server import requests as _requests from json...
position.py
from scipy.io import wavfile import numpy as np import sounddevice as sd import pygame from pygame.locals import * from threading import Thread pygame.init() def process(): global final tmp = np.zeros((dur + fs, 2), dtype=np.int16) for i in range(nfile): xf = np.arange(len(data[i])) dl =...
part2.py
import copy import sys import threading from collections import defaultdict def read_input(): # for puzzles where each input line is an object with open('input.txt') as fh: decks = [[], []] cur_player = 0 for line in fh.readlines(): if not line.strip(): cur...
test_connections.py
import socket import threading import ssl import OpenSSL import pytest from unittest import mock from mitmproxy import connections from mitmproxy import exceptions from mitmproxy.net import tcp from mitmproxy.net.http import http1 from mitmproxy.test import tflow from mitmproxy.test import tutils from .net import tser...
build.py
# Copyright 2014 The Oppia 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 applicable ...
service.py
import asyncio import base64 import logging import random import time import traceback from threading import Thread from typing import Dict, Any from bacpypes.debugging import ModuleLogger, bacpypes_debugging from hbmqtt.broker import Broker from bacprop import config from bacprop.bacnet.network import VirtualSensorN...
custom.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
PlatformManagerDarwin.py
""" Platform-specific code for Darwin is encapsulated in this module. """ import os import re import tempfile import threading import subprocess try: import Tkinter as tk import Queue as queue except ImportError: import tkinter as tk import queue import numpy import AppKit import Quartz from PIL impor...
archiver.py
import argparse import errno import io import json import logging import os import pstats import random import re import shutil import socket import stat import subprocess import sys import tempfile import time import unittest from binascii import unhexlify, b2a_base64 from configparser import ConfigParser from datetim...
worker.py
"""Embedded workers for integration tests.""" from __future__ import absolute_import, unicode_literals import os import threading from contextlib import contextmanager from celery import worker from celery.result import _set_task_join_will_block, allow_join_result from celery.utils.dispatch import Signal from celery....
batcher.py
#Most of this file is copied form https://github.com/abisee/pointer-generator/blob/master/batcher.py import queue import time from random import shuffle from threading import Thread import numpy as np import tensorflow as tf from data_util import config from data_util import data import random random.seed(1234) c...
tasks_plugin.py
# =============================================================================== # Copyright 2013 Jake Ross # # 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...
config.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: r""" A Python module to maintain unique, run-wide *fMRIPrep* settings. This module implements the memory structures to keep a consistent, singleton config. Settings are passed across processes via filesyst...
periodic.py
#!/usr/bin/env python import argparse import sys import signal import hashlib import select import pickle import os import git import datetime import base64 import logging import imp import tempfile import time import json import argparse import random import re import shutil import traceback import xml.etree.ElementTr...
event_tests.py
import os import time import unittest import threading import classad import htcondor SAMPLE_EVENT_TEXT = """\ 006 (23515.000.000) 04/09 17:55:39 Image size of job updated: 260 1 - MemoryUsage of job (MB) 252 - ResidentSetSize of job (KB) ... """ class TestEventReader(unittest.TestCase): de...
server.py
import socketserver import os import random import threading # Clears the stuff file open(os.getcwd() + "/stuff.txt", 'w').close() f = open(os.getcwd() + "/stuff.txt", 'r+') class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): client, address = self.client_address r...
day27-8 互斥锁.py
# 互斥锁可以保证同一时间只有一个线程去执行代码,能够保证全局变量的数据没有问题 # 线程等待(join)和互斥锁都是将多任务改成单任务去执行,保证了数据的准确性,但是执行效率降低。 import threading # 全局变量 g_num = 0 # 创建互斥锁,Lock本质上是一个函数,通过调用函数创建一个互斥锁 lock = threading.Lock() def task1(): # 为了保证全局变量在使用中不能有其他线程进行操作,所以在使用全局变量前加锁 # 所有使用全局变量的任务都要上锁,不然别处还是会修改全局变量 lock.acquire() for i in range(10...
grpc_bridge_test.py
# Copyright 2020 Adap GmbH. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
threaded.py
from time import sleep from threading import Thread from threading import Event class Threaded: def __init__(self, name=None): self.__threaded_name = name self.__threaded_thread = None self.__threaded_stop_event = Event() def work(self): pass def __thread_worker(self): ...
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...