source
stringlengths
3
86
python
stringlengths
75
1.04M
02_incomplete_multiprocessing.py
import multiprocessing import time start = time.perf_counter() def schlafen(n_sec=1): print(f"Sleep for {n_sec}(s) ...") time.sleep(n_sec) print(f"Done sleeping {n_sec}(s) ...") p1 = multiprocessing.Process(target=schlafen) p2 = multiprocessing.Process(target=schlafen) finish = time.perf_counter() print...
shellutil.py
#!/usr/bin/env python """ Helpers for running shell commands and manipulating the console/terminal in a cross-platform way """ #pylint: disable=bare-except import os import shlex import struct import platform import subprocess import threading from .logutil import GetLogger LOCAL_SYS = platform.system() if LOCAL_SYS...
_updater.py
# coding: utf-8 """ Python 3.6 only because using f-strings """ __appname__ = 'selfupdater' __version__ = '2017.208.1030' import os import sys import time import shutil import signal import subprocess import urllib.request import multiprocessing def _get_args_for_reloading(): ret_val = [sys.execu...
test_worker.py
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os import shutil import signal import subprocess import sys import time import zlib from datetime import datetime, timedelta from multiprocessing import Process from time import ...
contractlistener.py
from web3.auto import w3 from threading import Thread import time import sys from pprint import pprint import loghandler log_handler = loghandler.LogHandler() class EventListener: def __init__(self): self.logger = log_handler.create_logger("eventlistener") def handle_event(self, event): ppr...
zen.py
import re import sys import json import argparse import threading from requests import get from requests.auth import HTTPBasicAuth parser = argparse.ArgumentParser() parser.add_argument('target', help='target') parser.add_argument('-o', help='output file', dest='output') parser.add_argument('-u', help='your username',...
mqtt_s3_comm_manager.py
# -*-coding:utf-8-*- import json import time import traceback import uuid from typing import List import paho.mqtt.client as mqtt import yaml from .remote_storage import S3Storage from ..base_com_manager import BaseCommunicationManager from ..message import Message from ..observer import Observer import logging cla...
logwriter.py
""" A log destination for use by Twisted applications. Runs in a thread, so that we don't do blocking I/O in the event loop thread. """ from __future__ import unicode_literals, absolute_import import threading import select from warnings import warn from twisted.application.service import Service from twisted.inter...
server.py
from math import floor from world import World import Queue import SocketServer import datetime import random import re import requests import sqlite3 import sys import threading import time import traceback DEFAULT_HOST = '0.0.0.0' DEFAULT_PORT = 4080 DB_PATH = 'craft.db' LOG_PATH = 'log.txt' CHUNK_SIZE = 32 BUFFER...
plotGraph.py
import code import collections import math import numbers import threading import time import warnings from warnings import warn as _warn import matplotlib.pyplot as plt import numpy as np class _FRange(collections.Sequence): # Mind that some methods have not been overriden yet, and the # complexity of running the...
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...
tb_device_mqtt.py
# Copyright 2020. ThingsBoard # # 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 ...
provider.py
# BLE provider implementation using Linux's bluez library over its DBus # interface. # Author: Tony DiCola # # Copyright (c) 2015 Adafruit Industries # # 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 ...
email.py
from flask import render_template, current_app from flask_mail import Message from app import mail from threading import Thread def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body Thre...
gui.py
import tkinter as tk from threading import Thread from PIL import Image, ImageTk import copy import time import math from typing import Any, Tuple import os from game import Game from neural_network import NNet import constants as c import ai image_dir = f'{os.path.dirname(os.path.abspath(__file__))}\\images' class...
utils.py
import asyncio import socket import time from contextlib import closing from functools import wraps from importlib import import_module from pathlib import Path from threading import Event, Thread from typing import Any, Callable, List, Optional from typing_extensions import ParamSpec import idom from .types import ...
HTTPListener.py
import logging from ConfigParser import ConfigParser import os import sys import imp import threading import SocketServer import BaseHTTPServer import ssl import socket import posixpath import mimetypes import time from . import * MIME_FILE_RESPONSE = { 'text/html': 'FakeNet.html', 'image/png': 'Fa...
test_code_1.py
import glob import os import sys import random import time import numpy as np import cv2 import math from collections import deque from keras.applications.xception import Xception from keras.layers import Dense, GlobalAveragePooling2D from keras.optimizers import Adam from keras.models import Model from keras.callbacks...
cpu_bound_threaded.py
""" cpu bound single demo """ from collections.abc import Generator import itertools import time import threading def fibonacci() -> Generator[int, None, None]: """ generate an infinite fibonacci sequence """ num_1 = 0 num_2 = 1 yield num_1 yield num_2 while True: next_num = num_1 ...
event_dispatcher.py
""" Event listener based on unix domain sockets or win32 named pipes """ from __future__ import print_function import abc import logging from multiprocessing.connection import Listener, Client import os import socket from threading import Thread from chalmers import errors from chalmers import config import sys lo...
file_observer.py
""" Wraps watchdog to observe file system for any change. """ import logging import threading from abc import ABC, abstractmethod from pathlib import Path from threading import Thread, Lock from typing import Callable, List, Dict, Optional import docker from docker import DockerClient from docker.errors import ImageN...
doh-async-thread.py
#!/usr/bin/env python3 import asyncio, aiohttp import threading, random host = '127.0.0.1' port = 5053 headers = {'accept': 'application/dns-message', 'content-type': 'application/dns-message'} upstreams = ('https://1.1.1.1/dns-query', 'https://1.0.0.1/dns-query') conns = [] forwarder_loop = asyncio.new_event_loop()...
daemon-threads.py
import sys import threading import time def main(argv): thread_type = argv[1] if len(argv) > 1 else None if thread_type == 'daemon': start_thread(daemon=True) else: start_thread(daemon=False) print('Done main') def start_thread(daemon): thread = threading.Thread(target=thread_targe...
nb.py
"""Utility functions for data science in Jupyter/JupyterLab notebooks""" # Python Built-Ins: import os import subprocess import threading import time # External Dependencies: import boto3 from IPython.display import display, HTML import ipywidgets as widgets s3 = boto3.client("s3") def upload_in_background(local_pa...
val.py
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Validate a trained YOLOv5 model accuracy on a custom dataset Usage: $ python path/to/val.py --weights yolov5s.pt --data coco128.yaml --img 640 Usage - formats: $ python path/to/val.py --weights yolov5s.pt # PyTorch ...
test_kernelmanager.py
"""Tests for the KernelManager""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json import os pjoin = os.path.join import signal from subprocess import PIPE import sys import time import threading import multiprocessing as mp import pytest from unittest ...
DarunGrim.py
from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSql import * import DarunGrimDatabase import DiffEngine from Graphs import * import FlowGrapher import FileStoreBrowser import FileStoreDatabase import DarunGrimEngine import pprint from multiprocessing import Process from multiprocessing import Que...
test_mysqlx_crud.py
# -*- coding: utf-8 -*- # Copyright (c) 2016, 2021, Oracle and/or its affiliates. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2.0, as # published by the Free Software Foundation. # # This program is also distributed with certa...
s3.py
import json import boto3 import os import requests import StringIO from flask import send_file from botocore.exceptions import ClientError from threading import Thread from time import sleep client = boto3.client('s3') resource = boto3.resource('s3') region = 'eu-west-1' def pather(*args): return "/".join([arg for...
procesx.py
from multiprocessing import Process import time import myo l = [1, 2]; def app (x, delay): try: myo. initialize (l); print ("master {}". format (l)); l. append (4); myo. start (l); print ("master {}". format (l)); time.sleep(delay) except KeyboardInterrupt: print ("Yes"); l....
StackingTest.py
#!/usr/bin/python from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor import time import atexit import threading import random # bottom hat is default address 0x60 bottomhat = Adafruit_MotorHAT(addr=0x60) # top hat has A0 jumper closed, so its address 0x61 tophat = Adafruit_MotorHA...
popcop_test.py
#!/usr/bin/env python3 # # The MIT License (MIT) # # Copyright (c) 2017-2018 Zubax Robotics # # 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...
gui.py
# # Copyright (C) 2014 Tommy Winther # http://tommy.winther.nu # # Modified for FTV Guide (09/2014 onwards) # by Thomas Geppert [bluezed] - bluezed.apps@gmail.com # # Modified for Stargate Guide (2016) # by wardoctor - wardoctor@tardisbuilds.com # # This Program is free software; you can ...
extension.py
import time from datetime import datetime from multiprocessing import Event, Process, Queue from chainer.training import extension, trigger as trigger_module from dateutil import tz from six.moves.queue import Empty from .misc import Message, WatchItem class Watchdog(extension.Extension): """Trainer extension...
data_proc_pipeline.py
import argparse import numpy as np import torch.multiprocessing as mp from initialize import proc_exec, single_dev_init, multi_dev_init def log_params(params): """ Print all the command line arguments for debugging purposes. Parameters: ----------- params: argparse object Argument Parser stru...
hayai_annotationServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from wsgiref.simple_server import make_server import sys import json import traceback import datetime from multiprocessing import Process from getopt import getopt, GetoptError from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\ JSONRPCError, Inva...
test_monitor.py
import functools import random import sys import time import unittest import xtimeout try: import _thread thread_enabled = True del _thread except ImportError: thread_enabled = False if thread_enabled: import threading def busy(seconds): if seconds == -1: while 1: pass ...
test_reading.py
# coding: utf-8 from __future__ import with_statement import random, threading, time from whoosh import analysis, fields, formats, reading from whoosh.compat import b, u, xrange from whoosh.reading import SegmentReader from whoosh.filedb.filestore import RamStorage from whoosh.util.testing import TempIndex def _cre...
test_focuser.py
import time import pytest from threading import Thread from panoptes.utils.config.helpers import load_config from panoptes.pocs.focuser.simulator import Focuser as SimFocuser from panoptes.pocs.focuser.birger import Focuser as BirgerFocuser from panoptes.pocs.focuser.astromechanics import Focuser as AstroMechanicsFo...
plain_psycopg2.py
import random from threading import Thread import psycopg2 if __name__ == "__main__": def add_and_select_data(cur, data): cur.execute( "insert into mytable(data) values (%s) returning id", (data,) ) row = cur.fetchone() id_ = row[0] cur.execute("select data fro...
main.py
import tkinter as tk from PIL import Image, ImageTk import utils import os import urllib.request import threading # If "result" and "replacement" folder don't exist, create it and download the images from the GitHub repository if not os.path.exists("result"): os.makedirs("result") if not os.path.exists("replacemen...
worker.py
import threading import time import os import subprocess import uvicorn from fastapi import FastAPI import sqliteprocess app = FastAPI() @app.get("/") async def home(): return {"Hello": "FastAPI"} def DBwatcher(): sp = sqliteprocess.SqliteProcess() while(True): process = sp.getNextProcess() ...
reporte.py
""" #Reporte v1.0 #Autor: Javier Arturo Hernández Sosa #Fecha: 8/Dic/2017 #Descripcion: Crea reportes a partir de un archivo excel """ #Librerias import pandas as pd import numpy as np import threading import time from tkinter import * from tkinter import ttk from tkinter import filedialog from tkinte...
parallel_preproc.py
import itertools import logging import queue import threading import numpy as np import tensorflow as tf import tfu import util def parallel_map_as_tf_dataset( fun, iterable, *, output_types=None, output_shapes=None, shuffle_before_each_epoch=False, extra_args=None, n_workers=10, rng=None, max_uncon...
rest_client.py
import sys import traceback from datetime import datetime from typing import Any, Callable, Optional, Union, Type from types import TracebackType, coroutine from threading import Thread from asyncio import ( get_event_loop, set_event_loop, run_coroutine_threadsafe, AbstractEventLoop, Future ) from j...
thread_rlock.py
from threading import Thread, RLock import logging import time class DoubleCounter: def __init__(self): self.first_counter = 1 self.second_counter = 5 self.lock = RLock() def increment_first_counter(self): with self.lock: self.first_counter += 1 logging....
executorwebdriver.py
import json import os import socket import threading import traceback import urlparse import uuid from .base import (CallbackHandler, RefTestExecutor, RefTestImplementation, TestharnessExecutor, extra_timeout, strip_server) ...
wikitablestosql.py
import os import sys import argparse import multiprocessing import threading import functools import time from . import wikitableprocessing from . import multistreamfilehandling from . import tosql # Progress bar code def progress_animator(indicators, symbol_loop=('--', "\\", '|', '/'), suffix='', ...
twitter_bot.py
import time import tweepy import logging from typing import List, Optional from queue import Queue from threading import Thread from src.image_captioning import CaptionPredictor from src.openai_clip import ClipPredictor from src.google_vision_api import GoogleVisionPredictor from src.prediction_processing import Predi...
test.py
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import os import threading import time from typing import Dict, Optional, Union from unittest.mock import MagicMock import boto3 import mock import pytest from moto import ( mock_applicationautoscaling, ...
main.py
#!/usr/bin/env python3 """ Copyright (C) 2021 Intel Corporation SPDX-License-Identifier: BSD-3-Clause """ from session_helper import Session, SessionCache import _config as config from threading import Thread import time log = config.get_logger() publisher = config.get_session_publish_port() session_store = {} ...
AdcpSerialPortServer.py
import glob import threading import serial import logging import sys import codecs import binascii import struct from twisted.internet import reactor, protocol, endpoints from twisted.protocols import basic from twisted.internet.serialport import SerialPort from log import logger class SerialDevice(basic.LineReceive...
greedy_ddos.py
import hek import time import random, threading import argparse class Greedy_ddos: def __init__(self): self.packet_count = 0 self.agent = Greedy_ddos.load_agents(self) self.headers = Greedy_ddos.load_headers(self) def load_headers(self): print("[+] LOADING HEADERS") fi...
stl_capture_test.py
#!/router/bin/python from .stl_general_test import CStlGeneral_Test, CTRexScenario from trex_stl_lib.api import * import os, sys import pprint import zmq import threading import time import tempfile import socket from scapy.utils import RawPcapReader from nose.tools import assert_raises, nottest def ip2num (ip_str): ...
state_context.py
"""Provides contexts for states. The substate_context allows using the state at a level below the first, the Written by Peter Duerr """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import multiprocessing import t...
Baidu_detect.py
# 使用百度云内置的APP完成手势识别, 链接在这里https://www.easck.com/cos/2020/0728/562711.shtml import os import cv2 from aip import AipBodyAnalysis from aip import AipSpeech from threading import Thread import time from playsound import playsound """ 你的 APPID AK SK """ APP_ID = '24036624' API_KEY = 'tqUXUxLV0Gl6ON29N0cSqgfP' SECRET_KEY ...
01_starting_and_stopping_threads.py
import time from threading import Thread def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep(1) t = Thread(target=countdown, args=(5,)) # Daemonic threads can’t be joined. # However, they are destroyed automatically when the main thread terminates. t.start()
kafka.py
from typing import Callable, Type import json from threading import Thread from kafka import KafkaConsumer from ...shared.model import BaseEvent from ..model import events as account_module_events class KafkaEventConsumer: def __init__(self, bootstrap_servers: str, topic: str, consumer_group_id: str): sel...
launcher.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import zmq from zmq.eventloop import ioloop as ioloop_mod import zmqdecorators import time import re import glob import serial import os,sys if os.name == 'posix' and sys.version_info[0] < 3: import subprocess32 as subprocess else: import subprocess import multipr...
request_reply_processes.py
import zmq import time import sys from multiprocessing import Process def server(port="5556"): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % port) print "Running server on port: ", port # serves only 5 request and dies for reqnum in range(5): # Wai...
auth.py
# coding: utf-8 import bottle import os from threading import Thread, Event import webbrowser from wsgiref.simple_server import WSGIServer, WSGIRequestHandler, make_server from boxsdk import OAuth2 CLIENT_ID = '' # Insert Box client ID here CLIENT_SECRET = '' # Insert Box client secret here def authenticate(oau...
transform_videos.py
import os import multiprocessing as mp import argparse import cv2 parser = argparse.ArgumentParser() parser.add_argument('thread_num', type=int) parser.add_argument('--video_dir', type=str, default='datasets/activitynet/v1-3/train_val') parser.add_argument('--output_dir', type=str, default='datasets/activitynet/train_...
image.py
"""Defintion of abstract classes for image handling. The central data structure is :py:class:`Image`, a subclass of :py:class:`Data`, specialized to work with images. It provides, for example, properties like size and channels. Relation to other `image` modules in the Deep Learning ToolBox: * :py:mod:`dltb.util.ima...
corellator_once.py
import os import sys import django from django.utils.timezone import now from datetime import datetime from multiprocessing import Process from time import sleep import json from elasticsearch import Elasticsearch from art_time_generator.common_once import * sys.path.append(os.path.join(os.path.dirname(__file__), "we...
idebench.py
import importlib import json import csv import time import hashlib import multiprocessing import statistics from common import util from threading import Thread from queue import Empty from collections import OrderedDict import numpy as np import os from common.schema import Schema from common.vizgraph import VizGraph...
test_712_buffering.py
import datetime import re import sys import time import subprocess from datetime import timedelta from threading import Thread import pytest from h2_conf import HttpdConf class CurlPiper: def __init__(self, url: str): self.url = url self.proc = None self.args = None self.header...
ping_gui.py
from ip2geotools.databases.noncommercial import DbIpCity from colorama import Fore from tkinter import * from tkinter import ttk from tqdm import tqdm from queue import Queue import urllib.request, re import time import os import socket import subprocess import ipaddress import threading import speedtest class Vindu(T...
__main__.py
from pbpy.pbtools import error_state import os.path import os import sys import argparse import webbrowser import threading import multiprocessing import time from pathlib import Path from pbpy import pblog from pbpy import pbgh from pbpy import pbtools from pbpy import pbunreal from pbpy import pbgit from pbpy impor...
swhear_2.py
""" The core SWHEar class for continuously monitoring microphone data. The Ear class is the primary method used to access microphone data. It has extra routines to audomatically detec/test sound card, channel, and rate combinations to maximize likelihood of finding one that works on your system (all without requiring ...
localweb.py
# run using: # ./go.sh web import os import time import http.server import socketserver import threading import webbrowser PORT = 9040 socketserver.TCPServer.allow_reuse_address = True Handler = http.server.SimpleHTTPRequestHandler os.chdir('./_build/html/') httpd = socketserver.ThreadingTCPServer(("", PORT), Han...
zinc.py
#queue/server import sys import zmq import time import threading import ratchromadata_pb2 import photonHit_pb2 import random import cProfile #chroma #import chroma.api as api # api.use_cuda() # import numpy as np # from chroma.sim import Simulation # from chroma.event import Photons # import chroma.event # from uboone...
Opencart.py
# uncompyle6 version 2.11.5 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.18 (default, Apr 20 2020, 20:30:41) # [GCC 9.3.0] # Embedded file name: BruteForce\Opencart.py import requests import re import threading import time from Exploits import printModule r = '\x1b[31m' g = '\x1b[32m' y = '\x1b[33m' b =...
luminosity.py
from __future__ import division import logging import os from os import kill, getpid from sys import version_info from ast import literal_eval # @modified 20191115 - Branch #3262: py3 # try: # from Queue import Empty # except: # from queue import Empty from time import time, sleep from threading import Thread...
pytach.py
#!/usr/bin/python # -*- coding: utf-8 -*- """PyTach. Usage: pytach.py device <device> <command> [-v] pytach.py activity <activity> <command> [-v] pytach.py --web [-v] pytach.py --arduino [<command>] [-v] pytach.py --discover pytach.py --devices pytach.py --activities Options: --web ...
utils.py
import re import sys import json import requests import urlparse import hashlib from app import app from certutil import * from distutils.version import StrictVersion from datetime import datetime,timedelta from threading import Thread from onelogin.saml2.auth import OneLogin_Saml2_Auth from onelogin.saml2.utils impor...
test_imperative_thread_local_has_grad.py
# Copyright (c) 2021 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 appli...
test_flush.py
import time import pdb import threading import logging from multiprocessing import Pool, Process import pytest from utils.utils import * from common.constants import * DELETE_TIMEOUT = 60 default_single_query = { "bool": { "must": [ {"vector": {default_float_vec_field_name: {"topk": 10, "query"...
lm_client_tests.py
#!/usr/bin/env python3 # # Copyright (c) 2014-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals fro...
test.py
import pytest from helpers.cluster import ClickHouseCluster from helpers.network import PartitionManager import threading import time cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance('node1', main_configs=['configs/named_collections.xml'], with_zookeeper=False, with_hdfs=True) @pytest.fixture(scop...
dataloader_iter.py
# Copyright (c) 2020 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 appli...
func.py
""" 面向用户的函数 ,提供极其便捷的体验 """ import logging import os import platform from datetime import time, datetime, timedelta from inspect import isfunction from multiprocessing import Process from time import sleep from typing import Text, Any, List from ctpbee.constant import \ (OrderRequest, CancelRequest, Direction, Ex...
lisp-core.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...
smux.py
#!/usr/bin/env python3 # Copyright (c) 2014-2020 Henry Qin # # 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, modi...
qactabase.py
import datetime import json import os import re import sys import threading import time import copy import uuid import pandas as pd import pymongo import requests from qaenv import (eventmq_amqp, eventmq_ip, eventmq_password, eventmq_port, eventmq_username, mongo_ip, mongo_uri) import QUANTAXIS as ...
broker.py
# # Copyright (c) 2018 Sébastien RAMAGE # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. # import threading import socket import sys class Broker(threading.Thread): def __init__(self, zigate, port=9999, host='0.0.0.0'): threadi...
run.py
#!/usr/bin/python from types import SimpleNamespace import click import sys import os import inspect #### imports that should be here for py installer ot replaced with --hidden-import import requests import logging import logging.handlers from flashtext import KeywordProcessor ###### end of work around currentdir = os...
main.py
import threading from queue import Queue from spider import Spider from domain import * from functions import * PROJECT_NAME = 'nirvana' HOMEPAGE = 'http://cwe.mitre.org/' DOMAIN_NAME = get_domain_name(HOMEPAGE) QUEUE_FILE = PROJECT_NAME + '/queue.txt' CRAWLED_FILE = PROJECT_NAME + '/crawled.txt' NUMBER_OF_THREADS = 1...
background.py
from __future__ import absolute_import from threading import Thread, Event from apscheduler.schedulers.base import BaseScheduler from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.util import asbool class BackgroundScheduler(BlockingScheduler): """ A scheduler that runs in the ba...
client.py
# Anthony Tiongson (ast119) with assistance from Nicolas Gundersen (neg62) # Client side DNS # resources: # https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python # https://www.pythonforbeginners.com/system/python-sys-argv # https://www.w3schools.com/python/ref_string_split.asp import sys, ...
bfv.py
import argparse import logging as log import os import pickle try: import psycopg2 import psycopg2.extras except: print 'psycogp2 could not be found' import re import threading import xxhash as xh from graph.building.edgelist import parse_spo def find_path( dataset ): """""" if dataset['path_edge...
pg_python.py
#!/usr/bin/env python import pika, sys, os, threading from flask import Flask, request, jsonify app = Flask(__name__) def start_rmq_connection(): def callback(ch, method, properties, body): print(" [x] Received %r" % body) message = "Hello from pg-python!" channel.basic_publish(exchange='p...
activity.py
from datetime import datetime from threading import Thread from django import forms from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.core.mail import send_mail from django.db.models import Count from django.http import Http404 from django.http im...
model.py
import time import os import sys import sqlite3 import queue import threading import datetime import random from IrcQueuedCommands import IRCQueuedCommands from blinker import signal from util import random_characters, hours, minutes, days, listify, chance import math class Bot: def __init__(self,servername,transport...
sdca_ops_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...
hierarchical_align.py
import logging from tqdm import * import numpy as np import os import nltk from multiprocessing import Process, Manager, cpu_count import itertools from align.align_base import AlignerBase class HierarchicalAligner(AlignerBase): """Hierarchical Aligner Performs Global --> Local alignment.""" def __init_...
pi_camera_video_capture.py
import logging import time from threading import Thread from queue import Queue class PiCameraVideoCapture: def __init__(self, src=0, resolution=(320, 240), fps=32, transform=None, **kwargs): self.logger = logging.getLogger(__name__) self.src = src self.resolution = resolution sel...
io_base.py
from fiery_snap.impl.util.page import TestPage, JsonUploadPage from fiery_snap.impl.util.service import GenericService from fiery_snap.utils import random_str, generate_obj_name from .connections import PubSubConnection, KombuPubSubConnection import logging import threading import time class IOBase(object): SLEEP ...
views.py
# encoding: UTF-8 from flask import render_template,flash,url_for,session,redirect,request,g ,jsonify from app import app, db,lm , celery from flask_login import login_user, logout_user, current_user, login_required from app.models import Post,User from app.forms import LoginForm,EditForm,PostForm,SignUpForm,ChangeFor...
scrape.py
# The author disclaims copyright to this source code. Please see the # accompanying UNLICENSE file. """Several long-lived-daemon-style classes to scrape BTN and update the cache. """ import feedparser import logging import os import Queue import threading import time from urllib import parse as urllib_parse import b...
sample_splashscreen.py
from ctypes import windll import tkinter as tk import tkinter.ttk as ttk from tkinter.font import Font import threading from time import sleep class SplashScreen(tk.Tk): def __init__(self): super(SplashScreen, self).__init__() self.attributes('-topmost', 1) self.attributes('-alpha', 0.0) ...