source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
endpoint.py | import os
import io
import threading
import hashlib
import functools
import secrets
import typing
from http import HTTPStatus
import zipfile
import requests
import flask
from werkzeug import utils
from azure.common import AzureMissingResourceHttpError
from extract_endpoint import azure_utils
from extract_endpoint impor... |
pyshell.py | #! /usr/bin/env python3
import sys
if __name__ == "__main__":
sys.modules['idlelib.pyshell'] = sys.modules['__main__']
try:
from tkinter import *
except ImportError:
print("** IDLE can't import Tkinter.\n"
"Your Python may not be configured for Tk. **", file=sys.__stderr__)
raise SystemExit(... |
installwizard.py | import sys
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore
import electrum_dash
from electrum_dash import Wallet, WalletStorage
from electrum_dash.util import UserCancelled, InvalidPassword
from electrum_dash.base_wizard import BaseWizard
from electrum_dash.i18n import _
... |
__init__.py | #!/usr/bin/env python
"""IonServer - This library allows playing of matches on network via the
WebSockets protocol.
Functions:
init() - If you want to run the application normally
run(max_players, max_matches, port, timeout, mode, ui_en=True,
exit_handler=True) - If you want to programatically launch the server ... |
runCtaTrading.py | # encoding: UTF-8
import multiprocessing
from time import sleep
from datetime import datetime, time
from vnpy.event import EventEngine2
from vnpy.trader.vtEvent import EVENT_LOG
from vnpy.trader.vtEngine import MainEngine, LogEngine
from vnpy.trader.gateway import ctpGateway
from vnpy.trader.app import ctaStrategy
fr... |
http_com.py | import logging
import base64
import random
import os
import ssl
import time
import copy
import json
import sys
from pydispatch import dispatcher
from flask import Flask, request, make_response, send_from_directory
# Empire imports
from lib.common import helpers
from lib.common import agents
from lib.common import encr... |
tests.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import errno
import os
import shutil
import sys
import tempfile
import threading
import time
import unittest
from datetime import datetime, timedelta
from django.core.cache import cache
from django.core.exceptions import SuspiciousFileOperation, Suspicio... |
test_concurrent_futures.py | from test import support
from test.support import import_helper
from test.support import threading_helper
# Skip tests if _multiprocessing wasn't built.
import_helper.import_module('_multiprocessing')
# Skip tests if sem_open implementation is broken.
support.skip_if_broken_multiprocessing_synchronize()
from test.sup... |
test_thread.py | from threading import Thread
import time
import os
stop = 0
def yes():
global stop
while True:
if stop == 1:
print('stopped yes')
break
else:
print('i am yes')
print('stop : ', stop)
time.sleep(2)
def yes1():
global stop
... |
anialtools.py | import hdnntools as hdt
import nmstools as nmt
import pyanitools as pyt
import pyaniasetools as aat
import pyanitrainer as atr
import pymolfrag as pmf
from pyNeuroChem import cachegenerator as cg
import numpy as np
from time import sleep
import subprocess
import random
#import pyssh
import re
import os
import pyani... |
email.py | from threading import Thread
from flask import current_app, render_template
from flask_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 = Mess... |
gazeNets.py | #!/usr/bin/env python
import cv2
import os
import subprocess as sp
import sys
import numpy as np
import time
import pickle as pk
# import datetime
from matrix import get_pupil_transformation_matrix
from threading import Thread
sys.path.append(os.path.abspath('../../TEST'))
sys.path.append(os.path.abspath('../../TEST/sh... |
red_test.py | #!/usr/bin/env python
import logging
from redbot.resource import HttpResource
import redbot.speak as rs
import thor
import threading
from tornado import gen
from tornado.options import parse_command_line
from tornado.testing import AsyncHTTPTestCase
from tornado.web import RequestHandler, Application, asynchronous
imp... |
mapping_web_app_install.py | #!/usr/bin/env python
__author__ = "bt3"
import urllib2
import Queue
import os
import threading
THREADS = 10
TARGET = 'http://www.blackhatpython.com'
# local directory into which we have downloaded and extracted the web app
#DIRECTORY = '/home/User/Desktop/Joomla'
#DIRECTORY = '/home/User/Desktop/wordpress'
DIRECTOR... |
scan.py | import click
import collections
import datetime
import shodan
import shodan.helpers as helpers
import socket
import threading
import time
from shodan.cli.helpers import get_api_key, async_spinner
from shodan.cli.settings import COLORIZE_FIELDS
@click.group()
def scan():
"""Scan an IP/ netblock using Shodan."""
... |
cluster_test.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... |
OB_tkwindowv1.py | import OB_v2
from OB_v2 import On_Box_Window
import Decoder2v7
from Decoder2v7 import *
from threading import Thread
ser = None
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.flush()
parser = binaryPacketParser()
#First time running the Decoder will give empty packets, so throw those away immediately.
IMU_... |
lisp-etr.py | #-----------------------------------------------------------------------------
#
# Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.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 ... |
smoketest.py | """
Agent smoketest code.
This python script is meant to be invoked within a docker image in which the proper python version is activated (e.g.
via pyenv). In this way, the agent can be validated against different python versions.
Concept:
This code serves as a common code-base for different types of smoketest "... |
core_test.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... |
communicating_with_pipe.py | # Using Pipes with multiprocessing – Chapter 3: Process Based Parallelism
import multiprocessing
def create_items(pipe):
output_pipe, _ = pipe
for item in range(10):
output_pipe.send(item)
output_pipe.close()
def multiply_items(p_1, p_2):
close, input_pipe = p_1
close.close()
output... |
nose_tests_runner.py |
#
# PS Move API - An interface for the PS Move Motion Controller
# Copyright (c) 2012 Thomas Perl <m@thp.io>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source co... |
runner_mp.py | # -*- coding: UTF-8 -*-
"""
This module provides multiprocessing Runner class.
"""
import six
import os
import multiprocessing
from behave.formatter._registry import make_formatters
from behave.runner import Runner, Context
from behave.model import Feature, Scenario, ScenarioOutline, NoMatch
from behave.runner_util i... |
test_console_task.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import thr... |
jroutils_ftp.py | '''
@author: Daniel Suarez
'''
import os
import glob
import ftplib
try:
import paramiko
import scp
except:
pass
import time
import threading
Thread = threading.Thread
# try:
# from gevent import sleep
# except:
from time import sleep
from schainpy.model.proc.jroproc_base import ProcessingUnit, Oper... |
mscigraph.py | import socket
import datetime
import threading
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("Agg")
import matplotlib.backends.backend_agg as agg
import ssl
from time import sleep
import pygame
"""
DataVisBot for SARP 2021
Adam Furman
You need to have
"pip install matplotlib pygam... |
rd_server.py | #!/usr/bin/env python3
import tornado.ioloop
import tornado.web
import os
import codecs
import json
import argparse
import sshslot
import threading
import time
import awsremote
from work import *
from utility import *
video_sets_f = codecs.open('sets.json','r',encoding='utf-8')
video_sets = json.load(video_sets_f)
m... |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Han Xiao <artex.xh@gmail.com> <https://hanxiao.github.io>
import sys
import threading
import time
import uuid
from collections import namedtuple
import numpy as np
import zmq
from zmq.utils import jsonapi
# in the future client version must match with server version
__... |
drive_with_gamepad.py | import os
import time
import yaml
import threading
import inputs # https://inputs.readthedocs.io/en/latest/user/intro.html
import deepracer_vehicle_api
steer = 0
drive = 0
done = False
stop = False
def event_loop():
"""
This function is called in a loop, and will get the events from the
controller and s... |
afgn_transaction_receipt_origin_contract_address.py | #!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.address import *
import threading
def waitforlogs(node, contract_address):
logs = node.cli.waitforlo... |
kosmos.py | import logging
import json
from homeassistant import core
try:
import thread
except ImportError:
import _thread as thread
import time
import threading
from .const import DOMAIN # pylint:disable=unused-import
import asyncio
import re
from kosmos_client import KosmosClient, KosmosEvent, KosmosDev... |
api_server.py | from typing import Dict, Optional
from multiprocessing import Queue, Process
import uvicorn
from pydantic import BaseModel
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler
from fastapi import Query, FastAPI, Request, Back... |
coap.py | import logging
import random
import socket
import struct
import threading
from coapthon import defines
from coapthon.layers.blocklayer import BlockLayer
from coapthon.layers.messagelayer import MessageLayer
from coapthon.layers.observelayer import ObserveLayer
from coapthon.layers.requestlayer import RequestLayer
from... |
runner.py | """This module contains classes for an asynchronous thread
The thread periodically checks the database for unfinished tasks
If an unfinished task is encountered the slurm frontend of the cluster
is checked for the jobs state.
Unfinished tasks are defined as tasks which have executed
a slurm job whi... |
postmaster.py | import logging
import multiprocessing
import os
import psutil
import re
import signal
import subprocess
from patroni.config import Config
logger = logging.getLogger(__name__)
STOP_SIGNALS = {
'smart': signal.SIGTERM,
'fast': signal.SIGINT,
'immediate': signal.SIGQUIT if os.name != 'nt' else signal.SIGABR... |
ex3.py | import threading
import random
import time
AVG_COUNT = 10
cond = threading.Condition ()
numbers = []
random.seed (0)
def generate_rand():
global numbers
cond.acquire()
numbers.append (random.randint(2000, 3000))
if (len(numbers) == AVG_COUNT):
cond.notify()
cond.release()
def compute_avg... |
nanny.py | from __future__ import annotations
import asyncio
import errno
import logging
import os
import shutil
import threading
import uuid
import warnings
import weakref
from contextlib import suppress
from inspect import isawaitable
from queue import Empty
from time import sleep as sync_sleep
from typing import ClassVar
imp... |
safe_t.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... |
HttpTransport.py | from Transport import Transport
from base64 import b64encode
from json import dumps, loads
from log import *
from sha256 import *
from threading import Thread
from time import sleep, time
from urlparse import urlsplit
from util import *
import httplib
import traceback
class NotAuthorized(Exception): pass... |
client.py | import socket
import tkinter
import tkinter.messagebox
import threading
import json
import tkinter.filedialog
from tkinter.scrolledtext import ScrolledText
host = ''
port = ''
user = ''
listbox1 = '' # online users listbox
show = 1 # listbox shown or not
users = [] # online users list
chat = '------Group chat------... |
multiprocessing.py | import atexit
import logging
import multiprocessing as mp
import sys
import traceback
class ExceptionWrapper(object):
r"""Wraps an exception plus traceback to communicate across threads"""
def __init__(self, exc_info):
self.exc_type = exc_info[0]
self.exc_msg = "".join(traceback.format_except... |
test_sys.py | # -*- coding: iso-8859-1 -*-
import unittest, test.support
import sys, io, os
import struct
import subprocess
import textwrap
class SysModuleTest(unittest.TestCase):
def setUp(self):
self.orig_stdout = sys.stdout
self.orig_stderr = sys.stderr
self.orig_displayhook = sys.displayhook
de... |
AbstractHandle_server_test.py | # -*- coding: utf-8 -*-
import os
import unittest
from configparser import ConfigParser
import inspect
import copy
import requests as _requests
from unittest.mock import patch
import threading
import queue
from random import randrange
from AbstractHandle.AbstractHandleImpl import AbstractHandle
from AbstractHandle.Abs... |
pydas.py | #!/usr/bin/python3
# pylint: disable=locally-disabled, broad-except, line-too-long
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Copyright (c) 1995-2019, Ecometer s.n.c.
# Author: Paolo Saudin.
#
# Desc : Collect data from temperature sensors
# File : pydas.py
#
... |
test_parallel.py | """Test `parallel.py`."""
from dataclasses import dataclass
from threading import Thread
from time import sleep
import pytest
from .parallel import Guard
def test__Guard__int() -> None:
"""Test `Guard` with `int`."""
guarded_variable = 1
guard = Guard(guarded_variable)
with guard as variable:
... |
iterator.py | from __future__ import division, print_function, absolute_import
import sys
import SharedArray
import multiprocessing
import os
import threading
from uuid import uuid4
import numpy as np
from . import data
is_py2 = sys.version[0] == '2'
if is_py2:
import Queue
else:
import queue as Queue
class BatchIterator(o... |
wxStocks_aaii_xls_data_importer.py | import sys, pprint, os, inspect, string, time, logging, config, threading
try:
import xlrd
except:
try:
import modules.xlrd as xlrd # AAII is all excel files
except:
logging.info("Error: xlrd is not installed")
sys.exit()
from wxStocks_modules import wxStocks_utilities as utils
fro... |
vnhuobi.py | # encoding: utf-8
import urllib
import hmac
import base64
import hashlib
import requests
import traceback
from copy import copy
from datetime import datetime
from threading import Thread
from Queue import Queue, Empty
from multiprocessing.dummy import Pool
from time import sleep
import json
import zlib
# retrieve p... |
httpserver.py | # -*- coding: utf-8 -*-
"""
The httpserver module contains an easy and ready-to-use HTTP file server.
o ServeDirectoryWithHTTP: Spawns an HTTP file server in a separate thread.
Source: https://gist.github.com/kwk/5387c0e8d629d09f93665169879ccb86
"""
import http.server
from threading import Thread, current_thread
fro... |
test_io.py | """Unit tests for the io module."""
# Tests of io are scattered over the test suite:
# * test_bufio - tests file buffering
# * test_memoryio - tests BytesIO and StringIO
# * test_fileio - tests FileIO
# * test_file - tests the file interface
# * test_io - tests everything else in the io module
# * test_univnewlines - ... |
discord.py | import base64, json, websocket, time, threading, re, httpx
from urllib.request import Request, urlopen
config = json.load(open('./config.json'))
class Payload:
@staticmethod
def simple_register(username: str, fingerprint: str, captcha_key: str) -> dict:
return {
"consent": True,
... |
wsdump.py | #!/home/pi/AI-Smart-Mirror/aienv/bin/python3
import argparse
import code
import sys
import threading
import time
import ssl
import six
from six.moves.urllib.parse import urlparse
import websocket
try:
import readline
except ImportError:
pass
def get_encoding():
encoding = getattr(sys.stdin, "encoding"... |
processor.py | import sublime
import sublime_plugin
import os
import xml
import urllib
import json
import threading
import time
import pprint
import urllib.parse
import shutil
import datetime
import math
from xml.sax.saxutils import unescape
from . import requests, context, util
from .context import COMPONENT_METADATA_SETTINGS
from ... |
model.py | """
Control Model
=============
Module storing an implementation of the control model.
The `ControlManager` class is the implementation of a closed loop control system for the ROV, with the readings
from both the manual and the autonomous modes.
The normalised values are then converted to the ranges expected by hard... |
sdk_worker.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... |
queue_runner.py | <<<<<<< HEAD
# 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 requir... |
ytarchive.py | #!/usr/bin/env python3
from enum import Enum
import faulthandler
import getopt
from html.parser import HTMLParser
import http.cookiejar
import io
import json
import logging
import os
import platform
import queue
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import t... |
api.py | import json
import os
import requests
import uvicorn
import logging
import threading
import time
from scanflow import tools
from scanflow.deploy.deploy import Deploy
from fastapi import FastAPI, BackgroundTasks
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%d-%b... |
compute_process.py | import logging
import os
import time
import json
import copy
import numpy as np
from abc import ABC, abstractmethod
from typing import Dict, List
from configs import BACKEND_INTERNAL_CONFIG, NXS_BACKEND_CONFIG, NXS_CONFIG
from nxs_types.infer import NxsInferRequestMetadata
from nxs_types.nxs_args import NxsBackendArgs
... |
rman_render.py | import time
import os
import rman
import bpy
import sys
from .rman_constants import RFB_VIEWPORT_MAX_BUCKETS, RMAN_RENDERMAN_BLUE
from .rman_scene import RmanScene
from .rman_scene_sync import RmanSceneSync
from. import rman_spool
from. import chatserver
from .rfb_logger import rfb_log
import socketserver
import thread... |
vpn_service.py | # -*- coding: utf-8 -*-
import threading
import time
import properties
import utils
VPN_CONNECTED_STATUS = 'connected\n'
VPN_DISCONNECTED_STATUS = 'disconnected\n'
def get_vpn_names():
output = utils.execute_cmd('scutil --nc list')
output_lines = output.split('\n')
vpn_names = list()
if len(output... |
thread_test.py | #####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Microsoft Public License. A
# copy of the license can be found in the License.html file at the root of this ... |
test_browser.py | # coding=utf-8
from __future__ import print_function
import multiprocessing, os, shutil, subprocess, unittest, zlib, webbrowser, time, shlex
from runner import BrowserCore, path_from_root, has_browser, get_browser
from tools.shared import *
try:
from http.server import BaseHTTPRequestHandler, HTTPServer
except Impo... |
simple_hdlc.py | #!/usr/bin/python
# coding: utf8
# License posted here: https://github.com/wuttem/simple-hdlc/blob/master/LICENSE
# and copied below:
#
# MIT License
#
# Copyright (c) 2016 wuttem
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... |
test_exp_csvsed.py | """
These are tests on csvsed's experimental features, i.e. multiple expressions, which are
currently hidden from the API
"""
import contextlib
from io import StringIO
from subprocess import Popen, PIPE
import sys
from tests.mk import CmkTestCase, stdin_as_string, skiptest
from csvmedkit.utils.csvsed import CSVSed
... |
nes_env.py | import logging
import os
import multiprocessing
import signal
import subprocess
import tempfile
from distutils import spawn
from threading import Thread, Lock
from time import sleep
import numpy as np
import gym
from gym.gym import utils, spaces
from gym.gym.utils import seeding
SEARCH_PATH = os.pathsep.join([os.env... |
web.py | from flask import Flask
from flask import jsonify
import os
import threading
from multiprocessing import Process
class FlaskServer(object):
def start_server(self):
t = RunServer('')
p = Process(target=t.start())
p.start()
def stop_server(self):
os.system('')
class RunServer(... |
create_patches.py | from dolfin import *
from mshr import *
import numpy as np
import numpy.linalg as la
import numpy.random as rnd
import logging
import sa_utils
from sa_utils import myeps, comm, rank, size, adapt
import sa_hdf5
import os
import time
import gc
import multiprocessing
corner_refine = 4
def create_patches(box = np.arr... |
DataCache.py | import threading
import time
import numpy as np
class DataCache:
def __init__(self, lifetime=30, modify_data_fn=None):
self.__cached_data = None
self.__cached_uuid = None
self.__last_requested = time.time()
self.lifetime = lifetime
self.modify_data_fn = modify_data_fn if ca... |
labelImg.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import distutils.spawn
import os.path
import platform
import re
import sys
import subprocess
import time, threading
import csv
import tensorflow as tf
import numpy as np
from PIL import Image
from PIL import ImageDraw
from PIL import ImageColor
from PIL impor... |
process.py | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, with_statement
import copy
import os
import sys
import time
import errno
import types
import signal
import logging
import threading
import contextlib
import subprocess
import multiprocessing
import multiprocessing.util
# Import salt... |
Trading.py | # -*- coding: UTF-8 -*-
# @yasinkuyu
# Define Python imports
import os
import sys
import time
import config
import threading
import math
import logging
import logging.handlers
import json
# from binance_f import RequestClient
# from binance_f.constant.test import *
# from binance_f.base.printobject import *
# from bi... |
run.py | #import packages
import time
import threading
import numpy as np
import torch
import matplotlib.pyplot as plt
import os
import pandas as pd
import random
import gc
from datetime import datetime
import torch.cuda as cuda
import torchvision as tv
import torchvision.transforms as transforms
from torchvision import mode... |
simple_task_queue_logging.py | # simple_task_queue_logging.py
import os
import time
import logging
import multiprocessing
from tasks import get_word_counts
PROCESSES = multiprocessing.cpu_count() - 1
NUMBER_OF_TASKS = 10
def create_logger():
logger = multiprocessing.get_logger()
logger.setLevel(logging.INFO)
fh = logging.FileHandle... |
client.py | import socket
from random import randint
from threading import Thread
from json import dumps, loads
clients = {}
class Client:
def __init__(self, id:int, conn, addr) -> None:
clients[str(id)] = self
self.id = str(id)
self.conn = conn
self... |
git_common.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Monkeypatch IMapIterator so that Ctrl-C can kill everything properly.
# Derived from https://gist.github.com/aljungberg/626518
from __future__ import prin... |
executors.py | # -*- coding: utf-8 -*-
""" Single and multi-threaded executors."""
import datetime
import os
import tempfile
import threading
from abc import ABCMeta, abstractmethod
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
import psutil
from six import string_types, with_metaclass
from typing import ... |
utils.py | from __future__ import print_function, division, absolute_import
import atexit
from collections import deque
from contextlib import contextmanager
from datetime import timedelta
import functools
from hashlib import md5
import inspect
import json
import logging
import multiprocessing
from numbers import Number
import o... |
main.py | import threading
from time import sleep
from logging import getLogger
from importlib import import_module
from python.repl import start as repl_start
from python.logger import get_top_level_logger
from python.updater import updater_init
def execute_main(args, default_device_name):
# NOTE: The placement of this ... |
thumbnail_queue.py | # thumbnail_maker.py
import time
import os
import logging
from urllib.parse import urlparse
from urllib.request import urlretrieve
from queue import Queue
from threading import Thread
import PIL
from PIL import Image
logging.basicConfig(filename='logfile.log', level=logging.DEBUG)
class ThumbnailMakerService(object... |
stress_test.py | from threading import Thread
import requests
import time
KERAS_REST_API_URL = "http://localhost:5000/predict"
IMAGE_PATH = "test.jpg"
NUM_REQUESTS = 500
SLEEP_COUNT = 0.05
def call_prediction_endpoint(n):
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image}
r = requests.post(KERAS_REST_API_U... |
mockserver.py | # encoding: utf-8
import json
import re
import socket
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import requests
class MockServerRequestHandler(BaseHTTPRequestHandler):
API_PATTERN = re.compile(r"/data|query|/")
def do_GET(self):
if re.search... |
lightchain_shell.py | """
Run a LightChain (on Ropsten) in a separate thread, allowing users to interact
with it via the python interpreter running on the main thread.
See docs/quickstart.rst for more info on how to use this.
"""
import argparse
import asyncio
import atexit
import logging
import threading
from evm.db.chain import ChainDB
... |
test_misc.py | import importlib
import logging
import platform
import traceback
import xml.dom.minidom
import stomp
from stomp.exception import *
from stomp.listener import *
from .testutils import *
class TransformationListener(TestListener):
def __init__(self, receipt, print_to_log):
TestListener.__init__(self, recei... |
TianContigFilterServer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import os
import random as _random
import sys
import traceback
from getopt import getopt, GetoptError
from multiprocessing import Process
from os import environ
from wsgiref.simple_server import make_server
import requests as _requests
from json... |
utils.py | # -*- coding: utf-8 -*-
import base64
import functools
import logging
import os
import re
import string
import time
import unicodedata
import warnings
import zipfile
from datetime import datetime
from getpass import getpass
from threading import Event, Thread
from urllib.parse import quote
from xml.etree import Element... |
hopper-v3.py | import os, sys, signal
import random
import numpy as np
from multiprocessing import Process, Queue, current_process, freeze_support
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--pgmorl', default=False, action='store_true')
parser.add_argument('--ra', default=False, action='store_true')
pars... |
io.py | """
Wrapping the :py:class:`Cache <cachecat.cache.Cache>` and
:py:class:`Session <cachecat.session.Session>` interfaces in more familiar
`file-like interfaces <https://docs.python.org/3/library/io.html>`_ simplifies
the user experience and enables more complex buffering techniques which
ultimately improve tunneling cap... |
sexy.py | import re
import requests
from queue import Queue
from threading import Lock, Thread
lock = Lock()
def get_pic(in_q):
while in_q.empty() is not True:
url = in_q.get()
res = requests.get(url)
try:
while url[-3:] != 'jpg':
url = re.findall("(.*)\?\d+",url)[0]
... |
actor.py | import multiprocessing as mp
import os
import logging
log = logging.getLogger(__name__)
class DeadActorException(Exception):
pass
def die(msg="Giving up!"):
raise RuntimeError(msg)
class Actor(object):
inbox_size = 4
SEND_TIMEOUT = 3600 * 4
def __init__(self, inbox_size=None):
self.... |
fakeSensor.py | #!/usr/bin/python3
# Simple demo of fifo mode on the MMA8451.
# Author: Philip Crotwell
import time
import math
import struct
import queue
from threading import Thread
from datetime import datetime, timedelta, timezone
import sys, os, signal
from pathlib import Path
import asyncio
import traceback
import faulthandler
... |
RealtimeServer.py | import socketserver
import threading
import time
import services.realtime.messaging.RMSUtil as RMSUtil
from services.realtime.messaging.RMSClient import RMSClient
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class RealtimeServer(object):
instance = None
@staticmet... |
tensorflow.py | # -*- coding: utf-8 -*-
try:
import tensorflow as tf
from object_detection.utils import label_map_util as lm_util
except ImportError as error:
raise ImportError(
"Usage of the TensorFlow detectors requires that TensorFlow and the research module of "
"the TensorFlow Model Garden are install... |
test_unix_events.py | """Tests for unix_events.py."""
import collections
import contextlib
import errno
import io
import os
import pathlib
import signal
import socket
import stat
import sys
import tempfile
import threading
import unittest
from unittest import mock
from test import support
if sys.platform == 'win32':
... |
utils.py | # -*- coding: utf-8 -*-
import json
from tabulate import tabulate
import pandas as pd
import constants
import itertools
import logging
import coloredlogs
import time
from multiprocessing import Process, Manager
import numpy
import requests
import ast
coloredlogs.install(level=logging.INFO)
class RequestException(Exce... |
main.py | import subprocess
import os
from threading import Thread
from django.core.management import execute_from_command_line
from kivy.app import App
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_web_app.settings'
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.floatlayout import ... |
utility.py | #encoding:utf-8
#-*- coding: utf-8 -*-
from optparse import OptionParser
import os.path
import pandas as pd
import numpy as np
import os
import sys
import math
import random
import scipy
import scipy.io
from numpy.lib.recfunctions import append_fields
import sklearn.preprocessing
from sklearn.extern... |
ping_of_death_flood.py | #!/usr/bin/env python
from scapy.all import *
import sys
import threading
import time
import os
os.system('clear||cls')
if len(sys.argv) < 2:
print "Usage: <target> <broadcast IP> <threads>"
#dont put threads too high
print "Basic PingOfDeath flood by Khanejo"
sys.exit()
host = sys.argv[1]
refl... |
workstation_server.py | '''
socket between android and demo computer use port 1234
socket between demo computer and workstation use port 8888
'''
import socket
import os
import threading
import sys
# sys.path.append('./tools')
# import demo
host = '192.168.0.107'
# host = '192.168.0.106'
port = 8888
address = (host, port)
... |
sources.py | import asyncio
import csv
import queue
import threading
from datetime import datetime, timezone
from typing import List, Optional, Union
import pandas
from .dtypes import _termination_obj, Event, FlowError
from .flow import Flow
class AwaitableResult:
"""Future result of a computation. Calling await_result() wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.