source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
executor_service.py | from queue import SimpleQueue
from threading import Thread
from concurrent.futures import Future
from typing import Any, Callable, TypeVar
T = TypeVar("T")
class ExecutorService:
def __init__(self) -> None:
self.__thread = Thread(target=self._loop, daemon=True)
self._queue: SimpleQueue = SimpleQ... |
skeleton.py | import threading
from copy import copy
from helpers import setup_logger
logger = setup_logger(__name__, "warning")
KEY_PRESSED = 1
KEY_RELEASED = 0
KEY_HELD = 2
class InputSkeleton(object):
"""Base class for input devices. Expectations from children:
* ``self.default_mapping`` variable to be set unless you'... |
tpu_estimator.py | # Copyright 2017 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... |
deploy_model.py | # -*- encoding:utf-8 -*-
# @Time : 2019/10/7 22:12
# @Author : gfjiang
# @Site :
# @File : deploy_model.py
# @Software: PyCharm
import flask
import io
import cv2.cv2 as cv
from PIL import Image
import numpy as np
import cvtools
import os
import os.path as osp
from threading import Thread
from werkzeug.utils... |
views.py | #
# SPDX-License-Identifier: Apache-2.0
#
import logging
import base64
import shutil
import os
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from drf_yasg.utils import swagger_auto_schema
from django.core.paginator import Paginator... |
test.py | import json
import os.path as p
import random
import socket
import subprocess
import threading
import time
import io
import string
import avro.schema
import avro.io
import avro.datafile
from confluent_kafka.avro.cached_schema_registry_client import CachedSchemaRegistryClient
from confluent_kafka.avro.serializer.messag... |
ColdDataRetriever.py | import logging
import os
import signal
import csv
import time
import shutil
import subprocess
import datetime
import json
import sys
import schedule
import pickle
import threading
import argparse
from collections import defaultdict
config = defaultdict(lambda: None)
# Read Default config.json file
with open('config.j... |
cross_device_ops_test.py | # Copyright 2020 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... |
test_program_for_PhidgetAnalog4Output1002_ReubenPython2and3Class.py | # -*- coding: utf-8 -*-
'''
Reuben Brewer, Ph.D.
reuben.brewer@gmail.com,
www.reubotics.com
Apache 2 License
Software Revision E, 03/13/2022
Verified working on: Python 2.7, 3.8 for Windows 8.1, 10 64-bit and Raspberry Pi Buster (no Mac testing yet).
'''
__author__ = 'reuben.brewer'
from PhidgetAnal... |
views.py | # 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 agreed to ... |
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... |
logmein_host.py | #!/usr/bin/env python3
#
# Copyright (c) 2018 LogMeIn, Inc.
#
# 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, ... |
audiowrite.py | import io
import numpy as np
import threading
from pathlib import Path
import soundfile
from paderbox.utils.mapping import Dispatcher
from paderbox.io.path_utils import normalize_path
int16_max = np.iinfo(np.int16).max
int16_min = np.iinfo(np.int16).min
def dump_audio(
obj,
path,
*,
... |
nDim_Symbolic_Function.py | # TODO : write docstring and code explinations ;P
from __future__ import division
import numpy as np
import sympy as sym
from sympy.utilities.lambdify import lambdastr
import math
import linecache
import sys
import concurrent.futures
import torch
from threading import Thread
import multiprocessing
import threading
impo... |
acceptor.py | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE... |
fb.py | # -*- coding: utf-8 -*-
import os, sys, time, datetime, random, hashlib, re, threading, json, getpass, urllib, requests, mechanize
from multiprocessing.pool import ThreadPool
try:
import mechanize
except ImportError:
os.system('pip2 install mechanize')
else:
try:
import requests
except ImportEr... |
train_ac_f18.py | """
Original code from John Schulman for CS294 Deep Reinforcement Learning Spring 2017
Adapted for CS294-112 Fall 2017 by Abhishek Gupta and Joshua Achiam
Adapted for CS294-112 Fall 2018 by Soroush Nasiriany, Sid Reddy, and Greg Kahn
"""
import numpy as np
import tensorflow as tf
#import tensorflow_probability as tfp
i... |
continuousModel.py | from collections import defaultdict
import random
import os
import os.path
import math
from soba.models.timeControl import Time
from soba.models.generalModel import GeneralModel
from soba.agents.continuousOccupant import ContinuousOccupant
from soba.agents.roomsOccupant import RoomsOccupant
import soba.agents.... |
basestation_lora.py | import pickle
import pprint
import queue
import sys
import threading
import zmq
import logging.config
from driver import LoRaHatDriver
from config_lora import lora_hat_config, logging_config_dict
from message import TimeAttGPSMessage, DeserializeError
logging.config.dictConfig(logging_config_dict)
# overwrite bases... |
io.py | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
framework_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... |
daemon.py | import logging
import threading
import time
import dbus
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
def daemon():
logging.debug('Starting')
time.sleep(2)
logging.debug('Exiting')
d = threading.Thread(name='daemon', target=d... |
rc_driver.py | import struct
import io
from PIL import Image
__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(... |
test_reservation.py | import threading
import time
import unittest
from tensorflowonspark.reservation import Reservations, Server, Client
class ReservationTest(unittest.TestCase):
def test_reservation_class(self):
"""Test core reservation class, expecting 2 reservations"""
r = Reservations(2)
self.assertFalse(r.done())
... |
cnc.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#Code by LeeOn123
#Created at 16/7/2019
#############################################################
# d8888 #
# d88888 #
# d88P888 ... |
lock.py | from threading import Thread, current_thread
num = 0
def calc():
global num
print("thread {} is running...".format(current_thread().name))
for _ in range(1000):
num += 1
print("thread {} ended.".format(current_thread().name))
if __name__ == '__main__':
print("thread {} is running...".f... |
webServer.py | """Web Server module which provides the web user interface to control and monitor experiments"""
import tornado.web
import tornado.websocket
import os
import ssl
import json
import queue
import logging
import re
import toml
import shlex
import uuid
import asyncio
import threading
import subprocess
from pathlib import ... |
utils.py | # -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... |
__init__.py | #!/usr/bin/env python3
"""Library for performing speech recognition, with support for several engines and APIs, online and offline."""
import io
import os
import subprocess
import wave
import aifc
import math
import audioop
import collections
import json
import base64
import threading
import platform
import stat
impo... |
pants_daemon.py | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
import os
import sys
import threading
from contextlib import contextmanager
from dataclasses import dataclass
from typing import IO, Iterator, Optional, cast
from setprocti... |
util.py | #!/usr/bin/env python
# encoding: utf-8
"""Common utilities."""
from contextlib import contextmanager
from shutil import rmtree
from six.moves.queue import Queue
from tempfile import mkstemp
from threading import Thread
import logging as lg
import os
import os.path as osp
_logger = lg.getLogger(__name__)
class Hd... |
aira_graph.py | # -*- coding: utf-8 -*-
#
# AIRA graph node
#
from eth_account.messages import defunct_hash_message
from ipfs_common.pubsub import subscribe, publish
from ipfs_common.ipfs_common import build_client
from time import sleep, time
from web3.auto import w3
from json import dumps, loads
from threading import Thread
from et... |
multithreading.py | # coding=utf-8
from queue import Queue, Empty, Full
import sqlite3
from threading import Thread
from time import monotonic
from weakref import finalize
class CloseableQueue(Queue):
def __init__(self, maxsize=0):
super().__init__(maxsize)
self._closed = False
def get(self, block=True, timeout=... |
manager.py | from dataclasses import dataclass
import logging
import threading
import time
import traceback
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from concurrent.futures.thread import ThreadPoolExecutor
from blspy import G1Element
from chiapos import DiskProver
from chia.conse... |
core.py | # -*- coding: utf-8 -*-
#
# 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
#... |
parallel.py | #
# Two processes are incrementing a counter in parallel
#
# In this example we use the shared_lock=True parameter.
# This way of shared locking is save accross independent
# processes but it is slower than using the built-in default
# locking method using `multiprocessing.RLock()`.
#
# UltraDict uses the atomics packa... |
gcsio.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... |
job_array.py | import threading
import time
import weakref
from collections import defaultdict
from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Tuple
from redun.scheduler import Job
# Per AWS documentation, see:
# https://docs.aws.amazon.com/batch/latest/userguide/service_limits.html
MAX_ARRAY_SIZE = 10000
# https://d... |
netattack3.py | #!/usr/bin/env python3
# imports that won't cause errors
import sys
import os
import signal
import subprocess
from threading import Thread
from time import sleep
import datetime
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) # scapy, please shut up..
# terminal colors
RED = "\033[1;31m"
B... |
controller.py | import glob
import json
import os
import re
import shutil
import subprocess
import tarfile
import time
import traceback
from datetime import datetime
from math import floor
from pathlib import Path
from threading import Thread
from typing import List, Set, Type, Tuple, Dict, Iterable, Optional
import requests
from ba... |
runserver.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import sys
from threading import Thread
from pogom import config
from pogom.app import Pogom
from pogom.models import create_tables
from pogom.search import search_loop, set_cover, set_location, search_loop_async
from pogom.utils import get_args
log = logging.... |
thread_runner.py | import threading
import asyncio
from .base_runner import BaseRunner, OrphanedReturn
class ThreadRunner(BaseRunner):
"""
Runner for subroutines with :py:mod:`threading`
Active payloads are *not* cancelled when the runner is closed.
Only program termination forcefully cancels leftover payloads.
""... |
GrpcStat.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by eeliu at 6/1/20
import threading
import time
import psutil
from CollectorAgent.GrpcClient import GrpcClient
from Common.Logger import TCLogger
from PinpointAgent.Type import STAT_INTERVAL
from Proto.grpc.Service_pb2_grpc import StatStub
from Proto.grpc.Stat_p... |
column_no_mat.py | #!/usr/bin/python
#
# This file is part of PyRQA.
# Copyright 2015 Tobias Rawald, Mike Sips.
"""
RQA, Fixed Radius, OpenCL, ColumnNoMat
"""
import numpy as np
import os
import pyopencl as cl
import threading
import Queue
from ....abstract_classes import AbstractRunnable
from ....opencl import OpenCL
from ....proces... |
subproc_vec_env.py | import multiprocessing
from collections import OrderedDict
from typing import Sequence
import gym
import numpy as np
from stable_baselines.common.vec_env.base_vec_env import VecEnv, CloudpickleWrapper
def _worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.var()
wh... |
snowball_uploader_25-success.py | '''
status: completed
version: v25
way: using multi-part uploading
ref: https://gist.github.com/teasherm/bb73f21ed2f3b46bc1c2ca48ec2c1cf5
changelog:
- 2021.02.10
- replacing os.path with scandir.path to improve performance of file listing
- 2021.02.09
- python2 compatibility for "open(filename, endoding)"
... |
Matchup.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 use ... |
speedtest_cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012-2014 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... |
crypto_util_test.py | """Tests for acme.crypto_util."""
import itertools
import socket
import threading
import time
import unittest
import six
from six.moves import socketserver # pylint: disable=import-error
import OpenSSL
from acme import errors
from acme import jose
from acme import test_util
class SSLSocketAndProbeSNITest(unittest... |
streaming_problem.py | ##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import logging
import uuid
import io
import gzip
import json
import threading
import sys
from typing import List, Union, Dict, Optional
from azure.quantum import Workspace
from azure.quantum.optimization import Term, P... |
general_utils.py | import ujson
import base64
import urllib2
import socket
from ftplib import FTP, error_perm
import re
from StringIO import StringIO
import time
import multiprocessing
import pickle
import multiprocessing as mp
import gc
import signal
import csv
import codecs
import cStringIO
#######Code from http://www.filosophy.org/po... |
threading_queue.py | import queue
import threading
num_worker_threads = 4
def do_work(item):
print(item)
def source():
return range(100)
def worker():
while True:
item = q.get()
if item is None:
break
do_work(item)
q.task_done()
q = queue.Queue()
threads = []
for i in range... |
bruteforcescan.py | #!/usr/bin/python
## Binary Analysis Tool
## Copyright 2009-2016 Armijn Hemel for Tjaldur Software Governance Solutions
## Licensed under Apache 2.0, see LICENSE file for details
'''
This script tries to analyse binary blobs, using a "brute force" approach
The script has a few separate scanning phases:
1. marker sc... |
run.py | # encoding: UTF-8
"""
无人值守运行服务
"""
from __future__ import print_function
from time import sleep
from datetime import datetime, time
from multiprocessing import Process
import webbrowser
from webServer import run as runWebServer
from tradingServer import main as runTradingServer
from vnpy.trader.vtEngine import LogE... |
_threading_local.py | """Thread-local objects.
(Note that this module provides a Python version of the threading.local
class. Depending on the version of Python you're using, there may be a
faster one available. You should always import the `local` class from
`threading`.)
Thread-local objects support the management of thread-local d... |
conditional_accumulator_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... |
main.py | #!/usr/bin/python3
# ____ _ _ ____ _ _ _
# / ___|___ _ __ ___ _ __ ___ _ _ _ __ (_) |_ _ _ / ___|___ _ __ | |_ _ __ ___ | | | ___ _ __
# | | / _ \| '_ ` _ \| '_ ` _ \| | | | '_ \| | __| | | | | / _ \| '_ \| __| '__/ _ \| | |... |
runner.py | #!/usr/bin/env python2
# This Python file uses the following encoding: utf-8
'''
Simple test runner.
'''
# XXX Use EM_ALL_ENGINES=1 in the env to test all engines!
from __future__ import print_function
from subprocess import Popen, PIPE, STDOUT
import os, unittest, tempfile, shutil, time, inspect, sys, math, glob, ... |
pi_camera.py | """The Raspberry Pi camera module."""
import io
import time
import threading
import picamera
from ..base_camera import BaseCamera
class Frame(object):
def __init__(self):
self.stream = io.BytesIO()
self.frame = None
class Camera(BaseCamera):
def __init__(self):
self.resolution = (640... |
mobile_insight_gui.py | #!/usr/bin/python3
"""
Python GUI for MobileInsight
Author: Moustafa Alzantot
Date : Feb 26, 2016
"""
import sys
import wx
import wx.grid
import wx.adv
from threading import Thread
from random import random
from datetime import datetime, timedelta
import matplotlib
from matplotlib.backends.backend_wxagg import Figur... |
solved.py | #! /usr/bin/env python3
# requirements: apt-get install build-essential python-dev libnetfilter-queue-dev
# requirements: pip install NetfilterQueue
from multiprocessing import Process
from netfilterqueue import *
from scapy.all import *
from evilify import evilify
import os
import socket
import sys
class Solver:
... |
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... |
vip_decompiled.py | #Decompiled At:Sat Mar 14 12:05:29 2020
import os, sys, time, datetime, random, hashlib, re, threading, json, getpass, urllib, cookielib
from multiprocessing.pool import ThreadPool
try:
import mechanize
except ImportError:
os.system('pip2 install mechanize')
try:
import requests
except ImportError:
o... |
A2DP-old.py | import dbus, dbus.mainloop.glib
from device.SteeringWheel import SteeringWheel
from device.InstrumentPanel.Screen import InstrumentPanel
from device.Radio import Radio, DisplayMode
from gi.repository import GLib
from module.ThreadModuleAbstract import ThreadModuleAbstract
import can
# from utils.EventBus import eventBu... |
test_executors.py | import os
import multiprocessing
import sys
import threading
import tempfile
import time
from datetime import timedelta
from unittest.mock import MagicMock
import pytest
import prefect
from prefect.utilities.configuration import set_temporary_config
from prefect.utilities.executors import (
timeout_handler,
t... |
clientbasicstatus.py | """
获取当前电脑的运行状态
包括cpu,内存,存储,或者gpu
create by judy 2018/10/19
update by judy 2019/03/05
更改为统一输出output
"""
from datetime import datetime
import threading
import time
import traceback
import psutil
import pytz
from datacontract import StatusBasic
from idownclient.config_client import basic_client_config
from idownclient... |
main.py | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 22:28:38 2021
@author: ASUS GAMER
"""
import serial
import threading
import psycopg2
import time
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
class proyectoWindow(FloatLayout):
def __init__... |
mlcontext.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... |
portable_runner.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... |
user_app.py | import cv2
import serial
import time
import msvcrt
from threading import *
serialComm = serial.Serial('COM3',9600)
serialComm.timeout=1
import Object_detection_image
from tkinter import *
import os
root= Tk()
total_price=0
def takePhoto():
cap = cv2.VideoCapture('http://192.168.43.1:8080/video')
... |
__init__.py | import codecs
import sys
import os
import traceback, linecache
import re
import time
import random
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from nodebox.gui.qt.baseclasses import NodeBoxDocumentBaseClass, NodeBoxApplicationBaseClass, ExportMoviePanel
from nodebox.gui.qt.document import DocumentController
... |
SquidSpammer.py | import smtplib, time, threading, random, sys, os
class SpamBot:
def __init__(self, email, reciever, subject, msg):
self.emaillist = email
self.reciever = reciever
self.subject = subject
self.msg = msg
self.clients = []
print("\n[+] Preparing Spam Bots.....")
def ... |
test_urllib.py | # expected: fail
"""Regresssion tests for urllib"""
import urllib
import httplib
import unittest
import os
import sys
import mimetools
import tempfile
import StringIO
from test import test_support
from base64 import b64encode
def hexescape(char):
"""Escape char as RFC 2396 specifies"""
hex_repr = hex(ord(ch... |
mriqc_run.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: oesteban
# @Date: 2015-11-19 16:44:27
"""
=====
MRIQC
=====
"""
from __future__ import print_function, division, absolute_import, unicode_literals
from os import cpu_count
import logging
import gc
from pathlib import Path
from .. import __version__
logging.... |
performer.py | # Created By: Virgil Dupras
# Created On: 2010-11-19
# Copyright 2011 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licens... |
expert_system.py | # coding: utf-8
import os
import time
import signal
import random
import logging
import argparse
import requests
import threading
from flask import Flask, request, jsonify
from werkzeug.routing import BaseConverter
logging.basicConfig(filename='log/mlapp.log',level=logging.INFO, filemode='a', format='%(created)f::ML... |
multicore.py | from multiprocessing import Process, Queue
from .singlecore import SingleCoreSampler
import numpy as np
import random
import logging
import cloudpickle as pickle
from jabbar import jabbar
from .multicorebase import MultiCoreSampler, get_if_worker_healthy
logger = logging.getLogger("ABC.Sampler")
SENTINEL = None
de... |
email.py | from threading import Thread
from flask import current_app, render_template
from flask.ext.mail import Message
from . import mail
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = ... |
threads.py | import time
from threading import Thread
def countdown(n):
while n > 0:
n -= 1
COUNT = 10_000_000
N_THREADS = 4
if __name__ == "__main__":
times = []
for _ in range(3):
start_time = time.time()
threads = [Thread(target=countdown, args=(COUNT // N_THREADS,)) for _ in range(N_TH... |
__init__.py | """
Set up the Salt integration test suite
"""
import atexit
import copy
import errno
import logging
import multiprocessing
import os
import pprint
import re
import shutil
import signal
import socket
import stat
import subprocess
import sys
import tempfile
import threading
import time
from datetime import datetime, ti... |
yeshup_tests.py | #!/usr/bin/env python3
"""x
test making sure child processes exit when parent exits
it won't magically continue to children of children right now
maybe there's a way to make this more likely
This is used internally in the system
it should be used by user processes that are launched unless
you want them to not exi... |
test_fuse.py | import os
import signal
import time
from multiprocessing import Process
import pytest
pytest.importorskip("fuse") # noqa: E402
from fsspec.fuse import run
from fsspec.implementations.memory import MemoryFileSystem
def host_fuse(mountdir):
fs = MemoryFileSystem()
fs.touch("/mounted/testfile")
run(fs, "... |
common.py | #common
import sys, argparse, os.path, json, io, glob, time
import pathlib, urllib.request, shutil
from collections import OrderedDict
def as_bytes(x, encoding='utf-8'):
if isinstance(x, str):
return x.encode(encoding)
if isinstance(x, bytes):
return x
if isinstance(x, bytearray):
... |
bsync_stats.py | import glob
from functools import reduce
import os
import sys
sys.path.append(".")
import pandas as pd
from driver import Driver
import requests
import threading
import time
add = lambda x,y: x+y
get = lambda uri: requests.get(uri).json()
if len(sys.argv) < 2:
print("Usage: python evaluation/bsync_stats.py <file_... |
server.py | import getpass
import os
import signal
import socket
import subprocess
import sys
import threading
from cryptography.fernet import Fernet
HOME = f"/Users/{getpass.getuser()}"
def signal_handler(sig, frame):
os._exit(1)
# message statuses (each is first byte of message):
# 1 - message received
# 2 - someone join... |
toggle_fullscreen.py | import webview
import threading
import time
"""
This example demonstrates how to toggle fullscreen mode programmatically.
"""
def toggle_fullscreen():
# wait a few seconds before toggle fullscreen:
time.sleep(5)
webview.toggle_fullscreen()
if __name__ == '__main__':
t = threading.Thread(target=tog... |
test_arduino.py | import torch
import cv2
import os
import ChessboardCalibration_master.tools.predict as predict #calibration
import time
from text_to_speech import *
from text_to_speech import *
from threading import Thread
from similary import *
def yolo(image):
model = torch.hub.load('ultralytics/yolov5', 'custom', path='su... |
oandav20store.py | #!/usr/bin/env python
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import collections
import threading
import copy
import time as _time
from datetime import datetime
import v20
import backtrader as bt
from backtrader.metabase import MetaParams
from back... |
processify.py | import os
import time
import pickle
import signal
import struct
import functools
from multiprocessing import Process
from threading import Thread
def processify(fn):
"""
Decorator to run `fn` in a separate process.
Note
----
It doesn't encrypt communications with a child process.
"""
from... |
echo_server.py | import socket
from threading import Thread
class EchoServer():
def __init__(self, host="0.0.0.0", port=5002, message_size=1024):
"""初期化
Parameters
----------
host : str
サーバーのIPアドレス。 規定値 "0.0.0.0"
port : int
サーバー側のポート番号。 規定値 5002
message_si... |
test05.py | # encoding: utf-8
import serial
import Queue
import threading
import struct
import time
ser = None
def do_imu(data):
temp = struct.unpack('h', bytearray(data[4:6]))[0]
print(data[4],data[5])
# acc
ax = struct.unpack('h', bytearray(data[6:8]))[0]
ay = struct.unpack('h', bytearray(data[8:10]))[0]
... |
single_machine_simulation.py | import os
import time
from multiprocessing import Process
from typing import Tuple
import flwr as fl
import numpy as np
import tensorflow as tf
from flwr.server.strategy import FedAvg
import dataset
# generate random integer values
from random import seed
from random import randint
# Make TensorFlow log less verbos... |
machineCom.py | """MachineCom handles communication with GCode based printers trough (USB)
serial ports.
For actual printing of objects this module is used from
Cura.serialCommunication and ran in a separate process.
"""
__copyright__ = 'Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License'
import os
import g... |
viewleader.py | #!/usr/bin/python
import time
import common
import common2
import threading
##############
# Globals
# Stores global configuration variables
config = {
"epoch": 0,
# List of expired leases
"expired": [],
}
# Stores all server leases
leases = []
# Store all locks
locks = []
###################
# RPC i... |
run_app.py | import logging
import time
from datetime import timedelta
from threading import Thread
from databay import Link
from databay.inlets.file_inlet import FileInlet, FileInletMode
from databay.planners import APSPlanner, SchedulePlanner
from databay.inlets import HttpInlet
from databay.outlets import CsvOutlet
from databay... |
pipeline.py | """
Module includes classes that accept single or multiple `arus.core.stream` instances, synchronize data from the streams, process the data using customized processor function, and output using the same iterator interface as `arus.core.stream`.
# Usage of `arus.core.pipeline.Pipeline`
# Single stream case
```python... |
widgets.py | """A Jupyter Notebook interface to Klampt.
Examples:
Basic usage::
from klampt import *
from klampt.vis.ipython import KlamptWidget
from IPython.display import display
world = WorldModel()
... #set up the world...
kvis = KlamptWidget(world,width=800,height=640)
... |
elevator.py | import time
import sched
import threading
import multiprocessing
from person import Person
#from control_system import control_system
from constants import RATIO, DAY_SECONDS, POPULATION, YEAR, FLOOR_HEIGHT, MAX_FLOOR
from leetCode import Solution
from listNode import ListNode
# def new_day(scheduler, base_time, de... |
base_events.py | """Base implementation of event loop.
The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.
Whenever a public API takes a c... |
test_multiprocessing.py | #
# Unit tests for the multiprocessing package
#
import unittest
import Queue
import time
import sys
import os
import gc
import signal
import array
import socket
import random
import logging
import errno
import weakref
import test.script_helper
from test import support
from StringIO import StringIO
_multiprocessing = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.