text stringlengths 3.07k 12.6k |
|---|
import sys
from sys import argv, exit
from os.path import basename, expanduser
from argparse import ArgumentParser
from logging import basicConfig, DEBUG, INFO, info, error, debug
from datetime import datetime
from urllib.parse import urlparse
from subprocess import Popen, PIPE, run, call
from json import loads
from re... |
from app.kasumi.cipher_mode.cbc import CBC
from app.kasumi.cipher_mode.cfb import CFB
from app.kasumi.cipher_mode.ctr import CTR
from app.kasumi.cipher_mode.gcm import GCM
from app.kasumi.cipher_mode.ofb import OFB
from app.kasumi.cipher_mode.ecb import ECB
from app.kasumi.cipher_mode.pcbc import PCBC
from app.kasumi.k... |
# Deleting a key on a B-tree in Python
# Btree node
class BTreeNode:
def __init__(self, leaf=False):
self.leaf = leaf
self.keys = []
self.child = []
class BTree:
def __init__(self, t):
self.root = BTreeNode(True)
self.t = t
# Insert a key
def... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Modules to compute the matching cost and solve the corresponding LSAP.
"""
import torch
from scipy.optimize import linear_sum_assignment
from torch import nn
from util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou
class HungarianMatc... |
# -*- coding: utf-8 -*-
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 require... |
"""Module for particles (namely neutrinos) and neutrino interactions in the ice.
Interactions include Earth shadowing (absorption) effect."""
import logging
import numpy as np
from pyrex.internal_functions import normalize
import pyrex.earth_model as earth_model
logger = logging.getLogger(__name__)
AVOGADRO_NUMBER =... |
from typing import Dict, List, Set, Optional
import numpy as np
import tensorflow as tf
from typeguard import check_argument_types
from neuralmonkey.logging import log, warn
from neuralmonkey.model.model_part import ModelPart
from neuralmonkey.runners.base_runner import (
BaseRunner, Executable, ExecutionResult, ... |
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
import socket, psutil, os, ipaddress,itertools,argparse
from _thread import *
import threading
class Serveur : #Class permettant de gérer le serveur
def __init__(self,PortEcoute = 1998) : #Contructeur On initialise les variables | PortEcoute falcultatif
self.PortEcoute = PortEcoute
def LaunchServeur (... |
from qtpy.QtCore import (
Qt, QSize, QPoint, QPointF, QRectF,
QEasingCurve, QPropertyAnimation, QSequentialAnimationGroup,
Slot, Property)
from qtpy.QtWidgets import QCheckBox
from qtpy.QtGui import QColor, QBrush, QPaintEvent, QPen, QPainter
class Toggle(QCheckBox):
_transparent_pen = QPen(Qt.tran... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
# imports
import os
import random
import sys
def GetMatches(descriptorI,descriptorJ):
bf = cv2.BFMatcher()
matches = np.array(bf.knnMatch(descriptorI,descriptorJ, k=2))
return [[match[0]] for match in matche... |
import csv
import sys
from collections import namedtuple, defaultdict
from intervaltree import IntervalTree
Primer = namedtuple("Primer", ["name", "seq", "left", "forward", "pos"])
def load_amplicon_schemes(amplicon_tsvs):
return dict(
[
(s, AmpliconSet.from_tsv(tsv, shortname=s))
... |
from objects.interface.dbconn import DB
from utils import globals as _globals
from utils.enums import Months, month_string_to_enum
from utils.exceptions import NoDataFound, NoTotalBetweenDates, NoTotalFound
from utils.logger.logger import log
from utils.dates.dates import get_dates, get_total_between_dates, get_all_yea... |
from __future__ import print_function, unicode_literals
try:
import coverage
cov = coverage.coverage()
except ImportError:
class DummyCoverage(object):
def start(self):
pass
def stop(self):
pass
def save(self):
pass
def report(self, *a... |
from .ffi import ffi, lib
from .ffi.lib import *
try:
from threading import local as _thread_local
except ImportError:
class _thread_local: pass # there's only one thread anyway
_thread_local = _thread_local()
def _str(b):
'''struct cno_buffer_t -> str'''
return str(ffi.buffer(b.data, b.size), 'utf-... |
import subprocess
import time
from multiprocessing.pool import ThreadPool
import requests
from Postgres_connection.connection import get_postgres_connection
from bigdata_logs.logger import getLoggingInstance
log = getLoggingInstance()
get_host_ip = "getent hosts "
updated_at = ""
def get_ip(host):
try:
... |
import sys
import os
import csv
import numpy as np
import json
from tqdm import tqdm
csv.field_size_limit(sys.maxsize)
def rle2bbox(rle, shape):
'''
from: https://www.kaggle.com/eigrad/convert-rle-to-bounding-box-x0-y0-x1-y1
rle: run-length encoded image mask, as string
shape: (height, width)... |
import csv
import datetime
class InvalidDoc(Exception):
pass
def len_var(line):
return int(line[0:4])
def line_is_valid_len(line):
if len(line.strip()) != len_var(line) + 105:
raise InvalidDoc("not right length")
def create_date_time(line):
try:
return datetime.datetime.strptime(line... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# @Author: <NAME> (<EMAIL>)
# @Created: 2018-06-11
# @LastModified: 2018-06-11
# @Filename: collect.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
# @Copyright: <NAME>
import os
import pathlib
import re
import astropy.io.fits
import astropy... |
# -*- coding: utf-8 -*-
# @Author : DevinYang(<EMAIL>)
__all__ = ['SwitchNorm2d', 'SwitchNorm3d', 'EvoNormB0', 'EvoNormS0', 'DropBlock2d', 'DropPath']
import torch
from torch import nn
from . import functional as F
class _SwitchNorm(nn.Module):
"""
Avoid to feed 1xCxHxW and NxCx1x1 data to this.
"""
... |
# -*- coding: utf-8 -*- #
# Copyright 2017 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 requir... |
import pytest
from anchorecli.cli import utils
class TestFormatErrorOutput:
def setup(self):
self.config = {'jsonmode': False}
def test_fails_on_invalid_json(self):
payload = Exception('could not access anchore service (user=None url=http://localhost:8228/v1)')
result = utils.format_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 12:02:52 2020
@author: kunal001
"""
import os
from math import ceil
from .merge_nodes import merge_nodes
from .write_constraint import symmnet_device_pairs
import logging
import json
logger = logging.getLogger(__name__)
def WriteCap(graph,name... |
"""
Defines a complex polynomial object from coefficients:
f(z) = a_0 + a_1 * z + a_2 * z^2 + ... + a_n * z^n
where for each i, a_i is a complex interval
Author:
<NAME>
Princeton University
"""
from interval import interval, inf, imath
from complexinterval import ComplexInterval, _one, _zero, _real
import operator
i... |
from urlparse import urlparse
from ceph_deploy.lib import remoto
from ceph_deploy.util import pkg_managers
from ceph_deploy.util.paths import gpg
def install(distro, version_kind, version, adjust_repos, **kw):
# note: when split packages for ceph land for Debian/Ubuntu,
# `kw['components']` will have those. ... |
#!/usr/bin/env python3
# coding: utf-8
# Imports
import argparse
import os
import sys
import wave
import subprocess
from kaldi_align_conf import container_name, singularity_wrapper
def parse_arguments():
parser = argparse.ArgumentParser(description='Write individual .txt files from kaldi text file')
parser.a... |
"""
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -msatextractor` python will execute
``__main__.py`` as... |
import os
import torch
import numpy as np
from torch.nn import Parameter
def load_state_dict(model, ckpt_file, only_base='no', without_fc='no'):
print('\n\n\n')
src_state_dict = torch.load(ckpt_file, map_location=lambda storage, loc: storage)
#target_dict_name_list = list(model.state_dict().keys())
#b... |
import math
import sys
import itertools
def strange_multiplication_1225():
case_arr = list(map(int, sys.stdin.readline().split()))
case_1_val = 0
case_2_val = 0
for num1 in str(case_arr[0]):
case_1_val += int(num1)
for num2 in str(case_arr[1]):
case_2_val += int(num2)
sys.stdou... |
import pdfkit
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render, get_list_or_404
from accounts.models import Doctor
from chemotherapy.models import ChemoTherapy
from history.m... |
from datetime import datetime
import zeeguu.core
from zeeguu.core.model import (
Bookmark,
UserArticle,
Text,
UserWord,
UserActivityData,
Language,
Exercise,
)
from zeeguu.core.model.bookmark import bookmark_exercise_mapping, Bookmark
from zeeguu.core.model.word_knowledge.word_interaction... |
from flask import Flask, render_template, request
import json
import requests
import random
app = Flask(__name__)
base_URL_rv = 'https://sheetlabs.com/IND/rv'
base_URL_vs = 'https://sheetlabs.com/IND/vs'
wiki_en_URL = 'https://en.wikisource.org/wiki/The_Rig_Veda/'
@app.route('/')
def first_page():
return render_... |
# -*- coding: utf-8 -*-
import gc
import uos
import utime
import hw_urequests
import machine
import portable_firmware_constants
strMAC = ''.join(['%02X'%i for i in machine.unique_id()])
#
# Watchdog
#
objWdt = None
feedWatchdog = lambda: None
'''True if power on. False if reboot by software or watchdog.'''
bPowerO... |
# -*- coding: utf-8 -*-
"""
flask_bitmapist.views
~~~~~~~~~~~~~~~~~~~~~
This module provides the views for Flask-Bitmapist's web interface.
:copyright: (c) 2016 by Cuttlesoft, LLC.
:license: MIT, see LICENSE for more details.
"""
import json
import os
from datetime import datetime
from flask imp... |
import heapq
# Upacking for sums
def sum(items):
head, *tail = items
return head + sum(tail) if tail else head
print(sum([1, 2, 3]))
# Creating a priority queue
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heap... |
#!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... |
import os
import numpy as np
import pickle
import random
from tqdm import tqdm
import logging
from nas_201_api import NASBench201API as API
from utils import get_index_of_max_or_min_element_in_list, write_dict_of_lists_to_csv, dict_to_array, rank_columns_of_2d_array
RAWPATH = os.environ['NASBENCH_RAW']
OUTPATH = os.e... |
import sys
import xml.sax
import zipfile
import redis
import shutil
import os
from pymongo import MongoClient
from bson.objectid import ObjectId
if len(sys.argv) < 3:
raise ValueError('Missing arguments. First argument must be the path to .ead, second, a version id string')
scenes = {'nodes': {}}
flags = []
vars ... |
"""PURPOSE:
This module identifies a 'shared list of commands' in two command lists. A
shared tail is a shared list of commands which can be moved at the end of the
two lists. Example:
List 1: List 2:
[0] a = *p [0] a = *p
[1] b = a + b ... |
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
from tqdm import tqdm
from easydict import EasyDict as edict
from thop import clever_format
# import wandb
import os, sys
import torch
from torch.utils.data import DataLoader
from torch import distributions
import torch.nn as nn
impo... |
from typing import List, Union
import numpy as np
import pandas as pd
from shapely.geometry import Polygon, MultiPolygon
from shapely.ops import cascaded_union
import shapely.wkt
from sklearn.neighbors import NearestNeighbors
from vresutils.graph import voronoi_partition_pts
import scipy as sp
from scipy.sparse impo... |
from flask import jsonify, render_template, request, abort
from app.geojson import bp
from app import db
from sqlalchemy import text
import json
import time
@bp.route('/geojson')
def geojson_points():
sql = text('SELECT *, st_x(position) lon, st_y(position) lat, encode(sha256(d.identifier::bytea), \'hex\')... |
# Copyright 2019 ZTE corporation. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import subprocess # nosec
import xml.etree.ElementTree as xmlTree # nosec
from typing import Any, Dict, List, Mapping, NamedTuple, Optional
from .models.data_type import DataType
from .protos.generated.model_config_pb2 impo... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 27 16:43:15 2017
@author: chinwei
note that thought it's called energy function here, they are actually
log-density (negative energy)
"""
import torch as T
from utils import log_normal, varify
import torch
cuda = torch.cuda.is_available()
from... |
# Copyright 2018 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.
from google.appengine.ext import ndb
from dto.commit_id_range import CommitID
from services import git
from services.flake_failure import flake_constants
fr... |
"""
dataset processing
"""
import re
import os
import random
from Bio import SeqIO
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import torch
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
def setup_seed(seed):
# Ref: https://pytorch.org/docs/s... |
import lib.settings as settings
import lib.logger
log = lib.logger.get_logger('BasicShareLimiter')
import DBInterface
dbi = DBInterface.DBInterface()
dbi.clear_worker_diff()
from twisted.internet import defer
from mining.interfaces import Interfaces
import time
''' This is just a customized ring buffer '''
class Sp... |
from __future__ import print_function
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFrame, QHBoxLayout
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSplitter, QSpinBox, QDialogButtonBox, QFormLayout, QDialog
# TODO: for the output function, make it so that all panels are an increment of 1/n wh... |
"""Freezes wiki_music into standalone executable."""
import argparse
import logging
import shutil
import sys
from multiprocessing import Process
from pathlib import Path
from typing import List, Set
from zipfile import ZipFile
import PyInstaller
import PyInstaller.__main__
from PyInstaller.depend.imphook import Modul... |
import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
import solt.core as slc
import solt.transforms as slt
import torch
import torch.nn.functional as F
import torchvision.transforms as tv_transforms
from sklearn.preprocessing import OneHotEncoder
from tqdm import tqdm
from oaprogression.training.dat... |
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# 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/LICEN... |
#!/usr/bin/env python2
import sys
import yaml
import re
import os
import json
import mist.api
this_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(this_dir)
paths = ['src', 'libcloud', 'celerybeat-mongo']
for p in paths:
sys.path.append(os.path.join(parent_dir, p))
BASE_FILE_PATH = ... |
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import requests
import traceback
from typing import Dict
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
class Error(Exception):
"""Base class fo... |
"""Docker helper to simplify retrieving/sending single files."""
import os
import shutil
import tarfile
import docker
class _DLReader:
"""Wrapper to turn an iterator into a file object.
This is for piping the result of a streaming `requests.get` into `tarfile`.
"""
def read(self, count):
buf... |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
from PIL import ImageColor
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageOps
from six import BytesIO
from six.moves.urllib.request import urlopen
# Print Tensorflow v... |
#!/usr/bin/env python3
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
'''
Merge training configs into a single inference config.
The single inference config is for CLI, which only takes a single config to do inferencing.
The trainig configs includes: model config, preprocess config, decode conf... |
# Copyright 2017 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import re
import os
APP_PATH = os.path.join(*os.path.split(os.path.dirname(os.path.realpath(__file__)))[:-1])
import sys
if APP_PATH not in sys.path:
sys.path.append(APP_PATH)
import MyTrack
import PowerShell
import Phonebook
import Overlord
import Log
LOGGER = Log.MyLog(name=__name__)
# # # #
"""
Special setup ... |
from ctypes import *
from enum import Enum, unique
from functools import total_ordering
import webcolors
# just for better documentation and BE support. No need to define __bool__(self)
class Bool(c_uint8):
pass
@unique
class VP_Type(Enum):
TEXT = -1
BIT = -2
NONE = 0
BYTE = 1
W... |
def kirilica_do_latinici(text):
text = str.replace(text,'ньј', 'ńj')
text = str.replace(text,'ь', '')
text = str.replace(text,'а', 'a')
text = str.replace(text,'ӑ', 'å')
text = str.replace(text,'б', 'b')
text = str.replace(text,'в', 'v')
text = str.replace(text,'ў', 'v')
text = str... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
from collections import deque
import numpy as np
import scipy.stats as ss
import pandas as pd
import pysam
def process_rdtest(rdtest):
"""Standardize rdtest column names"""
# Drop metadata columns (available from VCF) and rename CNVID... |
import wx
import string
from BaseUI import BaseUI
from threading import Thread
from AlarmistExceptions import WrongOptionsError
ID_TOGGLE_MENUEL = wx.NewId()
ID_HOTKEY = wx.NewId()
class IconBar:
def __init__(self,l_off=[255,0,0],l_on=[0,255,0],r_off=[0,128,0],r_on=[0,255,0]):
self.s_line = '\xff\xff\xff' + '\0\0\... |
"""
Copyright 2015, Cisco Systems, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... |
'''
Added a simple camera class to an existing example.
The camera class is built using following tutorials:
https://learnopengl.com/Getting-started/Camera
http://in2gpu.com/2016/03/14/opengl-fps-camera-quaternion/
Controls:
Move:
Forward - W
Backwards - S
... |
#!/usr/bin/env python3
# %% Imports
import argparse
import atexit
import numpy as np
import os
import sys
import tempfile
from pyminc.volumes.factory import *
from subprocess import call
# %% Argument parsing
parser = argparse.ArgumentParser(description='Orient Allen Institute CCFv3 imaging data to standard spaces'... |
import numpy as np
from uncertainties import ufloat
from background_file_handler.backgroundResults import BackgroundResults
from data_handler.signal_features import compute_periodogram, nyqFreq
from scipy.signal import butter, filtfilt
from plotter.plot_handler import plot_f_space, plot_delta_nu_acf,plot_delta_nu_fit
f... |
# -*- coding: utf-8 -*-
import pandas as pd
import requests
import re
import nltk
from textstat.textstat import textstat
from nltk.sentiment.vader import SentimentIntensityAnalyzer
#nltk.download('vader_lexicon')
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from collections import Counter
import ... |
# generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/JointTrajectoryControllerState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_JointTrajectoryControllerState... |
import requests
import itertools
from pathlib import Path
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def extract_vote_record(state, timestamp, data_dict):
vote_info = {}
vote_info['state'] = state
county = data_dict['locality_name'].lower().replace(' ','-')
... |
import numpy as np
from subprocess import call
import os
from LuyckxFeatures import exportC5, importC5
from collections import Counter
"""
Wraps the Tillburg Memory Based Learner (TIMBL) into python, including some help functions, e.g. to calculate confusion
matrices, the F-score and accuracy.
"""
def classify(trainDat... |
import collections
import pkgutil
def preprocess_words_scores(type2freq_1, type2score_1, type2freq_2, type2score_2,
stop_lens, stop_words, handle_missing_scores):
"""
Filters stop words according to a list of words or stop lens on the scores
Parameters
----------
type2... |
from datetime import datetime
import numpy as np
import pytest
from pytz import UTC
from pandas._libs.tslibs import (
OutOfBoundsTimedelta,
conversion,
iNaT,
timezones,
tzconversion,
)
from pandas import (
Timestamp,
date_range,
)
import pandas._testing as tm
def _compare_utc_to_local(t... |
# temps.py
import time
import csv
import os
import numpy as np
import glob
from datetime import datetime
HUGE = 1000000000
TEENY_WEENY = 0.0000001
# prompt the user to name this experiment
ename = input("Enter Experiment Name: ")
# While true, with some time delay,
# sleep(10) sleep for 1000ms -- we only want one r... |
import math
import random
from ask_sdk_model.interfaces.alexa.presentation.apl import \
RenderDocumentDirective
from models import Operation
import utils
@utils.randomize
def confirmation(_locale):
return ['OK.', 'Alright.', 'Got it.'] # add some speechcons? gotcha?
@utils.randomize
def congratulations(_lo... |
#!/usr/bin/python
# $Id:$
# wxPython + pyglet integration, by subclassing wx.Window.
# Win32 works fine, though flickery resize.
# GDK sort of works, but keeps getting overdrawn by the window background
# (resize to see).
import wx
import pyglet
from pyglet.gl import *
import sys
if sys.platform == ... |
"""
The gametime module handles the global passage of time in the mud.
It also supplies some useful methods to convert between
in-mud time and real-world time as well allows to get the
total runtime of the server and the current uptime.
"""
from django.conf import settings
from src.scripts.scripts import Script
from ... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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.apac... |
import csv
from django.http import HttpResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import exceptions, mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from lego.apps.permissions.api.views import AllowedPer... |
from ..types import (
ModeResult,
NativeRawCalcResult,
NativeRawPP,
NativeRawStars,
OsuModeInt,
OsuModeStr
)
from ..functions.common import osu_mode_str
from ..utils import _read_only_property_generator, _get_attrs_dict, _get_attrs_str
from typing import Dict, Optional, Tuple, Union
_str = str... |
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('name', help='name under which the model will be saved')
parser.add_argument('--num_epochs', help='number of epochs to train the model', type=int, default=1)
parser.add_argument('--batch_size', help='batch... |
from browser import document as doc
from browser import html, window, bind, worker
from browser.html import TABLE, TR, TH, TD
from browser.local_storage import storage
storage_key = "poe_crafting_bench"
myWorker = worker.Worker("myworker")
# Setter storage so that we can differentiate values on this site from other... |
from tkinter import filedialog
import pandas as pd
import cv2
try:
from . import detect
except ImportError:
import detect
import tempfile, time
up = 38
down = 40
left = 37
right = 39
esc = 27
def label_images(img_list, attribute_lists):
flag = cv2.WINDOW_NORMAL
images = len(img_list)
attri... |
from palettecleanser import palette
from palettecleanser import config
import os
import pytest
class TestColor:
def test_distance(self):
color0 = palette.Color(255, 0, 19)
color1 = palette.Color(50, 45, 70)
assert round(color0.distance(color1), ndigits=3) == 215.988
def test_closest(se... |
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.optim import lr_scheduler
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
import numpy as np
from ... |
#!/usr/bin/env python
"""Run the modification pipeline for r9 reads using deepmod"""
########################################################################
# File: run_deep_mod_r9.py
#
# Authors: <NAME>
#
# History: 04/03/19
########################################################################
import shutil
impor... |
import json
from flask_restful import reqparse
from ColorsCollection import ColorCollection
class PlotAttributesAndParser:
"""
This Class is used as a wrapper for [flask_restful.reqparse.RequestParser()] and
will be the base class and be used to parse the arguments for different kind of plot
The ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@title: pm_synth_controller.py
@date: 08/13/2016
@author: <NAME>
@purpose: Provide controller system for pm_synth.
"""
import pm_synth_defaults as default
class Controller(object):
"""
Controller object master class.
Each major section of the pm_synt... |
"""
Module to handle one or more clients requesting video stream.
Using async with intentional blocking sockets because I had issues using
async non-blocking sockets, and because it yielded much better performance
compared to threading only prototype.
"""
import asyncio as aio
import socket
import logging
import queu... |
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 03 21:05:00 2021
@author: iv
"""
import sys
import os
import pandas as pd
import numpy as np
from textblob import TextBlob
import re
from textblob.sentiments import NaiveBayesAnalyzer
from googletrans import Translator
import unicodedata
### SYSTEM D... |
"""
Tests candid_changes_are_backwards_compatible.
To run this manually, do the usual thing when it comes to the unittest standard
library module:
cd "${where_this_file_lives}"
python3 -m unittest candid_changes_are_backwards_compatible_test
This gets run automatically by the python-tests Gitlab CI job, which is... |
import unittest
from ..periph import *
from ..memory import MemoryMap
from .. import event
class ConstantBoolTestCase(unittest.TestCase):
def test_init(self):
a = ConstantBool(True)
b = ConstantBool(False)
self.assertTrue(a.value)
self.assertFalse(b.value)
def test_value_wron... |
import logging
import random
from asyncio import Lock, sleep
from contextlib import suppress
from functools import wraps
from typing import Callable, Container, Union
from weakref import WeakValueDictionary
from discord import Colour, Embed, Member
from discord.errors import NotFound
from discord.ext import commands
f... |
#!/usr/bin/env python
import click as ck
import numpy as np
import pandas as pd
from collections import Counter
from utils import Ontology, FUNC_DICT
import logging
import json
import gzip
logging.basicConfig(level=logging.INFO)
@ck.command()
@ck.option(
'--go-file', '-gf', default='data/go.obo',
help='Gene ... |
# -*- coding: utf-8 -*-
from error import JsonFormatError
from arg import Arg
from common import ind1
from common import ind2
from common import ind3
class _PropGen(object):
def __init__(self, conf):
self.filename = ""
self.class_list = []
self.arg_list = []
self.conf = conf
... |
import re, requests, json
import numpy as np
import pandas as pd
from functools import reduce
import matplotlib.pyplot as plt
import seaborn as sns
import sys, io, base64
from tabulate import tabulate
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignor... |
# -*- coding: UTF-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2021, InterlockLedger
# 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 code must retain the above c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project: Proverbial Hangman
File: hangman-pyside.py
Author: <NAME>
Created: 2017-11-24
IDE: PyCharm Community Edition
Description:
A simple hangman game written using PySide.
To play the game, figure out a proverb by gu... |
#! python
#
#
from behave import given, then
from renderer.sphere import Sphere, GlassSphere
from renderer.matrix import IdentityMatrix
from renderer.transformations import Scaling, Translation, Rotation_z
from renderer.material import Material
from renderer.bolts import Point, Color
from math import isclose, sqrt, pi... |
"""Collect information on document sections and Pygame API objects
The following persistent Pygame specific environment structures are built:
pyg_sections: [{'docname': <docname>,
'fullname': <fullname>,
'refid': <ref>},
...]
all Pygame api sections in the documents ... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Rows of tree widgets on workflow tabs."""
from lib.app_entity_factory import workflow_entity_factory
from lib.page.widget import tree_widget, table_with_headers
from lib.utils import date_utils, test_utils... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.