text
stringlengths
3.07k
12.6k
import os import pytest from intervaltree import Interval from viridian_workflow import self_qc, primers this_dir = os.path.dirname(os.path.abspath(__file__)) data_dir = os.path.join(this_dir, "data", "primers") class StatsTest: def __init__(self, fail): self.fail = fail self.log = [] se...
""" File keeps Factory method to prepare required puller information with its producers and consumers """ import logging from typing import List, Optional from botocore.exceptions import ClientError from samcli.commands.exceptions import UserException from samcli.commands.logs.console_consumers import CWConsoleEventC...
import logging import os import tensorflow as tf from tqdm import trange from models.evaluation import evaluate_sess from models.simple_model import model from utils.file import save_dict_to_json def train(train_inputs, test_inputs): train_images = train_inputs["images"] train_labels = tf.cast(train_inputs[...
# Copyright (c) 2014 OpenStack Foundation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
from abc import ABC from video_streaming import settings from video_streaming.celery import celery_app from video_streaming.core.tasks import ChainCallbackMixin from video_streaming.ffmpeg.utils import FfmpegCallback from video_streaming.ffmpeg.constants import TASK_DECORATOR_KWARGS from .base import BaseStreamingTask ...
""" The MIT License (MIT) Copyright (c) 2017-2018 <NAME> 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, modify, merge, ...
import pandas as pd import numpy as np import warnings import sklearn.metrics as mt from sklearn.impute import SimpleImputer from sklearn.preprocessing import LabelEncoder from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_tes...
# coding: utf-8 from astropy import convolution as astro_conv from scipy.stats import vonmises, expon from scipy import signal from scipy import ndimage from scipy.special import iv from math import pi#, pow #this doesn't support elementwise operations from numpy import zeros_like, linspace, roll, exp, sqrt, where i...
from datetime import datetime as dt import requests, re import pandas as pd import numpy as np import json import time import os import tushare as ts import logging from bs4 import BeautifulSoup logger = logging.getLogger('main.fetch') def fetch_index(index_name): path = os.path.dirname(os.path.abspath(__file__))...
import threading import requests import argparse import random import json import time import sys import re import os status = { 'sent': 0, 'errors': 0, } class youtube: vid = None session = None def __init__(self, vid): self.vid = vid self.session = requests.session() def getPlayerConfig(self): r = sel...
""" The Mirror API is responsible for mapping file requests to a URL, local filename, file-like object, or something that can construct a NetCDF ``Dataset``. These are usually constructred using :func:`argopandas.url_mirror` and/or :func:`argopandas.file_mirror`. """ from argopandas.downloader import download_async ...
"""Helper for identifying details of Linux network devices. This tool extracts network MAC, vendor, and device information from sysfs. It will then use any available PCI databases to look up details of the device, preferring: 1. External list from pciids 2. Ubuntu hwdata PCI list 3. Debian PCI list 4. Externa...
import pickle import plotly.express as px import numpy as np import gspread_dataframe as gd import pandas as pd from scipy.spatial.distance import pdist, squareform def get_raw_data(context): _query = ''' SELECT * FROM `moz-fx-data-shared-prod.regrets_reporter_analysis.yt_a...
import os import sys import enum import textwrap from cryptography.fernet import Fernet import environ from environ._environ_config import _env_to_bool def split_by_comma(value): return tuple(e.strip() for e in value.split(",")) @environ.config(prefix="") class NoeConfig: debug = environ.bool_var( d...
import allocate # Function to decode parsed instruction into it's binary equivalents def decoder(field1, field2, field3, labels): binString = "" if field1.isdigit() and field2 == "" and field3 == "": binString = toBinary(field1) elif (field2.isalnum() and field3.isalpha()) or (field1.isalpha() and field...
""" Functions which generate reports from the JPER system """ from service.models import RoutedNotification, Account import os from octopus.lib import clcsv from copy import deepcopy from datetime import datetime from octopus.core import app def delivery_report(from_date, to_date, reportfile): """ Generate t...
""" test_run_chronostar.py Integration test, testing some simple scenarios for NaiveFit """ import logging import numpy as np import sys from distutils.dir_util import mkpath sys.path.insert(0, '..') from chronostar.naivefit import NaiveFit from chronostar.synthdata import SynthData from chronostar.component import...
#!/usr/bin/env python3 import pytest import random import json import os from assets import resource def test_send_no_thread(): test_message = str(random.getrandbits(128)) code, message = resource.send("https://httpbin.org/post", test_message, False) assert code == 200 assert test_message in message ...
# -*- coding: utf-8 -*- """ORCID Blueprint Module Module that contains the full blueprint for ORCID OAuth """ from flask import flash, redirect, session, url_for, current_app, Markup from flask_user import current_user from flask_login import login_user from app.oauth.orcid_flask_dance import make_orcid_blueprint fro...
# Readme: https://github.com/nikhilgaba001/YoutubeToSpotify/blob/master/README.md from apiclient.discovery import build import csv import spotipy import spotipy.util as util import sys # Number of titles to get from each channel MAX_RESULT = 50 # Spotify credentials SPOTIFY_USERNAME = '' CLIENT_ID = '' ...
import itertools from pathlib import Path import pytest from fpdf import FPDF from fpdf.errors import FPDFException from fpdf.fonts import fpdf_charwidths from test.conftest import assert_pdf_equal HERE = Path(__file__).resolve().parent def test_no_set_font(): pdf = FPDF() pdf.add_page() with pytest.ra...
from unittest import mock import pytest from .cherry_picker import get_base_branch, get_current_branch, \ get_full_sha_from_short, is_cpython_repo, CherryPicker, \ normalize_commit_message def test_get_base_branch(): cherry_pick_branch = 'backport-afc23f4-2.7' result = get_base_branch(cherry_pick_br...
import logging import os import platform import pwd import threading import ipaddress import requests import yaml from containercluster import ca, utils __all__ = [ "Config", "SSHKeyPair" ] class Config(object): dir_lock = threading.RLock() log = logging.getLogger(__name__) def __init__(sel...
"""Module for GWAS analysis algorithms.""" ## For usage/API see: ## Logistic regrssion: https://gist.github.com/VibhuJawa/316792903e90b7379c06a9c9cb4187ef ## Both: https://gist.github.com/VibhuJawa/b33927bda957355ebdc9bc261a24b142 from cuml import linear_model as cuml_linear_model import cupy as cp import cudf import ...
"""Install or upgrade a bcbio-nextgen installation. """ from __future__ import print_function import os import subprocess import sys import yaml from bcbiovm.docker import manage, mounts DEFAULT_IMAGE = "quay.io/bcbio/bcbio-vc" def full(args, dockerconf): """Full installaction of docker image and data. """...
import numpy as np import torch from PIL import Image import torchvision.utils as vutils import torch.nn as nn def get_lr(optimizer): for param_group in optimizer.param_groups: return param_group["lr"] def text_to_array(text, width=640, height=40): """ Creates a numpy array of shape height x wid...
from shop.shopper_base import ShopperBase import datetime import os import time import math import random from typing import Dict, Tuple, Union, List, Callable import keyboard import numpy as np from screen import convert_screen_to_monitor, grab, convert_abs_to_monitor, convert_screen_to_abs, convert_monitor_to_scree...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2018 bily Huazhong University of Science and Technology # # Distributed under terms of the MIT license. """Show tracking results Platform: Windows or Linux Dependencies: pillow sacred bilib Usages: 1. Set the absolute path ...
import os import re import subprocess BASE_COMMAND = 'python bert_experiments.py' def evaluate(model, task, max_seq_length, checkpoint_dir, linformer_k=None, blocks=None): command = ('{0} --model {1} --task {2} --max_seq_length {3} ' '--load_from_checkpoint --checkpoint_dir {4} --eval'...
import subprocess import sys from . import sites from . import init from . import global_vars from . import build_blog def _create_make_file(pages, posts, blog_pages, config): panblog_posts_file = global_vars._PANBLOGDIR + "/" + global_vars._POSTS src_dir = config["DIR"]["source"] + "/" bin_dir = config...
from django.contrib import admin from apps.website.models.article import Article from apps.website.models.inbox import Inbox from apps.website.models.comments import Comments from apps.website.models.authors import Authors from apps.website.models.settings import WebsiteSettings from django.utils import timezone from d...
import pandas as pd from woodwork.exceptions import TypeConversionError from woodwork.logical_types import Datetime, LatLong, Ordinal from woodwork.type_sys.utils import _get_ltype_class from woodwork.utils import ( _get_column_logical_type, _reformat_to_latlong, import_or_none ) dd = import_or_none('dask...
# Lint as: python3 # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
# -*- coding: utf-8 -*- """ Simple newline fix for translated messages in .po files When using, some tools (for example OmegaT), translated test is split into sentences to simplify translation. So in sone ceses newline may break small sentence that looks strange and \n may be skipped by translator in the translated bl...
import collections import json import os from ..common import Manager from copy import deepcopy from pymongo.cursor import Cursor from datacatalog.jsonschemas import JSONSchemaBaseObject from datacatalog.extensible import ExtensibleAttrDict from datacatalog.identifiers import typeduuid from datacatalog.linkedstores.ass...
# Copyright 2015 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...
import boto3 import sys import traceback import re from collections import defaultdict from datetime import datetime from itertools import islice from tilequeue.tile import coord_marshall_int from tilequeue.tile import create_coord from time import time from botocore.credentials import RefreshableCredentials from botoc...
"""Helper neural network training module.""" from collections import OrderedDict from pathlib import Path from time import time import torch from torch import nn from torch.utils.tensorboard import SummaryWriter from ..datasets import IMAGE_SHAPES, get_loader from ..models import fit_to_dataset, get_model from ..mod...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import random seed_num = 5 torch.manual_seed(seed_num) random.seed(seed_num) class linear(nn.Module): def __init__(self, in_chs, out_chs, opt): super(linear, self).__init__() ...
# -------------- # Importing the neccessary packages import numpy as np import cv2 from matplotlib import pyplot as plt #load the image 'path' using opencv library cv2 image = cv2.imread(path) #convert the above image into grayscale image_gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Now we split th...
import numpy as np import torch as t from torch.utils.data import DataLoader import cv2 from os.path import exists from os import mkdir from model import student_teacher import dataset.dataset as dataset import dataset.mit1003 as mit1003 import dataset.mit300 as mit300 import dataset.DHF1K as dhf1k from metrics.utils ...
#!/usr/bin/env python # Install boto before running the script # Setup AWS keys to get details from AWS Account import argparse import re import sys import time import boto.ec2 AMI_NAMES_TO_USER = { 'amzn' : 'ec2-user', 'ubuntu' : 'ubuntu', 'CentOS' : 'root', 'DataStax' : 'ubuntu', 'CoreOS' : 'c...
""" REST API Resource Routing http://flask-restplus.readthedocs.io """ from datetime import datetime from flask import request from flask_restx import Resource import json from io import StringIO import boto3 import pandas as pd import numpy as np from .security import require_auth from . import api_rest class Sec...
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import re from .ply import lex, yacc from collections import OrderedDict import sublime class Parser: """ Base class for a lexer/parser that has the rules defined as methods """ tokens = () precedence = () def __init__(self, **kw): ...
import PyPluMA def isNumeric(s): for i in range(len(s)): if ((not s[i].isdigit()) and (s[i] != '.')): return False return True class Qiime2PhyloSeqPlugin: def input(self, filename): infile = open(filename, 'r') self.parameters = dict() for line in infile: ...
import logging from enum import Enum from pathlib import Path from typing import Callable, List, Literal, NamedTuple, Optional, Set from pydantic import Extra from pydantic.class_validators import root_validator, validator from pydantic.fields import Field from hydrolib.core.io.ini.io_models import Property, Section ...
import logging import numpy as np from typing import Callable, Union, Iterable from ..objective.constants import GRAD from ..optimize import Optimizer, OptimizerResult from ..problem import Problem from ..result import Result from .result import ProfilerResult from .profile_next_guess import next_guess from .options i...
from __future__ import print_function, unicode_literals from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.utils.translation import ugettext_lazy as _ from rest_framework.exceptions import ValidationError from rest_framework.fields import empty from rest_framework.serializers im...
#!/usr/bin/env python # -*- coding: utf-8 -*- import abc import torch import torch.nn as nn import torch.nn.functional as F from .cfg import Config from .SphereProjection import SphereProjection class RowBilinear(nn.Module): def __init__(self, n_in, kernel_shapes, pad=0): super(RowBilinear, self).__ini...
# -*- coding: utf-8 -*- import os import requests import google.oauth2.credentials import google_auth_oauthlib.flow import googleapiclient.discovery from datetime import datetime, timezone from datetime import timedelta import json from django.conf import settings credentials_file = settings.BASE_DIR+'/file_app/cred...
import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True) def normalize(input_image, input_mask): input_image = tf.cast(input_image, tf.float32) / 255.0 input_mask -= 1 return input_image, input_mask @tf...
from Estoque import Estoque_Menu list_estoque = list() # Contém todas as produtos registrados e seu disponibilidade list_verifica_id = list() # Contém todos os ids já registrados para tratamento de erro list_entrada_de_produto = list() # Registra toda a entrada de produto list_saída_de_produto = list() # Registra tod...
# -*- coding: utf-8 -*- # Copyright 2019 IBM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
from __future__ import absolute_import, division, unicode_literals import logging import os from builtins import map from datetime import datetime, timedelta from past.utils import old_div from .config import * from .constants import * from .database import Database from .encoder import MetaData from .method import ...
# importing libraries import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go import requests import csv import dash from dash import dcc from dash import html """functions for state data""" def hist_covid_state_data(): '''func to get historic covid data by state''' ...
# This is a script for plotting the pose results # from a raw poses txt file. import sys import numpy as np from scipy import interpolate def processPoseLine(line): """"Process a text line the pose format # timestamp x y z roll pitch yaw id input: line output: float x, float y, string id, ...
# Copyright 2021, Battelle Energy Alliance, LLC import os import logging import argparse import configparser import pyhit import moosetree import utils def getParserArguments(): """ Gets the arguments provided by the user via the command-line Return args: the arguments provided by the user and ...
import requests import pyexcel as pe from bs4 import BeautifulSoup from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import csv import re from datetime import datetime class Text: def __init__(self, body): self.body = body def calculate_sentiment(self, analyzer): vs = analyz...
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): self.sum...
import secrets import time import asyncio from typing import ( Any, cast, Dict, List, ) from eth_utils import encode_hex from hp2p.constants import PEER_STAKE_GONE_STALE_TIME_PERIOD from hvm.exceptions import ( CanonicalHeadNotFound, ) from hp2p.exceptions import HandshakeFailure from hp2p.p2p_...
from flask import Flask, flash, redirect, render_template, request, session, url_for, Response, make_response from flask_session import Session from tempfile import gettempdir import json from helper import * from sql import * import authenticator import ledgers import vouchers import gstr import download import drive ...
import os import os.path as osp import numpy as np from scipy.integrate import odeint import moviepy.editor as mpy from qtpy.QtCore import Qt from qtpy.QtCore import QPointF from qtpy.QtGui import QColor from nezzle.graphics import EllipseNode from nezzle.graphics import TextLabel from nezzle.graphics import CurvedE...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime import unittest import warnings from mixpanel_jql import JQL, raw, Events, People from mixpanel_jql.query import _f from mixpanel_jql.exceptions import InvalidJavaScriptText, JQLSyntaxError class TestJavaScriptArgs(unitte...
from os.path import join as opj import numpy as np from pandas import DataFrame, concat import matplotlib.pylab as plt import seaborn as sns from configs.nucleus_style_defaults import DefaultAnnotationStyles as das, Interrater from interrater.interrater_utils import \ _maybe_mkdir, get_fovs_annotated_by_almost_eve...
"""CM-793 V2 DB changes Revision ID: 69f06b708589 Revises: <PASSWORD> Create Date: 2021-12-14 19:22:07.245900 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mssql # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "d699bd7eb7e9" branch_labels = None depend...
import logging import re import glob import codecs import os from io import StringIO from optparse import make_option from collections import ChainMap import yaml, yaml.parser import markdown from django.db.models.fields.related import RelatedField from django.core.management.base import BaseCommand, CommandError fro...
import signal import sys import time import os from artemis.config import get_artemis_config_value from artemis.remote.child_processes import PythonChildProcess, RemotePythonProcess from artemis.remote.remote_execution import ParamikoPrintThread, execute_command from artemis.remote.utils import get_local_ips, get_rem...
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
import matplotlib.pyplot as plt import numpy as np import os import pathlib from labvision import images import pandas as pd from math import sqrt ### CONSTANT #### FONTSIZE = 12 XMIN = 100 XMAX = 700 FIGX = 6 FIGY = 6 LINEWIDTH = 2 PANELS = 3 liquid_file = "/media/data/Data/Orderphobic/TwoIntruders/SpikyIntruder/L...
import json import pandas as pd import os import urllib.request from bs4 import BeautifulSoup import argparse import sys import logging parser = argparse.ArgumentParser(description='A script to query the European Nucleotide Archive (ENA) website to create a CSV file with information for each read sequence file.') par...
""" Basic tools for working with BTC blockchain/blocks/transactions. """ import os import json import decimal from datetime import datetime from http.client import CannotSendRequest, ResponseNotReady, BadStatusLine from bitcoinrpc.authproxy import AuthServiceProxy ####################################################...
from __future__ import division import numpy as np from astropy.io import fits from math import fsum from warnings import warn # TODO: Investigate using scipy.fftpack instead? def pad_and_rfft_image(img, newshape): """ Pads the psf array to the size described by imgshape, then run rfft to put it in Fourie...
import unittest import warnings # for suppressing numpy.array PendingDeprecationWarning's from importlib import reload import sys sys.path.append("..") import numpy as np import sympy as sp import Ch6.utilities as ch6_utils import Ch7.utilities as ch7_utils reload(ch7_utils) import control def fullOrderCompensator(A,...
import os import pandas as pd import numpy as np from scipy.optimize import linear_sum_assignment from scipy.spatial import distance from IPython.display import clear_output from itertools import combinations import multiprocessing as mp import logging import argparse import time ''' This script will compare action se...
from __future__ import division, print_function import theano from theano import tensor as T from theano.tensor import signal from theano.tensor.signal import pool import numpy as np import sys def run_function_in_batches(func, input_data_list, learning_phase=No...
""" This file contains specific functions for computing losses of YOOO file """ import torch from torch import nn import os from fcos_core.layers import IOULoss from fcos_core.layers import SigmoidFocalLoss from fcos_core.layers import TIOULoss def get_num_gpus(): return int(os.environ["WORLD_SIZE"]) if "...
import os import shutil import eos.log import eos.tools import eos.util def _check_return_code(code): if code != 0: raise RuntimeError("repository operation failed") def _remove_directory(directory): if os.path.exists(directory): shutil.rmtree(directory) def _execute(command): print_co...
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# -*- coding: utf-8 -*- """Module with classes to format results from the Google Cloud Translation API""" import logging import pandas as pd from typing import AnyStr, Dict from plugin_io_utils import ( API_COLUMN_NAMES_DESCRIPTION_DICT, ErrorHandlingEnum, build_unique_column_names, generate_unique, ...
import warnings warnings.filterwarnings('ignore', category=FutureWarning) from flask import abort, render_template, Flask import logging import db APP = Flask(__name__) # Start page @APP.route('/') def index(): stats = {} x = db.execute('SELECT COUNT(*) AS movies FROM MOVIE').fetchone() stats.update(x) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import logging import tensorflow as tf from invoke import run, exceptions log = logging.getLogger('biomedbert') log.setLevel(logging.INFO) def fine_tune_ner(ner_dataset: str, model_dir: str, model_type: str, bucket_name: str, tpu_n...
# -*- coding: utf-8 -*- import simpy, scipy, numpy, random from src.core.linear_congruential_generator import LinearCongruentialGenerator RANDOM_SEED = 42 NUM_COMPONENTES_INDEPENDENTES = 2 QUANTIDADE_TESTES = 5 TEMPO_SIMULACAO = 7 * 24 def tef_uniform(): """return a random value from uniform distribuition""" ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # This library supports functionality needed for global transcription. # The global transcription method works by considering transcribed words that # co-occur from different sources, near in time (less than 0.1 seconds) # within a conversation, an...
#!/usr/bin/python # Simple test uses just the timepoint of weibo from collections import defaultdict import matplotlib.pyplot as plt import pandas as pd import networkx as nx import pickle from repost_record import RepostRecord FILE_PATH = '/home/hp/Documents/DeepLearning/DataCastle/Weibo/Data/testRepostBeforeFirst...
# coding=utf-8 """Command line interface to add tasks to 2Doapp.""" import argparse import sys import subprocess import twodolib from . urlhelper import TwoDoTask usage_description = """\ Program to create tasks in 2Do. The default behavior is to print the generated URL to stdout. Please use the '-e' or '--execute''...
import numpy as np from importlib import reload import utils.geometries as geometries; reload(geometries) import utils.WignerD as WignerD from lie_learn.representations.SO3 import wigner_d as wd from lie_learn.representations.SO3 import spherical_harmonics as sh from lie_learn.spaces import S2 import ipdb import os fro...
"""Provides statistical utilities functions used by the simulator """ from __future__ import division import math import random import collections import numpy as np import scipy.stats as ss __all__ = [ 'DiscreteDist', 'TruncatedZipfDist', 'means_confidence_interval', 'proportions_confid...
import json import pandas as pd import numpy as np import os from os.path import isfile, join import datetime import matplotlib.pyplot as plt project_dir = os.path.dirname(os.path.dirname(os.getcwd())) out_path = os.path.join(project_dir, "data", "pecan") fig_path = os.path.join(project_dir, "data", "pecan_info") de...
import asyncio import collections import errno import logging import socket import remotes import tasks from config.bot import settings as defaultsettings from strings import encode, decode # flood control setting RECEIVE_QUEUE_SIZE = 1024 # determine acceptable socket error ERR = errno.WSAEWOULDBLOCK if hasattr(err...
from __future__ import print_function import requests import getpass import time import StringIO import subprocess import numpy as np from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry def requests_retry_session( retries=10, backoff_factor=0.3, status_forcelis...
"""dict implementation specialized for object loaded by the _pypyjson module. Somewhat similar to MapDictStrategy, also uses a map. """ from rpython.rlib import jit, rerased, objectmodel, debug from pypy.objspace.std.dictmultiobject import ( UnicodeDictStrategy, DictStrategy, create_iterator_classes, W_DictO...
"""Views used for manipulation.""" import os import copy from box import Box from kopf.structs.diffs import diff import digi.util as util from digi.util import deep_set class ModelView: """ Return all models in the current world/root view keyed by the namespaced name; if the nsn starts with default, ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm import time from sklearn.metrics import accuracy_score, f1_score from sklearn.naive_bayes import GaussianNB from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.model_s...
# Copyright (c) 2013 Rex from datetime import datetime from types import Block, Transaction from connection import BitcoinConnection from lxml import html UNIX_EPOCH = datetime(1970, 1, 1, 0, 0) def fetch_data(url): """ :type url: str """ import urllib2 return urllib2.urlopen(url).read() def...
#MIT License #Copyright (c) 2022 Fazz #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, modify, merge, publish, distri...
# -*- coding: utf-8 -*- import glob import logging import multiprocessing import sys from os import path, makedirs from os.path import exists import glove import pandas as pd from joblib import Parallel from sklearn.ensemble import RandomForestClassifier from sklearn.externals.joblib import delayed from sklearn.linea...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import csv import pandas as pd from time import sleep import os def login(driver): driver.maximize_window() url = 'https://www.instagram.com/accounts/login/' driver.get(url...
import logging import time import datetime import random import weaved # BEGIN Configuration # Weaved related configuration PLUG_IP = '192.168.1.201' # Assumes the Smart Plug is configured for SSH and IR blaster PLUG_USER = 'root' # Assumes password-less (key based) SSH authentication is set up # ...
# -*- coding: utf-8 -*- # Copyright (c) 2021, libracore and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe import time from spo.utils.payrexx import get_payment_status, create_payment @frappe.whitelist(allow_guest=True) def check_membership(member,...
import errno import os import sys from contextlib import contextmanager from cbfeeds import CbFeed, CbFeedInfo from tempfile import NamedTemporaryFile import logging from logging.handlers import RotatingFileHandler import time class AlreadyRunningError(Exception): pass # TODO: investigate psutil package instead ...