text stringlengths 1 927k |
|---|
"""
Test for UserProfile model
"""
import random
import statistics
import pytz
from model_mommy import mommy
from rest_framework.authtoken.models import Token
from kaznet.apps.main.tests.base import MainTestBase
from kaznet.apps.users.models import UserProfile
from kaznet.apps.main.models import Submission
from kazne... |
from bluepy.btle import Scanner
def getDevices(full_info):
"""
The method searches BLE devices around in the and prints them.
SUDO is required.
:param full_info: The method prints all device information if true, it prints just the MAC and name if false.
"""
scanner = Scanner()
devices = sc... |
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle=rectangle
self.pos=[]
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.pos.append([row1,col1,row2,col2,newValue])
... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
#!/usr/bin/env python
"""
upload_matching_files.py
Recursivly search for files, given in a text file and upload to FTP server.
Dan Clewley - 11/04/2015
"""
from __future__ import print_function
import subprocess
import argparse
import sys
import os
# Fill in details of FTP Server here
FTP_ADDRESS = ''
FTP_USER = ... |
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import envir... |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2020, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... |
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['carla_manual_control'],
package_dir={'': 'src'}
)
setup(**d) |
"""
from https://gist.github.com/bwhite/3726239
Information Retrieval metrics
Useful Resources:
http://www.cs.utexas.edu/~mooney/ir-course/slides/Evaluation.ppt
http://www.nii.ac.jp/TechReports/05-014E.pdf
http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf
http://hal.archives-ouvertes.fr/doc... |
# model settings
model = dict(
type='FasterRCNN',
pretrained='torchvision://resnet101',
backbone=dict(
type='ResNet',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[... |
"""Amazon NeptuneClient Module."""
import logging
from typing import Any, Dict, List, Optional
import boto3
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from gremlin_python.driver import client
from SPARQLWrapper import SPARQLWrapper
from awswrangler import exception... |
#!/usr/bin/env python
__all__ = ['mixcloud_download']
from ..common import *
def mixcloud_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
html = get_html(url, faker=True)
title = r1(r'<meta property="og:title" content="([^"]*)"', html)
preview_url = r1(r'm-preview=\"([^\"]+)\"', htm... |
import os
idade = int(input("Digite sua Idade: \n"))
acertos = int(input("Digite a Nota da Prova: \n"))
if idade >= 18 != acertos >= 21:
print("Você foi Habilitado para receber a CNH")
else:
print("Você não foi Habilitado para receber a CNH")
input("Pressione <enter> para sair") |
from typing import List
from aiogram.types import Message, BotCommand
from app.misc.command_description import CommandDescription
def register_main_group_start(storage: List[CommandDescription]):
async def cmd_help(message: Message):
help_message = "".join(f"/{command.command} - {command.description}\n" f... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Z(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "surface.contours"
_path_str = "surface.contours.z"
_valid_props = {
"color",
"end... |
import unittest, random, sys, time
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_rf, h2o_hosts, h2o_import as h2i
# we can pass ntree thru kwargs if we don't use the "trees" parameter in runRF
# only classes 1-7 in the 55th col
# don't allow None on ntree..causes 50 tree default!
print "Temporarily not usi... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
walltypes = UnwrapElement(IN[0])
kindlist = list()
for item in walltypes:
try:
kindlist.append(str(item.Kind))
except:
kindlist.append('No Wall')
OUT = kindlist |
import time
import unittest
from Health_Card_Index.check_healthcard_home_screen import health_card_homepage
from reuse_func import GetData
class Health_card_functionalTest(unittest.TestCase):
@classmethod
def setUpClass(self):
self.data = GetData()
self.driver = self.data.get_driver()
... |
"""General controls.""" |
# based on https://ruder.io/optimizing-gradient-descent/#adam
# and https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/deep_learning/optimizers.py#L106
import numpy as np
class Adam:
"""Adam - Adaptive Moment Estimation
Parameters:
-----------
learning_rate: float = 0.001
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Mirantis 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 ... |
import os
import sys
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
base_dir = os.path.dirname(os.path.abspath(__file__))
def main():
command = sys.argv[1]
if command == "db":
from client.database import db
from client.factory import create_app
a... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
import math
import numpy as np
# ------------------------------------------------------------------------------
# Transformer model from: https://github.com/JayParks/transforme... |
from HyperAPI.hdp_api.routes import Resource, Route
class Color(Resource):
name = "Color"
class _getColors(Route):
name = "get Project Color sList"
httpMethod = Route.GET
path = "/projects/{project_ID}/colors"
_path_keys = {
'project_ID': Route.VALIDATOR_OBJECTID,
... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/topics/item-pipeline.html
import json
from collections import defaultdict
from scrapy import signals
from scrapy.exporters import BaseItemExporter
from scrapy.exceptions import DropItem
f... |
from django import template
from ..models import Post,Category
register = template.Library()
@register.simple_tag
def get_recent_posts(num=5):
return Post.objects.all().order_by('-created_time')[:num]
@register.simple_tag
def archives():
return Post.objects.dates('created_time', 'month', order='DESC')
@register.s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
===============================
|module_summary| object_data.py
===============================
TOWRITE
"""
OBJ_TYPE_NULL = 0
""":NOTE: Allow this enum to evaluate false"""
OBJ_TYPE_BASE = 100000
""":NOTE: Values >= 65536 ensure compatibility wit... |
from djitellopy import Tello
import gcdetection
# Connect to tello using djitellopy package
tello = Tello(host="172.20.10.8")
tello.connect()
# Open the tello's camera
tello.streamon()
# Start the app
detect_window = gcdetection.Interface()
class Control:
"""Class for controlling the tello with keypress
T... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import unittest
import sys
sys.path.insert(0, "../")
from opetopy.common import DerivationError
from opetopy import NamedOpetope
class Test_NamedOpetope_Variable(unittest.TestCase):
def setUp(self):
self.a0 = NamedOpetope.Variable("a", 0)
self.b0 = NamedOpetope.Variable("b", 0)
self.c... |
import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
collapses = html.Div(
[
dbc.Button(
"Toggle left",
color="primary",
id="left",
className="me-1",
n_clicks=0,
),
dbc.Button(
"Toggle rig... |
# -*- coding: utf-8 -*-
"""
Pharmacopedia.Py v1.0
Pharmacy Counting Project
Arhur D. Dysart
DESCRIPTION
Analyzes and organizes medical pharmacy data. Using data from the Centers for
Medicare & Medicaid Services, this script calculates: (1) total number of
prescribers and (2) total prescriber expenditure for all list... |
import pytest
import pyansys
from pyansys import examples
from vtki.plotting import running_xserver
import os
@pytest.mark.skipif(not running_xserver(), reason="Requires active X Server")
def test_show_hex_archive():
examples.show_hex_archive(off_screen=True)
def test_load_result():
examples.load_result()
... |
# Python 词频统计
with open('a.txt', 'r') as f:
str = f.read()
str = str.replace(",", " ")
str = str.replace(".", " ")
str = str.replace("!", " ")
str = str.replace("?", " ")
str = str.replace(":", " ")
str = str.replace(";", " ")
str = str.replace("\'", " ")
str = str.replace("/", " ")
str_list = str.split()
str_dict ... |
from django.db import models
from django.contrib.auth import get_user_model
from uuid import uuid4
User = get_user_model()
class Post(models.Model):
post_id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
title = models.CharField(max_length=50)
tag = models.CharField(max_length=50, n... |
def extractWwwWastedproductionsCom(item):
'''
Parser for 'www.wastedproductions.com'
'''
badwords = [
'#ninerwrimo',
'#NaNoWriMo',
'#ThursdayTales',
'#StoryCubes',
]
if any([bad in item['tags'] for bad in badwords]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item[... |
from flask import Flask
from .config import DevConfig
from flask_bootstrap import Bootstrap
# Initializing application
app = Flask(__name__, instance_relative_config=True)
# setting up configuration
app.config.from_object(DevConfig)
app.config.from_pyfile('config.py')
# initialize Flask Extension
bootstrap = Bootstr... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 30 13:06:52 2017
@author: Mostafa Hammoud
This script contains various functions that will be used
"""
import numpy as np
import operator
from os import listdir
from os.path import isfile, join
from matplotlib import pyplot as plt
"""
This function takes the R waves that... |
import numpy as np
import pandas as pd
import json
import csv
import time
from scipy.integrate import RK45, solve_ivp
class circulation_closed_loop:
"""
Closed loop circulation model.
References
----------
F. Regazzoni, M. Salvador, P. C. Africa, M. Fedele, L. Dede', A. Quarteroni,
"A cardiac ... |
#STP header feilds
#list, fields containing following keys
#dict, head containing key, value pairs
#1. source port #
#2. dest port #
#3. seq_nb
#4. ack_nb
#5. ACK
#6. SYN
#7. FIN
#8. RST
#example ['1234', '1234', '100000', '4294967295', '4294967295', '0', '1', '1', '1']
#max len of header = 46 bytes
#b'1234+1234+10000... |
# TODO: import
# REQUIRES: num_items >= 0, capacity >= 0,
# size of item_values >= num_items,
# size of item_weights >= num_items,
# item_values are all >= 0, item_weights are all >= 0
# EFFECTS: Computes the max value that can be obtained by picking
# from a set of num_items items without exceed... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import plistlib
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows
def get_appleMapsSearchHistory(files_found, report_folder, seeker):
data_list = []
for file_found in files_found:
file_found = str(file_found)
with... |
#!/usr/bin/env python
# imglob - expand list of image filenames
# Stephen Smith, Mark Jenkinson and Matthew Webster FMRIB Image Analysis Group
# Copyright (C) 2009 University of Oxford
# Part of FSL - FMRIB's Software Library
# http://www.fmrib.ox.ac.uk/fsl
# fsl@fmrib.ox.ac.uk
#
# Developed at FMRIB (Oxf... |
# Generated by Django 2.2 on 2019-10-09 18:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Faq',
fields=[
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import datetime
import json
import random
import time
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import DataLoader, DistributedSampler
import datasets
import util.misc as utils
from datasets impo... |
# %% [markdown]
# This is a simple notebook for Autogluon AutoMl prediction.
# MLflow used as tracking tool since experiments take long time complete
# and it is hard to manage too many experiments.
#%%
# Importing necessary libraries
import os
import re
import random
import string
import math
import pandas as pd
impor... |
#
# __COPYRIGHT__
#
# 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 rights to use, copy, modify, merge, publish,
# distribute, sublicen... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from datetime import datetime, timedelta
from flask import reque... |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import re
from typing import Optional, Sequence, Union
from .base_dataset import BaseDataset
from .builder import DATASETS
# these files contain nan, so exclude them.
exclude_files = dict(
left_into_future=[
'0004573.flo',
... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ..helperfunctions import _xml_to_list
from ...worksheet import Worksheet
class TestAss... |
from typing import Tuple, Union
import numpy as np
from PIL import Image
from torch.utils.data import Dataset as TorchDataset
from torchvision import transforms
from continuum.viz import plot
class TaskSet(TorchDataset):
"""A task dataset returned by the CLLoader.
:param x: The data, either image-arrays or... |
print("\n**Username should be characters\n\n**Password should be numbers")
def verify():
print("SIGN UP")
u=str(input("User name : "))
p=int(input("\nPassword : "))
print("SIGN IN")
username=str(input("\nUser name : "))
paw=int(input("Password : "))
if username==u and paw==p :
print(... |
# l = len(s1). Slide over a window of size l on s2 and keep creating counters. If ctr_s1==ctr_s2: return true.
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
l = len(s1)
if len(s2) < l:
return False
for i in range(len(s2) - l + 1):
subst... |
from typing import List, Optional
from view_model.user_viewmodel import UserOutViewModel
class StreamViewModel(UserOutViewModel):
id: Optional[str]
user_id: Optional[str]
user_name: Optional[str]
title: Optional[str]
viewer_count: Optional[int]
started_at: Optional[str]
thumbnail_url: Opt... |
__version__ = '1.24.3' |
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' # 服务器的主机名或者 IP 地址
PORT = 10009 # 服务器使用的端口
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print(s)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
print(s)
data = s.recv(1024)
print('Received', repr(data)) |
"""a simple ETL modulle
Usage:
bonobo_etl.py load [--conn=<conn-string>] [--file=<file>] [-v | --verbose]
Options:
--conn=<conn-string> The connection string to use. e.g., sqlite:///data/outbound/pandas_etl.db [default: sqlite:///:memory:]
--file=<file> The input file to process [default: data/inboun... |
"""Test for smart home alexa support."""
from unittest.mock import patch
import pytest
from homeassistant.components.alexa import messages, smart_home
import homeassistant.components.camera as camera
from homeassistant.components.cover import DEVICE_CLASS_GATE
from homeassistant.components.media_player.const import ... |
import os
import traceback
import time
from conans.util import progress_bar
from conans.client.rest import response_to_str
from conans.errors import AuthenticationException, ConanConnectionError, ConanException, \
NotFoundException, ForbiddenException, RequestErrorException
from conans.util.files import mkdir, sav... |
# -*- coding: utf-8 -*-
#
# 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
#... |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... |
import xarray as xr
def compute_dataset(ds, period='1W', incl_stdev=False):
if incl_stdev:
resample_obj = ds.resample(time=period)
ds_mean = resample_obj.mean(dim='time')
ds_std = resample_obj.std(dim='time').rename(name_dict={name: f"{name}_stdev" for name in ds.data_vars})
ds_mer... |
"""Custom evaluation metrics"""
from __future__ import absolute_import
from .coco_detection import COCODetectionMetric
from .voc_detection import VOCMApMetric, VOC07MApMetric
from .segmentation import SegmentationMetric |
from KTH_DataModule import KTH_DataModule
from KTH_VideoBlockClassifier import KTH_VideoBlockClassifier
import pytorch_lightning as pl
from argparse import ArgumentParser
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("--data_path", type=str, default="/data", dest="data_path")
... |
class ShipperError(Exception):
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
import functools
from wire.element import ToElementConverter
from wire.helpers import identifiers
from wire.helpers import logging
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-10-06 08:39
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0008_fix_project_type'),
('projects', '0008_merge'),
]
operations = [
... |
"""
Memory
"""
import numpy as np
import os
from utils import export
@export
class NumpyArrayMemory:
"""
Datastructure for all the experiences (states, actions, rewards, next_states)
the agent saw.
"""
def __init__(self, size, input_shape, nb_actions, data_dir):
self.data_dir = data_dir
... |
import csv
from osint_sources.tinder import *
from osint_sources.model import *
from osint_sources.google import *
from osint_sources.twitter import *
from osint_sources.facebook import *
from osint_sources.instagram import *
from osint_sources.boe import *
from osint_sources.yandex import *
def tinder(token):
#sta... |
from nio import AsyncClient, UnknownEvent
from core.plugin import Plugin
from typing import Dict, List, Tuple
import time
import random
import re
from shlex import split
from sys import maxsize
import logging
logger = logging.getLogger(__name__)
quote_attributes: List[str] = ["user", "members"]
"""valid attributes t... |
# Copyright 1999-2021 Alibaba Group Holding 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 a... |
import collections
import logging
import os
import stat
import uuid
from functools import partial
from typing import Any, Callable, Iterable, Set, Text, Tuple, Union
import schema_salad.validate as validate
from schema_salad.ref_resolver import uri_file_path
from schema_salad.sourceline import SourceLine
from six.move... |
# -*- coding: utf-8 -*-
# Author: XuMing <shibing624@126.com>
# Data: 17/10/10
# Brief:
import tensorflow as tf
import numpy as np
# 使用 NumPy 生成假数据(phony data), 总共 100 个点.
x_data = np.float32(np.random.rand(2, 100)) # 随机输入
y_data = np.dot([0.100, 0.200], x_data) + 0.300
# 构造一个线性模型
#
b = tf.Variable(tf.zeros([1]))
W ... |
from django.urls import path
from . import views
urlpatterns = [
path('get-orbit-list', views.GetOrbitList.as_view()),
path('get-instrument-list', views.GetInstrumentList.as_view()),
path('evaluate-architecture', views.EvaluateArchitecture.as_view()),
path('run-local-search', views.RunLocalSearc... |
from .functions import *
from scipy.io import loadmat
import os
DIRNAME = os.path.dirname(__file__)
class CI_HS:
def __init__(self):
mat = loadmat(os.path.join(DIRNAME, 'data/CI_H.mat'))
self.M1 = mat['Rotation_Task1']
self.M2 = mat['Rotation_Task2']
self.functions = [self.f1, sel... |
# -*- coding: utf-8 -*-
r"""
Modular parametrization of elliptic curves over `\QQ`
By the work of Taylor--Wiles et al. it is known that there
is a surjective morphism
.. math::
\phi_E: X_0(N) \rightarrow E.
from the modular curve `X_0(N)`, where `N` is the conductor of `E`.
The map sends the cusp `\infty` to th... |
"""Install script for the dialogKit Package.
This script installs a _link_ to the current location
of dialogKit. It does not copy anything. It also means that
if you move your dialogKit folder, you'll have to run the
install script again.
"""
from distutils.sysconfig import get_python_lib
import os, sys
def instal... |
import PySimpleGUI as sg
from random import randint
sg.theme('Dark Blue 3')
layout = [ [sg.Text('Temperature'), sg.T(' '*30), sg.Text(size=(8,1), key='-TEMP OUT-')],
[sg.Text('Set Temp'), sg.T(' '*8), sg.Input(size=(8,1), key='-IN-'), sg.T(' '*10), sg.Button('Set')],
[sg.Button('Off'), sg.T('... |
from pypif.obj.common import Property, Scalar
from .base import DFTParser, Value_if_true, InvalidIngesterException
import os
from pypif.obj.common.value import Value
from dftparse.pwscf.stdout_parser import PwscfStdOutputParser
from ase import Atoms
class PwscfParser(DFTParser):
'''
Parser for PWSCF calculat... |
#!/usr/bin/env python3
import requests
from requests.auth import HTTPBasicAuth
import urllib3
import json
import pprint
##########
# SET-UP #
##########
urllib3.disable_warnings()
#############
# FUNCTIONS #
#############
def get_Epnm_Events(epnm):
#retrieve epnm events with epnm api
base_uri = 'https://' +... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try... |
"""
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 not use this ... |
import os.path
import random
from scripts.token.read_freq_batch import read_tokens
def select_sentences(select_tokens, src_filename, tgt_filename, hint='', copy_num=1, random_select=0):
filter_src, filter_tgt = [], []
non_select_src, non_select_tgt = [], []
with open(src_filename) as f_src, open(tgt_file... |
# Generated by Django 2.1.3 on 2018-12-03 16:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("api", "0022_change_default_on_results"),
("api", "0021_plan_post_install_message"),
]
operations = [] |
# Generated by Django 3.0.8 on 2020-07-18 04:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0007_auto_20200717_2347'),
]
operations = [
migrations.CreateModel(
name='TCN_RX',
fields=[
... |
from __future__ import annotations
from collections import defaultdict
import copy
import itertools
from typing import TYPE_CHECKING, Dict, List, Sequence, cast
import numpy as np
from pandas._libs import internals as libinternals
from pandas._typing import ArrayLike, DtypeObj, Manager, Shape
from pandas.util._decor... |
__author__ = 'ing' |
from ddtrace import patch_all
from .base.celery import app as celery_app
from .base.wsgi import application
patch_all(requests=True) |
# Create your views here.
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import QuerySet
from django.http import HttpResponse, JsonResponse, Http404, HttpResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf impor... |
from .... import service_session
from .... import exceptions
import abc
def generator(iterable):
for item in iterable:
yield item
class SimpleStorageServiceSession(service_session.StackServiceSession, abc.ABC):
@abc.abstractmethod
def list_buckets(self, **kwargs):
return generator(())
... |
#!/usr/bin/env python3.7
from logging import DEBUG
from ai.lib.map_envi_cos.Envi import Envi
from ai.COS import COS
from logger import logger
log = logger.getLogger('test')
log.setLevel(DEBUG)
cos = COS('./cos_credentials', './recipe-test.json', logger)
envi = Envi('./recipe-test.json', cos.resource, logger)
log.... |
import glob
import json
import os
from tqdm import tqdm
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('out_dir')
args = parser.parse_args()
out_dir = args.out_dir
papers = {}
for path in tqdm(sorted(glob.glob(os.path.join(out_dir, '_*.js... |
print('hello!! welcome to albar coffe shop!!')
name = input('what is your name? ')
order = input('okay '+name+', we are serving some tea, cappucino, espresso, and coffe\nwhat do you want order for today? ')
if order == "tea":
quantity = input('how much '+order+' do you want? (number) ')
total = int(quantity)*2000
... |
# Copyright (c) 2020 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 appli... |
#!/bin/python
from deap import tools
from deap import base
import promoterz
import statistics
class Locale():
def __init__(self, World, name, position, loop):
self.World = World
self.name = name
self.EPOCH = 0
self.position = position
self.EvolutionStatistics = []
... |
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRe... |
# tests.cloud.auth.credentials is python-3.6 source file
# MIT License
#
# Copyright (c) 2021 Handle.
#
# 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 witho... |
"""Check whether a sequence can be converted to a Lena Sequence."""
# otherwise import errors arise
# from . import source
def is_fill_compute_el(obj):
"""Object contains executable methods 'fill' and 'compute'."""
return hasattr(obj, 'fill') and hasattr(obj, 'compute') \
and callable(obj.fill) an... |
# Copyright (c) 2014, Hubert Kario
#
# See the LICENSE file for legal information regarding use of this file.
"""Implementation of the TLS Record Layer protocol"""
import socket
import errno
import copy
try:
# in python 3 the native zip() returns iterator
from itertools import izip
except ImportError:
izi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.