text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- def main(): s, t, u = map(str, input().split()) if len(s) == 5 and len(t) == 7 and len(u) == 5: print('valid') else: print('invalid') if __name__ == '__main__': main()
243
110
""" 嵌套的列表的坑 """ names = ['关羽', '张飞', '赵云', '马超', '黄忠'] courses = ['语文', '数学', '英语'] # 录入五个学生三门课程的成绩 scores = [[None] * len(courses) for _ in range(len(names))] for row, name in enumerate(names): for col, course in enumerate(courses): scores[row][col] = float(input(f'请输入{name}的{course}的成绩:')) print...
328
169
import logging import random import numpy as np import pypinyin import tensorflow as tf from augmentations.augments import Augmentation from utils.speech_featurizers import SpeechFeaturizer from utils.text_featurizers import TextFeaturizer logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(le...
18,672
5,470
"""empty message Revision ID: 2018_04_20_data_src_refactor Revises: 2018_04_11_add_sandbox_topic Create Date: 2018-04-20 13:03:32.478880 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. from sqlalchemy.dialects.postgresql import ARRAY revision = '2018_04_20_data_src_refac...
7,612
2,667
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # coded by Vikas Kundu https://github.com/vikas-kundu # ------------------------------------------- import sys import getopt import time import config from lib.core.parse import banner from lib.core import util from lib.core import installer def options(): ...
1,897
609
# Copyright 2013 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # Copyright 2015 - 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:/...
1,634
489
import xmltodict import json from .models import Tunein from .utils import _init_session from .Exceptions import APIException base_url = 'http://api.shoutcast.com' tunein_url = 'http://yp.shoutcast.com/{base}?id={id}' tuneins = [Tunein('/sbin/tunein-station.pls'), Tunein('/sbin/tunein-station.m3u'), Tunein('/sbin/tun...
2,660
844
from django.core.management.base import BaseCommand, no_translations from django.contrib.auth.models import Group from django.conf import settings import sys class Command(BaseCommand): def handle(self, *args, **options): sys.stdout.write("\nResolving app groups") app_list = [app_name.lower...
581
177
# Copyright (c) 2010-2012 OpenStack Foundation # # 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 agree...
34,343
9,518
"""Prop limits are used to validate the input given to xdl elements. For example, a volume property should be a positive number, optionally followed by volume units. The prop limit is used to check that input supplied is valid for that property. """ import re from typing import List, Optional class PropLimit(object):...
12,101
4,210
""" Provides usable args and kwargs from inspect.getcallargs. For Python 3.3 and above, this module is unnecessary and can be achieved using features from PEP 362: http://www.python.org/dev/peps/pep-0362/ For example, to override a parameter of some function: >>> import inspect >>> def func(a, b=1, c=2,...
3,884
1,287
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import json import os import sys import time from marionette import MarionetteTestCase from marionette.by import By fro...
36,370
10,761
def buttonClick(button): JS(""" var doc = button.ownerDocument; if (doc != null) { var evt = doc.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, null, 0, 0, 0, 0, 0, false, false, false, false, 0, null); button.d...
5,591
1,854
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-10 21:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vendors', '0089_auto_20160602_2123'), ] operations = [ migrations.AlterField...
485
179
from depth_first_search import DFS def articulation_points(graph): n = len(graph) dfs = DFS(graph) order = [None] * n for i, x in enumerate(dfs.preorder): order[x] = i lower = order[:] for x in dfs.preorder[::-1]: for y in graph[x]: if y == dfs.parent[x]: ...
540
195
import pymongo from conf import Configuracoes class Mongo_Database: """ Singleton com a conexao com o MongoDB """ _instancia = None def __new__(cls, *args, **kwargs): if not(cls._instancia): cls._instancia = super(Mongo_Database, cls).__new__(cls, *args, **kwargs) return cls._in...
1,558
481
import machine import pycom import utime from exceptions import Exceptions class Sleep: @property def wakeReason(self): return machine.wake_reason()[0] @property def wakePins(self): return machine.wake_reason()[1] @property def powerOnWake(self): return...
2,947
1,088
import torch import argparse from collections import defaultdict import os import json def load_predictions(input_path): pred_list = [] for file_name in os.listdir(input_path): if file_name.endswith('.pt'): preds = torch.load(os.path.join(input_path, file_name)) pred_list.extend(preds) question_scores = ...
1,260
476
casa = int(input('Qual o valor da casa? ')) sal = int(input('Qual seu salario? ')) prazo = int(input('Quantos meses deseja pagar ? ')) parcela = casa/prazo margem = sal* (30/100) if parcela > margem: print('Este negocio não foi aprovado, aumente o prazo .') else: print("Negocio aprovado pois a parcela é...
388
159
# Generated by Django 3.1.7 on 2021-03-27 18:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('HackBitApp', '0002_company_photo'), ] operations = [ migrations.CreateModel( name='Roadmap', fields=[ ...
1,000
305
# -*- coding: utf-8 -*- """ Created on Wed Jul 22 14:36:48 2020 @author: matth """ import autograd.numpy as np #%% Kernel operations # Returns the norm of the pairwise difference def norm_matrix(matrix_1, matrix_2): norm_square_1 = np.sum(np.square(matrix_1), axis = 1) norm_square_1 = np.reshape(norm_square_...
1,051
425
import json from wptserve.utils import isomorphic_decode def main(request, response): origin = request.GET.first(b"origin", request.headers.get(b'origin') or b'none') if b"check" in request.GET: token = request.GET.first(b"token") value = request.server.stash.take(token) if value is n...
2,371
751
#!/usr/bin/env python3 from pythonosc import osc_bundle_builder from pythonosc import osc_message_builder from pythonosc import udp_client from .device import DeviceObj # OSC Grid Object class OSCGrid(DeviceObj): def __init__(self, name, width, height, ip, port, bri=1): DeviceObj.__init__(self, name, "os...
1,053
352
from .app import db class Project(db.Model): __tablename__ = 'projects' id = db.Column(db.Integer,primary_key=True,autoincrement=True) project_name = db.Column(db.String(64),unique=True,index=True) def to_dict(self): mydict = { 'id': self.id, 'project_name': self.projec...
965
327
from iron_cache import * import unittest import requests class TestIronCache(unittest.TestCase): def setUp(self): self.cache = IronCache("test_cache") def test_get(self): self.cache.put("test_item", "testing") item = self.cache.get("test_item") self.assertEqual(item.value, "te...
1,274
420
#!/usr/bin/env python # -*- coding: utf-8 -*- # __BEGIN_LICENSE__ # Copyright (c) 2009-2013, United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The NGT platform is licensed under the Apache License, Version 2.0 (the # "Lic...
3,914
1,245
#!/usr/bin/env python import argparse DELIMITER = "\t" def merge(genotypes_filename, gq_filename, merged_filename): with open(genotypes_filename, "r") as genotypes, open(gq_filename, "r") as gq, open(merged_filename, "w") as merged: # Integrity check: do the files have same columns? genotypes_...
1,550
524
from .api.server import run_app
32
11
import tweepy import traceback import time import pymongo from tweepy import OAuthHandler from pymongo import MongoClient from pymongo.cursor import CursorType twitter_consumer_key = "" twitter_consumer_secret = "" twitter_access_token = "" twitter_access_secret = "" auth = OAuthHandler(twitter_consumer_key, twitter_...
3,091
1,207
#!/usr/bin/env python """Handles Earth Engine service account configuration.""" import ee # The service account email address authorized by your Google contact. # Set up a service account as described in the README. EE_ACCOUNT = 'your-service-account-id@developer.gserviceaccount.com' # The private key associated wit...
698
218
""" Demonstration of numbers in Python """ # Python has an integer type called int print("int") print("---") print(0) print(1) print(-3) print(70383028364830) print("") # Python has a real number type called float print("float") print("-----") print(0.0) print(7.35) print(-43.2) print("") # Limited precision print...
2,716
1,139
from source.solving_strategies.strategies.solver import Solver class LinearSolver(Solver): def __init__(self, array_time, time_integration_scheme, dt, comp_model, initial_conditions, force, structure_model): super().__ini...
1,676
458
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-24 16:22 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('payment', '0001_initial'), ] ...
1,095
402
"""Implementation of Rule L024.""" from sqlfluff.core.rules.doc_decorators import document_fix_compatible from sqlfluff.rules.L023 import Rule_L023 @document_fix_compatible class Rule_L024(Rule_L023): """Single whitespace expected after USING in JOIN clause. | **Anti-pattern** .. code-block:: sql ...
841
270
""" Plot CMDs for each component. """ import numpy as np from astropy.table import Table import matplotlib.pyplot as plt import matplotlib.cm as cm plt.ion() # Pretty plots from fig_settings import * ############################################ # Some things are the same for all the plotting scripts and we put # thi...
2,847
1,207
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved. # import pytest from snowflake.connector.errors import (ProgrammingError) def test_binding_security(conn_cnx, db_parameters): """ SQL Injection Tests """ try: with conn_cnx()...
5,326
1,538
# Natural Language Toolkit: Language Models # # Copyright (C) 2001-2008 University of Pennsylvania # Author: Steven Bird <sb@csse.unimelb.edu.au> # URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT class ModelI(object): """ A processing interface for assigning a probability to the next word....
1,071
304
import os from graphene_sqlalchemy import SQLAlchemyObjectType from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base POSTGRES_CONNECTION_STRING = ( os.environ.get("POSTGRES_CONNECTION_STRING") ...
1,047
340
# microsig """ Author: Maximilliano Rossi More detail about the MicroSIG can be found at: Website: https://gitlab.com/defocustracking/microsig-python Publication: Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020) DOI:10.1088/1361-6501/ab42bb. "...
16,478
6,510
# Copyright 2020 Tier IV, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
4,146
1,495
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() # If you don't do this you cannot use Bootstrap CSS class LoginFor...
2,642
766
import pandas as pd from pandas import DataFrame df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True) df['H-L'] = df.High - df.Low # Giving us count (rows), mean (avg), std (standard deviation for the entire # set), minimum for the set, maximum for the set, and some %s in that range. print( df.des...
5,641
1,975
import cv2 import numpy as np import threading def test(): while 1: img1=cv2.imread('captured car1.jpg') print("{}".format(img1.shape)) print("{}".format(img1)) cv2.imshow('asd',img1) cv2.waitKey(1) t1 = threading.Thread(target=test) t1.start()
292
112
# Copyright 2013 Cloudbase Solutions Srl # # Author: Claudiu Belu <cbelu@cloudbasesolutions.com> # Alessandro Pilotti <apilotti@cloudbasesolutions.com> # # 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 o...
7,856
2,612
# system from io import IOBase, StringIO import os # 3rd party import click # internal from days import DayFactory # import logging # logger = logging.getLogger(__name__) # logger.setLevel(logging.DEBUG) # ch = logging.StreamHandler() # logger.addHandler(ch) @click.group(invoke_without_command=True) @click.option...
1,126
415
from matplotlib.colors import LinearSegmentedColormap from numpy import nan, inf # Used to reconstruct the colormap in viscm parameters = {'xp': [-5.4895292543686764, 14.790571669586654, 82.5546687431056, 29.15531114139253, -4.1316769886951761, -13.002076438907238], 'yp': [-35.948168839230306, -42.27337...
17,033
13,521
import matplotlib.pyplot as plt import numpy as np import math from algorithm.planner.utils.car_utils import Car_C PI = np.pi class Arrow: def __init__(self, x, y, theta, L, c): angle = np.deg2rad(30) d = 0.3 * L w = 2 x_start = x y_start = y x_end = x + L * np.co...
3,885
1,810
from sqlalchemy import Integer, Text, DateTime, func, Boolean, text from models.database_models import Base, Column class Comment(Base): __tablename__ = "comment" id = Column(Integer, primary_key=True, ) user_id = Column(Integer, nullable=False, comment="评论用户的 ID") post_id = Column(Integer, nullable...
696
237
import json import re from datetime import datetime from json.decoder import JSONDecodeError import click from boto3.session import Session from boto3_type_annotations.ecs import Client from botocore.exceptions import ClientError, NoCredentialsError from dateutil.tz.tz import tzlocal from dictdiffer import diff JSON_...
27,779
7,433
import networkx as nx from scipy.special import comb import attr @attr.s class Count(object): """Count class with monochromatic and bichromatic counts""" n = attr.ib() monochromatic = attr.ib(default=0) bichromatic = attr.ib(default=0) def count_edge(self, u, v): if (u < self.n / 2) != (v...
3,715
1,391
from typing import Callable, Collection, Iterable, List, Union from data.anagram import anagram_iter from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer Transformer = Callable[['bloom_node.BloomNode'], 'bloom_node.BloomNode'] _SPACE_MASK = bloom_mask.for_alpha(' ') def merge_fn( host: 'b...
4,516
1,518
import json import re import logging import html.parser import zlib import requests from gogapi import urls from gogapi.base import NotAuthorizedError, logger from gogapi.product import Product, Series from gogapi.search import SearchResult DEBUG_JSON = False GOGDATA_RE = re.compile(r"gogData\.?(.*?) = (.+);") CLIEN...
15,854
5,103
import pathlib import os from setuptools import setup # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # specify requirements of your package here REQUIREMENTS = ['biopython', 'numpy', 'pandas'] setup(name='stacksPairwi...
943
298
#! /usr/bin/env python import os import sys args = sys.argv[1:] os.system('python -O -m spanningtree.csv_experiment_statistics ' + ' '.join(args))
156
58
import torch import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact.utils.experiment_util...
2,536
812
from numpy import array from pickle import load from pandas import read_csv import os from BioCAT.src.Combinatorics import multi_thread_shuffling, multi_thread_calculating_scores, make_combine, get_score, get_max_aminochain, skipper # Importing random forest model modelpath = os.path.dirname(os.path.abspath(__file__)...
12,328
3,729
# built-in from typing import Optional # app from .common import TOKENS, Extractor, Token, traverse from .value import UNKNOWN, get_value get_returns = Extractor() inner_extractor = Extractor() def has_returns(body: list) -> bool: for expr in traverse(body=body): if isinstance(expr, TOKENS.RETURN + TOK...
857
296
def aaa(): # trick sphinx to build link in doc pass # retired ibmqx2_c_to_tars =\ { 0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2] } # 6 edges # retired ibmqx4_c_to_tars =\ { 0: [], 1: [0], 2: [0, 1, 4], 3: [2, 4], 4: [] } # 6 edges # retired ibmq16Rus_c_to_tars = \ { ...
1,526
1,045
import signal import requests import time from math import floor shutdown = False MAIN_TAKER = 0.0065 MAIN_MAKER = 0.002 ALT_TAKER = 0.005 ALT_MAKER = 0.0035 TAKER = (MAIN_TAKER + ALT_TAKER)*2 MAKER = MAIN_MAKER + ALT_MAKER TAKEMAIN = MAIN_TAKER - ALT_MAKER TAKEALT = ALT_TAKER - MAIN_MAKER BUFFER = 0.0...
14,599
5,140
""" ========================================== Genrating feedthrough from single instance ========================================== This example demostrates how to generate a feedthrough wire connection for a given scalar or vector wires. **Initial Design** .. hdl-diagram:: ../../../examples/basic/_initial_design.v...
1,479
520
from __future__ import annotations from typing import Optional, Union from tools import tools from exceptions import workflow_exceptions class Workflow: """A class to represent a workflow. Workflow class provides set of methods to manage state of the workflow. It allows for tool insertions, removals and...
9,131
2,577
class Donation_text: # Shown as a message across the top of the page on return from a donation # used in views.py:new_donation() thank_you = ( "Thank you for your donation. " "You may need to refresh this page to see the donation." ) confirmation_email_subject = ( 'Thank y...
2,849
829
from django.apps import apps from django.test import override_settings from wagtail_live.signals import live_page_update def test_live_page_update_signal_receivers(): assert len(live_page_update.receivers) == 0 @override_settings( WAGTAIL_LIVE_PUBLISHER="tests.testapp.publishers.DummyWebsocketPublisher" ) ...
624
205
# -*- coding: utf-8 -*- """ Script Name: Author: Do Trinh/Jimmy - 3D artist. Description: """ # ------------------------------------------------------------------------------------------------------------- """ Import """ import os from PySide2.QtWidgets import (QFrame, QStyle, QAbstractItemView, QSizePolicy...
14,826
4,611
from selenium import webdriver from selenium.webdriver.chrome.options import Options import sys import time import urllib.request import os sys.stdin = open('idpwd.txt') site = input() id = input() pwd = input() # selenium에서 사용할 웹 드라이버 절대 경로 정보 chromedriver = 'C:\Webdriver\chromedriver.exe' # selenum의 webdriver에 앞서 설치...
2,509
1,046
from io import StringIO # 定义一个 StringIO 对象,写入并读取其在内存中的内容 f = StringIO() f.write('Python-100') str = f.getvalue() # 读取写入的内容 print('写入内存中的字符串为:%s' %str) f.write('\n') # 追加内容 f.write('坚持100天') f.close() # 关闭 f1 = StringIO('Python-100' + '\n' + '坚持100天') # 读取内容 print(f1.read()) f1.close() # 假设的爬虫数据输出函数 outputDa...
1,433
927
import biothings.hub.dataload.uploader as uploader class DrugCentralUploader(uploader.DummySourceUploader): name = "drugcentral" __metadata__ = { "src_meta" : { "url" : "http://drugcentral.org/", "license_url" : "http://drugcentral.org/privacy", "lic...
10,595
2,091
"""Contains tests for finpack/core/cli.py """ __copyright__ = "Copyright (C) 2021 Matt Ferreira" import os import unittest from importlib import metadata from docopt import docopt from finpack.core import cli class TestCli(unittest.TestCase): @classmethod def setUpClass(cls): cls.DATA_DIR = "temp" ...
2,751
992
class Yaratik(object): def move_left(self): print('Moving left...') def move_right(self): print('Moving left...') class Ejderha(Yaratik): def Ates_puskurtme(self): print('ates puskurtum!') class Zombie(Yaratik): def Isirmak(self): print('Isirdim simdi!') enemy =...
612
239
""" Author: Peratham Wiriyathammabhum """ import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors def affinity_graph(X): ''' This function returns a numpy array. ''' ni, nd = X.shape A = np.zeros((ni, ni)) for i in range(ni): for j in range(i+1, ni): dist = ((X[i] - X[j])**...
1,527
713
# Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """This package houses all subcommands for the recipe engine. See implementation_details.md for the expectations of the modules in this directory...
10,124
3,203
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """STCPipelinemodule.""" import numpy as np import gzip as gz from .pipeline import TransformationPipeline, Transformer class SparsityTransformer(Transformer): """A transformer class to sparsify input data.""" def __init__(s...
7,295
2,142
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ------------------------------------------------------------ # File: __init__.py.py # Created Date: 2020/6/24 # Created Time: 0:12 # Author: Hypdncy # Author Mail: hypdncy@outlook.com # Copyright (c) 2020 Hypdncy # ---------------------------------------------------------...
1,150
383
import numpy as np import pytest from pytest import approx from pymt.component.grid import GridMixIn class Port: def __init__(self, name, uses=None, provides=None): self._name = name self._uses = uses or [] self._provides = provides or [] def get_component_name(self): return ...
7,146
2,853
import sys def load_log_sp(filename): data = [] with open(filename) as f: for line in f.readlines(): tokens = line.split(" ") spidx = line.find("SP:") endidx = line.find(' ', spidx) data.append((line[0:4], line[spidx+3:endidx])) return data if __nam...
730
271
"""Exercise 1 Usage: $ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100 To know which GPU to use, you can check it with the command $ nvidia-smi """ import argparse import os import mlflow import pickle import numpy as np impo...
10,203
2,632
# -*- coding: utf-8 -*- from __future__ import absolute_import from pkg_resources import parse_version from warnings import warn from copy import deepcopy import networkx as nx from networkx.readwrite import json_graph from catpy.applications.base import CatmaidClientApplication NX_VERSION_INFO = parse_version(nx....
7,576
2,244
from typing import Optional from watchmen_auth import PrincipalService from watchmen_data_kernel.cache import CacheService from watchmen_data_kernel.common import DataKernelException from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator from watchmen_meta.common...
1,993
600
nota1 = float(input('Digite a nota da primeira nota ')) peso1 = float(input('Digite o peso da primeira nota ')) nota2 = float(input('Digite a nota da seugundo nota ')) peso2 = float(input('Digite o peso da segundo nota ')) media = (nota1/peso1+nota2/peso2)/2 print('A média das duas notas é:', media)
304
122
from importlib import import_module from typing import Any def import_string(path: str) -> Any: """Imports a dotted path name and returns the class/attribute. Parameters ---------- path: str Dotted module path to retrieve. Returns ------- Class/attribute at the given import path....
882
246
#!/usr/bin/env python import json import os import re from enum import Enum from os.path import join from le_utils.constants import content_kinds from le_utils.constants import exercises from le_utils.constants import file_formats from le_utils.constants import licenses from ricecooker.chefs import SushiChef from ric...
27,448
10,111
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
19,118
6,581
import numpy as np import os import json import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset from naslib.utils.utils import AverageMeterGroup from naslib.predictors.utils.encodings import encode from naslib.predictors imp...
7,175
2,261
from pythonforandroid.toolchain import Recipe, shprint, current_directory, ArchARM from os.path import exists, join, realpath from os import uname import glob import sh class LibX264Recipe(Recipe): version = 'x264-snapshot-20170608-2245-stable' # using mirror url since can't use ftp url = 'http://mirror.yand...
1,301
449
#coding=utf-8 try: if __name__.startswith('qgb.Win'): from .. import py else: import py except Exception as ei: raise ei raise EnvironmentError(__name__) if py.is2(): import _winreg as winreg from _winreg import * else: import winreg from winreg import * def get(skey,name,root=HKEY_CURRENT_USER,returnTyp...
1,704
754
import unittest import paramiko from tornado.httputil import HTTPServerRequest from tests.utils import read_file, make_tests_data_path from webssh.handler import MixinHandler, IndexHandler, InvalidValueError class TestMixinHandler(unittest.TestCase): def test_get_real_client_addr(self): handler = MixinH...
3,555
1,212
import logging from unittest import mock from unittest.mock import call from django.conf import settings from django.contrib.auth import get_user_model from django.core.signing import Signer from django.urls import reverse from django.http import Http404 from django.test import RequestFactory from braces.views import...
17,499
5,417
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os sys.path.insert(0, os.path.abspath('..')) from clint import resources resources.init('kennethreitz', 'clint') lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt...
1,032
350
from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^image/$', views.add_image, name='upload_image'), url(r'^profile/$', views.profile_info, name='profile'), url(r'...
813
291
import random import math from fractions import Fraction from datetime import datetime from jinja2 import Template # empty class for passing to template engine class Recipe: def __init__(self): return # returns flour percent using flour type def get_special_flour_percent(flourType: str, breadFlourPercent:int) -> ...
11,247
4,576
import datetime from unittest.mock import patch import dns.resolver import dns.rrset import pytest import pytz from django.utils import timezone from freezegun import freeze_time from rest_framework import status from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team from posthog.te...
19,177
6,015
import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt from os import listdir from tensorflow.keras.callbacks import ModelCheckpoint dataDir = "./data/trainSmallFA/" files = listdir(dataDir) files.sort() totalLength = len(files) inputs = np.empty((len(files), 3, 64, 64)...
1,248
520
from pepper.framework import * from pepper import logger from pepper.language import Utterance from pepper.language.generation.thoughts_phrasing import phrase_thoughts from pepper.language.generation.reply import reply_to_question from .responder import Responder, ResponderType from pepper.language import UtteranceTy...
2,781
757
# -*- coding: utf-8 -*- import re from unicodedata import normalize from flask import Blueprint, render_template, current_app from flask import redirect, url_for, g, abort from sqlalchemy import desc from fedora_college.core.database import db from fedora_college.modules.content.forms import * # noqa from fedora_colle...
7,076
2,029
"""Test the Airthings config flow.""" from unittest.mock import patch import airthings from homeassistant import config_entries from homeassistant.components.airthings.const import CONF_ID, CONF_SECRET, DOMAIN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import RESULT_TYPE_CREATE_EN...
3,611
1,151
# ------------------------------------------------------------------------------ # Copyright (c) NKU # Licensed under the MIT License. # Written by Xuanyi Li (xuanyili.edu@gmail.com) # ------------------------------------------------------------------------------ import os import torch import torch.nn.functional as F #...
1,726
673
from aiohttp import web import base64 import io import face_recognition async def encode(request): request_data = await request.json() # Read base64 encoded image url = request_data['image'].split(',')[1] image = io.BytesIO(base64.b64decode(url)) # Load image data np_array = face_recognition....
1,036
339
# ~~~ # This file is part of the paper: # # " An Online Efficient Two-Scale Reduced Basis Approach # for the Localized Orthogonal Decomposition " # # https://github.com/TiKeil/Two-scale-RBLOD.git # # Copyright 2019-2021 all developers. All rights reserved. # License: Licensed as BSD 2-Clause ...
657
237
import os import shutil import numpy as np import pandas as pd ...
8,060
1,939
import os if __name__ == "__main__": dims = ["32", "64", "128", "256", "512", "1024", "2048"] for dim in dims: os.system( f"perf stat -e r11 -x, -r 10 ../matmul.out ../data/mat-A-{dim}.txt ../data/mat-B-{dim}.txt ./out/out-{dim}.txt 2>>res_arm.csv" ) print(f"Finished {dim}...
346
158