content stringlengths 5 1.05M |
|---|
import os
from typing import Dict
from controller.invoker.invoker_task_base import TaskBaseInvoker
from controller.utils import code, utils
from proto import backend_pb2
class TaskExportingInvoker(TaskBaseInvoker):
@classmethod
def task_invoke(cls, sandbox_root: str, repo_root: str, assets_config: Dict, work... |
# NOTE: this must be imported first
from ._version import __version__
from .core import fix_observation
__all__ = ['fix_observation', '__version__'] |
import os
from getpass import getuser
class Alias:
def __init__(self, pos, line):
self.startPos = pos
self.rawAlias = line
def split(self):
for i in range(0, len(self.rawAlias)):
if self.rawAlias[i] == '=':
break
key = self.rawAlias[6:i]
con... |
from Task2B import run
from floodsystem.flood import stations_highest_rel_level, stations_level_over_threshold
from floodsystem.stationdata import build_station_list, update_water_levels
def run():
stations = build_station_list()
update_water_levels(stations)
stations_highest_rel_level_list = stations_hig... |
worker_metrics = [(72, 3, 2), (9, 15, 22), (200, 32, 45)]
|
#some utility function
import argparse
import os
from itertools import repeat
from typing import Any, List, Tuple, Union, Iterable
import psutil
# from torch._six import container_abcs
def identity_fn(x, *args, **kwargs):
"""return first input"""
return x
def Identity_fn(*args, **kwargs):
"""return an... |
#!/usr/bin/python
###############################################################################
#
#
###############################################################################
import numpy,sys,os
from diag_functions import *
from plot_functions import *
import matplotlib.pyplot as plt
import argparse
#---... |
#
# Copyright (c) 2019 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# 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
#
# h... |
import training_data_provider
import numpy as np
from absolute_path import _get_full_path
import training_routines
import os.path
import json
if __name__ == '__main__':
# load config
config_path = training_routines._get_full_path("training_config.json")
if not os.path.isfile(config_path):
copyfile(config_path+".d... |
import setuptools
def long_description():
with open('README.md', 'r') as file:
return file.read()
setuptools.setup(
name='aiodnsresolver',
version='0.0.151',
description='Pure asyncio Python DNS resolver',
long_description=long_description(),
long_description_content_type='text/markd... |
import heapq
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
result = []
if len(nums) == 0 or k == 0:
return result
i = 0
while i <= len(nums) - k:
result.append(heapq.nlargest(1, nums[i:i+k])[0])
i += 1
r... |
'''
Module that contains all ANSCII escape colors.
'''
# CONSTANTS
CYAN = '\033[96m'
PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
WHITE = '\033[0m'
MAGENTA = '\033[35m'
BOLD = '\033[01m'
UNDERLINE = '\033[04m'
# COLOR FUNCTIONS
def bold(str):
return BOLD + str + ... |
from unittest.mock import NonCallableMagicMock, MagicMock
from collections import namedtuple
import pytest
from clanimtk import util
from asynctest import CoroutineMock
SupervisorTestVariables = namedtuple(
'SupervisorTestValues',
('async_function', 'sync_function', 'return_value', 'animation', 'step'))
@pyt... |
import os
import numpy as np
import torchvision
from torch.utils.data import DataLoader
stl10_mean = (0.5, 0.5, 0.5)
stl10_std = (0.5, 0.5, 0.5)
def normalise(x, mean=stl10_mean, std=stl10_std):
x, mean, std = [np.array(a, np.float32) for a in (x, mean, std)]
x -= mean * 255
x *= 1.0 / (255 *... |
#!/usr/bin/python
"""
Plot functions of redshift for RSDs.
"""
import numpy as np
import pylab as P
from rfwrapper import rf
import matplotlib.patches
import matplotlib.cm
e = rf.experiments
eg = rf.experiments_galaxy
cosmo = rf.experiments.cosmo
fname = 'mg-fbsigma8-combined.pdf'
names = ['SKA1MID900_mg', 'SKA1MID35... |
#!/usr/bin/env python
## Program: femri2dboxkspace.py
## Module: $RCSfile: femri2dboxkspace.py,v $
## Language: Python
## Date: $Date: 2007/07/07 15:38:01 $
## Version: $Revision: 1.2 $
## Copyright (c) Luca Antiga, David Steinman. All rights reserved.
## See LICENCE file for details.
## This s... |
#
#
# Package libApp in directory source
#
#
print("Loaded libApp")
#
# This file can be left empty, but its presence informs the import mechanism
#
|
import json
from typing import Dict
import urllib.request
import smtplib
import time
from email.header import Header
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
import sys
import signal
import yaml
import aiohttp
import chardet
import asyncio
result = []
filtered = []
class NoRedirect(urllib.re... |
#!/usr/bin/env python3
import argparse
import logging
import os
import sys
import cron
# PYTHONPATH
dir_chief = os.path.dirname(os.path.realpath(__file__))
dir_base = os.path.realpath(__file__ + "/../..")
sys.path += [dir_chief, dir_base]
def main():
# Parse parameters
parser = argparse.ArgumentParser()
... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from .config import db_uri
# This thing will be the superclass of all our model classes
Base = declarative_base()
# This is where we'll be using the session from
class BaseService(obje... |
import urllib2
from datetime import datetime
def getOnlineUTCTime():
webpage = urllib2.urlopen("http://just-the-time.appspot.com/")
internettime = webpage.read()
OnlineUTCTime = datetime.strptime(internettime.strip(), '%Y-%m-%d %H:%M:%S')
return OnlineUTCTime
|
# Theory: Regexps in Python
# A regular expression is a sequence of characters defining a
# search pattern, that is, a pattern describing a set of strings.
# These patterns are used for searching and editing text,
# replacing one substring with another, and so on. The simplest
# example of using a regular expression i... |
"""
This module implements the functionality to calculate the phonon density of
states (PDOS) from MD trajectories. For parsing output files into a format
which is used here, see parse.py and test/* for examples. For a theory
overview, see [1]_.
Other codes which do that are [2]_ and [3]_.
.. [1] doc/source/written/b... |
# ----------------------------------------------------------------------
# Ttronics.KUB.get_interfaces
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# ... |
from aws_cdk import aws_nimblestudio as nimblestudio
from constructs import Construct
from nimble_studio_perforce_server_stacks.nimble_studio_perforce_server_common_stack import (
NimbleStudioPerforceServerCommonStack,
PERFORCE_SERVER_RECORD_PREFIX,
)
class NimbleStudioPerforceServerResourceStack(NimbleStudio... |
# Import relevant tools for NLP and load the english language library
import spacy
#from spacy.cli import download
#download('en')
nlp = spacy.load('en_core_web_sm')
#import numpy as np
import pandas as pd
import nltk
nltk.download('wordnet')
# Import the relevant tools to get text from a website
from bs4 import Beaut... |
"""
File containing methods to label evidence for the digit experiment
"""
import re
def label_digit(input_path, evidence_path, label_path):
with open(input_path, "r") as input_file,\
open(evidence_path, "w") as evidence_file,\
open(label_path, "w") as label_file:
for line in input... |
from copy import copy
from arcana.exceptions import (
ArcanaError, ArcanaUsageError, ArcanaIndexError)
from .base import BaseFileset, BaseField
from .item import Fileset, Field
from collections import OrderedDict
from operator import itemgetter
from itertools import chain
DICOM_SERIES_NUMBER_TAG = ('0020', '0011'... |
"""The |pydwf.core.dwf_device| module implements a single class: |DwfWaveformsDevice|."""
from typing import List, TYPE_CHECKING
from pydwf.core.auxiliary.enum_types import DwfTriggerSource, DwfTriggerSlope, DwfDeviceParameter
from pydwf.core.auxiliary.typespec_ctypes import typespec_ctypes
from pydwf.core.auxiliary.... |
import os
import sys
from os.path import realpath
from pathlib import Path
import openpnm as op
import pytest
@pytest.mark.skip(reason="Installing paraview takes forever!")
class ParaViewTest:
def setup_class(self):
self.path = os.path.dirname(os.path.abspath(sys.argv[0]))
def test_export_data(self)... |
from math import ceil
from operator import truediv
def how_many_times(annual_price, individual_price):
return int(ceil(truediv(annual_price, individual_price)))
|
from torch.utils.data import Dataset
from datasets import load_dataset
import json
from utils import EditBatchSampler, dict_to, scr
import logging
import random
import copy
LOG = logging.getLogger(__name__)
def is_ascii(s):
return all(ord(c) < 128 for c in s)
def filter_text(iterator):
valid = []
for t... |
"""Unit tests for traditional_cnn.py."""
import unittest
from generalexam.machine_learning import traditional_cnn
MODEL_FILE_NAME = 'foo/bar/model.h5'
MODEL_METAFILE_NAME = 'foo/bar/model_metadata.p'
class TraditionalCnnTests(unittest.TestCase):
"""Each method is a unit test for traditional_cnn.py."""
def ... |
#!/usr/bin/env python3
from __future__ import print_function
import math
import time
from cereal import car
from opendbc.can.parser import CANParser
from selfdrive.car.gm.values import DBC, CAR, CanBus
from selfdrive.config import Conversions as CV
from selfdrive.car.interfaces import RadarInterfaceBase
RADAR_HEADER_M... |
## @ StitchLoader.py
# This is a python stitching script for Slim Bootloader WHL/CFL build
#
# Copyright (c) 2019, Intel Corporation. All rights reserved. <BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
import sys
import argparse
from ctypes import *
ExtraUsageTxt = """
This script creates a new Whiskeylake... |
from geode import listen
class KeysTracker:
def __init__(self, keys_value, lookup_value_function):
self.keys_value = keys_value
self.lookup_value_function = lookup_value_function
self.keys_listener = listen(self.keys_value, lambda: self.on_keys_change())
self.keys_up_to_date = False
self.tracker ... |
class Constants:
APP_NAME= "inaf.arcetri.ao.pysilico"
APP_AUTHOR= "INAF Arcetri Adaptive Optics"
THIS_PACKAGE= 'pysilico'
|
from .building_create import BuildingCreate
__all__ = ['BuildingCreate'] |
#!/usr/bin/env python2
# coding: utf-8
#import time
#st = time.time()
#print time.time()-st,'begin'
import argparse, socket, struct, sys, traceback, json
#print time.time()-st,'import'
parser = argparse.ArgumentParser('Check minecraft server status')
parser.add_argument('-H','--host', help='Server IP or hostname', re... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""
from model.speech import asr
input_datas = [
'../data/speechs/16k.wav',
'../data/speechs/16k.wav',
]
model = asr.ASR()
for input_data in input_datas:
check_ret = model.check_file(input_data)
print(check_ret)
out = chec... |
import numpy as np
import pytest
import torch
from baal.utils.iterutils import map_on_tensor
def test_map_on_tensor():
x = [torch.zeros([10]), torch.zeros([10])]
assert np.allclose(map_on_tensor(lambda xi: (xi + 1).numpy(), x),
[np.ones([10]), np.ones([10])])
x = torch.zeros([10])
... |
@bot.message_handler(commands=['ban'])
def ban_user(message):
userlang = redisserver.hget("messenger:settings:userlanguage", message.from_user.id)
if message.from_user.id in ADMINS_IDS:
if len(message.text.split()) < 2:
if message.reply_to_message and message.reply_to_message.forward_from:
userid ... |
# Tutorials > 10 Days of Statistics > Day 4: Geometric Distribution II
# Problems based on basic statistical distributions.
#
# https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem
# challenge id: 21245
#
def g(n, p):
return p * (1 - p) ** (n - 1)
ko, total = map(int, input().split())
n = in... |
# -*- coding=utf-8 -*-
__version__ = "0.0.8.dev0"
__all__ = ["version"]
|
# =============================================================================
#
# This module contains the :class:`Board` and the :class:`Game` class.
#
# =============================================================================
# Note: some (great) implementation ideas were inspired by Patrick Westerhoff:
# h... |
from __future__ import annotations
import enum
import logging
from typing import Any, Dict, List
logger = logging.getLogger(__name__)
__all__ = ["Enum"]
class EnumMeta(type):
def __iter__(self):
return self.values() # nocover
class Enum(enum.Enum):
"""Extends Enum builtin for easier lookups and ... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Firefox()
driver.get('https://www.google.com')
time.sleep(60)
driver.close()
|
# @Author: BingWu Yang <detailyang>
# @Date: 2016-03-30T20:27:36+08:00
# @Email: detailyang@gmail.com
# @Last modified by: detailyang
# @Last modified time: 2016-04-16T15:23:48+08:00
# @License: The MIT License (MIT)
from setuptools import setup, find_packages
setup(
name = 'esl',
version = '0.5.1',
... |
import sys
from qt import *
from frmpreferences import frmPreferences
from kuralib import kuraapp
from kuragui.guiconfig import guiConf
from kuragui.comboproxy import ComboProxy
from resource import *
class dlgPreferences(frmPreferences):
"""
Proxy class for the generated frmPreferences.
"""
def _... |
from django.shortcuts import render
from rest_framework import viewsets, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
import sys
sys.path.append("..")
from core.models import Tag
from . import serializers
# Create your views here.
class T... |
# Generated by Django 3.1.13 on 2021-09-05 17:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cars', '0032_auto_20210905_1742'),
]
operations = [
migrations.AlterField(
model_name='autosearch',
name='car_body'... |
# Generated by Django 2.0.13 on 2019-04-29 15:27
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schools', '0004_auto_20190428_1629'),
]
operations = [
migrations.AlterFi... |
# %% [markdown]
# ## Testing the intake package
import intake
|
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=32)
class Meta():
verbose_name_plural = "companies"
def __str__(self):
return self.name
class Partner(models.Model):
name = models.CharField(max_length=32)
def __str__(self):
ret... |
# External Imports
from time import sleep # delay needed due to adjustment method
# Internal Imports
from mavlinkinterface.logger import getLogger # For Logging
class lights(object):
steps = 8 # number of brightness levels the light has
def __init__(self, mli):
for i in range(0, self.steps):
... |
import unittest
import json
import requests
def get_test_message():
with open('tests/data/sample_telegram_update_message.json', "r") as in_file:
json_str = in_file.read()
return json.loads(json_str)
def send_message(chat_id, message):
with open('app-secrets.json', "r") as in_file:
secr... |
"""
Shor's Order Finding Algorithm Benchmark - Cirq
"""
from collections import defaultdict
import math
import sys
import time
import cirq
import numpy as np
sys.path[1:1] = ["_common", "_common/cirq", "shors/_common", "quantum-fourier-transform/cirq"]
sys.path[1:1] = ["../../_common", "../../_common/cirq", "../../s... |
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, 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 o... |
"""
Copyright 2015 Rackspace
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, software
dist... |
from __future__ import absolute_import, division, print_function
from glue.utils import defer_draw, decorate_all_methods
from glue.viewers.image.layer_artist import ImageLayerArtist, ImageSubsetLayerArtist
from glue.viewers.scatter.layer_artist import ScatterLayerArtist
from glue.viewers.image.state import ImageViewer... |
from rx.internal import extensionmethod
from rx.core.blockingobservable import BlockingObservable
@extensionmethod(BlockingObservable)
def last(self):
"""
Blocks until the last element emits from a BlockingObservable.
If no item is emitted when on_completed() is called, an exception is thrown
Note:... |
from adj_mat_func import *
from tensorflow.python.keras import backend as k
def custom_adj_loss_l1(batch_size, lambda_loss=1, pixel_distance=1):
"""
:param batch_size:
:param lambda_loss:
:param pixel_distance:
:return: adjacency loss L1 with (0-1) matrix
"""
def adj_loss(y_true, y_pred):
... |
from View import View
from PieceType import PieceType
class ConsoleView(View):
def __init__(self):
pass
def finish(self):
pass
def display(self, board, game, moves = set(), prevPos = None, hintStart = None,\
hintEnd = None):
self.displayBoard( board, game, moves, prevPos, hintStart,... |
import serial
class SerialProcess():
def __init__(self, port, baud, callback):
self.callback = callback
try:
print(port, baud)
self.sp = serial.Serial(port, baud, timeout=1)
print ("SUCCESS: Arduino was found!")
except Exception as e:
self.sp = None
print ("ERROR: Arduino is not attached! Check to... |
# Copyright 2016 James Hensman
#
# 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, so... |
from __future__ import unicode_literals
import os
import re
import sys
from prompt_toolkit import prompt, AbortAction
from prompt_toolkit.history import FileHistory
from prompt_toolkit.contrib.completers import WordCompleter
from pygments.lexers import SqlLexer
from pygments.style import Style
from pygments.token imp... |
#!/usr/bin/env python
#
# By @Matioupi
# provided under dbad licence http://dbad-license.org/
#
# Version 2.0
#
# Made possible thanks to all OG's work and especially ideas from @jan2642 and
# patience of @jezzab in explaining me some stuff
#
#
# RTFM before asking for support
#
#addresses must be given in... |
import FWCore.ParameterSet.Config as cms
# configuration to model pileup for initial physics phase
# Now, import base configuration instead of specfiying all parameters
from SimGeneral.MixingModule.mix_probFunction_25ns_PoissonOOTPU_cfi import *
mix.input.nbPileupEvents.probFunctionVariable = cms.vint32(0,1,2,3,4,5,6,... |
from .conversion import Converter, \
cilNumpyMETAImageWriter,\
WriteNumpyAsMETAImage
from .colormaps import *
from .visualisation_pipeline import cilClipPolyDataBetweenPlanes, cilPlaneClipper, cilMaskPolyData
from .io import ImageDataCreator
|
from time import sleep
print('Vai começar a queima de fogos!!!')
for c in range(10, 0, -1):
print(c)
sleep(1)
print('BOOM BOOM BOOM BOOM BOOM BOOM BOOM')
|
from aiomessaging.event import Event
def test_simple():
e1 = Event('echo')
e2 = Event.from_dict({'type': 'echo'})
assert e1.type == e2.type
def test_to_dict():
e = Event('echo')
e.to_dict()
|
import sublime_plugin
from ..helper import Helper
from ..utils import Utils
from ..constant import Constant
class PhpmePostGetterSetterCommand(sublime_plugin.TextCommand):
"""Do generate getter setter"""
def run(self, edit, mode, properties, cname):
self.uses = []
self.methods = []
se... |
""" Storage objects
:Author: Aaron Watters
:Maintainers: http://gadfly.sf.net/
:Copyright: Aaron Robert Watters, 1994
:Id: $Id: store.py,v 1.6 2009/01/27 12:38:10 Michael Butscher Exp $:
"""
verbosity = 0
import sys, os, hashlib, types, marshal
from consts import MARSHAL_VERSION
from kjbuckets_select imp... |
from astropy.table import Table
import pandas as pd
import os
this_file_location = os.path.dirname(os.path.abspath(__file__))
nsa_catalog = Table.read(
'/Users/tlingard/PhD/galaxy-builder/subjectUpload/nsa_v1_0_1.fits',
format='fits'
)
nsa_keys = (
'NSAID', 'ISDSS', 'INED', 'IAUNAME', # identifiers
'R... |
#imports
import tkinter
import tkinter.messagebox
from tkinter import *
#defs
#makes sure thats the number is in range
def email_check():
email.get()
if email.find("@")<0:
tkinter.messagebox.showinfo("Email Error","Please enter an actual email" )
def limit_num_check():
if length1.ge... |
# BSD 3-Clause License
# Copyright (c) 2021, S Radcliffe
# Copyright (c) 2017, Project Jupyter Contributors
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must... |
import numpy as np
import pandas as pd
import plotly.express as px
import os
from pet.flags import save_yaml, load_yaml
import dataclasses
from joblib import load
from glob import glob
from shutil import rmtree, copytree, copyfile
from sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score
fr... |
from unittest.mock import MagicMock, patch
import unittest
from helperFunctions.helperFunctions import stdRet
class TestHelperFunctions_getSchoolYear(unittest.TestCase):
def setUp(self):
# Set up a number of items that will be used for these tests.
# -- Mock the os.environ method so that we can ... |
"""
SCons.Tool.quex
Tool-specific initializaton for the Quex lexer generator.
For the following options, target/source dependencies are not properly
handled:
- ``--language dot``
- ``--derived-class``, ``--dc``
- ``--derived-class-file``
- ``--token-class-file``
- ``--token-class``, ``--tc``
- ``--codec-file``
"""
... |
""".. Ignore pydocstyle D400.
.. _resdk_resdk_logger:
=======
Logging
=======
Module contents:
#. Parent logger for all modules in resdk library
#. Handler STDOUT_HANDLER is "turned off" by default
#. Handler configuration functions
#. Override sys.excepthook to log all uncaught exceptions
Parent logger
=========... |
#!/usr/bin/env python
import re
log = "test-sample.log"
prog = re.compile(".*\s<=\s.*\sid=(?P<msg_id>.*\s+).*T=\"(?P<subject>.*)\".*")
with open(log) as f:
for line in f:
match = prog.match(line)
if match:
print('ID: {:<50} Subject: {}'.format(match.group('msg_id'), match.group('subje... |
import re
from scripts_utils import get_soup
def cleanWiki(text):
text = re.sub(r"\[\[([^||:\]]+)\]\]", "\\1", text) # [[a]] -> a
text = re.sub(r"\[\[[^|]+\|(.+?(?=\]\]))\]\]", "\\1", text) # [[a|b]] -> b
return text
url = "https://de.wiktionary.org/w/index.php?title=Vorlage:K/Abk&action=edit"
soup = ... |
"""
Based on Django's field tests:
https://github.com/django/django/tree/stable/3.0.x/tests/forms_tests/field_tests
"""
import datetime
import logging
from enum import Enum
from unittest import mock
from django.conf import settings
from django.core.files import File
from django.core.validators import EMPTY_VALUES
fro... |
import json
import os
import signal
import subprocess
import sys
import time
from functools import partial
from absl import app as abslapp
from absl import flags as flags_
from devapp import gevent_patched # noqa
from devapp import load, tools
from devapp.lib import sh
from structlogging import sl
from theming.absl_c... |
import os
import urllib2
import time
from HTMLParser import HTMLParser
import wx
import wx.lib.scrolledpanel as scrolled
URL_WXFALSECOLOR = "http://code.google.com/p/pyrat/downloads/detail?name=wxfalsecolor.exe"
class DummyLogger(object):
def debug(self, msg):
print "D " + msg.strip()
def info(... |
#!/usr/bin/env python3
import argparse
import os.path as osp
from glob import iglob
import torch
import numpy as np
from skimage.io import imread, imsave
import core
import impl.builders
import impl.trainers
from core.misc import R
from core.config import parse_args
from core.factories import model_factory
from util... |
#!/usr/bin/env python3
import os, sys, opencc
def convert(src_path, dst_path, cfg='s2twp.json'):
converter = opencc.OpenCC(cfg)
with open(src_path, "r", encoding='utf-8') as src, open(dst_path, "w+", encoding='utf-8') as dst:
dst.write("\n".join(
converter.convert(line.rstrip()).replace('(i... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
import json
from django.core.management import execute_from_command_line
FILE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
site_config = os.path.join(FILE_DIR, 'sporttech', 'sporttech', 'settings', 'site_config.... |
class Settings():
def __init__(self):
"""初始化游戏静态设置"""
self.screen_width = 1200
self.screen_height = 600
self.bg_color = (0, 230, 230)
self.ship_speed_factor = 1.5
self.ship_limit = 3
#子弹
self.bullet_speed_factor = 1
self.bullet_width ... |
"""
Implement the Numpy backend, and collect timing information with different parameters
William Nourse
August 26th, 2021
I have set myself beyond the pale. I am nothing. I am hardly human anymore.
"""
import numpy as np
import pickle
import time
import sys
"""
#######################################################... |
# -*- coding: utf-8 -*-
# Python core imports
import unittest
import json
# Jsonty import
from ..context import jsonty
# Test models
import tests.util.models as models
class TypingDump(unittest.TestCase):
"""Dump test operation with attributes anottated as typing"""
def test_post_list(self):
""" Te... |
import argparse
import torch
import torch.nn as nn
from pytorch_lightning import Trainer
from config import AVAIL_GPUS
from src.datasets import get_cifar100_dataloader, FilterDataset
from src.models import Classifier, GAN, Discriminator
def train(args):
# Initialize a trainer
trainer = Trainer(
gpus... |
# -*- coding: utf-8 -*-
"""Make interpretation tables
1.) Which interaction model was always among the top 5/top 10-performing configurations for each dataset?
2.) Which loss function was always among the top 5/top 10-performing configuration for each dataset?
3.) Which training assumption was always among the top 5/... |
class Solution:
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
c=0
for s in S:
if s.isalpha():
c+=1
res=[]
for i in range(2**c):
l=[]
for t in S[::-1]:
... |
""""
Copyright © Harshit Raushan 2021 - https://github.com/HarshitRaushan
Description:
All Rights Reserved to HR © 2021.
Version: 3.0
"""
import json
import os
import platform
import random
import sys
import collections
import datetime
import math
import subprocess
import asyncio
import random
import glob
import ... |
from datetime import datetime
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
def print_hello():
return 'Hello world from first Airflow DAG!'
dag = DAG('hello_world', description='Hello World DAG',
schedule_i... |
from re import compile
pattern = compile(r"(?<!^)(?=[A-Z0-9])")
def camel_to_snake(string):
return pattern.sub("_", string).lower()
def snake_to_camel(string):
split = string.split('_')
return split[0] + "".join(word.title() for word in split[1:])
def camel_to_kebab(string):
return pattern.sub("... |
def leiaDinheiro(mensagem):
while True:
n = input(mensagem).replace(',', '.').strip()
a = n.replace('.', '')
if a.isdigit() == True:
return float(n)
break
else:
print(f'\033[0;31mERRO: "{n}" é um preço inválido!\033[m')
def leiaDinheiro(mensagem)... |
# !/usr/bin/env python3
# -*- cosing: utf-8 -*-
import sys
def fun1(to_replace, replacer, string):
result = string.replace(replacer, to_replace)
return result
|
import inspect
import logging
import enum
import uuid
import Pyro5.api
import TimeTagger as TT
from . import helper
EXCLUDED_LIBRARY_MEMBERS = [
'TimeTaggerBase', 'IteratorBase', 'Iterator', 'FlimAbstract',
'TimeTaggerVirtual', 'createTimeTaggerVirtual',
'CustomMeasurement', 'CustomMeasure... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.