source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
helpers.py | """High-level functions to help perform complex tasks
"""
from __future__ import print_function, division
import os
import multiprocessing as mp
import warnings
from datetime import datetime
import platform
import struct
import shutil
import copy
import numpy as np
import pandas as pd
import time
pd.options.display.m... |
app.py | # -*- coding: utf-8 -*-
"""
:author: Grey Li (李辉)
:url: http://greyli.com
:copyright: © 2018 Grey Li
:license: MIT, see LICENSE for more details.
"""
import os
from threading import Thread
import sendgrid
from sendgrid.helpers.mail import Email as SGEmail, Content, Mail as SGMail
from flask_mail import... |
camera.py | import os
import glob
import time
import datetime
import threading
import multiprocessing
import cv2
import firebase_admin
import playsound as playsound
from firebase_admin import credentials
from firebase_admin import storage
from firebase_admin import firestore
from uuid import uuid4
import numpy as np
from PIL impor... |
bridge.py | import serial.tools.list_ports
import serial
import threading
from sys import exit,stderr
from time import sleep
stm = None
ball = None
def persistentOpen(description,baudrate=115200):
while True:
try:
for p in serial.tools.list_ports.comports():
if p.description.s... |
trezor.py | from binascii import hexlify, unhexlify
import traceback
import sys
from electrum.util import bfh, bh2u, versiontuple, UserCancelled
from electrum.bitcoin import (b58_address_to_hash160, xpub_from_pubkey, deserialize_xpub,
TYPE_ADDRESS, TYPE_SCRIPT, is_address)
from electrum import consta... |
spl.py | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015,2019
"""
SPL Python primitive operators.
********
Overview
********
SPL primitive operators that call a Python function or
class methods are created by decorators provided by this module.
The name of the function or callable class becom... |
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... |
mp_image.py | #!/usr/bin/env python
'''
display a image with scrollbars in a subprocess
Andrew Tridgell
June 2012
'''
import mp_util, time, wx, cv, mp_widgets
class MPImage():
'''
a generic image viewer widget for use in MP tools
'''
def __init__(self,
title='MPImage',
width=512,
... |
client4_3.py | import socket, sys
from threading import Thread
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 53331))
print("Connected to chat")
def messenger():
while True:
message = input()
if message == "exit":
sock.send(message.encode())
... |
joshua.py | #!/usr/bin/env python3
"""
joshua.py
"""
# This source file is part of the FoundationDB open source project
#
# Copyright 2013-2020 Apple Inc. and the FoundationDB project authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
store.py | import datetime
import json
import threading
import uuid
from collections import defaultdict
from copy import deepcopy
from dictdiffer import diff
from inspect import signature
from threading import Lock
from pathlib import Path
from tzlocal import get_localzone
from .logger import logger
from .settings import CACHE_... |
rasp.py | import multiprocessing as mp
import sys
import time
import os
import cv2
import numpy as np
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5 import uic
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
alert = 24
GPIO.setup(alert, GPIO.OUT)
idleTime = 10 # second
threshold = 1.6
label_w = 800
label_h = 600
#
de... |
tello-state.py | #!/usr/bin/python3
"""
@brief This is program for stream sensor states from Tello.
@author Murtadha Bazli Tukimat
@date 17-Nov-2020
"""
import threading
import socket
import time
"""
@brief Host IP address. 0.0.0.0 referring to current
host/computer IP address.
"""
host_ip = "0.0.0.0"
"""
... |
host_callback_test.py | # Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
wrappers_atari.py | # This code is mainly excerpted from openai baseline code.
# https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py
import numpy as np
from collections import deque
import gym
from gym import spaces
import cv2
from abc import ABC,abstractmethod
from multiprocessing import Process, Pipe
from ... |
test.py | #!/usr/bin/env python3
import json
import tempfile
import time
import threading
import unittest
from multiprocessing import Process
from selfdrive.athena import athenad
from selfdrive.athena.athenad import dispatcher
from selfdrive.athena.test_helpers import MockParams, MockApi
from cereal import messaging
class Tes... |
__init__.py | # -*- coding: utf-8 -*-
"""
keyboard
========
Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.
## Features
- **Global event hook** on all keyboards (captures keys regardless of focus).
- **Listen** and **send** keyboard event... |
test_api.py | """Tests for the `api` module."""
import threading
import time
import pytest
from aria2p import API, Client, ClientException, Download
from . import BUNSENLABS_MAGNET, BUNSENLABS_TORRENT, CONFIGS_DIR, DEBIAN_METALINK, INPUT_FILES, XUBUNTU_MIRRORS
from .conftest import Aria2Server
def test_add_magnet_method(server... |
main.py | # -*- coding: utf-8 -*-
import os
import socket
import re
import subprocess
import struct
import sys
import blessed
import random
import http.server
import socketserver
import multiprocessing
from Crypto.Cipher import AES
import base64
import string
import glob
import readline
import time
#from lib.psexec import *
impo... |
parallel.py | from multiprocessing import Process, Pipe, Value
import time
import os
class StopGenerator:
def __init__(self, pid=None):
self.pid = pid
class DataLoader:
def __init__(self, generator, batch_size=4, maxsize=32, collate_fn=None, shuffle=False):
self.generator = generator
self.batch_si... |
cvcameraperipheral.py | import asyncio
import traceback
import logging
from jdiotclient import logger
from jdiotclient.client import JDIoTClient
from jdiotclient.pheripheral import JDIoTCameraPeripheral
from jdiotclient.protocol.python.jdiotprotocol_pb2 import *
import cv2
import threading
import time
class CVCameraPeripheral(JDIoTCameraPe... |
webcam2rgb.py | import cv2
import numpy as np
import threading
class Webcam2rgb():
def start(self, callback, cameraNumber=0, width = None, height = None, fps = None, directShow = False):
self.callback = callback
try:
self.cam = cv2.VideoCapture(cameraNumber + (cv2.CAP_DSHOW if directShow else cv2.C... |
reminders.py | import datetime
import os
import threading
from ...helpers import save_json, load_json, is_channel_name
from ...signals import message_out, on_exception
from ...message import Message
from .. import BaseResponder
from ..lib import parse_command
import re
def make_msg_entry(author, target, message, time):
return {... |
experiment_distributed_deltahq.py | #!/usr/bin/env python3
import subprocess as sp
import sys
import os
import numpy as np
from multiprocessing import Process
scenario_dir = "../deltahq_distributed_json"
def run_deltahq(idx):
command = ["./deltaHQ", "-t", "1", "-i", str(idx), "100node.json", "-L", "10000"]
result = sp.Popen(command, stdout=sp.... |
SubprocessorBase.py | import traceback
import multiprocessing
import time
import sys
from interact import interact as io
class Subprocessor(object):
class SilenceException(Exception):
pass
class Cli(object):
def __init__ ( self, client_dict ):
self.s2c = multiprocessing.Queue()
self.c2s = ... |
__init__.py | from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from flask_migrate import Migrate
import os
import logging
import threading
basedir = os.path.abspath(os.path.dirname(__name__))
# Init app
app = Flask(__name__)
CORS(app)
# Database
app.co... |
coordinator_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... |
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 KPD.src.utils.img import load_image, cropBox, im_to_torch
from opt import opt
from yolo.preprocess import prep_image, prep_frame, inp_to_image
from... |
run_nvmf.py | #!/usr/bin/env python3
import os
import re
import sys
import json
import paramiko
import zipfile
import threading
import subprocess
import itertools
import time
import uuid
import rpc
import rpc.client
from common import *
class Server:
def __init__(self, name, username, password, mode, nic_ips, transport):
... |
zmirror.py | #!/usr/bin/env python3
# coding=utf-8
import os
import sys
import re
import copy
import zlib
import sched
import queue
import base64
import random
import traceback
import ipaddress
import threading
from fnmatch import fnmatch
from time import time, sleep, process_time
from html import escape as html_escape
from dateti... |
event_processor.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
GoodClock.py | import ntplib
import time
from datetime import datetime, timedelta
import threading
class ResponseTime():
sum_RTT = 0
num_requests = 0
def add(self, delay):
self.sum_RTT += float(delay)
self.num_requests += 1
def avg(self):
return self.sum_RTT / self.num_requests
class NTPResponse():
monotonic = 0
offset... |
scheduler.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
USAGE = """
## Example
For any existing app
Create File: app/models/scheduler.py ======
from gluon.scheduler import Scheduler
def demo1(*args,**vars):
print 'you passed args=%s and vars=%s' % (args, vars)
return 'done!'
def demo2():
1/0
scheduler = Schedul... |
sanic_test.py | import pytest
from multiprocessing import Process
from common import send_requests, mode_list, kwargs_list
def server_process(port, mode, **kwargs):
from sanic import Sanic, response
app = Sanic(__name__)
@app.get(r'/hello/world')
async def index_handler(request):
return response.text('Hell... |
user.py | #!/usr/bin/env python2.7
import argparse # new in Python2.7
import os
import time
import string
import atexit
import threading
import logging
import sys
logging.basicConfig(level=logging.ERROR)
from yapsy.PluginManager import PluginManager
# Load the plugins from the plugin directory.
manager = PluginManager()
runO... |
file_server.py | #########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. 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... |
extract_methods.py | """Different methods for extraction to be used by the calling process"""
import time
import queue
import threading
import logging
import redis
import can
# Intermediate data format read from CAN Bus is: "timestamp.nnnn 0xID 0xDATA"
CANBUS_DATA_FORMAT = "{} {:02X} {}"
log = logging.getLogger()
log.setLevel("INFO")
... |
ProjE_softmax_noweight.py | import argparse
import math
import os.path
import timeit
from multiprocessing import JoinableQueue, Queue, Process
import numpy as np
import tensorflow as tf
class ProjE:
@property
def n_entity(self):
return self.__n_entity
@property
def n_train(self):
return self.__train_triple.shap... |
dataset.py |
# Global dependencies
from OAI.config import IMG_DIR_PATH, CLINICAL_CONTROL_COLUMNS, IMG_CODES_FILENAME, NON_IMG_DATA_FILENAME, \
N_DATALOADER_WORKERS, CACHE_LIMIT
import os
import pdb
import copy
import random
import pickle
import cv2
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, ... |
cnn_util.py | # coding=utf-8
# Copyright 2019 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... |
dask.py | # pylint: disable=too-many-arguments, too-many-locals, no-name-in-module
# pylint: disable=missing-class-docstring, invalid-name
# pylint: disable=too-many-lines, fixme
# pylint: disable=too-few-public-methods
# pylint: disable=import-error
"""
Dask extensions for distributed training
----------------------------------... |
driller.py | import os
import re
import time
import shutil
import logging
import tarfile
import pathlib
import tempfile
import webbrowser
import threading
from contextlib import suppress
from timeout_decorator.timeout_decorator import TimeoutError
from . import utils
from . import engines
from . import messages
from . import decode... |
test_replication.py | """TestCases for distributed transactions.
"""
import os
import time
import unittest
from test_all import db, test_support, have_threads, verbose, \
get_new_environment_path, get_new_database_path
#----------------------------------------------------------------------
class DBReplicationManage... |
bjtalk_test.py | import time
import socket
from threading import Thread
import pyaudio
def log(*args):
print(*args)
class BjtalkClient:
def __init__(self, serv_addr):
# ('127.0.0.1', 27010)
self.serv_addr = serv_addr
self.c = socket.socket(2, 2)
self.c.bind(('127.0.0.1', 27012))
p = p... |
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()
ips = IP("10.0.1.0/24")
def f(i,q):
while True:
if q.empty():
sys.exit()
print "Process Number: %s" % i
ip = q.get()
ret = subprocess... |
backups.py | # Copyright (C) 2018-2020 Amano Team <contact@amanoteam.com>
#
# 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, mod... |
test_identifiers.py | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
adv_train.py | #!/usr/bin/env python3
import argparse
import collections
import math
import multiprocessing
import os
import random
import shutil
import signal
import time
from typing import Any, Dict, Optional, Tuple
import numpy as np
import torch
from fairseq import data, distributed_utils, options, progress_bar, tasks, utils
fr... |
uvicorn.py | import os
import sys
import signal
import logging
import multiprocessing
from threading import Thread
from typing import Union
from uvicorn.server import Server
from uvicorn.config import Config
from uvicorn.supervisors import ChangeReload, Multiprocess
from uvicorn.middleware.debug import DebugMiddleware
from constant... |
server.py | """Basic http server for tests to simulate PyPI or custom indexes
"""
import time
import threading
from setuptools.extern.six.moves import BaseHTTPServer, SimpleHTTPServer
class IndexServer(BaseHTTPServer.HTTPServer):
"""Basic single-threaded http server simulating a package index
You can use this server i... |
chat.py | # chat.py
import sys
from threading import Thread
from prompt_toolkit.application import Application
from prompt_toolkit.document import Document
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import HSplit, Window
from prompt_toolkit.layout.layout import Layout
from prompt_t... |
executor.py | # Lint as: python3
# Copyright 2020 Google LLC. 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 ... |
fintch_processing_process_kantone.py | ######################################################################
# Copyright (C) 2021 BFH
#
# Script for processing Cantons in the FINT-CH project.
#
# Author: Christoph Schaller, BFH-HAFL, December 2021
######################################################################
import os
import sys
import math
impo... |
multithreaddbv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Display current decibel readings with a graphical gauge."""
# TODO: (interpolated) data points at 15 samples/second
# TODO: send most recent 300 samples at a time
# TODO: upload to FTP once per second
# Revised TODO items, for multithreaded version:
#
# don't write te... |
proxy.py | #!/usr/bin/env python2
#Author Phinfinity <rndanish@gmail.com>
"""
Simple hacked up https transparent proxy
works on desktops/laptops running linux
Add iptables rules (in order):
iptables -t nat -A OUTPUT -d 192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,127.0.0.1 -j ACCEPT
iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT... |
0_GazeCalibration_PL2D.py | from data_analysis import gaze
from data_analysis.session import Session
from data_analysis.utils import read_yaml
from data_analysis.process import BaseProcess
from data_analysis.gaze.pupil_detection_pl import run_pupil_detection_PL
from data_analysis.gaze.pupil_detection_pl import creat_output_data
from data_analysis... |
mainwindow.py | import json
import os
import sys
from threading import Thread
from typing import Dict, Optional, Tuple, Union
sys.path.append(os.getcwd()) # must be ran in sbumips directory (this is bc PYTHONPATH is weird in terminal)
from constants import *
from interpreter.interpreter import Interpreter
from interpreter.utility i... |
reconnectingwebsocket.py | # # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... |
socket_server.py | from http import server
from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
from threading import Thread
from time import sleep
HOST = ""
PORT = 8050
server = socket(AF_INET, SOCK_STREAM)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind((HOST, PORT))
print("Server bind success!")
c... |
test_kernel.py | """test the IPython Kernel"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import ast
import os.path
import platform
import subprocess
import sys
import time
from tempfile import TemporaryDirectory
from flaky import flaky
import pytest
from packaging import ver... |
v1.2.2.1.py | from random_user_agent.user_agent import UserAgent
import threading
import random
import logging
import socket
import socks
import time
import sys
import ssl
logging.basicConfig(
format="[%(asctime)s] %(message)s",
datefmt="%H:%m:%S",
level=logging.INFO
)
active_threads = 0
try:
max_threads = int(input("Max Threa... |
run_flask_bg_tasks.py | from flask import Flask
from time import sleep
from threading import Thread
from datetime import datetime
app = Flask(__name__)
def background_task():
while True:
print(datetime.now())
sleep(1)
@app.route('/')
def hello_world():
return '<p>Hello, World!</p>'
if __name__ == '__main__':
th... |
pdbMonomerExtractor.py | import os,sys,time
from multiprocessing import Queue, Process
import multiprocessing
def generateMonomerPDBFilesWork(taskQueue_pdbDict, allPDBFilesDirectory, generateMonomerPDBFilesErrorQueue):
while True:
pdbName, pdbDict = taskQueue_pdbDict.get()
taskQueue_pdbDict.task_done()
if pdbName is None:
break
pd... |
watch.py | import threading
import time, sys, datetime
from selenium import webdriver
import urllib
class WatchYoutube(object):
""" WatchYoutube class
The run() method will be started and it will run in the background
until the video ends.
"""
def __init__(self, interval=1, video_id='GSAfPHun-9I', download_a... |
__main__.py | import logging.handlers
import signal
import threading
from curses import window, wrapper # type: ignore
from functools import partial
from types import FrameType
from tg import config, update_handlers, utils
from tg.controllers import Controller
from tg.models import Model
from tg.tdlib import Tdlib
from tg.views im... |
numpyvisdomlogger.py | from __future__ import division, print_function
import atexit
from collections import defaultdict
import os
if os.name == "nt":
IS_WINDOWS = True
from queue import Queue
from threading import Thread as Process
else:
IS_WINDOWS = False
try:
from torch.multiprocessing import Queue, Process
... |
tests.py | from __future__ import unicode_literals
import sys
import threading
import time
from unittest import skipIf, skipUnless
from django.db import (
DatabaseError, Error, IntegrityError, OperationalError, connection,
transaction,
)
from django.test import (
TransactionTestCase, skipIfDBFeature, skipUnlessDBFea... |
draw_PL_IDs.py | #!/usr/bin/env python3
###############################################################################
# Includes
###############################################################################
import struct
from xml.sax.handler import property_xml_string
import rclpy
from rclpy.node import Node
from std_msgs.msg impo... |
tileparser_gui.py | #!/usr/bin/env python
from __future__ import division
from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork
import os
import time
from threading import Thread
from PyQt4.QtCore import QString
from merge_tiles import VERSION, get_available_layers
LAYERS = get_available_layers()
class Progress(QtCore.QThread):
noti... |
views.py | from django.shortcuts import render
from .models import OtherContributors,Job
from rest_framework import status
from rest_framework.generics import (
ListAPIView,
ListCreateAPIView,
ListAPIView,
RetrieveUpdateAPIView,)
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticat... |
OxygenX.py | version = "0.10.4"
# this needs to be the first line
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from multiprocessing.dummy import Pool as ThreadPool
from os import mkdir, path, system, name, rename, _exit
from random import choice
from re import compile... |
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... |
pyroserver.py | import numpy as np
import tensorflow as tf
import os
import subprocess
import threading
import uuid
import random
import queue
import traceback
import util
import time
import tempfile
import Pyro4
import dill as pickle
import cloudpickle
import collections
from neurosat import apply_neurosat, NeuroSATParams, NeuroSATAr... |
manager.py | #!/usr/bin/env python3.7
import os
import time
import sys
import fcntl
import errno
import signal
import shutil
import subprocess
import datetime
from common.basedir import BASEDIR, PARAMS
from common.android import ANDROID
sys.path.append(os.path.join(BASEDIR, "pyextra"))
os.environ['BASEDIR'] = BASEDIR
TOTAL_SCONS_... |
nbsp.py | # _*_ coding:UTF-8 _*_
import time
from threading import Thread, Event
from six.moves import queue
from .logger import get_logger
LOGGING = get_logger(__name__)
class NonBlockingStreamReader:
def __init__(self, stream, raise_EOF=False, print_output=True, print_new_line=True, name=None):
'''
strea... |
main.py | """
Remixatron Web UI
(c) 2019 - Dave Rensin - dave@rensin.com
This is a web ui for the Remixatron Infinite Jukebox project. (https://github.com/drensin/Remixatron)
The original project was a CLI that used curses, but that caused problems on Windows and other systems. So,
I wrote thsi UI to be a b... |
main.py | #Notation:
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | 8 | 9 |
# U - Up | D - Down - | L - Left | R - Right
import math
from multiprocessing import Process, Queue
from anytree import *
finished = "123456780" #for reference
def totalWeight(x): #Finds the total weight (using manhattan distance)
weight = 0;
for... |
4.rlock_simple_thread.py | '''
说明: 阻塞的例子
例子1: 对于互斥锁, 同一个线程连续调用两次acquire会阻塞
'''
from threading import Lock, RLock, Thread
def block():
lock = Lock()
lock.acquire()
print('===> 3')
# 阻塞在此
lock.acquire()
print('===> 4')
def alive():
lock = RLock()
lock.acquire()
print('===> 1')
# 不阻塞
lock.acquire()
... |
pyminer.py | # Copyright (c) 2009-2010 Satoshi Nakamoto
# Copyright (c) 2009-2014 The Bitcoin developers
# Copyright (c) 2011-2014 The Litecoin Developers
# Copyright (c) 2014-Present The Skryptex Devs
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-lic... |
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 ... |
test_windows_events.py | import os
import signal
import socket
import sys
import subprocess
import time
import threading
import unittest
from unittest import mock
if sys.platform != 'win32':
raise unittest.SkipTest('Windows only')
import _overlapped
import _testcapi
import _winapi
import asyncio
from asyncio import windows_events
from a... |
server_command_agent.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
util.py | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import base64
import binascii
import colorsys
import contextlib
import codecs
import errno
import functools
import gzip
import hashlib
import json
import logging
import math
import numbers
import traceback
impo... |
keepkey.py | from binascii import hexlify, unhexlify
import traceback
import sys
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
from electrum.util import bfh, bh2u, UserCancelled, UserFacingException
from electrum.bip32 import BIP32Node
from electrum import constants
from electrum.i18n import... |
autoreload.py | import functools
import itertools
import logging
import os
import signal
import subprocess
import sys
import threading
import time
import traceback
import weakref
from collections import defaultdict
from pathlib import Path
from types import ModuleType
from zipimport import zipimporter
from django.apps import apps
fro... |
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, Optional
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 (Objec... |
global_share_values.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : Max_Pengjb
@ date : 2018/9/23 22:37
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : pengjianbiao@hotmail.com
-----------... |
speedtest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012-2015 Matt Martz
# 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.or... |
backend.py | import os
import time
import queue
import typing
import datetime
import threading
import subprocess
import lib.handshake
import lib.admin.database as database
import lib.eviltwin.models as eviltwin_models
from lib import utils
from lib import settings
from lib.resp import Resp
from lib.eviltwin import const
from lib.... |
radiorec.py | #!/usr/bin/env python3
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
"""
radiorec.py – Recording internet radio streams
Copyright (C) 2013 Martin Brodbeck <martin@brodbeck-online.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as p... |
dag_processing.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... |
run.py | import os
import logging
from threading import Thread
from collections import deque
root = os.path.dirname(os.path.abspath(__file__))
logging.basicConfig(level=logging.INFO,
filename='./voc_resnet18_dilation_fcn.log',
filemode='w',
format='%(asctime)s - %(f... |
upnp.py | import logging
import threading
from queue import Queue
from typing import Optional
try:
import miniupnpc
except ImportError:
pass
log = logging.getLogger(__name__)
class UPnP:
thread: Optional[threading.Thread] = None
queue: Queue = Queue()
def __init__(self):
def run():
t... |
scheduler_job.py | # pylint: disable=no-name-in-module
#
# 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, Versio... |
data_plane_test.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... |
CanvasFrame.py |
"""
This class contains all code to graphically display progress in a window.
"""
import random as r
from itertools import cycle
import tkinter as tk
class CanvasFrame(tk.Frame):
""" This is main class for managing displaying visual changes to a path"""
#-------------------------------------... |
test_strategy.py | import random
import time
import threading
from typing import *
import nni.retiarii.execution.api
import nni.retiarii.nn.pytorch as nn
import nni.retiarii.strategy as strategy
import torch
import torch.nn.functional as F
from nni.retiarii import Model
from nni.retiarii.converter import convert_to_graph
from nni.retiar... |
statistics.py | import numpy as np
import multiprocessing
from sed_scores_eval.utils.scores import validate_score_dataframe
from sed_scores_eval.base_modules.ground_truth import multi_label_to_single_label_ground_truths
from sed_scores_eval.base_modules.detection import onset_offset_curves
from sed_scores_eval.base_modules.io import p... |
test_read_committed_update_deadlock.py | ##############
# Setup Django
import django
django.setup()
#############
# Test proper
import threading
import time
import pytest
from django.db import DatabaseError, connection, transaction
from django.db.models import F, Subquery
from app.models import Sock
@pytest.mark.django_db
def test_read_committed_update_... |
spyder.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2013 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""
Spyder, the Scientific PYthon Development EnviRonment
=====================================================
Developped and maintained by the Spyder Dev... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.