content stringlengths 5 1.05M |
|---|
from flask import Flask, render_template, Response
from imutils.video import VideoStream
import cv2
import time
import os
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as n... |
# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract
# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government
# retains certain rights in this software.
"""Functionality for working with hyperchunk specificati... |
__author__ = "Sergey Aganezov"
__email__ = "aganezov(at)cs.jhu.edu"
__status__ = "production"
import unittest
from bg.genome import BGGenome, BGGenome_JSON_SCHEMA_JSON_KEY, post_load
class BGGenomeTestCase(unittest.TestCase):
def test_initialization_incorrect(self):
# empty genomes are not allowed, a na... |
# Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
import logging
import salt.exceptions
import saltext.vmware.utils.common as utils_common
import saltext.vmware.utils.datacenter as utils_datacenter
import saltext.vmware.utils.vmware as utils_vmware
from saltext.vmware.utils.connect import get_service... |
import os
import glob
from flask import Flask
from flask import jsonify
from flask import request, render_template
from webapp import app
#from model.util import *
from SigNet import main1, getpredictions
valid_mimetypes = ['image/jpeg', 'image/png', 'image/tiff']
global model
# def get_predictions(img_name):
# ... |
from os import getenv
from sqlalchemy import create_engine, Column, String, Integer, Numeric
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from geoalchemy2 import Geometry
USER = getenv("DB_USER", "")
PASSWORD = getenv("DB_PASSWORD", "")
HOST = getenv("DB_HOST", "")
PO... |
#!/usr/bin/env python
# Copyright Contributors to the Testing Farm project.
# SPDX-License-Identifier: Apache-2.0
"""
Generate RST files documenting modules.
"""
import inspect
import os
import sys
import re
import six
import gluetool
LOGGER = gluetool.log.Logging.setup_logger()
OUTPUT_DIR = 'docs/source'
MOD_TE... |
# The MIT License (MIT)
#
# Copyright (c) 2021 Chris J Daly (github user cjdaly)
#
# 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... |
# Generated by Django 3.2.5 on 2021-09-10 17:14
import cloudinary.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('requests', '0012_alter_request_file'),
]
operations = [
migrations.AlterField(
model_name='request',
... |
"""this video library help to compress the video based on the requirement.
Please complete it by using the required packages or modules from the oto-helper library, and the logic for it to work.
"""
# Add the import statements below
# Write the functions definitions that are required for this module below
de... |
from sequana import snaketools, sequana_data
from sequana.snaketools import DOTParser
import os, shutil
import tempfile
from sequana import Module, SequanaConfig
from easydev import TempFile
import subprocess
def test_dot_parser():
s = DOTParser(sequana_data("test_dag.dot", "testing"))
s.add_urls(mapper={'bwa... |
def main():
from scrapyts.exceptions import (DownloadError, ParseError)
import argparse
import sys
import traceback
# python scrapyts.py url -t 18 --begin 4 --end 150 --step 2 --display --nodownload --index --prefix watch --sufix "by Yhash"
parser = argparse.ArgumentParse... |
# This is a file which does actually have a variable called 'answers'.
# This file is used in the test_check.py file which tests the check module
answers = 1
|
import tabix
import os
from ..util import file_util, seq_util, vcf_util
class PreprocGnomAD():
def __init__(self, data):
self.header = ""
self.fieldlist = []
self.dirpath = data['dirpath']
self.outfile_title = data['outfile_title']
self.rawfiles = data['rawfiles']
se... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
dataset = pd.read_csv('./data/titanic_train.csv')
survived_passengers = dataset['Survived'] == 1
survived_passengers_ages = dataset[survived_passengers]['Age']
survived_passengers_ages_with_missing_filled = survived_passengers_... |
import json
import pickle
import argparse
import re
import collections
import string
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
regex = re.compile(r'\b(a|an|the)\b', re.UNICODE)
return re.sub(regex, ' ', text)
... |
import click
from catacomb.common import constants
from catacomb.utils import catacomb_handler, formatter
@click.command(
constants.CMD_OPEN_NAME, help=constants.CMD_OPEN_DESC,
short_help=constants.CMD_OPEN_DESC)
@click.argument("tomb_name", nargs=1)
@click.option(
"--new", "-n", is_flag=True, default=Fa... |
# coding: utf-8
import json
def transform(item):
if not item:
return
elif isinstance(item, dict):
if 'description' in item:
del item['description']
for key in item:
transform(item[key])
elif isinstance(item, list):
for i in item:
transfo... |
import json
import os
import unittest
from pathlib import Path
from defusedxml import ElementTree
import utilities.file_utilities as file_utilities
from mhs_common.errors.ebxml_handler import handle_ebxml_error
class TestEbxmlHandler(unittest.TestCase):
message_dir = Path(os.path.dirname(os.path.abspath(__file_... |
import sys
import os
import math
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFilter
def crop(src_pixels, dst_pixels, x, y, w, h, dx, dy):
for ky in range(h):
for kx in range(w):
p = src_pixels[x+kx, y+ky];
dst_pixels[dx+kx, dy+ky] = p
... |
from .register import GenericRegister
|
"""This module contains the mappers to compute the Hessian/gradients in a distributed fashion
Copyright (c) 2017 The ADMML 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... |
"""
Blink RGB LEDs using Raspberry PI GPIO
"""
import RPi.GPIO as GPIO
import time
COLORS = {'red': [True, False, False],
'green': [False, True, False],
'blue': [False, False, True],
'yellow': [True, True, False],
'purple': [True, False, True],
'cyan': [False,... |
import threading
import multiprocessing
import Queue
import logging
import xml.sax
import nltk.data
from nltk.tokenize import *
import re
class WikipediaReader(threading.Thread):
'''allows to read a wikipedia xml dump file and extract articles
'''
'''constructor
@param path the path to the wikie... |
import numpy as np
import sys,os
import cv2
#set caffe-ssd path
caffe_root = '/home/di/workspace/caffe-ssd/build/install/'
sys.path.insert(0, caffe_root + 'python')
import caffe
import time
#caffe.set_device(0)
#caffe.set_mode_gpu()
#net_file= 'MobileNetSSD_deploy.prototxt'
net_file= 'MobileNetSSD_deploy_truncated.p... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class DistributedMMPianoAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory("DistributedMMPianoAI")
def requestSpeedUp(self):
pass
def requestChangeD... |
#Your program should print each number from 1 to 100 in turn.
#When the number is divisible by 3 then instead of printing the number it should print "Fizz".
#`When the number is divisible by 5, then instead of printing the number it should print "Buzz".`
#`When the number is divisible by 5, then instead of printing th... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Cnvnator(MakefilePackage):
"""A tool for CNV discovery and genotyping
from depth-of-co... |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
from rez.utils.resources import ResourcePool, ResourceHandle
from rez.utils.data_utils import cached_property
from rez.plugin_managers import plugin_manager
from rez.config import config
from rez.exceptions import ResourceError
from con... |
import numpy as np
from typing import Optional
from scipy import optimize as opt
from math import *
class Fourier:
"""
Fourier optimizer: a heuristic optimization method for QAOA,
implemented according to the paper
"Quantum Approximate Optimization Algorithm: Performance, Mechani... |
import asyncio
from typing import Type
from ..config import Config
from ..typing import ASGIFramework
class UnexpectedMessage(Exception):
pass
class Lifespan:
def __init__(self, app: Type[ASGIFramework], config: Config) -> None:
self.app = app
self.config = config
self.startup = asy... |
__author__ = 'valkyrie_Z'
import os
from urllib.request import urlretrieve
import zipfile
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import pandas as pd
from cnn_model import *
def show_all_kinds_images(figsize_input, X_data, y_data):
#show the 43 k... |
from cursor import data
from cursor import device
from cursor import path
from cursor import renderer
def save_wrapper(pc, projname, fname):
folder = data.DataDirHandler().jpg(projname)
jpeg_renderer = renderer.JpegRenderer(folder)
jpeg_renderer.render(pc, scale=4.0, thickness=6)
jpeg_renderer.save(f... |
""" Functions for generating statistical summaries from multi-state life tables """
import numpy as np
import pandas as pd
import itertools
import METER.table as tb
def bootstrapLE(data, transition_names, states, initial_states, n=1000, initial_time=0, censor_states='default', group_names='default', conditions='defau... |
import config
from gui.dc_gan_widget import DcGanWidget
from PySide2.QtWidgets import QApplication
def set_params(widget, opt):
widget.model.net.alpha1 = widget.alpha1 = opt.a1
widget.model.net.alpha2 = widget.alpha2 = opt.a2
widget.model.net.alpha3 = widget.alpha3 = opt.a3
widget.model.net.alpha4 = w... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Administrative division loader
# ----------------------------------------------------------------------
# Copyright (C) 2007-2015 The NOC Project
# See LICENSE for details
# -----------------------------------------------... |
#!/usr/bin/env python
"Only tensions analysis for VAMPy project"
import wx
from wxgui import tension, resources
class tensVamPyApp(wx.App):
'''Actual wxPython application'''
def OnInit(self):
customartprovider = resources.CustomArtProvider()
wx.ArtProvider.Push(customartprovider)
... |
"""
Support for FRITZ!DECT Switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.fritzdect/
"""
import logging
from requests.exceptions import RequestException, HTTPError
import voluptuous as vol
from homeassistant.components.switch import (... |
# Generated by Django 3.0.8 on 2020-08-14 13:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timetableapp', '0003_auto_20200814_1834'),
]
operations = [
migrations.AlterField(
model_name='professor',
name='pro... |
PROFESSIONAL_KEY = 9527 # 系统设置
WECHAT_CONNECTED = 100 # socket连接
HEART_BEAT = 101 # 心跳
WECHAT_DISCONNECT = 102 # socket断开
WECHAT_LOGIN = 200 # 微信登录
WECHAT_LOGOUT = 201 # 微信登出
CHAT_MESSAGE = 202 # 聊天消息
GROUP_MEMBER_DETAILS = 203 # 群成员详情
GROUP_MEMBER_EVENT = 204 # 群成员变动
GET_ACCOUNT_DETAILS = 300 # 账号详情
GET_CONTA... |
from prometheus_client import Counter, Histogram
from django.conf import settings
from django_prometheus.utils import PowersOf, Time, TimeSince
DEFAULT_LATENCY_BUCKETS = (
0.01,
0.025,
0.05,
0.075,
0.1,
0.25,
0.5,
0.75,
1.0,
2.5,
5.0,
7.5,
10.0,
25.0,
50.0,
... |
import csv
def write_interactions(filename,no_agents,num_rings):
agent_set=set()
if no_agents%num_rings!=0:
raise ValueError('Number of agents is not divisible by number of rings')
num_ring_agents = no_agents//num_rings
for ring in range(num_rings):
for agent_index in range(num_ring_agents):
agent_set.ad... |
import uuid
import json
from datetime import datetime
SECONDS_IN_DAY = 60 * 60 * 24
class BaseFunctionBuilder():
def __init__(self, command_name):
self.command_name = command_name
def is_registered(self):
"""
Determines if function is already registered in redis database.
... |
import unittest
from string_permutation import check_inclusion
class StringPermutationTests(unittest.TestCase):
"""Tests for string permutation challenge."""
def test_case_1(self):
self.assertTrue(check_inclusion("ab", "eidbaooo"))
def test_case_2(self):
self.assertFalse(check_inclusio... |
from kinetica_proc import ProcData
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
import h2o
"""
This is a demonstration of how to use H2O for model learning and inference in a distributed Kinetica UDF.
This UDF is registered and executed from register_execute_train_test.py
The demo is based... |
'''
@Date: 2019-11-11 23:23:36
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-11-11 23:31:03
'''
import math
def isVaild(side1, side2, side3):
if side1 + side2 <= side3 or side2 + side3 <= side1 or side1 + side3 <= side2:
return False
else:
... |
from datetime import date
print('Qual seu sexo?'
'\n1 para feminino'
'\n2 para masculino')
s = int(input('\nInsira: '))
if s == 1:
print('Pessoas do sexo feminino não precisam se alistar obrigatoriamente.')
else:
ano = int(input('Digite seu ano de nascimento: '))
idade = date.today().year - ano
... |
# Generated by Django 2.0.6 on 2018-10-26 10:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='career',
field=m... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from unittest import TestCase
from uw_libraries.mylib import get_account, get_account_html
from uw_libraries.util import fdao_mylib_override
from restclients_core.exceptions import DataFailureException
from datetime import date
@f... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from .position import Grid, OmniscientReference, Point
class InputPoints(Exception):
pass
class NoOutput(Exception):
pass
class Solver:
""" The TSP Solver
Movement from point to point is tracked more on a Grid Basis than
a Point to Poin... |
"""Contains the test fixtures for making tests."""
from __future__ import absolute_import
from .hook import Hook
from .suite import Suite
from .test import Test
|
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
dicci = { 'a': '0', 'b':'1' , 'c':'2','d':'3','e':'4',
'f':'5','g':'6','h':'7','i':'8','j':'9'}
stringe = test.strip()
salida = ""
for i in stringe:
if i in dicci:
sal... |
"""
Simple handlers for serializers.
"""
BINARY_PROTOCOL = 'wamp.2.msgpack'
JSON_PROTOCOL = 'wamp.2.json'
NONE_PROTOCOL = ''
|
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
# 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.or... |
from conans import ConanFile, tools
import os
class CplexConan(ConanFile):
name = "CPLEX"
version = "12.7.1"
settings = {"os": ["Windows"],
"compiler": {"Visual Studio": {"version": ['14', '15']}},
"arch": ["x86_64"],
"build_type": ["Release", "Debug", "RelWithDebInfo"]}
descr... |
def lerarquivo(nome):
"""
:param nome: Nome do arquivo a ser lido
:return:Ser um retorno
"""
try:
arqui = open(nome, 'r')
except:
print('ERRO ao ler o arquivo!')
else:
a = arqui.read()
print('')
print(a)
print('')
arqui.close()
def l... |
import json
import os
import sys
import argparse
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir))))
from allennlp.data.dataset_readers.dataset_utils.text2sql_utils import process_sql_data
from allennlp.semparse.contexts.sql_context_utils import SqlVisitor, format_grammar_string
fr... |
from log import Log
import json
from typing import Dict
# https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html
class Config:
class __Config:
"""Singleton class for Config"""
def __init__(self, path: str):
self.path = path
self.log = Log("config")... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from .models import DiscussionMarker
from sqlalchemy.orm import load_only
def main():
for marker in DiscussionMarker.query.options(load_only("id", "identifier")).all():
print(marker.identifier)
if __name__ == "__main__":
main()
|
#-- GAUDI jobOptions generated on Fri Jul 24 17:14:59 2015
#-- Contains event types :
#-- 13100008 - 98 files - 2062195 events - 558.40 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass Step-124834
#-- StepId : 124834
#-- StepName : Reco14a for MC
#-- ApplicationName : B... |
from datetime import datetime
import nlp
import pandas as pd
from sklearn.preprocessing import StandardScaler
class PullRequestVectorizator:
def __init__(self):
self.nlp = nlp.nlp()
def getPRinfos(self, df) :
pr_df = df.iloc[:,:22]
pr_df = pr_df.drop_duplicates(subse... |
from bs4 import BeautifulSoup
import pprint
print('Begin Evil Zillow Scrape')
data = {}
with open('zillow.html', encoding='utf8') as fp:
soup = BeautifulSoup(fp, 'html.parser')
# URL
canonical_list = soup.find_all(rel='canonical')
data['url'] = canonical_list[0].attrs['href']
# Key Details: bedrooms, bathrooms,... |
from qiskit import *
from qiskit import Aer, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.opflow import StateFn, PauliSumOp, AerPauliExpectation, ListOp, Gradient
from qiskit.utils import QuantumInstance
from qiskit import IBMQ
provider=... |
# 어떤 걸 기준으로 먼저 시행해야 시간이 줄어들 수 있는지 생각해보자.
# (이전작업종료시간- 다음작업시작시간) + 다음작업걸리는시간 을 비교해서 짧은 걸 먼저 처리하자.
# 갯수 만큼의 리스트를 만들고, 1초가 지날 때 마다 업데이트 해주는 방식 > index의 문제가 있어서 불가능할 듯 ? >> index를 잘 설정해주는 방향으로 ..?
# 그냥 시작시간이랑 걸리는 시간으로 계산해서 나갈까 ?? >> 그럼 종료되었다는 걸 어떻게 표현할래 ?
import collections
def solution(jobs) :
list_implementing = ... |
fruits = ['apple', 'pear', 'grapefruit', 'pineapple', 'avocado']
fruits.append('blueberry') #'blueberry'添加到列表中
fruits.remove('apple') #将'apple'从列表中删除
position = fruits.index('pineapple') #判断'pineapple'是在什么位置
fruits.insert(position, 'lemon') #在'pineapple'前插入'lemon'
is_mango_in = 'mango' in fruits #判断'mango'是否在... |
# Author: Luigi Berducci
# Data: 06 Feb 2019
# Purpose: implement ID3 algorithm
from anytree import Node, RenderTree
from anytree.exporter import DotExporter
import pandas as pd
import math
import datetime
class ID3:
def __init__(self, data, dependentVariable):
self.tree = Node("Root")
self.data =... |
# zadanie 9
# Przepisz jeden z napisanych przez siebie iteratorów na generator.
#
# na potrzeby tego zadania przepisze iterator z zadania 7 na generator
def parzysty(dane):
for i in range(0, len(dane), 1):
yield dane[i]
liczby = parzysty([0, 1, 2, 3, 4, 5, 6, 7, 8])
print(next(liczby), end=', ')
... |
# Copyright 2020 Advanced Remanufacturing and Technology Centre
# Copyright 2020 ROS-Industrial Consortium Asia Pacific Team
#
# 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.apa... |
import argparse
def new_ui_entry(ns: argparse.Namespace):
from .app import run, init
init(ns=ns)
run(no_init=True)
def old_ui_entry(_: argparse.Namespace):
from .viewer_old import ui
ui.run()
def main():
args = argparse.ArgumentParser(description="Moons - Vicar Image Processing And Analysi... |
# encoding:utf-8
import sys
sys.path.append("..")
import numpy as np
from numpy.linalg import norm
from configx.configx import ConfigX
config = ConfigX()
def l1(x):
return norm(x, ord=1)
def l2(x):
return norm(x)
def normalize(rating, minVal=config.min_val, maxVal=config.max_val):
'get the normaliz... |
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
# option = webdriver.FirefoxProfile("/Users/nishu/Library/Application Support/Firefox/Profiles/2m3vd669.robot")
driver = webdriver.Chrome()
driver.get("https://ww... |
# Original Author: Codec04
# Re-built by Itz-fork
# Project: Gofile2
import os
from re import findall
from setuptools import setup, find_packages
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
# Requirements
if os.path.isfile('requirements.txt'):
with open('requirements.txt') as ... |
import sys
import os
from datetime import datetime
demo_dir = os.path.dirname(os.path.abspath(__file__))
taichi_elements_path = os.path.dirname(demo_dir)
sys.path.append(taichi_elements_path)
def create_output_folder(prefix):
folder = prefix + '_' + datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
os.mkdir(folde... |
#! /usr/bin/env python
"""
This file publishes a square trajectory for the kuka
"""
from scara_square_trajectory_publisher import SquareTrajectoryPublisher
import rospy
import rospkg
rospack = rospkg.RosPack()
import sys
sys.path.insert(0, rospack.get_path('first_assignment')+"/scripts")
from sensor_msgs.msg impo... |
import unittest
from queue import Queue, Empty
from unittest.mock import Mock
from cltl.combot.infra.event import Event
from cltl.combot.infra.event.memory import SynchronousEventBus
from cltl.combot.event.emissor import TextSignalEvent
from cltl.eliza.api import Eliza
from cltl_service.eliza.service import ElizaServ... |
#!/usr/bin/python
# -*- coding: latin-1 -*-
"""---------------------------------------------------------------------------------*
* Copyright (c) 2010-2018 Pauli Parkkinen, Eelis Solala, Wen-Hua Xu, *
* Sergio Losilla, Elias Toivanen, Jonas Juselius *
* ... |
"""
Tests for fm/negfc*.py (3D ADI cube)
"""
import copy
from .helpers import aarc, np, parametrize, fixture
from vip_hci.fm import (confidence, firstguess, mcmc_negfc_sampling,
nested_negfc_sampling, nested_sampling_results,
speckle_noise_uncertainty, cube_planet_free,... |
'''FLAsk support for OIDC Access Tokens -- FLAAT. A set of decorators for authorising
access to OIDC authenticated REST APIs.'''
# This code is distributed under the MIT License
# pylint
# vim: tw=100 foldmethod=indent
# pylint: disable=invalid-name, superfluous-parens
# pylint: disable=logging-not-lazy, logging-format... |
sim_setting_control = {
"interval": 1.0, # seconds of each step
"threadNum": 1, # this .so is single thread version, this parameter is useless
"saveReplay": True, # set to True if your want to replay the traffic in GUI
"rlTrafficLight": True, # set to True to control the signal
"changeLane": Fal... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2021/7/24 21:45
# @author : Mo
# @function: Layer and Loss
from torch import nn
import numpy as np
import torch
__all__ = ["PriorMultiLabelSoftMarginLoss",
"LabelSmoothingCrossEntropyV2",
"LabelSmoothingCrossEntropy",
"MultiLa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created at 2015-12-07T20:41:54.110455 by corral 0.0.1
# =============================================================================
# DOCS
# =============================================================================
"""carpyncho main loader
"""
# =============... |
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import login, get_user_model
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import get_list_or_404, get_object_or_404, ren... |
@annot('void -> void')
def test():
pass
def main():
test()
return 0
|
import gzip
import os
import subprocess
def get_chrom(cfile):
with gzip.open(cfile,'rb') as f:
next(f)
chrom = f.read().decode('utf-8').replace('\n','')
return chrom.upper()
def itoseq(seqint,kmer):
nucleotides = {0:'A',1:'C',2:'G',3:'T'}
binrep = 0
seq = ""
while(seqint > 0):
... |
from absl import app
from absl import flags
from absl import logging
import numpy as np
import os.path as path
from sklearn.model_selection import train_test_split
import transformations.reader.generic as generic_reader
import transformations.tfhub_module as tfhub_module
import transformations.torchhub_model as torchh... |
import argparse
import matplotlib.pyplot as plt
import os
import collections
from tqdm import tqdm
import numpy as np
import math
import torch
import torch.nn as nn
import torch.optim as optim
from .data import Dataset, DataLoader
#from .data.tickers import tickers_df, ticker_feature_count
from .data.tickers import Ti... |
import os, inspect
import matlab_web_desktop_proxy
import jupyter_matlab_proxy
from pathlib import Path
from matlab_web_desktop_proxy import mwi_environment_variables as mwi_env
def test_get_env():
port = 10000
base_url = "foo/"
actual_env_config = jupyter_matlab_proxy._get_env(port, base_url)
expec... |
blackList = []
ignoredList = []
# with open( 'webapp/helpFiles/tagsBlackList.txt' ) as file:
# blackList = file.read().split("\n")
# with open( 'webapp/helpFiles/tagsIgnoredList.txt' ) as file:
# ignoredList = file.read().split("\n")
def distanceBetweenDictionaries(query, gallery):
distance = 0
for key in query... |
class Board:
'''
A 3x3 board for TicTacToe
'''
__board = ''
__print_board = ''
def __init__(self):
self.__board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
self.make_printable()
def __str__(self):
self.make_printable()
return self.__print_board
... |
try:
from urllib import quote_plus #python 2
except:
pass
try:
from urllib.parse import quote_plus #python 3
except:
pass
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from djang... |
#!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
from refinenet.code.linemod_tools import LabelInfo
import time
import os
import json
import numpy as np
import glob
from evaluation.e... |
import sys
import re
import pandas as pd
import numpy as np
from tcrdist import repertoire_db
import warnings
def mixcr_to_tcrdist2(chain:str,
organism:str,
seqs_fn:str = None,
clones_fn:str = None):
"""
Converts .clns.txt or .result.txt ou... |
# MIT License
#
# Copyright (c) 2018 Evgeny Medvedev, evge.medvedev@gmail.com
#
# 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
# ... |
from PhysicsTools.Heppy.analyzers.gen.GeneratorAnalyzer import GeneratorAnalyzer
from PhysicsTools.Heppy.analyzers.gen.GenHeavyFlavourAnalyzer import GenHeavyFlavourAnalyzer
from PhysicsTools.Heppy.analyzers.gen.HiggsDecayModeAnalyzer import HiggsDecayModeAnalyzer
from PhysicsTools.Heppy.analyzers.gen.PDFWeightsAnalyze... |
from django.http import HttpResponse
from mii_sorter.tasks import sort
def start_sort(request):
sort.delay()
return HttpResponse('OK, sort started') |
"""
Contains all classes and functions that provide utility of some kind, such as
debug printing capability.
"""
class DebugConsole:
"""
Represents a simple mechanism for creating and writing colored output
messages to the console.
Attributes:
colors (dict): The dictionary of color codes to u... |
import sys
from clcrypto import generate_salt, check_password
from models import User, make_connection
import argparse
def configure_parser():
new_parser = argparse.ArgumentParser(prog='python manage_user.py')
new_parser.add_argument('-u', '--username')
new_parser.add_argument('-p', '--password')
new_... |
import numpy as np
from psopy import init_feasible
from psopy import minimize
from scipy.optimize import rosen
class TestQuick:
"""Quick simple tests for early validation."""
def test_unconstrained(self):
"""Test against the Rosenbrock function."""
x0 = np.random.uniform(0, 2, (1000, 5))
... |
"""
Operational Sutras
"""
from sanskrit_parser.base.sanskrit_base import SanskritImmutableString, SLP1
from decimal import Decimal
from copy import deepcopy
from sanskrit_parser.generator.paninian_object import PaninianObject
import logging
logger = logging.getLogger(__name__)
# Global Domains
class GlobalDomains(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.