content stringlengths 5 1.05M |
|---|
# Generated by Django 3.2.9 on 2022-01-04 21:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='profile_image',
... |
import asyncio
import sys
import logging
import json
from pymadoka.controller import Controller
from pymadoka.connection import discover_devices, force_device_disconnect
logger = logging.getLogger(__name__)
async def main(madoka):
try:
await force_device_disconnect(madoka.connection.address)
awa... |
#User provided customizations for the gpaw setup
import os
# compiler
compiler = './gcc.py'
mpicompiler = './gcc.py'
mpilinker = 'cc'
extra_compile_args = ['-std=c99']
# libz
libraries = ['z']
# libxc
library_dirs += [os.environ['LIBXCDIR'] + '/lib']
include_dirs += [os.environ['LIBXCDIR'] + '/include']
libraries +=... |
# Copyright 2021 Yan Yan
#
# 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, s... |
""" Tests for mrbaviirc.common.util.imp """
from __future__ import absolute_import
__author__ = "Brian AllenVanderburg II"
__copyright__ = "Copyright 2018"
__license__ = "Apache License 2.0"
import pytest
from mrbaviirc.common import imp
# Exporter
def test_exporter_symbol():
glbls = {"__package__"... |
from src.Exceptions import SemanticError
from src.Visitor import visitor
from src.pyPEG.MiniPascalGrammars import *
from src.SemanticAnalysis.Symbols import *
from src.SemanticAnalysis.SymbolTable import SymbolTable
VOID, INTEGER, REAL, BOOLEAN, STRING, ARRAY = BaseType.VOID, \
B... |
__all__ = [
'ABILITY_CATEGORIES', 'FLAGS', 'UNIQUE_FLAGS', 'B_NONE', 'S_NONE',
'S_ALL', 'S_ALL_UNIQUE', 'B_ALL',
'S_ADAPTIVE', 'S_PAWN', 'S_PAWN_UNIQUE', 'S_KING',
'S_TYPE', 'S_UNIQUE_TYPE', 'B_TYPE', 'B_UNIQUE_TYPE',
]
ABILITY_CATEGORIES = (
'adaptive', 'pawn', 'king',
)
B_NONE = 0
S_NONE = ()
S... |
import pandas as pd
import glob
import os
import pathlib
import numpy as np
import time
import datetime
import random
toys_path ='K:\Center for Autism and Brain Development\Data Center Documentation\DukeACT\EEG_EGT_upload\EEG\ACT T1 EEG Text Files 3-30 Hz\Toys' # use your path
socl_path = 'K:\Center for Au... |
# https://leetcode.com/problems/word-search/
# By Jiapeng
# Runtime: 364 ms, faster than 74.90% of Python3 online submissions for Word Search.
# Memory Usage: 15 MB, less than 71.50% of Python3 online submissions for Word Search.
# DFS框架参考4:此方法可以作为DFS参考框架
class Solution:
def exist(self, board: List[List[str]], wo... |
#!/bin/python
import pylab as pl
import cPickle
import matplotlib.pyplot as plt
from sklearn import svm, metrics
import numpy as np
import sys
square = 13
imgloc = '../images/v012-penn.10-1hA5D1-cropb.png'
resd={'dot':0,'noise':1,'vein':2}
currimg=plt.imread(imgloc)
pkl_file=open('dots.pkl', 'r')
dots = cPickle.load... |
#!/home/belgardt/bin/python2.6
from sys import stdin
for line in stdin:
la=line.rstrip('\n').split('\t')
my_str = la[0] + '\t' + \
str( int(la[1]) + int( la[10].split(',')[0] ) - 1 ) + '\t' + \
str( int( la[2] ) - int( la[10].split(',')[1] ) + 1 ) + '\t' + la[5]
print my_str
|
#!/bin/python3
import sys
from cluster.CassandraCluster import CassandraCluster
from consistency.consistencyBenchmark import runIncreasingLoadBenchmark
NORMAL_BINDING = 'cassandra-10'
CONSISTENCY_BINDING = 'cassandra_consistency'
IPS_IN_CLUSTER = ['172.16.8.16', '172.16.8.17', '172.16.8.18', '172.16.8.19']
DESTINATI... |
def determine_font_color(background_color):
background_color = hex_to_rgb(background_color)
r = background_color[0]
g = background_color[1]
b = background_color[2]
font_color = '#000000' if (r*0.299 + g*0.587 + b*0.114) > 186 else '#ffffff'
return font_color
def hex_to_rgb(value):
v... |
###############################################
# #
# PoC: Smartshark #
# #
# USAGE: #
# #
# Script to clean dataset... |
from sln_summ.tokenizer import tokenize_sentences_and_words
from sln_summ.sln_construction import make_sln_noun_verb_pronoun, SLN, make_sln_noun_verb_pronoun_prep_adj_adv
text = "Existing researches of Semantic Link Network (SLN) in text space neglect the literal relations, reasoning and genre structure. This paper p... |
PANEL = 'library'
PANEL_DASHBOARD = 'admin'
PANEL_GROUP = 'policy'
ADD_PANEL = 'congress_dashboard.library.panel.PolicyLibrary'
AUTO_DISCOVER_STATIC_FILES = True
|
import copy
import os
import shutil
from conans import tools
from conans.client.file_copier import FileCopier
class active_conanfile:
""" Handle variant conanfiles in scope.
Currently just patch the shared output.
"""
def __init__(self, conanfile):
self._conanfile = conanfile
self... |
import numpy as np
import pandas as pd
import mxnet as mx
import logging
logging.basicConfig(level=logging.DEBUG)
train1=pd.read_csv('data/train.csv')
train1.shape
train1.iloc[0:4, 0:15]
train=np.asarray(train1.iloc[0:33600,:])
cv=np.asarray(train1.iloc[33600:,:])
trainx=train[:,1:]
trainx.shape
cvx=cv[:,1:]
cvx.sha... |
import json
import kubernetes
import yaml
from apischema import serialize
from apischema.json_schema import deserialization_schema
from kubernetes import utils
from kubernetes.client.models.v1_object_meta import V1ObjectMeta
# ObjectMeta_attribute_map is simply the reverse of the
# V1ObjectMeta.attribute_map , which ... |
import flask
from bunny3.bunny import DEFAULT_SEARCH_ENGINE
def test_core_commands_loaded(test_bunny):
""" Test core commands are loaded """
assert "Google" in test_bunny.commands
assert "google" in test_bunny.aliasDict
assert test_bunny.commands["Google"]["func"].name == "Google"
assert "List" i... |
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Adafruit MacroPad shortcut macropad with light up keys that play a tone or wav file when a key is
pressed. Displays the associated key command being sent on key press in a grid matching the key
layout for easily view... |
from __future__ import absolute_import, print_function
import torch
from torch import nn
from torch.nn import functional as F
class MemAELoss(nn.Module):
def __init__(self, regularization_parameter=0.0002):
super(MemAELoss, self).__init__()
self.reg_param = regularization_parameter
def forwar... |
from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='scribe_logger',
version='1.2',
description='Scribe log writer and logging han... |
import setuptools
def content_of(fpath):
with open(fpath, "r") as fd:
return fd.read()
setuptools.setup(
name="tox-battery",
description="Additional functionality for tox",
long_description=content_of("README.rst"),
license="http://opensource.org/licenses/MIT",
version="0.6.2",
a... |
# ---------------------------------------------------------------------------
# Copyright 2017-2018 OMRON Corporation
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 16:20:09 2019
@author: jonathan
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 12:14:51 2019
@author: jonathan
"""
base = \
'''
╔══════════════════════════════════════════════════════════════════════════════╗
║ ... |
import random
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import SimilarityTransform
from constants import TARGET_IMG_WIDTH, TARGET_IMG_HEIGHT
# -- Face extraction --
# Target transformation facial landmarks
# that are used for similarity transformation
#
# Reference point ... |
import glob
import json
wavfiles = glob.glob('/home/joseph/Desktop/LENA_praat/OLD PROTOCOL/**/*.wav', recursive = True)
wavfiles.sort()
import random
random.seed(0)
random.shuffle(wavfiles)
trainfiles = wavfiles[:80]
testfiles = wavfiles[80:]
print(len(trainfiles), len(testfiles))
def findmap(wavfile):
try:
... |
a = 1
print('there are', len(a.__dir__()), 'members of int')
print('they are', ', '.join(a.__dir__()))
|
from activation_functions import softmax_function
from cost_functions import softmax_cross_entropy_cost
from tools import dropout, add_bias
import numpy as np
default_settings = {
# Optional settings
"weights_low" : -0.1, # Lower bound on initial weight range
"weights_high" :... |
from .. import core
class TimestepObjectCache(object):
"""A temporary store for all objects in a timestep, allowing objects to be resolved without a further database query"""
def __init__(self, timestep):
"""Query the database for all objects in this timestep
:type timestep: core.TimeStep"""
... |
"""
Objects dealing with any sort of spatial and temporal filtering of output.
Spatial
-------
- `_find_indices` -- Find indices for a given lat/lon point on a meshgrid.
- `extract_region` -- Directly extracts a subset of a dataset.
"""
import numpy as np
def _find_indices(xgrid, ygrid, xpoint, ypoint):
"""
... |
# Generated by Django 3.2.3 on 2021-07-16 09:36
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CustomUser',
fields=[
('id', models.BigAuto... |
from django.contrib import messages
from saefportal.settings import MSG_SUCCESS_JOB_SAVED, MSG_SUCCESS_JOB_DELETED, MSG_SUCCESS_JOB_UPDATED
from ..models import Job
from ..forms import AddJobForm, UpdateJobForm
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth.decorators import ... |
# Team 4
import face_recognition
import cv2
import exifread
from loading_images import *
class Face:
possible_composition = "straight", "left-side", "right-side", "portrait", None
def __init__(self, photo, date_taken, path, composition=None, face=None):
self.photo = photo
self.date_taken = da... |
from utils.getter import *
from datasets.udacity_dataset import UdacityDataset
from models.regressor import Regressor
from losses.mseloss import MSELoss
import torchvision.transforms as tf
import os
import pandas as pd
from sklearn.model_selection import train_test_split
import torch.utils.data as data
import torch
im... |
from django.core.management import call_command
from django.test import TestCase
from frontend.models import Practice
class InferPracticeBoundariesTestCase(TestCase):
fixtures = ["orgs", "practices"]
def test_basic_smoketest(self):
should_have_boundary = Practice.objects.filter(
setting... |
import tensorflow as tf
import json
with open('Hyper_Parameters.json', 'r') as f:
hp_Dict = json.load(f)
class Encoder(tf.keras.layers.Layer):
def build(self, input_shapes):
self.layer_Dict = {}
self.layer_Dict['Label_Embedding'] = tf.keras.layers.Embedding(
input_dim= hp_Dict... |
"""``runway destroy`` command."""
# docs: file://./../../../docs/source/commands.rst
import logging
from typing import Any, Tuple # pylint: disable=W
import click
from ...core import Runway
from .. import options
from ..utils import select_deployments
LOGGER = logging.getLogger(__name__.replace("._", "."))
@click... |
# This contribution was made by: Rajat Sethi
# Date: 12/15/2020
import logging
import re
import aiohttp
import discord
import discord.ext.commands as commands
import bot.bot_secrets as bot_secrets
import bot.extensions as ext
from bot.consts import Colors
from bot.messaging.events import Events
log = logging.getLog... |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) 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
# "L... |
import getopt
import sys
from ..models import AUTOSAR, ARPackage, AtomicSwComponentType, VariableAccess, SwComponentType, DataTypeMappingSet
from ..models import SwcInternalBehavior, ImplementationDataType
from ..models import PortPrototype, RPortPrototype, PPortPrototype
from ..models import SenderReceiverInterface, ... |
########################################################################
# $Header: /var/local/cvsroot/4Suite/test/Xml/Xslt/Exslt/test_datetime.py,v 1.2 2006/01/04 16:00:55 jkloth Exp $
"""Tests for EXSLT Dates and Times"""
import re
from Ft.Lib import boolean, number
from Ft.Xml.Xslt.Exslt import DateTime
DATE = r'... |
# Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
# 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 later
# version.
#
# This program... |
"""
A plugin that lets you traverse a directory and process it's files
and sub-directories
"""
import os
import re
import confu.schema
import ctl
from ctl.docs import pymdgen_confu_types
@pymdgen_confu_types()
class MatchConfig(confu.schema.Schema):
"""
Configuration schema that maps a plugin
action ... |
# Copyright 2016 Luc Saffre
#
# License: BSD (see file COPYING for details)
"""Database models for this plugin.
"""
from __future__ import unicode_literals
# import logging
# logger = logging.getLogger(__name__)
from lino.api import dd, _
from lino.mixins import BabelNamed, Referrable
# users = dd.resolve_app('u... |
#!/usr/bin/env python3
# Advent of Code 2020
# Glenn G. Chappell
import sys # .stdin, .argv
import itertools # .combinations
# ======================================================================
# HELPER FUNCTIONS
# ======================================================================
def is_sum(va... |
import mss
import numpy as np
from PIL import Image
from config import BOARD_HEIGHT, BOARD_WIDTH
CELL_SIZE = 22
BOARD_X = 14
BOARD_Y = 111
COLOR_CODES = {
(0, 0, 255): 1,
(0, 123, 0): 2,
(255, 0, 0): 3,
(0, 0, 123): 4,
(123, 0, 0): 5,
(0, 123, 123): 6,
(0, 0, 0): 7,
(123, 123, 123): 8,
(189, 189, 189): 0 #uno... |
import logging
import os
import re
import sys
from kensu.utils.kensu_provider import KensuProvider
def setup_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format)
def setup_kensu_tracker(
... |
"""
Write integration tests for your model interface code here.
The TestCase class below is supplied a `container`
to each test method. This `container` object is a proxy to the
Dockerized application running your model. It exposes a single method:
```
predict_batch(instances: List[Instance]) -> List[Prediction]
```
... |
# ======================================================================
#
# sets the parameters and economic functions for the model
# "Growth Model"
#
# The model is described in Scheidegger & Bilionis (2017)
# https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2927400
#
# Simon Scheidegger, 01/1... |
import moonleap.resource.props as P
from moonleap import (
MemFun,
StoreOutputPaths,
create,
extend,
feeds,
kebab_to_camel,
rule,
)
from moonleap.render.storetemplatedirs import StoreTemplateDirs
from moonleap.verbs import has, runs, uses
from . import props
from .resources import Service, ... |
# -*- coding: utf-8
#Exercício 01:
#for
nota = media = soma = 0
print(nota, media, soma)
for _ in range(1,6):
nota = float(input('Digite a nota: '))
soma += nota
print(soma)
media = soma/5
print('A media é: ', media)
print()
#mesmo exercício com while:
nota = soma = 0
numero = 1
while numero <=5:
nota =... |
#!/usr/bin/python3
def string_match(a, b):
count = 0
for i in range(min(len(a), len(b)) - 1):
if a[i:i+2] == b[i:i+2]: count += 1
return count
def assert_eq(a, b):
print(f"\tAct:{a}==Exp:{b}")
assert(a == b)
def test():
print(f"Test ({__file__}):")
assert_eq(string_match('abc', 'abc'), 2)
assert_e... |
# Generated by Django 2.2.7 on 2019-11-22 05:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('forum', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='topic',
... |
class Turtle:
def __init__(self,num):
self.num=num
class Fish:
def __init__(self,num):
self.num=num
class Pool:
def __init__(self):
self.turtle=Turtle(20)
self.fish=Fish(29)
def pirintNum(self):
print('现在水池里面有%d只乌龟,%d条鱼'%(self.turtle.num,self.fish.num))
... |
#!/usr/bin/python
########################################################################################################################
#
# Copyright (c) 2014, Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permi... |
# -*- coding: utf-8 -*-
# Copyright 2012 splinter 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 .fake_webapp import EXAMPLE_APP
class StatusCodeTest(object):
def test_should_visit_index_of_example_app_and_get_200_status_c... |
r"""
Graded modules with basis
"""
#*****************************************************************************
# Copyright (C) 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
# 2008-2011 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General... |
class UserNotifyEvent:
ACCOUNT_CONFIRMATION = "account_confirmation"
ACCOUNT_PASSWORD_RESET = "account_password_reset"
ACCOUNT_CHANGE_EMAIL_REQUEST = "account_change_email_request"
ACCOUNT_CHANGE_EMAIL_CONFIRM = "account_change_email_confirm"
ACCOUNT_DELETE = "account_delete"
ACCOUNT_SET_CUSTOME... |
import os, sys, socket, urllib2
from xml.dom import minidom
import xbmc, xbmcgui, xbmcaddon
if sys.version_info < (2, 7):
import simplejson
else:
import json as simplejson
__addon__ = xbmcaddon.Addon()
__addonname__ = __addon__.getAddonInfo('name')
__addonid__ = __addon__.getAddonInfo('id')
__version_... |
from typing import List
from datetime import datetime
from github.Issue import Issue
from common import Common
_PYTHON_OWNER = {'msyyc', 'BigCat20196', 'Wzb123456789', 'kazrael2119'}
_PYTHON_REPO = 'Azure/azure-sdk-for-python'
_FILE_OUT_NAME_PYTHON = 'sdk_issue_python.md'
class Python(Common):
def collect_open... |
from cyberpunk.processing import parse_query, process_args
def test_process_args():
output = process_args("celtic_pt2.mp3", {"reverse": "true"})
assert output == ("processed_celtic_pt2.mp3.mp3", "audio/mp3")
def test_parse_query():
output = parse_query(
"audio.mp3",
{"reverse": "true", ... |
from __future__ import absolute_import
import uuid
import pytest
from django.conf import settings
from django.core.management import call_command
from django.core.urlresolvers import reverse
from django.db.utils import OperationalError
from django.test.testcases import TransactionTestCase
from django_concurrent_tests... |
import numpy as np
import datasets
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import cStringIO
class Graphs:
def __init__(self):
# self.nGraphs=number_of_graphs
self.cmaps=['Greys', 'GnBu', 'YlOrRd']
self.ss=[100,300,750]
self.markers=['o'... |
from datetime import datetime
import gc
import os
import time
import sys
sys.path.append(os.path.expanduser('~/.snap/snap-python'))
import snappy
from snappy import GPF
from snappy import (ProductIO, ProgressMonitor)
jpy = snappy.jpy
imageIO = jpy.get_type('javax.imageio.ImageIO')
File = jpy.get_type('java.io.File')
... |
# Import Libraries
import os
import cv2
import glob
import pandas as pd
import xml.etree.ElementTree as ET
import numpy as np
import tensorflow as tf
from object_detection.utils import config_util
from object_detection.protos import pipeline_pb2
from object_detection.utils import label_map_util
from object_detection.ut... |
from __future__ import absolute_import
from django.apps import AppConfig
class Config(AppConfig):
name = "auth_gitlab"
def ready(self):
from sentry import auth
from .provider import GitLabOAuth2Provider
auth.register('auth_gitlab', GitLabOAuth2Provider) |
color_aliceblue = 'aliceblue'
color_antiquewhite = 'antiquewhite'
color_aqua = 'aqua'
color_aquamarine = 'aquamarine'
color_azure = 'azure'
color_beige = 'beige'
color_bisque = 'bisque'
color_black = 'black'
color_blanchedalmond = 'blanchedalmond'
color_blue = 'blue'
color_blueviolet = 'blueviolet'
color_brown = 'brown... |
import os
import sys
import time
import unittest
import numpy as np
import torch
from torch.nn import functional as torch_F
from src.dpln.nn import functional as dpln_F
from src import dpln
from ..utils import np_feq
class TestConv2d(unittest.TestCase):
def test_conv2d_1(self):
for _ in range(100):
... |
from tir import Webapp
import unittest
from datetime import datetime
DateSystem = datetime.today().strftime("%d/%m/%Y")
class FATA530(unittest.TestCase):
@classmethod
def setUpClass(self):
self.oHelper = Webapp()
self.oHelper.Setup("SIGAFAT", DateSystem, "T1", "D MG 01 ", "05")
self.... |
#!/usr/bin/env python
a_list = range (8)
a_list.append ( {} )
a_list[-1]['ip_addr'] = '10.10.0.1'
a_list[-1]['mask'] = '255.255.255.0'
from pprint import pprint as pp
pp(a_list)
import json
import yaml
with open ("ex.yml", "w") as f:
yaml.dump( a_list, f, default_flow_style = False)
with open ("ex.json"... |
import pytest
from textx_ls_core.languages import LanguageTemplate
@pytest.fixture(scope="session", autouse=True)
def lang_template():
"""Test language template fixture."""
class TestLangTemplate(LanguageTemplate):
@property
def extensions(self):
return ['.test']
@property... |
signos_compatibles = {
# (mujer, hombre)
('aries', 'tauro'),
('aries', 'geminis'),
('aries', 'cancer'),
('aries', 'libra'),
('aries', 'escorpion'),
('aries', 'sagitario'),
('aries', 'acuario'),
('tauro', 'tauro'),
('tauro', 'leo'),
('tauro', 'virgo'),
('tauro', 'escorpion'... |
#!/usr/bin/env python3
import os
from datetime import datetime
from datetime import time
try:
import psycopg2
except:
print("You need to install the dependencies from requirements.txt")
exit(-1)
CONNECTION_STRING = 'dbname=news'
SQL_ARTICLES = """
SELECT title, qtd FROM articles a INNER JOIN
(SELEC... |
import os
import argparse
import logging
import mxnet as mx
from rec2idx import IndexCreator
DATASET_URL = 'http://data.mxnet.io/data/val_256_q90.rec'
def main():
logging.basicConfig()
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
parser = argparse.ArgumentParser(description='D... |
#!/bin/python3
'''
Copyright 2022 Joaquín Cuéllar.
This file is part of Hola Mundo Especial.
Hola Mundo Especial 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 3 of the ... |
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import os
import time
import numpy as np
import sys
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
from torchvision.transforms import TenCrop, Resize, Lambda, CenterC... |
import torch
import torch.nn as nn
from copy import deepcopy
# Import Binary net
from ..layers.binary_layers import LinearBin, ShiftNormBatch1d, BinConv2d
# Import Dorefa net
from ..layers.dorefa_layers import DorefaConv2d, LinearDorefa
# Import Xnor net
from ..layers.xnor_layers import XNORConv2d, LinearXNOR
# I... |
# -*- coding: utf-8 -*-
import csv
with open("GamWin_convert_test.tsv") as fd:
rd = csv.reader(fd, delimiter="\t", quotechar='"')
in_items = []
for row in rd:
if row[0][0] != "!":
new_row = (row[1], row[3], row[5])
in_items.append(new_row)
print("['%s', '%s', '%s']," % (new_row[0], new_row... |
"""
Logic to represent a game of Tetris.
"""
import random
from util import CallbackProperty, colors
GAME_PIECE_DIMENSION = 4 # game pieces are presented by a 4 x 4 pixel array
class GameState:
"""
Provide an enum of game states
"""
@property
def playing(self):
""" Represent the playing s... |
'''Reads a a set of HMIS CSV files into memory, parses their contents, and stores
their informaton into a postgresql database. This is a log database, so it holds
everything and doesn't worry about deduplication. The only thing it enforces
are exportids, which must be unique.'''
#import sys, os
from .reader impor... |
import matplotlib.pyplot as plt
import numpy as np
def visualize(line,data,fig):
line.set_ydata(data)
fig.canvas.draw()
fig.canvas.flush_events()
return
def init_vis(CHUNK):
fig, ax = plt.subplots(figsize=(14,6))
x = np.arange(0, 2 * CHUNK, 2)
ax.set_ylim(-200, 200)
ax.set_xlim(0, CHUNK) #make sure our x axi... |
# Copyright 2021 Zilliz. 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 agree... |
from typing import Any
from grpc import StatusCode
__all__ = (
"InvestError",
"RequestError",
"AioRequestError",
)
class InvestError(Exception):
pass
class RequestError(InvestError):
def __init__( # pylint:disable=super-init-not-called
self, code: StatusCode, details: str, metadata: A... |
import uuid
import string
import random
import sys
sys.path.insert(0, '../')
from spa_packet import *
password = 'thisisapassword'
seed = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))
aid = uuid.uuid4().hex
ip = "127.0.0.1"
port = 342
new_seed = ''.join(random.choice(string.ascii_up... |
from datetime import datetime
from typing import Iterable, Dict
import pytz
from nalomu.orm import Session_T
class Mixin(object):
__tablename__ = None
__table_args__ = {'extend_existing': True}
def save(self, *, session: Session_T) -> bool:
if hasattr(self, 'updated_at'):
setattr(se... |
class TensorboardSerializerMixin(object):
def get_tensorboard(self, obj):
return obj.tensorboard.id if obj.tensorboard else None
|
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
import ui
from ... enums import *
UI_LINE_CAP = {
LINE_CAP_BUTT: ui.LINE_CAP_BUTT,
LINE_CAP_SQUARE: ui.LINE_CAP_SQUARE,
LINE_CAP_ROUND: ui.LINE_CAP_ROUND}
UI_LINE_JOIN = {
LINE_JOIN_BEVEL: ui.LINE_JOIN_BEVEL,
LINE_JOIN... |
from django.shortcuts import render,redirect
from fbvApp.models import Student
from fbvApp.forms import StudentForm
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def getStudents(request):
students = Student.objects.all()
return render(request,'fbvApp/index.... |
from __future__ import annotations
from argparse import RawTextHelpFormatter, ArgumentParser, Namespace
from pathlib import Path
from typing import List
from src import const
def parse_arguments(args: List[str]) -> Namespace:
parser = init_praser()
ret = parser.parse_args(args)
validate_arguments(parser... |
from opentrons import protocol_api
from opentrons import labware
from opentrons import instruments
import csv
import re
metadata = {
'protocolName': 'Single head transfer',
'author': 'Oliver Chen <olichen@ucdavis.edu',
'description': 'Read in volumes from a CSV file and transfer volumes',
'apiLevel': '... |
from .__version__ import __version__
from .core import load |
from statsd.connection import Connection
from statsd.client import Client
from statsd.timer import Timer
from statsd.gauge import Gauge
from statsd.average import Average
from statsd.raw import Raw
from statsd.counter import Counter, increment, decrement
__all__ = [
'Client',
'Connection',
'Timer',
'Co... |
# Title: 연결 요소의 개수
# Link: https://www.acmicpc.net/problem/11724
import sys
sys.setrecursionlimit(10 ** 6)
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
class Graph:
def __init__(self, n):
self.childs = [[] for _ in range(n+1)]
def add_node(self, a, b)... |
import os
import time
import requests,ssl
import argparse
import sys
import json, re
import getpass
from pprint import pprint
import logging
logging.captureWarnings(True)
logger = logging.getLogger('ncc_app')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(leveln... |
from unittest import TestCase
from unittest.mock import Mock
import interfaces
from core.wl import *
from core.wl.object import MockObject
class TestUnresolvedObject(TestCase):
def test_resolves_to_object_returned_by_db(self):
o = UnresolvedObject(7, None)
db = Mock(spec=interfaces.ObjectDB)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Date : 2016-10-13 15:54:38
# @Author : Yunyu2019 (yunyu2010@yeah.net)
# @Link :
# @descp : The document description
import os
import re
import json
import copy
import time
import codecs
import requests
from lxml import etree
from bs4 import Beautifu... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
class Embedding(nn.Module):
def __init__(self, word_vec_mat, max_length, word_embedding_dim=50, pos_embedding_dim=5):
nn.Module.__init__(self)
self.max_length = max_length
se... |
from typing import Dict
_codes: Dict[int, str] = {
# Debug (1xxxx)
# System (100xx)
10000: 'Test debug',
# Pipe (103xx)
10301: 'Reindexing parser',
# Resolver (109xx)
10901: 'Executing catalog',
10902: 'Executing target',
10903: 'Catalog executed',
10904: 'Target executed',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.