source
stringlengths
3
86
python
stringlengths
75
1.04M
mp_utils.py
#!/usr/bin/env python '''Utilities for multiprocessing. @author: Zach Hafen @contact: zachary.h.hafen@gmail.com @status: Development ''' import multiprocessing as mp import os import pdb import sys from types import MethodType # Python 2/3 compatible copyreg try: import copy_reg except: import copyreg as cop...
util.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
load-data.py
#!/usr/bin/env impala-python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (...
worker_test.py
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
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...
example01.py
import threading import time start = time.perf_counter() def do_something(number): print(f'Do something {number}') time.sleep(1) print(f'Done sleep {number}') threads = [threading.Thread(target=do_something, args=(number,)) for number in range(10)] for thread in threads: thread.start() ...
guimotomandualcomplete.py
import matplotlib.pyplot as plt from mpl_toolkits import mplot3d import numpy as np import sympy as sp from matplotlib.widgets import Slider,CheckButtons,Button,TextBox,RadioButtons from robolink import * import serial import threading import time import sys fig, ax = plt.subplots() plt.subplots_adjust(lef...
test_events.py
#!/usr/bin/env python import time import hookio import threading import itertools import functools import json import logging from six.moves import queue log = logging.getLogger(__name__) get_error_model = { "error": True, "message": """\ "anonymous" does not have the role "events::read" which is required to a...
DotaServiceClient.py
from collections import Counter from time import time import asyncio import math import os import math import random import shutil import torch.multiprocessing as mp from grpclib.client import Channel from google.protobuf.json_format import MessageToDict from tensorboardX import SummaryWriter from pympler.tracker im...
helpers_3.py
""" helpers and wrappers for common rpyc tasks """ import threading from rpyc.lib.lib import WeakValueDictionary, callable from rpyc.core.consts import HANDLE_BUFFITER, HANDLE_CALL from rpyc.core.netref import BaseNetref, syncreq, asyncreq def buffiter(obj, chunk=10, max_chunk=1000, factor=2): """buffering itera...
__main__.py
# ESPER Waveform and Variable viewer from __future__ import print_function from builtins import str as text import threading import os import sys import argparse import cmd import time import getpass import platform import configparser import zmq import socket import struct import signal import re import queue import...
httptiming.py
import time import requests from performance.driver.core.classes import Observer from performance.driver.core.events import Event, TeardownEvent, StartEvent, ParameterUpdateEvent from performance.driver.core.reflection import subscribesToHint, publishesHint from threading import Thread class HTTPTimingResultEvent(Ev...
spark.py
from __future__ import print_function import copy import threading import time import timeit from hyperopt import base, fmin, Trials from hyperopt.base import validate_timeout, validate_loss_threshold from hyperopt.utils import coarse_utcnow, _get_logger, _get_random_id try: from pyspark.sql import SparkSession ...
vul_recheck_v2.py
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:owefsad # software: PyCharm # project: lingzhi-webapi import logging import time from dongtai.models.agent import IastAgent from dongtai.models.project import IastProject from dongtai.models.replay_queue import IastReplayQueue from dongtai.models.vulnerablity impor...
test_datamol_import_time.py
import multiprocessing import platform DATAMOL_MAX_IMPORT_DURATION = {} # in seconds DATAMOL_MAX_IMPORT_DURATION["default"] = 2 DATAMOL_MAX_IMPORT_DURATION["linux"] = 2 DATAMOL_MAX_IMPORT_DURATION["osx"] = 5 DATAMOL_MAX_IMPORT_DURATION["windows"] = 4 def _get_max_import_duration(): if platform.system() == "Wind...
test_master_slave.py
# coding: utf-8 """Test the master talking to the slave""" import logging import os import threading import signal import subprocess import sys import time import pytest from drmaa_futures.master import ZeroMQListener logger = logging.getLogger(__name__) def wait_until(condition, interval=0.1, timeout=1, *args): ...
map_editor.py
import traceback import sys import os from functools import partial os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' #hiding pygame greeting console output import pygame import json from engine import * import tkinter import tkinter.filedialog import tkinter.messagebox as mb from tkinter import scrolledtex...
generic_pubsub.py
"""Generic Pub/Sub implementation.""" from collections import deque from typing import Any, Callable, Deque, Dict, List, Optional, Union from datetime import datetime from threading import Thread from pydantic import PositiveInt from eepythontools.inheritable_object import InheritableObject class Publisher(Inheritab...
test_functools.py
import abc import builtins import collections import copy from itertools import permutations import pickle from random import choice import sys from test import support import time import unittest from weakref import proxy import contextlib try: import threading except ImportError: threading = None import func...
main_window.py
#!/usr/bin/env python3 # # 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 with...
test_InfluxDBClient.py
import http.server import json import os import threading import unittest from influxdb_client import InfluxDBClient class InfluxDBClientTest(unittest.TestCase): def tearDown(self) -> None: if self.client: self.client.close() if hasattr(self, 'httpd'): self.httpd.shutdown...
train_ltcn.py
import os import argparse import torch import numpy as np import pickle import sys sys.path.append('./utils') from torch import optim from torch import nn from torch import multiprocessing from torch.optim import lr_scheduler from torch.autograd import Variable from torch.utils.data import DataLoader, ConcatDataset fr...
retribusiPemerintah.py
#!/usr/bin/python import MySQLdb import time import sys import math import threading def check(bot, top, index): # print 'grader'+str(index) j = bot db_tunggak = MySQLdb.connect("10.151.63.12", "retribusi", "retribusi", "retribusi") cursor_tunggak = db_tunggak.cursor() db_retribus...
remote_executor.py
# Lint as: python3 # Copyright 2019, The TensorFlow Federated 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 ...
generate_data_2d.py
import os import tensorflow as tf from scipy import stats import numpy as np import math from sklearn import preprocessing import concurrent.futures import logging import threading from multiprocessing import Process # Duration of simulated trajectories (seconds) T = 15 # Width and height of environment, or diameter...
cli.py
import errno import json import logging import os import re import sys import tarfile from datetime import datetime from glob import glob from shutil import copyfile from threading import Thread import re import yaml import fnmatch import click from sqlalchemy import create_engine from sqlalchemy.exc import IntegrityE...
__init__.py
import json import logging import threading import time import uuid from contextlib import contextmanager from typing import Callable from typing import List from typing import Union import pika from flask import current_app from flask import Flask from retry import retry from .consumer import ReconnectingConsumer fr...
not_a_dam_fetcher.py
"""Flask app to generate imagery that does not contain a dam.""" import shutil import subprocess import requests import queue import json import datetime import sqlite3 import os import sys import logging import threading import pygeoprocessing from retrying import retry import numpy import taskgraph ...
scheduler.py
from collections import deque import time import random from threading import Thread from radio.audio import Clip, AudioClip import radio.library from math import sqrt from typing import Deque class Scheduler: def __init__(self, library: 'radio.library.ClipLibrary', preload: bool = True): self.library = l...
tilt.py
#!/usr/bin/python from wiiboard import Wiiboard, EventProcessor from pic_interface import PICInterface from get_angle import tilt2servo from get_ip import get_ip import serial import time import threading import pygame pygame.mixer.init() pygame.mixer.music.load('sound/background.mp3') pygame.mixer.music.play(loops...
all.py
#!/usr/bin/env python3 # Princípios utilizados: # Aplica todas as estratégias abaixo nas ações e mostra uma tabela contendo todos os rankings # A tabela resultante é ordenada pelo resultado da soma dos rankings depois de aplicar essas # 4 diferentes estratégias # Graham: # - [x] 1. Sobrevivência: Sobreviveu nos últ...
app.py
## See readme from flask import Flask from threading import Thread import time, json, pickle, os from datetime import datetime import praw app = Flask(__name__) ## RedditParser tracked = [] class RedditParser: reddit = praw.Reddit(client_id=os.environ['REDDIT_CLIENT_ID'], client_secret=...
test_dp_with_orc8r.py
""" Copyright 2022 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES O...
UPS_Main3.py
# Universal Power System Controller # USAID Middle East Water Security Initiative # # Developed by: Nathan Webster # Primary Investigator: Nathan Johnson # # Version History (mm_dd_yyyy) # 1.00 07_13_2018_NW # ###################################################### # Import Libraries from threading import Thread from PW...
api.py
# a few necessary imports import json from flask import Flask, make_response from tendo import singleton from multiprocessing import Process import random # first of all we create the Flask object api_app = Flask(__name__) # now we create an API entry point to create the list @api_app.route('/output', methods=['GET']...
leaser.py
# Copyright 2017, 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,...
process.py
import signal from threading import Thread from subprocess import Popen, PIPE, STDOUT import logging from lib.helper import * class Process: def fpipe(self): try: for line in self.proc.stdout: self.logger.info(line.decode("utf-8").rstrip()) self.logfile.write(l...
train_faster_rcnn_alt_opt.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Train a Faster R-CNN network using alternat...
ADS1299_API.py
""" # file: ADS1299_API.py # author: Frederic Simard (frederic.simard.1@outlook.com) # version: Fall 2017 # descr: This files implements the basic features required to operate the ADS1299 using the SPI port of a Raspberry Pi (tested on RPi 3, Raspbian Lite Jessie). The API handles the commun...
analysis_submission.py
##################################################################### # # # /analysis_submission.py # # # # Copyright 2013, Monash University ...
test_logging.py
# Copyright 2001-2017 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permissio...
utils.py
import json import time import unittest from threading import Thread from http.server import SimpleHTTPRequestHandler, HTTPServer import bugsnag class MissingRequestError(Exception): pass class IntegrationTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.server = FakeBugsnagServe...
hpds-02-B-01.py
# -*- coding: utf-8 -*- """ Created on Mon Dec 7 12:59:23 2020 Ilustrasi Pengaruh GIL (Multi thread) @author: Taufik Sutanto """ import time from threading import Thread COUNT = 50000000 def countdown(n): while n>0: n -= 1 t1 = Thread(target=countdown, args=(COUNT//2,)) t2 = Thread(target=countdown, arg...
smartcam.py
#!/usr/bin/env python import numpy import multiprocessing import os,time import conf.default as conf import lib.core as core import lib.service as service import Queue import logging def main(): logging.basicConfig(level=service.get_loglevel(os.environ['LOG_LEVEL'])) coreobj = core.Core() mgr = multiproc...
consumer_queue.py
from multiprocessing import Process, Queue # 多进程组件,队列 import time, random # 生产者方法 def producer(name, food, q): for i in range(4): time.sleep(random.randint(1, 3)) # 模拟获取数据时间 f = '%s生产的%s%s' % (name, food, i) print(f) q.put(f) # 添加进队列 # 消费者方法 def consumer(q, name): while Tr...
device_scheduler.py
import time from random import randint from copy import deepcopy from threading import Thread, Condition, Lock from xml.etree.ElementTree import TreeBuilder from flask import Flask from flask_mqtt import Mqtt from app.models import Device, User from app.models.db import db from app.mqtt.mqtt_message import MqttMesssa...
housekeeper.py
#SPDX-License-Identifier: MIT """ Keeps data up to date """ import coloredlogs from copy import deepcopy import logging, os, time, requests import logging.config from multiprocessing import Process, get_start_method from sqlalchemy.ext.automap import automap_base import sqlalchemy as s import pandas as pd from sqlalche...
variable_scope.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...
autolauncher.py
from __future__ import annotations import logging import multiprocessing from datetime import timedelta, datetime import concurrent.futures import sys import typing import time from pony.orm import db_session, select, commit from Utils import restricted_loads class CommonLocker(): """Uses a file lock to signal t...
video_ffpyplayer.py
''' FFmpeg based video abstraction ============================== To use, you need to install ffpyplyaer and have a compiled ffmpeg shared library. https://github.com/matham/ffpyplayer The docs there describe how to set this up. But briefly, first you need to compile ffmpeg using the shared flags while disabling...
listen.py
import numpy as np from config.config import * from lib.machinelearning import feature_engineering, feature_engineering_raw, get_label_for_directory, get_highest_intensity_of_wav_file, get_recording_power import pyaudio import wave import time import scipy import scipy.io.wavfile import hashlib import os import operato...
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 = ...
webstreaming.py
""" this is a web interface eidt by hichens """ import face_recognition from flask import Response from flask import Flask, request, redirect, url_for from flask import render_template import datetime import cv2 import os import sqlite3 as sq import numpy as np import time import sys; sys.path.append("../") from Face...
offboard3.py
import rospy import glob import json import math import os import px4tools import sys import time import actionlib import roslaunch from mavros import mavlink from mavros import action_server2 from mavros_msgs.msg import Mavlink, Waypoint, WaypointReached, GlobalPositionTarget, State, TakeoffAction, TakeoffGoal, LandAc...
multicpu_copy.py
import os from shutil import copyfile import sqlite3 from PIL import Image import uuid from multiprocessing import Process def do_chunk(pid,todo): out= open("all_detections_"+str(pid)+".csv","w") co=0 for line in todo: try: dest= os.path.join(root,line[2].replace(" ","_")) src= os.path.join('/dat...
tl.py
#!/usr/bin/env python import argparse import json import traceback import logging import os import signal import socket import sys import threading import time import shutil import select import fnmatch import subprocess import yaml ############## # dependencies # pip install pyyaml # pip install simplejson # pip ins...
host.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...
GUI.py
from tkinter import Tk, Frame, Scrollbar, Label, END, Entry, Text, VERTICAL, Button import socket import threading from tkinter import messagebox class GUI: client_socket = None last_received_message = None def __init__(self, master): self.root = master self.chat_transcript_area = None ...
gunicorn_worker.py
import logging import logging.config from multiprocessing import Process from typing import Union, TYPE_CHECKING from util.log import logfile_path if TYPE_CHECKING: from features import FeatureNameValue from workers.worker import Worker class GunicornWorker: """ GunicornWorker allows a Quay worker to...
db_tests.py
from itertools import permutations try: from Queue import Queue except ImportError: from queue import Queue import re import threading from peewee import * from peewee import Database from peewee import FIELD from peewee import attrdict from peewee import sort_models from .base import BaseTestCase from .base ...
sendmail.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time from multiprocessing import Process import email from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib from django.conf import settings class MailSender(ob...
test_browser.py
# coding=utf-8 # Copyright 2013 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. import argparse import json import multiprocessing imp...
system.py
import threading from mysql import connector from config import * import platform import modules.core.database as database import modules.core.extract as extract import time import speedtest #pip install speedtest-cli import psutil #pip install psutil import urllib.request import subprocess import socket import...
cpu_gpu_profiler.py
import os import signal import time import subprocess import pandas as pd from collections import defaultdict from threading import Event, Thread import psutil from .errors import CommandExecutionError # redirect the GPU memory usage to a file #GPU_MONITOR = "nvidia-smi --query-gpu=index,memory.used --format=csv -lms...