content stringlengths 5 1.05M |
|---|
import numpy as np
from math import log2
from scamp_filter.Item import Item as I
from termcolor import colored
def approx(target, depth=5, max_coeff=-1, silent=True):
coeffs = {}
total = 0.0
current = 256
for i in range(-8, depth):
if total == target:
break
... |
###########################################################
# Re-bindings for unpickling
#
# We want to ensure class
# sage.modular.congroup_element.CongruenceSubgroupElement still exists, so we
# can unpickle safely.
#
###########################################################
from sage.modular.arithgroup.arithgroup... |
"""Impementation for print_rel_notes."""
def print_rel_notes(
name,
repo,
version,
outs = None,
setup_file = "",
deps_method = "",
toolchains_method = "",
org = "bazelbuild",
changelog = None,
mirror_host = None):
tarball_name = ":%s-%... |
#!/usr/bin/env python
# Run VGG benchmark series.
# Prepares and runs multiple tasks on multiple GPUs: one task per GPU.
# Waits if no GPUs available. For GPU availability check uses "nvidia-smi dmon" command.
# 2018 (C) Peter Bryzgalov @ CHITECH Stair Lab
import multigpuexec
import time
import os
import datetime
#... |
from distutils.core import Extension, setup
import numpy as np
setup(
name="numpy_ctypes_example",
version="1.0",
description="numpy ctypes example",
author="Mateen Ulhaq",
author_email="mulhaq2005@gmail.com",
maintainer="mulhaq2005@gmail.com",
url="https://github.com/YodaEmbedding/experim... |
"""
Copyright 2015 Paul T. Grogan, Massachusetts Institute of Technology
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 applicabl... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... |
from utils.QtCore import *
class CustomAddCoinBtn (QPushButton):
def __init__(
self
):
super().__init__()
self.setCursor(Qt.PointingHandCursor)
self.setText('Add coin')
self.setObjectName('add_coin_btn')
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.P... |
from typing import Callable, List
import numpy as np
from qcodes.instrument.base import Instrument
from qcodes.instrument.parameter import Parameter
from qcodes.instrument.channel import InstrumentChannel, ChannelList
from qcodes.utils import validators as vals
from .SD_Module import SD_Module, keysightSD1, Signadyne... |
# -*- coding: utf-8 -*-
from urllib import request
import sys, os
import time, types, json
import os.path as op
import win32api, win32con, win32gui
# default_encoding = 'utf-8'
# if sys.getdefaultencoding() != default_encoding:
# reload(sys)
# sys.setdefaultencoding(default_encoding)
TRY_TIMES = 1
DEFA... |
from django.shortcuts import render
from django.urls import reverse, reverse_lazy
from django.views.generic import ListView, DetailView, DeleteView
from django.views.generic.edit import CreateView, UpdateView
from django.contrib.auth.mixins import PermissionRequiredMixin
from .models import AdvThreatEvent, NonAdvThrea... |
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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 os
from optparse import make_option
from django.core.management import call_command, BaseCommand
from django.conf import settings
from fixture_generator.base import get_available_fixtures
from django.db.models.loading import get_app
class Command(BaseCommand):
"""
Regenerate fixtures for all applicatio... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
"""
Builtin tools that come with pyiron base.
"""
from abc import ABC
from pyiron_base.job.factory import JobFactory
__... |
# -*- coding: utf-8 -*-
from yandex_checkout import ReceiptItem
from yandex_checkout.domain.common.receipt_type import ReceiptType
from yandex_checkout.domain.common.request_object import RequestObject
from yandex_checkout.domain.models.receipt_customer import ReceiptCustomer
from yandex_checkout.domain.models.settlem... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from flaky import flaky
from .. import SemparseTestCase
from allennlp.models.archival import load_archive
from allennlp.predictors import Predictor
class TestAtisParserPredictor(SemparseTestCase):
@flaky
def test_atis_parser_uses_named_inputs(self):
inputs = {"utterance": "show me the flights to seat... |
# Generated by Django 3.2.3 on 2021-05-29 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discordbot', '0021_auto_20210529_2045'),
]
operations = [
migrations.AddField(
model_name='member',
name='settings',... |
# Author: Jintao Huang
# Time: 2020-5-24
import torch.nn as nn
from .utils import FrozenBatchNorm2d
default_config = {
# backbone
"pretrained_backbone": True,
"backbone_norm_layer": nn.BatchNorm2d,
"backbone_freeze": ["conv_first", "layer1", "layer2"],
# "backbone_freeze": [""], # freeze backbone... |
# TOO EASY
T = int(input())
for _ in range(T):
lower, upper = map(int, input().split())
n = int(input())
# a < num <= b
for _ in range(n):
mid = (lower+upper)//2
print(mid)
res = input()
if res == "TOO_SMALL":
lower = mid + 1
elif res == "TOO_BIG":
... |
# -*- coding: utf-8 -*-
from odoo import _, api, fields, models
class Trainer(models.Model):
_name = "bista.trainer"
_description = "Bista Training Management System - Trainer"
_rec_name = "name"
profile_image = fields.Binary(string="Profile Image", attachement=True)
first_name = fields.Char(str... |
#coding: utf-8
#!python3
# 5) Solicite o preço de uma mercadoria e o percentual de desconto. Exiba o valor do desconto
# e o preço a pagar:
p_produto = float(input('Valor produto: '))
p_desconto = float(input('Percentual de desconto: '))
p_produto_atual = p_produto - (p_produto*p_desconto/100)
print('Preço... |
# Generated by Django 2.2.16 on 2020-10-02 08:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('routes', '0047_source_id_nullable'),
('routes', '0048_athlete_activities_imported'),
]
operations = [
]
|
#!/usr/bin/env python3
import unittest
import numpy as np
from selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver
def run_cruise_simulation(cruise, t_end=100.):
man = Maneuver(
'',
duration=t_end,
initial_speed=float(0.),
lead_relevancy=True,
initial_distance_lead=100,
cruise_valu... |
from __future__ import print_function
from mmstage import MicroManagerStage
|
# Copyright: 2006-2011 Brian Harring <ferringb@gmail.com>
# License: GPL2/BSD
"""
exceptions thrown by the MergeEngine
"""
__all__ = ("ModificationError", "BlockModification",
"TriggerUnknownCset",
)
class ModificationError(Exception):
"""Base Exception class for modification errors"""
def __init__(sel... |
# Generated by Django 2.1.7 on 2019-04-16 15:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('materials', '0068_auto_20190415_2140'),
]
operations = [
migrations.RenameField(
model_name='dataset',
old_name='experimenta... |
# -*- coding: utf-8 -*-
"""
flask_security.recoverable
~~~~~~~~~~~~~~~~~~~~~~~~~~
Flask-Security recoverable module
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
from flask import current_app as app
from werkzeug.local import LocalProxy
from werkzeug.securi... |
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report,accuracy_score,f1_score,precision_score,recall_score
from scikitplot.metrics import plot_confusion_matrix
class eval_metrics():
def __init__(self,targets,preds,classes):
try:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import itertools
from saliency_map import *
from utils import OpencvIo
class GaussianPyramidTest(unittest.TestCase):
def setUp(self):
oi = OpencvIo()
src = oi.imread('./images/fruit.jpg')
self.__gp = GaussianPyramid(src)
def t... |
# MODULE: TypeRig / Core / Ojects
# -----------------------------------------------------------
# (C) Vassil Kateliev, 2017-2020 (http://www.kateliev.com)
# (C) Karandash Type Foundry (http://www.karandash.eu)
#------------------------------------------------------------
# www.typerig.com
# No warranties. By using ... |
from pyomac.clustering.cluster_utils import (
ModalSet,
IndexedModalSet,
indexed_modal_sets_from_sequence,
modal_sets_from_lists,
modal_clusters,
single_set_statistics,
filter_clusters,
plot_indexed_clusters
)
|
# TextChart - Roll The Dice
import pygwidgets
from Constants import *
class TextView():
def __init__(self, window, oModel):
self.window = window
self.oModel = oModel
totalText = ['Roll total', '']
for rollTotal in range(MIN_TOTAL, MAX_TOTAL_PLUS_1):
totalText.append(r... |
"""
Exercise 1
Write a function that takes a string as an argument and displays the letters
backward, one per line.
"""
def backwards(word):
x = len(word) - 1
while x >= 0:
print(word[x])
x -= 1
backwards("hello")
|
# with open('./space.text', 'w') as message:
# message.write('我是写入的数据\n')
# message.write('我再写一段文字哦\n')
# message.write('继续写入\n')
with open('./space.text', 'a') as msg:
msg.write('附加一段文字\n')
msg.write('继续附加一段\n')
|
import modeli, dobi_zneske
from bottle import *
import hashlib # racunaje md5
import json,requests
import pandas as pd
secret = "to skrivnost je zelo tezko uganiti 1094107c907cw982982c42"
def get_administrator():
username = request.get_cookie('administrator', secret=secret)
return username
def get_user(a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
filepath = sys.argv[1]
path, filename = os.path.split(filepath)
filename, ext = os.path.splitext(filename)
for i in os.listdir(os.getcwd()+'/'+path):
file_i, ext = os.path.splitext(i)
if i.startswith(filename+'_segmented') and ext == '.ttl':
# ... |
from datetime import datetime, timedelta
import pendulum
import prefect
from prefect import task, Flow
from prefect.schedules import CronSchedule
import pandas as pd
from io import BytesIO
import zipfile
import requests
schedule = CronSchedule(
cron="*/30 * * * *",
start_date=pendulum.datetime(2021... |
import ROOT as root
qMap_Ag_C0_V0 = root.TProfile2D("qMap_Ag_C0_V0","qMap_Ag_C0 (V0)",52,0,52,80,0,80,0,0);
qMap_Ag_C0_V0.SetBinEntries(3585,29768);
qMap_Ag_C0_V0.SetBinEntries(3586,79524);
qMap_Ag_C0_V0.SetBinEntries(3639,83953);
qMap_Ag_C0_V0.SetBinEntries(3640,124982);
qMap_Ag_C0_V0.SetBinEntries(3641,14345);
qMap_... |
from . import start_watcher
def main():
start_watcher() |
from .market import Market, TradeException
import time
import hmac
import urllib.parse
import urllib.request
import requests
import hashlib
import config
import database
from datetime import datetime
class PrivateBter(Market):
url = "https://bter.com/api/1/private/"
def __init__(self):
super().__ini... |
import rlkit.misc.hyperparameter as hyp
from rlkit.launchers.launcher_util import run_experiment
import os
from rlkit.misc.asset_loader import sync_down
def experiment(variant):
from rlkit.core import logger
demo_path = sync_down(variant['demo_path'])
off_policy_path = sync_down(variant['off_policy_path'... |
# Generated by Django 3.2.7 on 2021-09-27 02:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='user_type',
... |
# encoding: utf-8
"""
route.py
Created by Thomas Mangin on 2015-06-22.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from exabgp.protocol.family import SAFI
from exabgp.bgp.message.update.nlri.qualifier import RouteDistinguisher
from exabgp.configurati... |
'''This file provides editor completions while working on DFHack using ycmd:
https://github.com/Valloric/ycmd
'''
# pylint: disable=import-error,invalid-name,missing-docstring,unused-argument
import os
import ycm_core
def DirectoryOfThisScript():
return os.path.dirname(os.path.abspath(__file__))
# We need to te... |
from twisted.trial import unittest
from signing.persistence import Persistence
class PersistenceTests(unittest.TestCase):
def setUp(self):
self.persistence = Persistence()
def test_set_get(self):
d = self.persistence.set('somekey', 'somefield', 'somevalue')
d.addCallback(lambda _: sel... |
""" Module storing the `~halotools.sim_manager.CachedHaloCatalog`,
the class responsible for retrieving halo catalogs from shorthand
keyword inputs such as ``simname`` and ``redshift``.
"""
import os
from warnings import warn
from copy import deepcopy
import numpy as np
from astropy.table import Table
from ..utils.pyt... |
import unittest, os
import cuisine
USER = os.popen("whoami").read()[:-1]
class Text(unittest.TestCase):
def testEnsureLine( self ):
some_text = "foo"
some_text = cuisine.text_ensure_line(some_text, "bar")
assert some_text == 'foo\nbar'
some_text = cuisine.text_ensure_line(some_text, "bar")
assert some_tex... |
import math
import numpy as np
from utils.functions.math.coordinate_trans import coordinate_transformation_in_angle
def circle_make(center_x, center_y, radius):
'''
Create circle matrix(2D)
Parameters
-------
center_x : float in meters
the center position of the circle coordinate x
cen... |
import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesRegressor, GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline, make_union
from sklearn.preprocessing import MaxAbsScaler
from tpot.builtins import StackingEstimator
# NOT... |
# 454. 4Sum II
import collections
class Solution:
def fourSumCount(self, A, B, C, D):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
ab = {}
for a in A:
for b in B:
ab... |
import soundfile as sf
import numpy as np
import librosa
from scipy import signal
import cPickle
import src.config as cfg
def to_mono(wav):
if wav.ndim == 1:
return wav
elif wav.ndim == 2:
return np.mean(wav, axis=-1)
def calculate_logmel(rd_fd):
wav, fs = sf.read(rd_fd)
wav = to_mono... |
from datetime import datetime as dt
from ..ff.window import Window
class BrowserSession(object):
def __init__(self, ss_json):
self._windows = WindowSet(ss_json["windows"])
self._start_time = dt.fromtimestamp(ss_json["session"]["startTime"] / 1000)
self._selected_window = ss_json["selectedW... |
import numpy as np;
import xlrd;
import xlwt;
sheet = xlrd.open_workbook('data1.xls');
workbook = xlwt.Workbook(encoding = 'ascii');
worksheet = workbook.add_sheet('school')
data = sheet.sheets()[0];
row = data.nrows;
col = data.ncols;
for i in range(0,row):
for j in range(0,col):
worksheet.write(i, j... |
import json
import sys
import os
import typer
from typing import List
import time
from .logger import get_logger
from .config.imports import check_imports
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
logger = get_logger()
cli = typer.Typer()
@cli.command('setup')
def setup_auto():
chk_libs = ['tensorflow', 'torch',... |
import re
import matplotlib.pyplot as plt
import numpy as np
import sklearn
from sklearn import svm
from sklearn import linear_model, tree
from sklearn.ensemble import RandomForestClassifier
from sklearn import neural_network
import copy
path = r"D:\THU\curriculum\Software Engineering\Course_Project\data_1109_0427_RGB... |
import csv
import re
from os import path
import numpy as np
FIELDNAMES = 'timeStamp', 'response_time', 'request_name', "status_code", "responseMessage", "threadName", "dataType",\
"success", "failureMessage", "bytes", "sentBytes", "grpThreads", "allThreads", "URL", "Latency",\
"IdleTime", "C... |
from setuptools import setup, find_packages
setup(
name='taxies',
version='0.1.dev',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Click',
],
entry_points='''
[console_scripts]
taxies=taxies.scripts.taxies:cli
''',
) |
"""App.
"""
import logging
import sys
from django.apps import AppConfig
from configs.part_detection import DF_PD_VIDEO_SOURCE_IS_OPENCV
logger = logging.getLogger(__name__)
class AzurePartDetectionConfig(AppConfig):
"""App Config."""
name = "vision_on_edge.azure_part_detections"
def ready(self):
... |
"""
Query suggestion hierarchical encoder-decoder code.
The code is inspired from nmt encdec code in groundhog
but we do not rely on groundhog infrastructure.
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Alessandro Sordoni")
__contact__ = "Alessandro Sordoni <sordonia@iro.umontreal>"
import theano
import th... |
# Copyright 2013-2015 ARM Limited
#
# 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 w... |
# 源程序文件名
SOURCE_FILE = "{filename}.hs"
# 输出程序文件名
OUTPUT_FILE = "{filename}.out"
# 编译命令行
COMPILE = "ghc {source} -o {output} {extra}"
# 运行命令行
RUN = 'sh -c "./{program} {redirect}"'
# 显示名
DISPLAY = "Haskell"
# 版本
VERSION = "GHC 8.0.2"
# Ace.js模式
ACE_MODE = "haskell"
|
# Generated by Django 2.1.7 on 2019-10-03 20:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0017_auto_20190921_1849'),
]
operations = [
migrations.RemoveField(
model_name='estrutu... |
import torch
from torch.optim import Adam,SGD
from opt import opt
import math
import random
import collections
from torch.utils.data import sampler
import torch.nn as nn
def extract_feature( model, loader):
features = torch.FloatTensor()
for (inputs, labels) in loader:
ff = torch.FloatTensor(inputs.... |
# WRITE YOUR SOLUTION HERE:
def add_numbers_to_list(numbers: list):
if len(numbers) % 5 != 0:
numbers.append(numbers[-1] +1 )
add_numbers_to_list(numbers)
if __name__=="__main__":
numbers = [1,3,4,5,10,11]
add_numbers_to_list(numbers)
print(numbers) |
#!/usr/bin/env python
import os, subprocess
from autopkglib import Processor, ProcessorError
__all__ = ["IzPackExecutor"]
class IzPackExecutor(Processor):
"""Runs IzPack installer with all install options checked."""
input_variables = {
"app_root": {
"required": True,
"des... |
"""
@author Yuto Watanabe
@version 1.0.0
Copyright (c) 2020 Yuto Watanabe
"""
|
import cProfile
import argparse
from app import Application
def parse_args():
parser = argparse.ArgumentParser(
description="A keyboard-oriented image viewer")
parser.add_argument("path", type=str, nargs='?', default="",
help="the file or directory to open")
parser.add_argum... |
__author__ = 'Mario'
import wx
import wx.xrc
from Engine_Asian import AsianOption
###########################################################################
## Class MainPanel
###########################################################################
class PanelAsian ( wx.Panel ):
def __init__( self, parent )... |
import tqdm
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from models.generator import ResNetGenerator
from train_script.utils import *
from utils.val import validation
from utils.quantize_model import *
def adjust_learning_rate... |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_db'
db = SQLAlchemy(app)
class UserDB(db.Model):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(32),unique=True)
passw... |
from .DtnAbstractParser import DtnAbstractParser
from enum import Enum
from pydantic import PositiveInt, PositiveFloat
import sys
from typing import List, Optional, Set, Union
class RouterMode(str, Enum):
FAST = 'fast'
SLOW = 'slow'
class RouterAlgorithm(str, Enum):
CGR = 'cgr'
BFS = 'bfs'
class DtnL... |
import numpy as np
import tensorflow as tf
class InferenceGraph:
def __init__(self):
pass
def run_inference_for_single_input_frame(self, model, input_frame,log, log_path):
"""
Method Name: run_inference_for_single_input_frame
Description: This function make prediction ... |
import selenium
import glob
from numpy import arange
from random import sample
from sys import exit
from time import sleep
from progress.spinner import Spinner
from progress.bar import ChargingBar
from threading import Thread
from selenium import webdriver
from selenium.webdriver.firefox.options import Option... |
from .page_article import * |
SECRET_KEY = "it's-a-secret-to-everyone"
INSTALLED_APPS = [
'channels',
'channels_irc',
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
},
}
|
# -*- coding: utf-8 -*-
import io
import os
import time
import fcntl
import socket
import struct
import picamera
import threading
from Led import *
from Servo import *
from Thread import *
from Buzzer import *
from Control import *
from ADS7830 import *
from Ultrasonic import *
from Command import COMMAND as cmd
class... |
import os
data_path_root = "E:\Projects\projectHO\data"
stock_list_path = os.path.join(data_path_root, "stock_list.csv")
split_span = 365 * 5 # split dates to download pre-historical data
retry_count = 5 # downloader max retry count
log_path = "E:\Projects\projectHO\log"
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Baidu.com, 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 requi... |
#!/usr/bin/python3 -OO
# Copyright 2007-2022 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any late... |
'''
generic functions
'''
def myfunc( x:int ):
print( x * 100 )
def myfunc( x:string ):
print( x + 'world' )
def main():
myfunc( 10 )
myfunc( 'hello' )
|
# Third-Party Imports
from django.core.exceptions import ValidationError
from django.db.models import ProtectedError
# App Imports
from core.tests import CoreBaseTestCase
from ..models import AssetCategory
class AssetCategoryModelTest(CoreBaseTestCase):
""" Tests for the Asset Category Model """
def test_c... |
from unittest.mock import Mock, patch, call
import pytest
from sqlalchemy import column
from sqlalchemy import text
from sqlalchemy import func
from sqlalchemy import not_
from sqlalchemy_filters import operators
from sqlalchemy_filters.exceptions import InvalidParamError
from tests.utils import compares_expressions
... |
import auditor
from event_manager.events import tensorboard
auditor.subscribe(tensorboard.TensorboardStartedEvent)
auditor.subscribe(tensorboard.TensorboardStartedTriggeredEvent)
auditor.subscribe(tensorboard.TensorboardSoppedEvent)
auditor.subscribe(tensorboard.TensorboardSoppedTriggeredEvent)
auditor.subscribe(tens... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 13 09:50:51 2017
@author: mkonrad
"""
import math
import pytest
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
from pdftabextract.geom import (pt, ptdist, vecangle, vecrotate, overlap, lineintersect,
... |
"""
Open stuff in Chromium
"""
from albertv0 import Item, ProcAction, ClipAction
import json
from shutil import which
__iid__ = "PythonInterface/v0.1"
__prettyname__ = "Web Browser"
__version__ = "1.0"
__trigger__ = "web "
__author__ = "Michael Farber Brodsky"
def handleQuery(query):
if query.isTriggered:
... |
from urllib.request import urlopen
SIMPLE_URL = "http://www.dinopass.com/password/simple"
COMPLEX_URL = "http://www.dinopass.com/password/strong"
def GetSimplePassword():
response = urlopen(SIMPLE_URL)
bytes = response.readline()
return bytes.decode()
def GetComplexPassword():
response = urlopen(COMPLEX_URL)
b... |
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved.
import io
import os
from urllib.parse import urlparse
from io import BytesIO
from speakeasy.errors import NetworkEmuError
def is_empty(bio):
if len(bio.getbuffer()) == bio.tell():
return True
return False
def normalize_response_path(path):
... |
from os.path import join, dirname, realpath
from re import match
def parse_input():
planties = set()
with open(join(dirname(realpath(__file__)), "input.txt")) as f:
# Parse initial config
m = match("initial state: (?P<init>[#.]+)", f.readline())
for i, c in enumerate(m.group("init")):
... |
#!/usr/bin/env python
"""
Generate an input MAF file for MutSigCV by converting SNV/INDEL calls by the Genomon2 pipeline.
The input is a multi-sample variant call in post_analysis/ directory.
Usage: python genomon2maf.py merge_mutation_filt.txt
"""
__author__ = "Masashi Fujita <mssfjt@gmail.com>"
__version__ = "0.0.1"
... |
import asyncio
from pypuss.app import Master
async def main():
my_app = Master()
await my_app.run()
if __name__ == '__main__':
print("[info]", "started running")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
except BaseException:
print("[info]", "shuttin... |
from rest_framework import generics, status, permissions, mixins
from .models import Post, Vote
from .serializers import PostSerializer, VoteSerializer
from .permissions import IsPostAuthorOrReadOnly
from helpers.response import Response
class PostView(generics.ListCreateAPIView):
serializer_class = PostSeriali... |
import numpy as np
import xarray as xr
from constants import R_earth
from xr_DataArrays import dll_from_arb_da
def xr_int_global(da, AREA, DZ):
""" global volume integral *[m^3] """
(z, lat, lon) = dll_from_arb_da(da)
return (da*AREA*DZ).sum(dim=[z, lat, lon]) # 0D
def xr_int_global_level(da, AREA, D... |
class Packet_Ops():
def __init__( self ):
self.frame_id = 1
self.rx_packet_table = {
0x88: self.parse_command_resp,
0x8a: self.parse_modem_status,
0x8b: self.parse_tx_status,
0x8d: self.parse_route_information,
0x8e: self.aggreate_address_update,
0x90: self.parse_rx_indicator,
0x9... |
from importlib import import_module
import six
from six.moves import reload_module
from typing import Optional, Union # noqa
from configloader import ConfigLoader
from wrapt import ObjectProxy
"""
Usage:
from flexisettings.conf import settings
There are two important env vars:
`<inital_namespace>_CONFIG_... |
"""
Contains a class that converts the pre-processed binary file into a numpy array. The logic behind
each conversion step is thoroughly document through comments in the code.
"""
import pickle
import os
import struct
import logging
import hashlib
import numpy as np
from tqdm import tqdm
import matplotlib
class Prepr... |
# ConnexionApiGenerator.py - Creates an object implementing a Connexion API
import os
from jinja2 import Environment, Template, FileSystemLoader
from smoacks.sconfig import sconfig
class ConnexionApiGenerator:
def __init__(self, app_object):
self._app_object = app_object
self.name = self._app_objec... |
"""PyTest fixtures and helper functions, etc."""
import pprint
import uuid
from configparser import ConfigParser
from configparser import ExtendedInterpolation
from inspect import getframeinfo
from pathlib import Path
import pytest
# =========================================================
# H ... |
import copy
import itertools
import re
import threading
import html5lib
import requests
import urllib.parse
from bs4 import BeautifulSoup
from typing import List
try:
import basesite
except (ModuleNotFoundError, ImportError) as e:
from . import basesite
class DaocaorenshuwuSite(basesite.BaseSite):
def _... |
from flask import render_template, flash, redirect, url_for, session
from flask_login import login_user, current_user, login_required
from app import app, db, lm
from app.models.tables import User, Challenges
from app.models.forms import FlagForm
import datetime
from notifications import *
@lm.user_loader
def load_us... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.