content stringlengths 5 1.05M |
|---|
from .wso import WSO
|
# -*- coding: utf-8 -*-
class BackoffGenerator(object):
"""Generates a sequence of values for use in backoff timing"""
def __init__(self, initial_value, max_value=None, exponent=2):
"""Sets the initial value, max value, and exponent for the backoff"""
super(BackoffGenerator, self).__init__()
... |
import calendar
import re
import datetime
class InvalidCard(Exception):
pass
class CardNotSupported(Exception):
pass
class CreditCard(object):
# The regexp attribute should be overriden by the subclasses.
# Attribute value should be a regexp instance
regexp = None
# Has to be set by the us... |
import os
from pathlib import Path, PurePath
DEFAULT_CONFIG = """
- files_location:
path: REPO_LOCATION
- files:
"""
CONFIG_PATH = str(PurePath(os.environ.get("MOJETO_CONFIG_LOCATION", str(PurePath(Path.home(), ".config", "mojeto"))),
".mojeto"))
CONFIG_OVERRIDE_QUESTION = "Mojeto conf... |
from pathlib import Path
from oneibl.one import ONE
import alf.io
from brainbox.core import Bunch
import qt
import numpy as np
import pyqtgraph as pg
import atlaselectrophysiology.ephys_atlas_gui as alignment_window
import data_exploration_gui.gui_main as trial_window
# some extra controls
class Ali... |
# -*- coding: utf-8 -*-
#******************************************************************************************
# Copyright (c) 2019
# School of Electronics and Computer Science, University of Southampton and Hitachi, Ltd.
# All rights reserved. This program and the accompanying materials are made available under
#... |
import argparse
from sdsparser.parser import SDSParser
from sdsparser.configs import Configs
from tqdm import tqdm
import csv
import os
import pprint
import sys
from tabulate import tabulate
def tabulate_sds_data(request_keys, sds_data):
print('='*100)
headers = ['file name'] + request_keys
out = list()... |
# coding: utf-8
# ML parameters.
import os
import torch
# Train params
BATCH_SIZE = int(os.environ.get('BATCH_SIZE', '32'))
EPOCHS = int(os.environ.get('EPOCHS', '50'))
EARLY_STOPPING_TEST_SIZE = float(os.environ.get('EARLY_STOPPING_TEST_SIZE', '0.2'))
LEARNING_RATE = float(os.environ.get('LEARNING_RATE', '0.01'))... |
import paramiko
import shlex
import subprocess
def ssh_command(ip, port, user, passwd, command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, port=port, username=user, password=passwd)
ssh_session = client.get_transport().open_session()
... |
import numpy as np
class GridWorld:
def __init__(self, states, initial_state, transition_table, reward_table, terminal_table):
self.states = states
self.initial_state = initial_state
self.transition_table = transition_table
self.reward_table = reward_table
self.terminal_tab... |
from setuptools import setup, find_packages
with open("requirements.txt") as f:
install_requires = f.read().strip().split("\n")
# get version from __version__ variable in order_packing/__init__.py
from order_packing import __version__ as version
setup(
name="order_packing",
version=version,
description="This mod... |
from django.contrib import admin
from gc_apps.gis_basic_file.models import GISDataFile
from shared_dataverse_information.dataverse_info.admin import DataverseInfoAdmin
class GISDataFileAdmin(DataverseInfoAdmin):
"""
Use the ModelAdmin from DataverseInfoAdmin and extend it to include GISDataFile specific fie... |
"""Constants for the securitas direct integration."""
# domain
DOMAIN = "securitas_direct"
# configuration properties
CONF_COUNTRY = "country"
CONF_LANG = "lang"
CONF_INSTALLATION = "installation"
# config flow
STEP_USER = "user"
STEP_REAUTH = "reauth_confirm"
MULTI_SEC_CONFIGS = "multiple_securitas_configs"
UNABLE_... |
"""merge bd438447496a and fd0f86cc5705
Revision ID: bcdf1134f0df
Revises: bd438447496a, fd0f86cc5705
Create Date: 2017-09-27 11:14:01.763062
"""
# revision identifiers, used by Alembic.
revision = 'bcdf1134f0df'
down_revision = ('bd438447496a', 'fd0f86cc5705')
branch_labels = None
depends_on = None
from alembic imp... |
from Themes.Check import Check
from Themes.AbsolutePin import AbsolutePin
themes = [Check(), AbsolutePin()]
|
# occiput - Tomographic Inference
# Stefano Pedemonte
# Harvard University, Martinos Center for Biomedical Imaging
# Dec. 2013, Boston, MA
from __future__ import absolute_import, print_function
from . import Shapes
|
from . import providers
def socialaccount(request):
ctx = { 'providers': providers.registry.get_list() }
return dict(socialaccount=ctx)
|
# flake8: noqa
from catalyst.contrib.runners import *
|
# -*- coding: UTF-8 -*-
from django import forms
from apps.postitulos.models import ValidezNacional
from apps.registro.models import Establecimiento, Anexo, Jurisdiccion
from apps.postitulos.models import CohortePostitulo
ANIOS_COHORTE_CHOICES = [('', '-------')] + [(i, i) for i in range(CohortePostitulo.PRIMER_ANIO,... |
"""
Test Factory to make fake objects for testing
"""
import factory
from factory.fuzzy import FuzzyChoice, FuzzyFloat
from service.models import Supplier
class SupplierFactory(factory.Factory):
"""Creates fake suppliers"""
class Meta:
"""Meta class
"""
model = Supplier
id = facto... |
from helper import greeting
def main():
greeting("Doing something really simply by using helper.py to print this message.")
if __name__=='__main__':
main()
|
import sys
import itertools
#print "This is the name of the script: ", sys.argv[0]
#print "Number of arguments: ", len(sys.argv)
#print "The arguments are: " , str(sys.argv)
use_circle_of_fifths = False
includeArpeggios = False
includeBackupArpeggiosOnly = True
UNIQUE_NOTES_MODE = True
IncludeAllOutput = False
colour... |
#!/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
"License");... |
import sys
def print_help():
print('Syntax: py charcases.py <path/to/input/file> <encoding> <path/to/output/file>')
def gen_case_permutations_matrix(n):
matrix_str = [bin(x)[2:].rjust(n, '0') for x in range(2 ** n)]
matrix = []
for line_str in matrix_str:
permutation = []
for digit ... |
import gi
gi.require_version('Gst', '1.0')
|
#
# Copyright (c) SAS Institute 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 w... |
import csv
import psycopg2
def seed_table(conn):
# evidence: id, link
with open('dbsetup/training_data.csv', 'r') as f:
reader = csv.reader(f)
next(f) # skipping the header row
# order: id 6, link 13
data = []
for row in reader:
# Converts strin... |
input_id = input('id : ')
id = 'joshua'
if input_id == id:
print('Welcome')
# if input_id != id:
# print('Who?')
else:
print('Who?') |
# -*- coding: utf-8 -*-
from flask import Markup
from flask.ext.wtf import Form
from wtforms import (ValidationError, HiddenField, BooleanField, TextField,
PasswordField, SubmitField)
from wtforms.validators import Required, Length, EqualTo, Email
from flask.ext.wtf.html5 import EmailField
from ..utils impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Negamax import Negamax
class HumanPlayer:
def __init__(self, sign):
self.sign = sign
def get_move(self, board, opponent):
while True:
move = raw_input()
if self.__is_valid(move, board):
break
... |
import copy
from collections import OrderedDict
from .run import Run
from .tables import Tables
class ParameterSet:
def __init__(self, ps_id, simulator, params):
"""
Note
---
Do not call the constructor directory.
Instead, use `simulator.find_or_create_parameter_set` metho... |
# ----------------------------------------------------
# Test Bench for Chess AI v1.0.2
# Created By: Jonathan Zia
# Last Edited: Thursday, May 10 2018
# Georgia Institute of Technology
# ----------------------------------------------------
import tensorflow as tf
import numpy as np
import pieces as p
import random as ... |
from lxml import html,etree
from urllib.parse import urljoin
import requests
import os, pyodbc
import pandas as pd
import csv
url='https://www.yelp.com/search?find_desc=Restaurants&find_loc=Cleveland%2C+OH'
server='HASNAIN2020'
database='YELP_RESTAURANTS'
table='REVIEWS'
def main():
... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import subprocess
import unittest
import unittest.mock
from antlir.common import run_stdout_to_err... |
import re
class Day13Solution:
def __init__(self):
file = open("day13.txt", "r")
self.start = int(file.readline())
line = file.readline()
self.buses = [int(i) for i in re.findall("(?P<num>\d+)", line)]
self.items = line.split(",")
def partOne(self) -> int:
w... |
import logging
import os
import json
import azure.functions as func
from azure.data.tables import TableClient
from azure.core.exceptions import HttpResponseError
from furl import furl
import requests
from azure.data.tables import UpdateMode
BASE_URL = "http://dev.virtualearth.net/REST/V1/Routes/Driving"
L... |
import unittest
from isobutane import *
class TestMethods(unittest.TestCase):
def test_get_oxygen_volume_of_air(self):
self.assertAlmostEqual(
get_oxygen_volume_of_air(100),
21
)
def test_get_air_volume_of_oxygen(self):
self.assertAlmostEqual(
get_... |
def is_valid_password(candidate: int) -> bool:
has_two_adjacent_digits = False
has_increasing_digits = True
digits = [int(digit) for digit in str(candidate)]
previous_digit = digits[0]
repeat_count = 0
for digit in digits[1:]:
if digit < previous_digit:
has_increasing_d... |
from releash import *
myself = add_package(".", "releash")
myself.version_source = VersionSource(myself, 'releash.py')
myself.version_targets.append(VersionTarget(myself, 'releash.py'))
myself.release_targets.append(ReleaseTargetSourceDist(myself))
myself.release_targets.append(ReleaseTargetGitTagVersion(myself.version... |
# Created on Mar 9, 2012
#
# @author: Richard Plevin
# @author: Sam Fendell
# @author: Ryan Jones
#
# Copyright (c) 2012-2015. The Regents of the University of California (Regents)
# and Richard Plevin. See the file COPYRIGHT.txt for details.
'''
This module includes contributions by Sam Fendell and Ryan Jones.
'''
fro... |
from rest_framework.serializers import (
ModelSerializer,
)
from articles.models import Articles
class ArticleSerializer(ModelSerializer):
class Meta:
model = Articles
fields = [
'id',
'title',
'body',
'img',
]
def create(self, vali... |
import pandas as pd
class File:
def __init__(self, fs, filename, bucket):
self.headers, self.order, self.temp_values, self.fs, self.filename, self.bucket = {},{},{},fs,filename,bucket
self.process()
def process(self):
if self.filename != None:
with self.fs.open(self.bu... |
import argparse
import datetime
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from tqdm import tqdm
from cltl.brain import LongTermMemory
def readCapsuleFromFile(jsonfile):
f = open(jsonfile, )
scenario = json.load(f)
return scenario
def main(log_path):
# Create brai... |
# Copyright 2015 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.
"""Logging utilities, for use with the standard logging module."""
import logging
def InitLogging(verbose_count):
"""Ensures that the logger (obtained ... |
import pytest # NOQA
from SuzuriTest import SuzuriTest
class TestClass(SuzuriTest):
@pytest.mark.parametrize('productId, limit, offset', [
(2737748, 30, 100),
])
def test_getFavoriteOfProduct(self, client, productId, limit, offset):
r = client.getFavoriteOfProduct(productId, limit, offse... |
import itertools
import json
import multiprocessing
import re
import networkx as nx
from quantlaw.utils.beautiful_soup import create_soup
from quantlaw.utils.files import list_dir
from quantlaw.utils.networkx import multi_to_weighted
from statics import DE_DECISIONS_NETWORK, DE_DECISIONS_REFERENCE_PARSED_XML
def co... |
import sublime_plugin
from .scopes import *
from .parse import get_sub_scopes
class MenuNode():
"""
Attributes:
view - sublime view into text buffer
scope - scope object associated with this node
parent - the parent of this node in the hierarchy tree.
this node is root... |
class CP2Kinput:
def __init__(self, version, year, compile_date, compile_revision):
self.version = version
self.year = year
self.compileDate = compile_date
self.compileRevision = compile_revision
@staticmethod
def __check_input_attribs(lxml_root):
root_attributes = [... |
import ctypes
import os
import six
from cupy import cuda
MAX_NDIM = 25
def _make_carray(n):
class CArray(ctypes.Structure):
_fields_ = (('data', ctypes.c_void_p),
('size', ctypes.c_int),
('shape', ctypes.c_int * n),
('strides', ctypes.c_int *... |
# Copyright 2021 The NetKet 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
from utils import pmts
from collections import namedtuple
from kivy.clock import Clock
from kivy.core.text import Label
from kivy.graphics import Color, Rectangle
from kivy.uix.widget import Widget
from kivy.metrics import pt
from kivy.uix.behaviors.focus import FocusBehavior
from annotations import Annotation
from c... |
import argparse
import torch
def args_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default='fmnist',
help="dataset we want to train on")
parser.add_argument('--num_agents', type=int, default=10,
help="number o... |
author_special_cases = {
"Jeanette Hellgren Kotaleski": ("Jeanette", "Hellgren Kotaleski"),
"Hellgren Kotaleski J": ("Jeanette", "Hellgren Kotaleski"),
"João Pedro Santos": ("João Pedro", "Santos"),
"Yi Ming Lai": ("Yi Ming", "Lai"),
"Luis Georg Romundstad": ("Luis Georg", "Romundstad"),
"Joha... |
import cv2
import numpy as np
import sys
sys.path.append('../')
from object_detection.feature_extraction.main import extract_hog_features, extract_features_single_img
from object_detection.color_hist.main import color_hist
from object_detection.bin_spatial.main import bin_spatial
from object_detection.hog.main import H... |
import os
from pykgr.subroutines import import_from_string
class Builder(object):
data = None
def __init__(self, **kwargs):
self.data = BuilderData(**kwargs)
if not self.data.directory:
raise Exception("What can we do without a directory?")
if not os.path.exists(self.dat... |
def friend_or_foe(x):
return [ f for f in x if len(f) == 4 ]
import unittest
class TestFriendOrFoe(unittest.TestCase):
def test_friend_or_foe(self):
self.assertEquals(
friend_or_foe(['Ryan', 'Kieran', 'Mark',]), ['Ryan', 'Mark'])
if __name__ == '__main__':
unittest.main()
|
import cv2
import numpy as np
import dlib
cap = cv2.VideoCapture(0)
#refer to the 68-face-landmarks-labeled-by-dlib-software-automatically.png to understand why certain coordinates are used to find certain parts of the face
detector = dlib.get_frontal_face_detector() #front face classifier
predictor = dlib... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Tue Mar 6 14:49:49 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attr... |
# terrascript/data/clc.py
import terrascript
__all__ = []
|
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
import sys, datetime
from CovBedClass import *
from pk2txt import bdgmsg, newmsg
class NormalizeProtocol(object):
def __init__(self, args):
#latestage, protocol=1, earlystage=False, pseudo=0.1, bandwidth=2500, quiet=False, impute=False, replace=False, replace_with='0', replace_this='.'
self.args =... |
import math
import os
import re
import tempfile
from pprint import pformat, pprint
from shutil import copy, copyfile, rmtree
from typing import Callable, Optional, Tuple, Union
from beartype import beartype
from rich import print as rich_print
from rich.console import Console
from rich.panel import Panel
from rich.tab... |
#!/usr/bin/python
import os
import subprocess
#import parmiko
#ssh = paramiko.SSHClient()
#ssh.connect('192.168.1.22', username=root, password=cloud123)
#ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(ls)
createCmd = "ssh root@192.168.1.22 sh scale_machine.sh"
subprocess.check_call(createCmd,shell=True)
|
from pathlib import Path
import datetime
import logging
import tensorflow as tf
from vesper.util.settings import Settings
import vesper.util.yaml_utils as yaml_utils
_TRAINING_DATA_DIR_PATH = Path(
'/Users/harold/Desktop/NFC/Data/Vesper ML/NOGO Coarse Classifier 0.0')
_MODEL_DIR_PATH = _TRAINING_DATA_DIR_PATH... |
from keras.models import Model
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import AveragePooling2D
from keras.layers.pooling import GlobalAveragePooling2D
from keras.layers import Input, merge
from keras.layers.normalization imp... |
''' show_ntp.py
Parser for the following show commands:
* show ntp detail
returns NTP configuration
'''
# Python
import re
# Metaparser
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Schema, Any, Optional
# ====================================================
# schema f... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = 42
print('Hello, World.{}'.format(x))
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import collections
class BBox(object):
def __init__(self):
self.xmin = self.xmax = None
self.ymin = self.ymax = None
def update(self, pt):
if self.xmin is None:
self.xmin = self.xmax = pt[0]
self.ymin = ... |
from pyspider.core.model.mysql_base import *
"""
每天的门店库存备份
"""
class ShopSkuDayStock(Model):
id = IntegerField(primary_key=True)
back_up_day = IntegerField(verbose_name='备份日期,截止到当日24时静态数据')
sku = CharField(verbose_name='skuBarCode')
warehouse_id = IntegerField(verbose_name='仓库ID')
shop_id = Integ... |
# -*- coding: utf-8 -*-
#
# This file is part of Sequana software
#
# Copyright (c) 2016-2020 - Sequana Development Team
#
# File author(s):
# Thomas Cokelaer <thomas.cokelaer@pasteur.fr>
#
# Distributed under the terms of the 3-clause BSD license.
# The full license is in the LICENSE file, distributed with t... |
# This is the configuration for fpm-config-generator. It exists in its own file
# because then a script can automatically update it easier.
global systemGroups
global groupName
global configTemplate
global outputDir
global customConfigs
systemGroups = "group" #where the list of secondary groups are.
groupName = "users... |
# listGroupConnectors
# Returns a list of information about all connectors within a group in your Fivetran account.
# Reference: https://fivetran.com/docs/rest-api/groups#listallconnectorswithinagroup
import fivetran_api
# Fivetran API URL (replace {group_id} with your group id)
url = "https://api.fivetran.com/v1/gr... |
"""
Test lockdown decorator
"""
# third-party imports
import webapp2
# local imports
from .utils import DecodeError
from .utils import decode
from .utils import encode
from .decorators import locked_down
from .mixins import LockedDownMixin
from nacelle.test.testcases import NacelleTestCase
# test fixtures: we need t... |
from dpsniper.attack.dpsniper import DPSniper
from dpsniper.classifiers.classifier_factory import LogisticRegressionFactory
from dpsniper.classifiers.torch_optimizer_factory import SGDOptimizerFactory
from dpsniper.search.ddconfig import DDConfig
from dpsniper.search.ddsearch import DDSearch
from dpsniper.input.input_d... |
# Generated by Django 3.0.6 on 2020-05-29 02:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("review", "0004_auto_20200512_1526"),
]
operations = [
migrations.AddField(
model_name="review", name="comments", field=models.Te... |
# -*- coding: utf-8 -*-
import os
from .helpers import display_title_header
from .commands import Commands
__version__ = "0.2.1"
def main():
display_title_header(__version__)
cmd = Commands(os.getcwd())
cmd.run()
|
#!/usr/bin/env python2
from __future__ import print_function
import os
import multiprocessing
import re
import shutil
import argparse
filesRemaining = []
botScores = {}
import random
from rgkit.run import Runner, Options
from rgkit.settings import settings as default_settings
def make_variants(variable, robot_file, po... |
"""Fixed tracks only being able to have one artist
Revision ID: 2528a69ac8e8
Revises: 8bd75fcafb3f
Create Date: 2020-05-09 23:54:46.757844
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "2528a69ac8e8"
down_revision = "8bd75fcafb3f"
branch_labels = ()
depends_on... |
from sklearn.model_selection import train_test_split
def split(x, y):
return train_test_split(x, y, test_size = 0.2, random_state =0) |
#!/usr/bin/env python3
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import os
import unittest
import jsonschema
class GoofyGhostSchemaTest(unittest.TestCase):
def loadJSON(self, na... |
from .base import *
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
if config("DJANGO_SECRET_KEY", default=None) is None:
raise RuntimeError(
"To start django with production conf the environment variable DJANGO_SECRET_... |
#!/usr/bin/env python3
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import torch
import pytest
import poptorch
def test_loop_constant():
class Model(torch.nn.Module):
def forward(self, x):
def body(x):
return x * 2
return poptorch.for_loop(10, body, [x... |
input_ = '1321131112'
def number(nb, time):
a = 0
while a<time:
for i in range(len(nb)):
if i == 0:
w = ''
v = nb[i]
c = 0
if nb[i] == v:
c += 1
if nb[i] != v:
w += str(c) + v
... |
from hash_power_client import HashPowerClient
if __name__ == "__main__":
slave = HashPowerClient(
server_address=("zjlab-1", 13105),
)
print(slave.get_system_info())
# print(slave.allocate_gpus(num_gpus=2, exclusive=False, mem_size=10e9))
# print(slave.allocate_gpus(num_gpus=2, exclusive=T... |
"""
Chat urls module
"""
from django.urls import path
from django.contrib.auth.decorators import login_required
from .views import Conversations
urlpatterns = [
path(
'chats/',
login_required(Conversations.ChatList.as_view()),
name='chat-list'),
path(
'chat/create/',
... |
from lxml import html
import re
import requests
from datetime import timedelta, datetime, date
class NrsrSpider:
name = 'NRSRspider'
from_date = date(2016, 3, 23)
to_date = date(2016, 3, 27)
period = '7'
increment = timedelta(days=1)
selector_class = '.alpha.omega'
url = "https://www.nrsr.... |
from robotpy_ext.autonomous import timed_state, StatefulAutonomous
class ThreeToteHot(StatefulAutonomous):
MODE_NAME = 'Three Totes'
DEFAULT = False
def initialize(self):
self.angle = 0
#self.register_sd_var('driveSpeed', .3)
#self.register_sd_var('rotateLeftT... |
import ctrnn
import min_cog_game
if __name__ == "__main__":
gtype = input()
num_input = 5
num_hidden = 2
num_output = 2
num_weights = num_hidden*(num_input + num_hidden) + num_output*(num_hidden + num_output)
num_biases = num_hidden + num_output
num_gains = num_hidden + num_output
num... |
"""Make predictions using encoder."""
# pylint: disable=no-name-in-module
from json import load
import numpy as np # type: ignore
from PIL import Image # type: ignore
from click import command, option, Path # type: ignore
from dataset import process_img
from model import HYP_FILE
from center import CENTERS_FILE
from... |
import numpy as np
import torch
from .normalize import normalize
from sklearn.neural_network import BernoulliRBM
import matplotlib.pyplot as plt
def generate_ensembles(attributions, methods, rbm_params, device="cpu"):
size = [len(methods)] + list(attributions.shape)[1:]
e = torch.empty(size=size).to(device)... |
#!/usr/bin/env python3
from collections import Counter
def isValid(s):
one_leeway = False
freqs = dict(Counter(s))
most_common_freq = Counter(freqs.values()).most_common(1)[0][0]
for k in freqs:
if freqs[k] != most_common_freq:
if not one_leeway and (abs(freqs[k] - most_common_fre... |
import csv
from collections import Counter
from pathlib import Path
from random import choice
BATTLE_CARD_FILE = "battle-table.csv"
class BattleCard:
def __init__(self, mapping: dict = None):
self.mapping = mapping
@property
def attackers(self):
if self.mapping:
return [x for... |
import struct
import json
import binascii
import os
import argparse
from collections import OrderedDict
DEFAULT_FILE_VERSION = "v0.1"
APPEARED_TYPES = {}
def read_bytes_as_hex(f, length):
return str(binascii.hexlify(f.read(length)), encoding="ascii")
def write_hex_as_bytes(f, hex):
f.write(binascii.unhexlify... |
from ..proxy import ObjectProxy
from ..specification import FirstCall, AlteredCall, Call
from .story import Story
from .given import Given
from .manipulation import Manipulator, Append, Remove, Update, \
CompositeManipulatorInitializer
story = ObjectProxy(Given.get_current)
response = ObjectProxy(lambda: story.r... |
# Copyright (C) 2015 Catalyst IT Ltd
#
# 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 o... |
import sys
import os
import yaml #PyYAML must be installed
import languageSwitcher
import CPlusPlusLanguageSwitcher
import CLanguageSwitcher
import JavaLanguageSwitcher
import PythonLanguageSwitcher
from UnsupportedLanguageException import *
sys.path.append("../util")
from Util import supportedLanguages
class Langua... |
"""djangoProject1 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home... |
import cv2
from frame_info import FrameInfo
class ImageProcessor:
def __init__(self, camera, threshold, perspective_transform, lane, lane_validator, lane_mask_factory, logger):
self.camera = camera
self.threshold = threshold
self.perspective_transform = perspective_transform
self.... |
# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The experiment runner module."""
from __future__ import print_function
import getpass
import os
import shutil
import time
import afe_lock_machine
... |
from ..utils import Object
class GetUser(Object):
"""
Returns information about a user by their identifier. This is an offline request if the current user is not a bot
Attributes:
ID (:obj:`str`): ``GetUser``
Args:
user_id (:obj:`int`):
User identifier
Returns:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.