content stringlengths 5 1.05M |
|---|
import torch
from collections import OrderedDict
from torch.autograd import Variable
import util.util as util
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import pudb
class UnetCNNModel(BaseModel):
def name(self):
return 'UnetCNNModel'
def initialize(... |
from pandas import read_csv
from .establish_fai_index import establish_fai_index
def get_chromosome_size_from_fasta_gz(fasta_gz_file_path):
establish_fai_index(fasta_gz_file_path)
return read_csv(
"{}.fai".format(fasta_gz_file_path),
sep="\t",
header=None,
usecols=(0, 1),
... |
import os
class TestCase:
def __init__(self, name):
self.name = name
|
#Copyright 2018 KAIST under XAI Project supported by Ministry of Science and ICT, Korea
#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
# https://www.apache.org/licenses/LICENSE-2.0
#Unless ... |
import os
import socket
def create_fds():
(sk1, sk2) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
(sk3, sk4) = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
return [(sk1.makefile("wb"), sk2.makefile("rb")),
(sk3.makefile("wb"), sk4.makefile("rb"))]
def __sock_ino(sockf):
... |
"""
RabinKarp1 vs RabinKarp2 vs RabinKarp3 execution time
"""
import matplotlib.pyplot as plt
from plot_utils import generate_legend_label
text_lengths = [100000]
pattern_lengths = [25, 50, 100, 300, 500]
algs = ['rabin_karp1', 'rabin_karp2', 'rabin_karp3']
for text_len in text_lengths:
for alg in algs:
... |
def main():
with open('../input/input04.txt','r') as f:
lower, upper = [int(i) for i in f.read().replace('\n','').split('-')]
counter = { str(i)+str(j)+str(k)+str(l)+str(m)+str(n)
for i in range(10)
for j in range(i,10)
for k in range(j,10)
for l in range(k,10)
for m in rang... |
import pandas as pd
# A function to summarize detection of bins in different groups designated by 3-letter sample prefixes
import pandas as pd
def summarize(detection_file, output):
# Read detection table, with bin names as indexes:
detection = pd.read_csv(detection_file, sep='\t', index_col='bins')
... |
# -*- coding: utf-8 -*-
import subprocess
from pathlib import Path
CODE = """
import sys
from pathlib import Path
sys.path.insert(0, str(Path(".")))
import dataiter as di
import numpy as np
di.PRINT_MAX_ITEMS = 3
di.PRINT_MAX_ROWS = 10
di.PRINT_MAX_WIDTH = 72
"""
def get_output(lines):
try:
return subpr... |
import argparse
import numpy as np
import gym
import roboschool
from tf2rl.algos.apex import apex_argument, run
from tf2rl.algos.ddpg import DDPG
from tf2rl.misc.target_update_ops import update_target_variables
if __name__ == '__main__':
parser = apex_argument()
parser.add_argument('--env-name', type=str,
... |
from util1113a import util1113_print
print "main"
util1113_print()
|
# version of the cvdata package, should match with setup.py
__version__ = "0.0.7"
|
from typing import Any, Awaitable, Callable
import asyncio
import json
class Server:
def __init__(self, *, port: int, host: str = "127.0.0.1"):
self._port = port
self._host = host
self._actions = {}
def add_action(self, action: str, callback: Callable[[Any], Awaitable[str]]):
... |
"""
Copyright 2020 Fazt Community ~ All rights reserved. MIT license.
"""
from datetime import datetime
from typing import Optional
from ..database import session
from ..enums import ModerationType
from ..models import Moderation
from . import create_one, paginate
def moderate(
moderation_type: ModerationType,
... |
from __future__ import absolute_import, division, print_function
import numpy as np
from skbeam.core import roi
import numpy.random
import skimage.draw as skd
from scipy.ndimage.morphology import binary_dilation
import skbeam.core.image as nimage
import pytest
from numpy.testing import assert_equal, assert_array_almos... |
"""JUnit metric collector."""
from datetime import datetime
from dateutil.parser import parse
from base_collectors import SourceUpToDatenessCollector, XMLFileSourceCollector
from collector_utilities.functions import parse_source_response_xml
from collector_utilities.type import Response
class JUnitSourceUpToDatene... |
from injector import singleton, inject, Injector
from .store import StoreClient
from .config import ConfigModule
from .data_builder import DataBuilder
from .data_log import DataLog
from .sensor_factory import SensorFactory
from .store import StoreModule
INJECTOR = Injector(
[StoreModule(), ConfigModule()])
@sin... |
import time
import typing as tp
from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
from satella.coding.concurrent.sync import sync_threadpool
from satella.coding.concurrent.monitor import Monitor
from satella.coding.recast_exceptions import silence_excs
from satella.coding.typing import V... |
from __future__ import unicode_literals
import pytest
import sys
from dtypes.linked_list import LinkedList, Node
#######################################################################
# Fixtures, helpers, and testing constants
#######################################################################
INSTANTIATION_ARG_1... |
def foo_function(debugger, args, result, dict):
print >>result, ("foobar says " + args)
return None
|
# Copyright 2020 Jack Brokenshire
# 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... |
import logging
from .constants.common import AUTHORIZATION_CODE_TYPE, LOGIN_SCOPE, \
DEFAULT_SUPER_TENANT, TOKEN_RESPONSE, REDIRECT, URL, USER
from .constants.token import STATE, ACCESS_TOKEN, ID_TOKEN, ID_TOKEN_JWT
from .constants.user import USERNAME
from .exception.asgardeo_auth_error import AsgardeoAuthError
f... |
import os
import yaml
class Config(dict):
def __init__(
self, file_config: str = None, dict_config: dict = None, env_prefix: str = None
) -> None:
super().__init__()
if file_config:
with open(file_config) as f:
self.update(**yaml.load(f, Loader=yaml.FullLo... |
# Import everything needed to edit video clips
from moviepy.editor import *
from PIL import Image, ImageFont, ImageDraw
import numpy as np
import textwrap
class VideoSplitter:
def __init__(self) -> None:
self.output_video_cover = """your video conver text"""
self.output_video_length = 60
s... |
from unittest import mock
import random
import uuid
from faker import Factory
import pytest
import pendulum
from django.conf import settings
from django.db import DatabaseError
from share.harvest.base import FetchResult
from share.harvest.exceptions import HarvesterConcurrencyError
from share.models import Source
... |
import pytest
from iexfinance.stocks import get_ipo_calendar
class TestIPOCalendar(object):
@pytest.mark.xfail(reason="Endpoint temporarily disabled by provider.", strict=True)
def test_ipo_calendar(self):
data = get_ipo_calendar()
assert isinstance(data, list)
def test_ipo_calendar_bad... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('../browser_interface/proxy')
class ProxyFactory(object):
def create(self, type, area, host='localhost', port=0, **kwargs):
return getattr(__import__(type), type)(area, host=host, port=port, **kwargs)
|
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from matplotlib.lines import Line2D
NAME = 'adv'
path_heat_seq = ['heat1_strong/output/000002/result/result.dat', 'heat2_strong/output/000004/result/result.dat', 'heat3_strong/output/000035/result/result.dat']
path_adv_seq = ['adv1_strong/output/... |
import os
class Config:
FLASK_ADMIN_SWATCH = 'cosmo'
SECRET_KEY = 'chave secreta'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URI']
SQLALCHEMY_TRACK_MODIFICATIONS = os.environ['DATABASE_TRACT_MODIFICATONS']
|
# $LicenseInfo:firstyear=2010&license=mit$
# Copyright (c) 2010, Linden Research, Inc.
#
# 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... |
from django.conf.urls import url,include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^blogapp/',include('blogapp.urls',namespace='blogapp')),
url(r'^admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=s... |
# The MIT License (MIT)
#
# Copyright (C) 2015 - Julien Desfossez <jdesfossez@efficios.com>
# 2015 - Antoine Busque <abusque@efficios.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 t... |
""" COCO, VOC, OpenImages dataset configurations
Copyright 2020 Ross Wightman
"""
import os
from dataclasses import dataclass, field
from typing import Dict
@dataclass
class CocoCfg:
variant: str = None
parser: str = 'coco'
num_classes: int = 80
splits: Dict[str, dict] = None
@dataclass
class Coco2... |
from __future__ import print_function
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="ticks")
sns.set_context("poster")
plt.rcParams["font.family"] = "Helvetica"
import sys, os
from nested_dict import nested_dict
import pandas as pd
import numpy as np
from p... |
from pyDatalog import pyDatalog
from tp_utils import run_env
hash_fn = run_env.get_extra()['options']['HASH_FN']
Action_output = 1
Action_output_reg = 2
Action_output_max_len = 3
Action_output_group = 4
Action_normal = 5
Action_flood = 6
Action_all = 7
Action_local = 8
Action_output_inport = 9
Action_enqueue = 20
Act... |
# coding=utf-8
from astwro.sampledata import fits_image
from astwro.coord import xy2sky, skycoo2xy, skyradec2xy
import astropy.units as u
def test_xy2sky():
coo1 = xy2sky(100,121,fits_image())
coo2 = xy2sky([100,100], [120,121], fits_image())
assert coo1.ra == coo2[1].ra
assert coo1.ra > 301*u.deg
... |
from .exit_code import ExitCode # NOQA
from .message import Message # NOQA
from .prompt import Prompt # NOQA
from .query import Query # NOQA
|
import itertools
from random import randint
deck = [ 'Ah', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Th', 'Jh' ,'Qh', 'Kh',
'Ac', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Tc', 'Jc' ,'Qc', 'Kc',
'As', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'Ts', 'Js' ,'Qs', 'Ks',... |
import inspect
import sys
'''
khazix
'''
def main():
# Have to account for unix vs windows
modulename = sys.argv[0]
if modulename.count('\\'):
modulename = modulename.split('\\')[-1].split('.')[0]
else:
modulename = modulename.split('/')[-1].split('.')[0]
module... |
"""curses.panel
Module for using panels with curses.
"""
__revision__ = "$Id: panel.py 36560 2004-07-18 06:16:08Z tim_one $"
from _curses_panel import *
|
# 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"); you may ... |
#!/usr/bin/env python3
# Copyright 2018 Canonical 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 la... |
import importlib.resources as pkg_resources
import arcade
from lyricdesigner import __version__
from lyricdesigner.data import charts
from lyricdesigner.views.start import StartView
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
SCREEN_TITLE = f"LyricDesigner {__version__}"
arcade.enable_timings()
class MyGame(arcade.W... |
from tensorflow import keras
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.text import Tokenizer
model = keras.models.load_model('GRU_model.h5')
word_to_index = imdb.get_word_index()
tokenizer = Tokenizer()
max_len = 30 |
from onesecmail import Mail
email = Mail()
print(email)
|
answer_filename='g0pA_taskb.txt'
n=3
answer_row = complete_df.loc[complete_df['File'] == answer_filename]
task = answer_row['Task'].values[0]
answer = answer_row['Text'].values[0]
source = complete_df.loc[(complete_df['Datatype'] == 'orig') &
(complete_df['Task'] == task... |
import numpy as np
import matplotlib.pyplot as plt
class View:
def __init__(self):
plt.ion()
self.board = np.zeros((4, 4), dtype=np.uint64)
_, self.view = plt.subplots()
def add_tile(self, new_tile, new_loc):
self.board[new_loc] = new_tile
def reset_view(self):
s... |
import ConfigParser
import optparse
import os.path
import subprocess
METRICS_CONFIG_FILENAME = 'eventually.conf'
PATHS_CONFIG_FILENAME = 'paths.conf'
def get_config(base_dir):
metrics = ConfigParser.SafeConfigParser()
paths = ConfigParser.SafeConfigParser()
base_dir = os.path.abspath(base_dir) + os.path.... |
"""
A preprocessing script that samples N points
"""
import sys
from multiprocessing import Pool
import numpy as np
import os
import trimesh
import pickle
from metrics import get_signed_distance
from tqdm import tqdm
np.random.seed(7)
N = 1000 # default value
part_output_dir = '/orion/u/ianhuang/superquadric_parsin... |
import pickle
import os
import logging
from tensorflow.keras.models import load_model
from tensorflow.keras.callbacks import ModelCheckpoint
from .callbacks import EpochCounter, HistoryLogger
from .utils import merge_dicts_with_only_lists_as_values
class ResumableModel(object):
"""Save and overwrite a model every '... |
# coding: utf8
from setuptools import setup, find_packages
__author__ = 'Tharun Mathew Paul (tmpaul06@gmail.com)'
setup(
name='unklearn_python_runtime',
version='0.1',
description='Python runtime for Unklearn notebooks',
author='Tharun Mathew Paul',
author_email='tmpaul06@gmail.com',
license='... |
# coding=utf-8
# reticular setup.py
from distutils.core import setup
setup(
name="reticular",
py_modules=["reticular"],
version="0.0.10",
description="Lightweight module to create powerful command-line tools",
author="Héctor Ramón Jiménez",
author_email="hector0193@gmail.com",
url="https://... |
import discord
import asyncio
import random
import os
import sys
from config import *
client = discord.Client()
token = sys.argv[1]
@client.event
async def on_ready():
print("Started Image Spam")
while not client.is_closed:
UpImage = random.choice(os.listdir(DirPictures))
... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import serializers
from . import RankSerializer
from ...core.serializers import MutableFields
User = get_user_model()
__all__ = ["StatusSerializer", "UserSerializer", "UserCardSerializer"]
class StatusSerializer(seri... |
from embedKB.models.base import GeneralFramework
import tensorflow as tf
from embedKB.utils import debug
class NeuralTensorNetwork(GeneralFramework):
name = 'NeuralTensorNetwork'
def __init__(self,
n_entities,
entity_embed_dim,
n_relationships,
... |
# web/tests/component/__init__.py
|
"""GUI Application for blink detection and seed identification"""
try:
import cv2
import heapq
import json
import os.path
import rngtool
import signal
import sys
import threading
import time
import tkinter as tk
import tkinter.filedialog as fd
from tkinter import ttk
... |
from requests import Response
from fixtures.login.model import LoginUser
from fixtures.validator import Validator
from common.deco import logging as log
class Auth(Validator):
def __init__(self, app):
self.app = app
POST_AUTH = "/auth"
@log("Login user")
def login(self, data: LoginUser, typ... |
from nnGame import Game
from nnSolve import nnSolve
from nnGreedySolve import nnGreedySolve
from nnIpoptSolve import nnIpoptSolve
from learn import LearnNN
import time
import numpy as np
import matplotlib.pyplot as plt
import copy
if __name__ == '__main__':
seed = 99
K = 12
K2 = 24
K3 = 12
L = 100
... |
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from platon_env.base.host import Host
class Process:
def __init__(self, host: 'Host', name=None, base_dir=None, port=None, pid=None):
self.host = host
self.name = name
self.base_dir = base_dir
self.port = port
self.pi... |
#!/usr/bin/python3
# 다음 코드를 실행하기 위해서는 protobuf3, six 모듈이 필요합니다.
from . import simple_message_pb2
import uuid
def create_new_msg():
new_msg = simple_message_pb2.SimpleMessage()
new_msg.name = u'문자열'
new_msg.num64 = 12345
new_msg.float64 = 12345.6
new_uuid = uuid.uuid4()
print('new_uuid={0}'.fo... |
#!/usr/bin/env python
# stdlib imports
import os.path
import subprocess
# local imports
from product.constants import CFG
def get_command_output(cmd):
"""
Method for calling external system command.
Args:
cmd: String command (e.g., 'ls -l', etc.).
Returns:
Three-element tuple conta... |
map_dict = {
'الف': 'alef',
'ب': 'be',
'پ': 'pe',
'ت': 'te',
'ث': 'se',
'ج': 'jim',
'چ': 'che',
'ح': 'heh',
'خ': 'khe',
'د': 'dal',
'ذ': 'zal',
'ر': 're',
'ز': 'ze',
'ژ': 'zhe',
'س': 'sin',
'ش': 'shin',
'ص': 'sad',
'ض': 'zad',
'ط': 'ta',
... |
def get_backend_url(route):
name, spec = _init_route(route)
return spec['backend-url']
def get_frontend_hostname(route):
_, spec = _init_route(route)
root_domain = spec['root-domain']
sub_domain = spec['sub-domain']
return f'{sub_domain}.{root_domain}'
def pre_deployment_hook(route, labels):... |
from invoke import task
@task
def mytask(ctx):
pass
|
# (c) @SpEcHIDe
# (c) @AlbertEinsteinTG
# (c) @Muhammed_RK, @Mo_Tech_YT , @Mo_Tech_Group, @MT_Botz
# Copyright permission under MIT License
# All rights reserved by PR0FESS0R-99
# License -> https://github.com/PR0FESS0R-99/DonLee_Robot/blob/main/LICENSE
import logging
import re, random, asyncio, aiofiles, aiofiles.os... |
"""Definition of class Entry and all evaluation related functions"""
import re
from datetime import datetime
class Entry(object):
"""This class represents one arxiv entry"""
def __init__(self, id: str, title: str,
authors: list, abstract: str, category: str = "",
date_submit... |
"""
Main module providing the application logic.
"""
import sys
# from textwrap import dedent
from collections import OrderedDict
import clingo
import clingoext
from pprint import pprint
class AppConfig(object):
"""
Class for application specific options.
"""
def __init__(self):
self.ecling... |
def solve(n, s):
ans = ""
for i in range(len(s)):
if s[i] == 'E':
ans += 'S'
else:
ans += 'E'
return ans
T = int(input())
for i in range(T):
n = int(input())
s = input()
print("Case #%d: %s" % (i+1, solve(n, s))) |
import json
class SdsStreamIndex(object):
"""Sds Stream Index definitions"""
@property
def sds_type_property_id(self):
return self.__sds_type_property_id
@sds_type_property_id.setter
def sds_type_property_id(self, sds_type_property_id):
self.__sds_type_property_id = sds_type_prop... |
"""
https://github.com/joe-siyuan-qiao/WeightStandardization
https://arxiv.org/abs/1903.10520
MIT License
Copyright (c) 2017 Wei Yang
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 wi... |
from .text_cnn import TextCNN
# from .text_lstm import TextLSTM
# from .fast_text import FastText
# from .text_bert import TextBERT
|
'''LogisticRegression by Alabs (https://www.instagram.com/aealabs/)'''
import numpy as np
class LogisticRegression(object):
'''Run logistic Regression.
Initialize an object and call the 'apply' function in this class.
Use the 'pred' method to predict with given X or 'pred_prob' to output the probabilities.
Use... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for `{{ cookiecutter.driver_name }}`
"""
import unittest
from driver import PowerService
class TestPowerSerivce(unittest.TestCase):
def __init__(self):
pass
def setUp(self):
pass
def tearDown(self):
pass
def test_00... |
from collections import defaultdict, namedtuple
import flask
import pytest
from voluptuous import Schema
from conftest import CODE_1, CODE_2, add_permissions, check_json_response
from core import APIException, cache, db
from core.hooks.before import check_rate_limit
from core.users.models import User
from core.utils ... |
from flask_caching import Cache
from flask import request
cache = Cache(config={'CACHE_TYPE': 'simple', 'CACHE_DEFAULT_TIMEOUT': 5 * 60})
def make_cache_key(*args, **kwargs):
path = request.path
args = str(hash(frozenset(request.args.items())))
return path + args
|
#
# Copyright (C) 2021 GrammaTech, Inc.
#
# This code is licensed under the MIT license. See the LICENSE file in
# the project root for license terms.
#
# This project is sponsored by the Office of Naval Research, One Liberty
# Center, 875 N. Randolph Street, Arlington, VA 22203 under contract #
# N68335-17-C-0700. Th... |
from cc3d import CompuCellSetup
from .scientificHistBarPlotsSteppables import HistPlotSteppable
from .scientificHistBarPlotsSteppables import BarPlotSteppable
CompuCellSetup.register_steppable(steppable=HistPlotSteppable(frequency=1))
CompuCellSetup.register_steppable(steppable=BarPlotSteppable(frequency=1))
CompuCel... |
from django.db import transaction
from rest_framework import serializers
from .models import Store, Item, Price, Coin
from .utils.auth import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('pk', 'username')
read_only_fields = ['pk', '... |
from settings.common import *
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
... |
# -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.auth import get_user_model
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import signal
import sys
import time
from unipath import P... |
import tornado.template
import tornado.ioloop
import tornado.web
import os, pwd, grp
def drop_privileges(uid_name='ctf', gid_name='ctf'):
running_uid = pwd.getpwnam(uid_name).pw_uid
running_gid = grp.getgrnam(gid_name).gr_gid
os.setgroups([])
os.setgid(running_gid)
os.setuid(running_uid)
old... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 19:45:33 2018
@author: anne
"""
import numpy as np
from beamforming import Fft, PowerSpectra, cls
cls
nfft=2048
print('nfft:',nfft)
#print(nfft)
nchannels = 2
t = np.linspace(0,1,nfft+1)
# print(t)
x1 = (np.cos(4*np.pi*t[:-1])+3.2*np.sin(6*np.pi... |
# Copyright (c) 2022 {{cookiecutter.author_name}}
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"""Version information for {{cookiecutter.project_name}}.
This file is imported by ``{{cookiecutter.package_name}}.__init__``, and parsed by
``setup.py``.
"""
# Note, that dev... |
def search_matrix(matrix, target):
if matrix is None or len(matrix) == 0 or matrix[0] is None or len(matrix[0]) == 0:
return False
m = len(matrix)
n = len(matrix[0])
start = 0
end = m * n - 1
while start + 1 < end:
mid = (start + end) // 2
if matrix[mid // n][mid % n] <... |
from itertools import chain
import resource
class Theme(object):
def __init__(self):
self._styles = {}
def set(self, class_name, state, key, value):
self._styles.setdefault(class_name, {}).setdefault(state, {})
self._styles[class_name][state][key] = value
def get_dict_for_class(self, class_name, state=None,... |
import re
data = """
@100
~0
+10
*2
N
*2
=200
+1
x2
|5
x1
"""
def decode(data):
out = []
base = 0
p_op,p_v = '',''
rows = [x.strip() for x in re.split('\n',data) if x.strip()]
for row in rows:
op,rest=row[0],row[1:]
if op=='N':
out+=[None]
continue
else:
v=int(rest)
if op=='=': out+=[v]
elif o... |
# Module used by InstanceGenerator and KernFeatureGenerator
import os
import time
import re
##############################################
# THE VALUES BELOW CAN BE EDITED AS NEEDED #
##############################################
kMarkFeatureFileName = "mark.fea"
kMkmkFeatureFileName = "mkmk.fea"
kMarkClassesFile... |
from fidget.widgets import FidgetTable, FidgetInt, FidgetCheckBox
from fidget.tests.gui.__util__ import test_as_main
@test_as_main('sample')
class MyTable(FidgetTable):
MAKE_TITLE = True
MAKE_PLAINTEXT = True
MAKE_INDICATOR = True
INNER_TEMPLATES = [
FidgetInt.template('X'),
FidgetCh... |
def printf(l): #. Prints the matrix
for i in l:
for j in i:
print j,
print ""
def rook(l,i,j): #It checks whether the squares between i,j are empty for a rook. This has been done for knight and bishop as well
if i[0]==j[0]:
for k in range(min(i[1],j[1])+1,max(i[1],j[1])):
if l[i[0]][k]!="#":... |
import os
import pwd
import grp
from setuptools import setup, Command
from setuptools.command.install import install
from distutils.util import convert_path
def prepare():
if os.getuid() != 0:
# This means we run in virtualenv
return
try:
grp.getgrnam('giraffe')
except KeyError:
... |
import json
from flask import g
from compliance_clock.resources.events import get_all_events
def test_put_single_event(client):
with client:
r = client.put('/event',
data=json.dumps({'work_status': 'D','time': 30}))
response = json.loads(r.data)
assert response['work... |
"""Converts times from Meetup to Xibo formats.
The Meetup API reports event dates and times in POSIX epoch milliseconds since
January 1, 1970, effectively UTC date/times. The Meetup API expects times in
ISO 8601 YYYY-MM-DDThh:mm:ss.000 format.
Xibo stores event date/times as strings in ISO 8601 ISO YYYY-MM-DD hh:mm:s... |
"""Tests for registered user metrics
This module tests metrics functionality in `figures.metrics` that work with
the "registered user" metric
The registered user metric provides the count of how many users have registered
for a given site for a time range
TODO: Provide details here
* Figures UI registered users on a... |
import pytest
from callbaker.functions import info_from_callback
@pytest.mark.parametrize("data", ["key_1=value_1", "&key_1=value_1"])
def test_call_data_1(data):
result = info_from_callback(call_data=data)
assert isinstance(result, dict)
assert len(result) == 1
assert result == {'key_1': 'value_1'}
... |
import re
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, FormRequest, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from productloader import load_product
from scrapy.http import FormRequest
cl... |
import logging
import sys
import wdm
import wdm.model as model
import wdm.env_config as env_config
import wdm.run as run
def do_test(dep, print_first_test=True):
if not dep.spec.test:
if dep.spec.install:
if print_first_test:
logging.debug(f"Nothing to test for '{dep.name}'. H... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from skl2... |
#!/usr/bin/env python3
from collections import defaultdict
import torch
import torch.nn as nn
from sklearn.metrics import f1_score
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from bool_net import NaiveBoolNet, HyperBoolNet
# specifications of the experiment
perf = defaultdict(list) # re... |
# Copyright 2020 Google LLC. 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 a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.