content stringlengths 5 1.05M |
|---|
# Copyright (c) 2021 PaddlePaddle 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 applic... |
#===============================================================================
# #Autor: Rosenio Pinto
# #e-mail: kenoi3d@gmail.com
#===============================================================================
import Singleton as Sing
class Batch_Thread_Info(Sing.Singleton, object):
_instance = None
... |
import pytest
from discovery import api
authorize_payload = {
"Target": "db",
"ClientCertURI": "spiffe://dc1-7e567ac2-551d-463f-8497-f78972856fc1.consul/ns/default/dc/dc1/svc/web",
"ClientCertSerial": "04:00:00:00:00:01:15:4b:5a:c3:94",
}
authorize_response = {
"Authorized": True,
"Reason": "Matc... |
#!python
# Copyright 2016 Google 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 by applicable... |
from django.apps import AppConfig
has_uwsgi = False
try:
import uwsgi
has_uwsgi = True
print("uWSGI launch detected")
except:
print("WARNING! No uWSGI found")
class DataconConfig(AppConfig):
name = 'datacon'
def ready(self):
if has_uwsgi:
from datacon.processing.base... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
# Futu Algo: Algorithmic High-Frequency Trading Framework
# Copyright (c) billpwchan - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Bill Chan <billpwchan@hotmail.com>, 2021
class Settings:
# APP SETTINGS
ENABLE_... |
# -*- coding: utf-8 -*-
"""
Copyright () 2018
All rights reserved
FILE: point_to_offer.py
AUTHOR: tianyuningmou
DATE CREATED: @Time : 2018/3/12 上午11:59
DESCRIPTION: .
VERSION: : #1
CHANGED By: : tianyuningmou
CHANGE: :
MODIFIED: : @Time : 2018/3/12 上午11:59
"""
class Solution:
# 找到和为s的数字
def find_num... |
import pvporcupine
import deepspeech
import pyaudio
from audio_tools import VADAudio
from state import State
from pvrecorder import PvRecorder
from secrets import *
from datetime import datetime
from eyes import Eyes
from back_lights import BackLights
import numpy as np
from k9tts import speak
# Define K9 States
... |
__title__ = "jobs"
__version__ = "1.0.1"
__author__ = "Daren Race"
__author_email__ = "daren.race@gmail.com"
__license__ = "MIT"
__cakes__ = u"\u2728 \U0001f370 \U0001f370 \U0001f370\u2728"
|
data = (
'Ruo ', # 0x00
'Bei ', # 0x01
'E ', # 0x02
'Yu ', # 0x03
'Juan ', # 0x04
'Yu ', # 0x05
'Yun ', # 0x06
'Hou ', # 0x07
'Kui ', # 0x08
'Xiang ', # 0x09
'Xiang ', # 0x0a
'Sou ', # 0x0b
'Tang ', # 0x0c
'Ming ', # 0x0d
'Xi ', # 0x0e
'Ru ', # 0x0f
'Chu ... |
# Copyright Alexander Baranin 2016
import sfml
from sfml import window
from engine.Reloadable import reloadable
_import_modules = (
('EngineCore', 'engine.EngineCore'),
('Logging', 'engine.Logging'))
SCHED_ORDER = 10
def onLoad(core):
global app_window
app_window = Window._persistent('WindowModu... |
# -*- test-case-name: xquotient.test.test_scrubber -*-
# Copyright 2005 Divmod, Inc. See LICENSE file for details
"""
Code which can take an incoming DOM tree and \"scrub\" it clean,
removing all tag attributes which could potentially be harmful, and
turning potentially harmful tags such as script and style tags into... |
# Source: https://github.com/flixpar/VisDa/tree/master/models
"""
Implementation of `Large Kernel Matters <https://arxiv.org/pdf/1703.02719>`_ with PSP backend
"""
from math import floor
import torch
import torch.nn.functional as F
from torch import nn
from torchvision import models
__all__ = ['GCN_PSP']
class _Gl... |
__author__ = 'Eunhwan Jude Park'
__email__ = 'judepark@{kookmin.ac.kr, jbnu.ac.kr}'
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
print(tokenizer('hello', 'world', return_tensors='pt')) |
class Solution:
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
out = []
m1, m2 = {}, {}
left = []
cnt1, cnt2 = 0, 0
if not words:
return out
for i in words:
... |
import numpy as np
import matplotlib.pyplot as plt
normal_hist_train = np.load('./results/ResNet18Siamese_train_20200303-211028.npy')
seed_hist_train = np.load('./results/ResNet18Siamese_train_20200304-122122.npy')
normal_loss_train, normal_acc_train = normal_hist_train[:,0], normal_hist_train[:,1]
seed_loss_train, se... |
# -*- encoding: utf-8 -*-
"""
Offers services for CWR files.
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
class CompanyInfo(object):
def __init__(self, name, url):
self._name = name
self._url = url
@property
def name(self):
return s... |
import re
import xml.etree.ElementTree as XML
from collections import Counter
from dataclasses import dataclass
from typing import Sequence, Union, Iterable, Tuple, List
from pathlib import Path
import constants
@dataclass
class Document:
"""Definition of a document"""
id: int
title: str
url: str
... |
# Author: Janek Groß
# Created: June 10th 2020
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def figure_to_rgb(figure, grayscale = False):
"""
Converts a matplotlib figure into a 3-channel numpy array.
Figures are returned by
gcf(), figure() or sub... |
import pytest
from data_pipeline.sql.statement.insert_statement import InsertStatement
from data_pipeline.sql.statement.update_statement import UpdateStatement
from data_pipeline.sql.statement.delete_statement import DeleteStatement
@pytest.fixture
def setup():
insert_statement = InsertStatement("table_name", {'fi... |
# TODO Do not edit this file directly! Instead, create a new file called
# TODO a03_username.py and copy this code into it!
#################################################################################
# Author: Micheala Jackson
# Username:Jacksonmic
#
# Assignment:A03
# Purpose:
# Google Doc Link:https://docs.go... |
# -*- coding: UTF-8 -*-
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class GithubWatchRepoTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.PhantomJS()
self.base_url = "https://github.com"
def test_github_watch_repo_annonymous... |
from base.base_train import BaseTrain
from tqdm import tqdm
import numpy as np
import tensorflow as tf
from utils.metrics import AverageMeter
from utils.logger import DefinedSummarizer
class CifarTrainer(BaseTrain):
def __init__(self, sess, model, config, logger, data_loader):
"""
Constructing t... |
import time
import threading
from concurrent import futures
from utils import logger
from collections import deque
class TaskTracker:
def __init__(self):
self.expiration_time = 300 # in seconds
self.future_dictionary_lock = threading.Lock()
self.current_taskID = 0
self.taskID_to_fu... |
import tensorflow as tf
from keras.models import load_model
# global graph, model, output_list
from keras.preprocessing import image
import numpy as np
import base64
import warnings
warnings.filterwarnings("ignore")
graph = tf.get_default_graph()
model = load_model('./models/AlexNetModel.hdf5')
output_dict = {'Apple_... |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
""" Finding a Python qimodule from C++
This is higly libqi specific
"""
import os
import qisys.sh
from qipy.test.conftest import qipy_action # pyl... |
import datetime
class DisruptionDirectionResponse:
def __init__(self, response):
self._id = response["direction_id"]
self._name = response["direction_name"]
self._route_direction_id = response["route_direction_id"]
self._service_time = None
if response["service_time"] is no... |
from __future__ import annotations
from typing import Any
class ASSyntaxError(Exception):
def __init__(self, message: str) -> None:
super().__init__(message)
class ASReturn(Exception):
def __init__(self, value: Any) -> None:
self.value = value
class ASReferenceError(Exception):
def __... |
#!/usr/bin/env python
from nodes import Node
class Not(Node):
char = "!"
args = 1
results = 1
contents = 333332
@Node.test_func([1], [0])
@Node.test_func([""], [1])
@Node.test_func([0], [1])
def func(self, a):
"""if a: return 0
else: return 1
Non-truthy values: 0, 0... |
# Generated by Django 3.2.6 on 2021-12-11 02:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('member', '0006_auto_20211211_0219'),
]
operations = [
migrations.AddField(
model_name='usertoken',
name='status',
... |
import collections
import unittest
import responses
from requests import HTTPError
from mock import patch
from batfish import Client
from batfish.__about__ import __version__
class TestClientDelete(unittest.TestCase):
def setUp(self):
with patch('batfish.client.read_token_from_conf',
... |
# -*- coding: utf-8 -*-
# Generated by Django 2.1.7 on 2019-05-24 03:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import jsonfield.fields
import wechat_django.pay.models.base
from wechat_django.models.permission impor... |
# coding: utf-8
# In[4]:
fl = lambda fn, ln: fn.strip()+ ' ' +ln.strip()
print(fl(" hello"," jd "))
# In[10]:
authors=['add ajo','iss newton','sidney sheldon','mmmm nnnn','aaa zzz']
authors.sort(key=lambda name: name.split(' ')[0].lower())
authors
|
#
# cogs/general/dice.py
#
# mawabot - Maware's selfbot
# Copyright (c) 2017 Ma-wa-re, Ammon Smith
#
# mawabot is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it will be useful, but
# WITHOUT ANY WAR... |
# Create your models here.
from __future__ import annotations
from typing import List
from django.db import models
class OrderedProduct(models.Model):
order = models.ForeignKey(to="orders.Order", on_delete=models.CASCADE)
product = models.ForeignKey(to="products.Product", on_delete=models.CASCADE)
count... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: xviz/v2/core.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobu... |
"""
Giải quyết yêu cầu sau:
- Thêm thuộc tính is_hungry = True cho class Dog
- Thêm một method eat() để thay đổi giá trị cho is_hungry thành False khi nó được gọi đến
- Kiểm tra và in ra
My dogs are not hungry.
nếu như tất cả các Dog trong Pet đều có is_hungry = False, ... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
"""Leaky integrate-and-fire implementations."""
from typing import Tuple
import numba as nb
import numpy as np
from . import utils
FloatArray = np.ndarray
IntArray = np.ndarray
@nb.njit()
def leaky_integrate_and_fire(
times: IntArray,
decay_time: int,
threshold: float = 2.0,
reset_potential: float ... |
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, generics, filters
from .models import Student, Course, Registration
from .serializer import StudentSerializer, CourseSerializer, RegistrationSerializer, ListRegistrationStudentSerializer, ListStudentRegistrationSerializer... |
# -*- coding: utf-8 -*-
#
# Created on Tue Jan 16 09:32:22 2018
#
# @author: hsauro
# ---------------------------------------------------------------------
# Plotting Utilities
# ---------------------------------------------------------------------
import tellurium as _te
from mpl_toolkits.mplot3d import Axes3D as _... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'mainwindow.ui'
##
## Created by: Qt User Interface Compiler version 5.14.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
###############... |
# -*- coding: utf-8 -*-
#
## copyright (C) 2018
# The Icecube Collaboration
#
# $Id$
#
# @version $Revision$
# @date $LastChangedDate$
# @author Hershal Pandya <hershal@udel.edu> Last changed by: $LastChangedBy$
#
import numpy as np
#muex bins
logEnergyBins = np.linspace(3,8,26)
logEnergyBins=np.array([logEnergyB... |
# Anchor-based BEV detection head template. Mofidied from OpenPCDet. https://github.com/open-mmlab/OpenPCDet
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import copy
from liga.utils import box_coder_utils, common_utils, loss_utils
from liga.utils.common_utils import dist_redu... |
# -*- coding: utf-8 -*-
# @Author: dmytro
# @Date: 2017-01-05 21:19:46
# @Last Modified by: Dmytro Kalpakchi
# @Last Modified time: 2017-01-15 22:27:08
import numpy as np
from numpy.linalg import inv, pinv
import logging
import cProfile
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.prepr... |
import sys
import re
import pandas as pd
import pickle
from sqlalchemy import create_engine
import matplotlib.pyplot as plt
#nltk.download(['punkt', 'wordnet', 'stopwords'])
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.pipelin... |
from torch.nn.modules import linear
import visdom
from cfg import Opts
import mlutils
from mlutils import Log
from torch.utils.data import DataLoader
from trainer import get_trainer
from nature_datasets import get_data
from networks import get_vae
import time
def inference(opt, trainer):
_, eval_dataset = get_dat... |
from django.conf import settings
import requests
from argos.libs.discovery import Discovery
__author__ = 'mphilpot'
class IconFactoryClient(object):
def __init__(self, token, url=None):
if url is None:
discovery = Discovery()
self.url = discovery.get_url("iconfactory")
el... |
# test.py
""" This file houses the suite of tests for main.py classes and functions
THIS FILE IS A MESS AND TOTALLY BROKEN AT THIS POINT
IT WILL NOT RUN
IT IS HERE THAT IT MAY BE CANABALISED FOR FUTURE ITERATIONS OF THE PROJECT
"""
def test_variables():
""" variables needed for various tests """
... |
# Copyright 2017 Intel 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import os
from leapp.models import FirewalldGlobalConfig
def read_config():
default_conf = FirewalldGlobalConfig()
path = '/etc/firewalld/firewalld.conf'
if not os.path.exists(path):
return default_conf
conf_dict = {}
with open(path) as conf_file:
for line in conf_file:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Ensure system commands and responses execute successfully."""
import pytest
from stepseries import commands, responses, step400
from tests.conftest import HardwareIncremental
@pytest.mark.skip_disconnected
class TestSpeedProfileSettings(HardwareIncremental):
de... |
# -*- test-case-name: twisted.lore.test.test_slides -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Rudimentary slide support for Lore.
TODO:
- Complete mgp output target
- syntax highlighting
- saner font handling
- probably lots more
- Add HTML output ... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@File : __init__.py
Description :
@Author : pchaos
tradedate: 2018-4-7
-------------------------------------------------
Change Activity:
2018-4-7:
@Contact : p19992003#gmail.com
-----------------------------... |
# Create a list of strings: mutants
mutants = ['charles xavier',
'bobby drake',
'kurt wagner',
'max eisenhardt',
'kitty pryde']
# Create a list of tuples: mutant_list
mutant_list = list(enumerate(mutants))
# Print the list of tuples
print(mutant_list)
# Unpack and ... |
import abc
import dataclasses
import datetime
from typing import Callable, List, Optional
from xlab.base import time
from xlab.data.proto import data_entry_pb2, data_type_pb2
class DataStore(abc.ABC):
# Add a single data entry to the store. No exception is thrown if the
# operation is successful.
@abc.ab... |
import subprocess;
from Thesis.util.ycsbCommands.Commands import getLoadCommand;
from Thesis.util.ycsbCommands.Commands import getRunCommand;
from Thesis.util.util import checkExitCodeOfProcess;
class Cluster(object):
def __init__(self, normalBinding, consistencyBinding, nodesInCluster):
self.__norma... |
from .KickerSystem import KickerSystem |
import pygame, sys
from pygame.locals import *
from camera import *
def event_system(width, height):
keys = pygame.key.get_pressed()
is_fs = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if keys[pygame.K_ESCAPE]:
... |
"""
This file handles their access credentials and tokens for various APIs required
to retrieve data for the website.
The file that contains the credentials is called "vault.zip", and is referenced
by a constant, `VAULT_FILE`. This file is accessed using a password stored in
the config called `VAULT_PASSWORD`.
Inside... |
import streamlit as st
container = st.container()
container.write("This is inside the container")
st.write("This is outside the container")
# Now insert some more in the container
container.write("This is inside too")
|
#!/usr/bin/env python
# Usage: ./twitget.py twitget.ini
import configparser
import time
import sys
from pymongo import MongoClient
import TwitterSearch
import requests
import logging
logging.basicConfig(level=logging.DEBUG)
DEFAULT_INTERVAL = 15 * 60
DEFAULT_LANGUAGE = 'en'
def get_tweets(tweets_col, config):
... |
from scrapers.memphis_council_calendar_scraper import MemphisCouncilCalScraper
from . import utils
def test_get_docs_from_page():
memphis_scraper = MemphisCouncilCalScraper()
page_str = open(utils.get_abs_filename(
'memphis-city-council-calendar.html'), 'r').read()
docs = memphis_scraper._get_docs... |
from exquiro.parsers.package_diagram_parser import PackageDiagramParser
from exquiro.models.package_diagram.package_node import PackageNode
from exquiro.models.package_diagram.package_relation import PackageRelation
from lxml import etree
import uuid
class OpenPonkPackageDiagramParser(PackageDiagramParser):
def p... |
import os
import numpy as np
import pandas as pd
import rampwf as rw
from rampwf.score_types.base import BaseScoreType
class Mechanics(object):
def __init__(self, workflow_element_names=[
'feature_extractor', 'classifier', 'regressor']):
self.element_names = workflow_element_names
self... |
# Copyright 2021 Huawei Technologies Co., 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 or agreed to... |
"""
Visdom server
-------------
.. autosummary::
:toctree: toctree/monitor
VisdomMighty
"""
import os
import sys
import time
from collections import defaultdict
import numpy as np
import visdom
from mighty.monitor.batch_timer import timer
from mighty.utils.constants import VISDOM_LOGS_DIR
class VisdomMig... |
"""
Gaze
@author Anthony Liu <igliu@mit.edu>
@version 1.1.0
"""
from context import Rasta
import numpy as np
class Scene(object):
x_range, y_range, z_range = 13.33333, 10., 10.
num_viewer_params = 3
num_box_params = 3
@classmethod
def sample(cls, num_boxes):
# generate the boxes
... |
v = int(input('Digite um valor'))
print('o numero antecessor é {} e o numero sucessor é {}'.format((v-1),(v+1)))
print('o numero somado a 10 é igual a {}'.format(v+10)) |
from .__version__ import __version__
from .util import environment_info
from .wrapper import (
convert_into,
convert_into_by_batch,
read_pdf,
read_pdf_with_template,
)
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... |
from sqlalchemy import Column, Integer, String, DECIMAL, ForeignKey, Date, Time, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class TimeEntry(Base):
__tablename__ = "time_entries"
time_entry_id = Column(Integer, primary_key... |
import json
import logging
import re
import sys
import urllib.parse
import requests
logger = logging.getLogger(__name__)
URL = sys.argv[1]
NETLOC = urllib.parse.urlparse(URL)[1]
ALLOWED_MAP = {
# if any of these strings is in url, error is allowed
405: ["/xmlrpc.php", "wp-comments-post.php"],
400: ["?re... |
import argparse
import time
from geopy.geocoders import Nominatim
app = Nominatim(user_agent="pycoordinates")
def get_location(latitude, longitude, verbose):
'''Takes in a latitude and longitude and returns the commensurate location.
:param latitude: the latitude
:param longitude: the longitude
:type... |
"""
This module consists of functions to calculate the [equivalent latitude](https://journals.ametsoc.org/doi/citedby/10.1175/1520-0469%282003%29060%3C0287%3ATELADT%3E2.0.CO%3B2) and edge of a polar vortex using [Nash criteria](https://agupubs.onlinelibrary.wiley.com/doi/10.1029/96JD00066).
### Installation
```
pip ... |
'''
Problem 9
25 January 2002
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
----------------------------------------... |
# from django_filters import Filter
# Add your filters here
|
import shap
import numpy as np
import cv2
class BetterImageMasker(shap.maskers.Image):
def __call__(self, mask, x):
if np.prod(x.shape) != np.prod(self.input_shape):
raise Exception("The length of the image to be masked must match the shape given in the " + \
"ImageM... |
# Generated by Django 2.1.5 on 2019-01-05 14:44
import django.contrib.postgres.fields
import django.core.validators
from django.db import migrations, models
import reader.validators
class Migration(migrations.Migration):
dependencies = [
('reader', '0011_auto_20181001_1853'),
]
operations = [
... |
# -*- coding: utf-8 -*-
import numpy as np
from ipywidgets import interact
from PIL import Image
# [Preparation]
# - check installation of jupyter and ipywidgets with
# `pip list | grep ipywidgets`
# - make the following jupyter extension enable
# jupyter nbextension enable --py widgetsnbextension --sys-prefix
de... |
i = 0
classe = []
continuar = ''
while True:
nome = str(input('Nome: ').strip())
nota1 = float(input('Nota 1: ').strip())
nota2 = float(input('Nota 2: ').strip())
classe.append([i, nome, nota1, nota2, (nota1 + nota2) / 2])
while True:
continuar = str(input('Quer continuar? [S/N] ').strip()[... |
# Individual image generator
import sys
HW_NUMBER = int(sys.argv[1])
Q_NUMBER = int(sys.argv[2])
HW_PATH = sys.argv[3] + "/body.tex"
f = open(HW_PATH, 'r')
content = [n for n in f.readlines() if (not n.startswith('%') and not n.startswith('\sol') and n.strip())]
def index_containing_substring(the_list, substring):
... |
from typing import Sequence, Union, Optional
from typing_extensions import Literal
from .transforms import CriteriaFn
from .deform import deform_image_random
from ..transforms import transforms
class TransformRandomDeformation(transforms.TransformBatchWithCriteria):
"""
Transform an image using a random defor... |
import stk
from .utilities import is_equivalent_atom
def test_repr(atom):
"""
Test :meth:`.Atom.__repr__`.
Parameters
----------
atom : :class:`.Atom`
The atom, whose representation should be tested.
Returns
-------
None : :class:`NoneType`
"""
other = eval(repr(at... |
#####################################################################################
# Manager class of Meal which deals with Meal saving / loading / setting / deleting #
#####################################################################################
from Manager import Manager
from Models.Meal import Meal
impor... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def gpa_cal(scores : str,base:int = 10) -> float:
"""Return float Grade Point Average for anyy base with default as 10
A- and B+ aree treated as similar, althouh functionality can be modified"""
gpa_final = 0.0
scores = scores.upper() # To allow fo... |
from docker import DockerClient
from aavm.utils.progress_bar import ProgressBar
from cpk.types import Machine, DockerImageName
ALL_STATUSES = [
"created", "restarting", "running", "removing", "paused", "exited", "dead"
]
STOPPED_STATUSES = [
"created", "exited", "dead"
]
UNSTABLE_STATUSES = [
"restarting"... |
"""Hyperopt templates for different models"""
# forked from hyperopt/hyperopt-sklearn
from functools import partial
import numpy as np
from hyperopt import hp
from hyperopt.pyll import scope
import sklearn.discriminant_analysis
import sklearn.ensemble
import sklearn.feature_extraction.text
import sklearn.preprocess... |
from unittest import TestCase
from unittest.mock import patch
from app.ingest.infrastructure.mq.publishers.process_ready_queue_publisher import ProcessReadyQueuePublisher
from test.resources.ingest.ingest_factory import create_ingest
class TestProcessReadyQueuePublisher(TestCase):
@classmethod
def setUpClass... |
from aioredis import Redis, ConnectionPool
from six.moves import xrange
from ._util import to_string
from .auto_complete import SuggestionParser
class AioAutoCompleter(object):
"""
An asyncio client to RediSearch's AutoCompleter API
It provides prefix searches with optionally fuzzy matching of prefixes ... |
from .files import sppasFilesPanel
__all__ = (
"sppasFilesPanel",
)
|
from telebot import types
from typing import List
from datetime import datetime
import logging
from tengi.telegram.telegram_bot import TelegramBot
logger = logging.getLogger(__file__)
class TelegramCursor:
def __init__(self, bot: TelegramBot, look_back_days: float, long_polling_timeout: float = 20):
sel... |
from willump.graph.willump_graph_node import WillumpGraphNode
from willump.graph.willump_python_node import WillumpPythonNode
from weld.types import *
import ast
from typing import List
from willump.willump_utilities import strip_linenos_from_var
class CascadeStackDenseNode(WillumpPythonNode):
"""
Willump S... |
import os
import sys
import argparse
from datetime import date
from collections import defaultdict
from egcg_core.app_logging import logging_default
from egcg_core.config import cfg
from egcg_core.util import query_dict
from egcg_core import rest_communication
from egcg_core.notifications.email import send_html_email
... |
# -*- coding: utf-8 -*-
import sys
import gettext
import Adventurer3.Controller
gettext.install(__name__)
class App:
"""UIアプリケーションクラス"""
def __init__(self, ipaddress):
self.adv3 = Adventurer3.Controller.Controller(ipaddress)
def user_interface(self):
while True:
cmd = input("... |
# coding: utf-8
import torch
from torch.nn import functional as F
import torch.utils.data
import torch.utils.data.distributed
from torch import autograd
import numpy as np
from gan_training.random_queue import Random_queue
class Trainer(object):
def __init__(self,
generator,
disc... |
# Copyright (c) 2018, NVIDIA CORPORATION. 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 appli... |
from apps import db
from datetime import datetime
#基础表
class BaseModel(object):
create_time = db.Column(db.DateTime,default=datetime.now)
update_time = db.Column(db.DateTime,default=datetime.now)
#分类表
class Cate(BaseModel,db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String... |
from decimal import Decimal
from simfile.ssc import SSCSimfile
import unittest
from .helpers import testing_timing_data
from .. import *
from simfile.sm import SMSimfile
class TestBeat(unittest.TestCase):
def test_from_str(self):
self.assertEqual(Beat(0, 1), Beat.from_str('0.000'))
self.assertEqua... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.