text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from models import * # Create your views here. def index(req): context = HomeContext("Home", Facade.getSkills(), Facade.getHobbies()) return render(req, 'index.html', context=vars(context)) def profile(req): ...
1,041
318
# -*- coding: utf-8 -*- # Date: 2020/3/17 12:16 """ an engine for deep learning task """ __author__ = 'tianyu' import abc import random import time import warnings import numpy as np import torch.backends.cudnn import torch.nn.functional as F import torch.utils.data from torch.optim.lr_scheduler import StepLR from ....
16,981
5,139
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `ninjadog` package.""" # TODO: test raises ValueError when pug cli can't be found and not passed explicitly to renderer def test_npm_installed(): from subprocess import Popen assert Popen(('which', 'npm')).wait() == 0, 'npm must be installed' def...
3,736
1,278
from rest_framework import viewsets, permissions from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.response import Response from rest_framework import status from core.serializers import TodoSerializer, TodoDetailSerializer from core.models import Todo class TodoApiViewSet(view...
1,610
470
from ._DeviceInfo import *
27
9
from django.contrib.auth.forms import UserCreationForm from users.models import User, Profile from django import forms class RegistrationForm(UserCreationForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') def clean_password2(self): cd = self.cleaned_data ...
788
233
from py2neo import Graph import numpy as np import pandas as pd graph = Graph("http://192.168.50.179:7474", auth=("neo4j", "qwer")) def create_attribute_question(): company = graph.run('MATCH (n:company) RETURN n.name as name').to_ndarray() person = graph.run('MATCH (n:person) RETURN n.name as name'...
2,513
992
import cv2 from scipy.spatial import distance as dist def mouth_aspect_ratio(mouth) -> float: # compute the euclidean distances between the two sets of # vertical mouth landmarks (x, y)-coordinates A = dist.euclidean(mouth[2], mouth[10]) # 51, 59 B = dist.euclidean(mouth[4], mouth[8]) # 53, 57 ...
1,095
364
import pandas as pd import os import tarfile import glob import json def unzip_rna_seq_data(file_name, desired_folder_name): ''' Downloaded RNA files are tarfiles, this unzips them''' if 'tar' in file_name: open_tar = tarfile.open(file_name) open_tar.extractall(f'{desired_folder_name}') ...
3,626
1,142
import re from collections import OrderedDict from django.conf.urls import url as django_url, include from django.core.urlresolvers import RegexURLResolver, RegexURLPattern from django.utils.encoding import force_text import logging # Using FastUrl has a couple of caveats: # 1. FastUrl tries to keep the resolution ord...
7,268
2,138
import os import json import keras import numpy as np import csv from experiments import config import utils import utils_train import models import argparse class Data(object): """Class that deals with all the data mess """ def __init__(self, data_splits_path, data_path, input_patch_size, batch_size, ...
6,679
2,180
# DEFUALT SETUP FOR NUMBERS DEFAULT_FLOAT = float # DEFAULT SETUP FOR STRINGS DEFAULT_LABEL_LENGTH = 120
106
44
from logging import exception, info from requests import post as request_post from requests.exceptions import RequestException from typing import Union from uuid import UUID from django.conf import settings from django.db.models import ( CASCADE, CharField, ForeignKey, OneToOneField, ) from web3.types ...
6,666
1,907
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ n = 0 k = len(nums) for i in range(k-n): if nums[i]==0: while k-1-n >= i or nums[k-...
494
188
import argparse from reward_surfaces.agents.make_agent import make_agent import torch import json import os from glob import glob def main(): parser = argparse.ArgumentParser(description='Train an agent and keep track of important information.') parser.add_argument('save_dir', type=str, help="Directory where ...
2,838
932
"""Tests on the base ladder structure.""" import pytest if __name__ == "__main__": pytest.main()
103
36
from django.conf.urls import url from django.urls import path from courses.views import courses_detail from courses.views.translate import get_translations urlpatterns = [ url(r'(?P<institution_id>[\w\-]+?)/(?P<course_id>[\w\-\~\$()]+?)/(?P<kis_mode>[\w\-]+?)/', courses_detail, name='courses_detail'), ...
390
138
from hamcrest import assert_that, equal_to, is_ from opencypher.ast import Expression, NonEmptySequence, Order, SortItem, SortOrder def test_order(): ast = Order( items=NonEmptySequence[SortItem]( SortItem( expression=Expression("foo"), order=SortOrder.DESCENDI...
447
129
from Model import Critic from mindspore import Tensor from mindspore import load_param_into_net import copy C1 = Critic(state_dim=2, action_dim=1) C2 = Critic(state_dim=2, action_dim=1) # C1.load_parameter_slice(C2.parameters_dict()) # load_param_into_net(C1, C2.parameters_dict()) c1_ = C1.parameters_dict() c2_ = C2.pa...
444
187
from .flatwrapper import FlatWrapper class ExprFlatWrapper(FlatWrapper): def flat_wrap(self): self.reset_wrapping() if self.should_wrap_children(self.original_node): self.body.extend(self.original_node.value.wrapper.flat_wrap()) else: self.body.append(self.original_...
351
106
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from cricdb_setup import Team, Player, Base, Batsman, Bowler, Fielder, PlayerStrength, PlayerWeakness, PlayerMoment, Video engine = create_engine('sqlite:///cricdb.db') # Bind the engine to the metadata of the Base class so that the #...
1,742
548
from dataclasses import dataclass, field from typing import Optional, Union from bindings.gmd.dq_evaluation_method_type_code import DqEvaluationMethodTypeCode from bindings.gmd.nil_reason_enumeration_value import NilReasonEnumerationValue __NAMESPACE__ = "http://www.isotc211.org/2005/gmd" @dataclass class DqEvaluati...
1,006
336
#import time from spark.ReqBase import ReqBase class ReqTwisted(ReqBase): """ specialized on Twisted requests """ def __init__(self, req, reactor, properties={}): self.twistedreq = req self.http_accept_language = self.twistedreq.getHeader('Accept-Language') #cookie give me major problem! self.saved_cookies={...
3,964
1,606
r""" This module contains several utility functions which can be used e.g. for thresholding the alpha-shearlet coefficients or for using the alpha-shearlet transform for denoising. Finally, it also contains the functions :func:`my_ravel` and :func:`my_unravel` which can be used to convert the alpha-shearlet coefficien...
11,093
3,337
# -*- coding: utf-8 -*- # Copyright (c) 2018-2021, earthobservations developers. # Distributed under the MIT License. See LICENSE for more info. import re from datetime import datetime import pytest from tests.provider.dwd.radar import station_reference_pattern_unsorted from wetterdienst.provider.dwd.radar import Dwd...
2,692
1,021
# -*- coding: utf-8 -*- import pytest import json from pathlib import Path @pytest.fixture def accounts_httpRequests1hGroupsFixture(scope="session"): with open("tests/data/accounts/httpRequests1hGroups.json") as data: res = json.load(data) return res @pytest.fixture def zones_httpRequests1hGroupsFix...
710
241
#!/usr/bin/env python import os import sys import glob import argparse from pathlib import Path from collections import defaultdict from hashlib import sha1 import numpy as np import sacrebleu import tabulate from pysimt.metrics.simnmt import AVPScorer, AVLScorer, CWMScorer, CWXScorer """This script should be run ...
4,529
1,542
import logging from django.views.generic.base import TemplateView from django.views.generic.detail import DetailView from django.shortcuts import redirect from .controller import ( create_canvas_course, start_course_template_copy, finalize_new_canvas_course, get_canvas_course_url ) from .mixins import C...
3,713
1,039
import sys import numpy as np from .sam_utils import load_samfile, fetch_reads def _check_SE_event(gene): """Check SE event""" if (len(gene.trans) != 2 or gene.trans[0].exons.shape[0] != 3 or gene.trans[1].exons.shape[0] != 2 or np.mean(gene.trans[0].exons[[0, 2], :] == ...
7,389
2,911
#==============================================================================# # Enasis Network Common Libraries # # Python Functions Time Processing # #============================================================================...
1,795
387
from colorama import Fore, Back, Style, init import pyautogui import time import os os.system("mode 120, 30") class Poxtrop(): def __init__(cuspida): cuspida.settings() def interface(cuspida): init() print(Fore.YELLOW + """ ######### ###### ## ##...
2,661
787
import click from typing import Callable, List from .effect_parade import AbstractEffectParade DISPLAY_OPTIONS = [ click.option('-p', '--parade', type=click.Choice(AbstractEffectParade.get_parade_options()), help="How the effects are displayed.", default=AbstractEffectParade.get_default_option()...
1,527
445
import boto3 import os import tarfile if __name__ == "__main__": s3 = boto3.client('s3', aws_access_key_id="AKIAY6UR252SQUQ3OSWZ", aws_secret_access_key="08LQj" "+ryk9SMojG18vERXKKzhNSYk5pLhAjrIAVX") output_path = "./data.tar.gz" with open(o...
587
227
import os, sys import logging import numpy as np import pandas as pd from matplotlib import pyplot as plt from scipy.ndimage import label from .utils import watershed_tissue_sections, get_spot_adjacency_matrix # Read in a series of Loupe annotation files and return the set of all unique categories. # NOTE: "Undefine...
8,247
3,181
from flask import ( Blueprint, render_template, request, session, current_app as app ) from flask_login import current_user from floa.extensions import loa from floa.models.library import Library bp = Blueprint( name='home', import_name=__name__, url_prefix="/" ) @app.errorhandler...
1,729
542
import logging import orangengine from api.models import Device as DeviceModel from celery.utils.log import get_task_logger from api import debug celery_logger = get_task_logger(__name__) if debug: celery_logger.setLevel(logging.DEBUG) celery_logger.debug('Enabled Debug mode') class OEDeviceFactory(object...
3,496
934
# Generated by Django 2.2.7 on 2020-12-22 16:01 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app1', '0059_auto_20201111_2321'), ] operations = [ migrations.RemoveField( model_name='event', name...
753
260
from stacks.decode_string import decode_string def test_decode_string(): assert decode_string("3[a]2[bc]") == "aaabcbc" assert decode_string("3[a2[c]]") == "accaccacc" assert decode_string("2[abc]3[cd]ef") == "abcabccdcdcdef"
240
94
# import socket ip = "127.0.0.1" port = 5001 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind((ip,port)) i=0 while True: data, addr = s.recvfrom(1024) print "Received from ",addr print "Received ",data s.close()
239
110
import copy import logging import pathlib import torch import torch.nn as nn from yolov3.config import get_default_config from yolov3.utils.config_node import ConfigNode class CheckPointer: def __init__( self, model, optimizer=None, scheduler=None, che...
4,240
1,215
# -*- coding: utf-8 -*- from autograd.blocks.trigo import sin, cos from autograd.variable import Variable import numpy as np import autograd as ad from autograd import config class test(): def __init__(self, x): self.x=x def parent(self): print('parent') class...
505
166
#!/usr/bin/python3 # 文件名:using_sys.py import sys print('命令行参数如下:') for i in sys.argv: print(i) print('\n\nPython路径为:',sys.path,'\n')
135
72
import math import numbers import torch from torch import nn from torch.nn import functional as F def gaussian_filter(in_channel, out_channel, kernel_size=15, sigma=3): """ This method returns 2d gaussian filter input : in_channel : Number of input channels out_channel : Expected number of output ...
1,749
570
from opfu.security import Security class Stock(Security): def __init__(self, S, T, is_short=False): self.S = S self.K = self.S self.T = T Security.__init__(self, is_short, price=0) def payoff_long(self, P): return P - self.S def graph_payoff(self, start=0, end=Non...
664
230
# ABC103a import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) a = list(map(int, input().split())) a.sort(reverse=True) print(abs(a[1]-a[0])+abs(a[1]-a[2]))
172
84
import os config = { #iam 'ACCOUNT_INACTIVE_DAYS': 30, #Accounts are inactive if not used for 30 days 'PASSWORD_ROTATION_DAYS': 90, #Paswords should be rotated every 90 days 'ACCESS_KEY_ROTATION_DAYS': 90 #Access Keys should be rotated every 90 days }
283
110
#!/usr/bin/env python from six import BytesIO import wx import wx.richtext as rt import images #---------------------------------------------------------------------- class RichTextFrame(wx.Frame): def __init__(self, *args, **kw): wx.Frame.__init__(self, *args, **kw) self.MakeMenuBar() ...
28,356
9,260
from django.db import models from django.contrib.auth.models import User class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=64, null=False) email = models.EmailField(max_length=100, null=False) class Advisor(Person): cpf = model...
1,105
348
"""Implements a HD44780 character LCD connected via NodeMCU GPIO pins.""" from machine import Pin from utime import sleep, ticks_ms from nodemcu_gpio_lcd import GpioLcd # Wiring used for this example: # # 1 - Vss (aka Ground) - Connect to one of the ground pins on you NodeMCU board. # 2 - VDD - Connect to 3V # 3 -...
1,784
694
import dgl import errno import numpy as np import os import random import torch from collections import defaultdict from rdkit import Chem def mkdir_p(path): """Create a folder for the given path. Parameters ---------- path: str Folder to create """ try: os.makedirs(path) ...
11,579
3,658
import json import os import re import uuid from knowledge_graph_attr import KnowledgeGraph, Dijkstra total = 0.0 ignored = 0.0 class Preprocessor(object): def __init__(self): pass def _word_cleanup(self, lookups): result = [] for word in lookups: try: a...
8,602
2,487
import csv import os import difflib import statistics import numpy as np import matplotlib.pyplot as plt SMALL_SIZE = 12 MEDIUM_SIZE = 14 LARGE_SIZE = 18 plt.rc('font', size=SMALL_SIZE) # controls default text sizes # plt.rc('title', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', lab...
5,168
2,192
# sys.stdin.readline() import sys input = sys.stdin.readline a, b, c, d = map(int, input().split()) if a+b > c+d: ans = 'Left' elif a+b == c+d: ans = 'Balanced' else: ans = 'Right' print(ans)
205
92
def flatten(elems): stack = [] if isinstance(elems, (list, tuple)): for x in elems: stack += flatten(x) elif isinstance(elems, (dict)): for x in elems.values(): stack += flatten(x) else: stack.append(elems) return stack
255
95
#!/usr/bin/env python import copy import os.path as op NAME_FMT = "%-20s" class FileStats(object): ANNOTS = ['code', 'annot', 'inv', 'harness'] def __init__(self, code=0, annot=0, inv=0, harness=0, comment='//'): self.code = code self.annot = annot self.inv = inv sel...
3,972
1,487
""" by_locator : tuple --> (<selenium By object>, <selector string>) x_offset : int --> integer value of x offset in pixels y_offset : int --> integer value of y offset in pixels x_destination : int --> integer value of x location on page y_desitination : int ...
3,822
1,213
n = int(input()) def even(x): yield x * 2 for number in range(n): print(next(even(number))) # Don't forget to print out the first n numbers one by one here
174
63
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 from __future__ import unicode_literals from django.db import connections from django.utils import timezone from django.utils.functional import cached_property from cronman.config import app_settings from cronman.job import BaseCronJob from cronman.models import Cro...
2,096
672
import re parse_re = re.compile( r'pos\=\<(?P<x>-?\d+),(?P<y>-?\d+),(?P<z>-?\d+)\>, r\=(?P<r>\d+)' ) def parse(text): m = parse_re.match(text) d = m.groupdict() pos = int(d['x']), int(d['y']), int(d['z']) r = int(d['r']) return pos, r def dist(a, b): return sum(abs(x1-x2) for x1, x2 in zi...
2,893
1,186
#!/usr/bin/env python from setuptools import find_packages, setup setup( name="lib_elo_calculator", packages=find_packages(include=['lib_elo_calculator']), version='0.1.0', description='contains functions and formulas for calculating elo', author='Connor Mullett', license='MIT', setup_requires=['pytest-r...
381
127
tot_name = os.path.join(os.path.dirname(__file__),'src/data', file_name) # open the json datafile and read it in with open(tot_name, 'r') as inputfile: doc = json.load(inputfile) # transform the data to the correct types and convert temp to celsius id_movie = int(doc['id']) movie_name = str(doc['origi...
1,526
500
""" Code for hierarchical multi-class classifiers. Author: Thomas Mortier Date: Feb. 2021 TODO: * Add option for set-valued prediction * Feature: allow tree structures with non-unique node labels (currently, warning is thrown) """ import time import warnings import numpy as np from .utils import HLabelEncod...
20,189
5,603
"""Fixtures for pytest.""" import pytest from nerdchess.board import Board from nerdchess import pieces @pytest.fixture def board_fixt(): """Wrap the boardfixt class as a pytest fixture.""" return BoardFixt(Board()) class BoardFixt(): """Helper functions to manipulate a board passed as fixture.""" ...
964
284
def Check(src): lang = None if src == "auto": lang = "Auto detect language" if src == "en": lang = "English - English" if src == "de": lang = "German - Deutsch" if src == "ar": lang = "Arabic - عربي" if src == "es": lang = "Spanish - español, castellano" if src == "ru": lang = "Ru...
2,649
1,156
"""Decorator unctions for displaying commands.""" from functools import wraps from shutil import get_terminal_size import click def command_handler(command_title, colour='green'): """Use this decorator for surrounding the functions with banners.""" def decorator(function): """Nested decorator functio...
1,003
299
from typing import List, Optional from pydantic import BaseModel, Field class ApiBase(BaseModel): class Config: orm_mode = True anystr_strip_whitespace = True use_enum_values = True arbitrary_types_allowed = True validate_assignment = True class UpdateResponse(BaseModel)...
869
249
""" Test adding 4D followed by 5D image layers to the viewer Intially only 2 sliders should be present, then a third slider should be created. """ import numpy as np from skimage import data import napari with napari.gui_qt(): viewer = napari.view_image(np.random.random((2, 10, 50, 100, 100)))
304
112
# A module to tests the methods of the Subsystem import unittest import os import shutil import re from copy import copy from qsome import cluster_subsystem, cluster_supersystem from pyscf import gto, lib, scf, dft, cc, mp, mcscf, tools from pyscf.cc import ccsd_t, uccsd_t import numpy as np import tempfile clas...
49,401
19,326
#!/usr/bin/env python import argparse import consulate class Options(object): pass options = Options() parser = argparse.ArgumentParser() parser.add_argument('-n', '--name', required=True, help='service name') parser.add_argument('-s', '--slice', help='slice name (optional)') parser.add_argument('-r', '--role',...
1,051
351
from value import Account acc1 = Account(10000, 3.2) print(acc1) acc1.__balance = 100000000 print(acc1) print(acc1.getBalance()) print(acc1.getInterest()) acc1.setInterest(2.8) print(acc1)
190
91
# Copyright 2021 Martin Kalcok # See LICENSE file for licensing details. """Pytest fixtures for functional tests.""" # pylint: disable=W0621 import logging import tempfile from pathlib import Path import pytest from kubernetes import client, config from pytest_operator.plugin import OpsTest logger = logging.getLogg...
2,717
850
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib.auth import get_user_model from django.contrib.admin.templatetags.admin_urls import admin_urlname from django.core.mail import mail_admins from django.core.urlresolvers import reverse from django.shortcuts import redir...
3,922
1,060
from tensorflow.python.platform import flags from tensorflow.contrib.data.python.ops import batching import tensorflow as tf import json from torch.utils.data import Dataset import pickle import os.path as osp import os import numpy as np import time from scipy.misc import imread, imresize from torchvision.datasets imp...
15,918
5,624
from flask import jsonify, g, request from flask_restful import Resource from Authentication import * from Service import * def get_service(): """ Gets an instance of 'Service' from the 'g' environment. """ if not hasattr(g, 'service'): g.service = Service() return g.service def specialty_quer...
3,751
1,179
class Solution: def isValid(self, s: str) -> bool: # String should have even length if len(s) % 2 != 0: return False # Use list as Stack DS bracStack = [] # If Bracket open add in Stack else Pop & Check for ele in s: if ele in ['(', '{', '[']...
981
266
# Generated by Django 3.1.3 on 2020-12-05 17:27 import django.db.models.deletion from django.conf import settings from django.db import migrations, models import core.cache class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODE...
19,404
4,520
""" Copyright (C) 2020 ETH Zurich. All rights reserved. Author: Sergei Vostrikov, ETH Zurich 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/LI...
2,984
1,030
#!/usr/bin/env python import sys import os import re import subprocess from enum import Enum class GitPushAction(Enum): BRANCH_NEW = 1 BRANCH_UPDATE = 2 BRANCH_REMOVE = 3 class GitLabProtector: """GitLab Protector: A git pre-receive hook""" NULL_HASH = '0000000000000000000000000000000000000000' ...
9,912
3,204
import os import pathlib import tempfile TEMP_DIR = tempfile.TemporaryDirectory() def test_entrypoint(): exit_status = os.system("word-search --help") assert exit_status == 0 def test_no_words_provided(): exit_status = os.system("word-search") assert os.WEXITSTATUS(exit_status) == 1 def test_jus...
1,151
400
import pickle from karas.version import __version__ def serialize(obj, filename): with open(filename, 'wb') as f: f.write(pickle.dumps(obj)) def deserialize(filename): with open(filename, 'rb') as f: obj = pickle.load(f) return obj def replace_type(key): return key.replace('scalar...
1,167
383
#!/usr/bin/python3 import calc def main(): try: while True: try: expression = input('calc> ') # Parse the expression. lexer = calc.Lexer(expression) tokens = lexer.parse() print(tokens) parser = ca...
681
177
import numpy as np from aiida.common import AttributeDict from aiida.engine import WorkChain, append_ from aiida.orm import Dict, List, StructureData from aiida.orm.nodes.data.upf import get_pseudos_from_structure from aiida.orm.utils import load_node from aiida.plugins import WorkflowFactory from aiida_quantumespresso...
8,534
2,585
import torch import numpy as np import pandas as pd from collections import OrderedDict class TrainingDataset(torch.utils.data.Dataset): is_categorical = False def __init__( self, X, y, output_mapping=None, categorical_mapping=None, columns=None, device...
6,481
2,089
# Analisador de textos # Crie um programa que leia o nome completo de uma pessoa e mostre: # - O nome com todas as letras maiúsculas e minúsculas. # - Quantas letras ao todo (sem considerar espaços). print('=*'*20, 'CADASTRO', '=*'*20) nome = str(input('Nome Completo:')).strip()#Para ler com letras maiúsculas print(...
699
257
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from core import game admin.autodiscover() game.autodiscover() urlpatterns = patterns("", ("^admin/", include(admin.site.urls)), url("", include("social_auth.urls")), url("", include("core.urls")), )
312
103
# -*- coding: utf-8 -*- """ Created on Fri Sep 13 20:11:22 2019 @author: drone911 """ from helper import * from models import * import numpy as np from keras.datasets import mnist from tqdm import tqdm import warnings def train(train_images, generator, discriminator, gan, num_classes=120, random_dim=128, epochs=100,...
3,258
1,147
# HEAD # DataType - List method -index() Usage Error # DESCRIPTION # Describes index method of lists # and its error incase item is not there # RESOURCES # lists = ['hello', 'hi', 'howdy', 'heyas'] # returns an error - ValueError print(lists.index('hello hello'))
275
92
from pyspark import SparkContext, SparkConf, SQLContext from pyspark.sql.functions import count, lit, col, udf, expr, collect_list, explode from pyspark.sql.types import IntegerType, StringType, MapType, ArrayType, BooleanType, FloatType from pyspark.sql import HiveContext from datetime import datetime, timedelta from ...
2,418
978
import pytest import pyhash def test_metro_64_1(hash_tester): hash_tester(hasher_type=pyhash.metro_64_1, bytes_hash=7555593383206836236, seed_hash=9613011798576657330, unicode_hash=5634638029758084150) @pytest.mark.skipif(not pyhash.build_with_int128, reason="req...
4,443
2,324
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import copy import numpy as np from torchvision import datasets, transforms import torch import math from utils.sampling import mnist_iid, mnist_noniid, cifar_iid from utils.opti...
9,922
3,769
from flask import current_app from scaner.utils import add_metadata import json # PRUEBA EXTRACION USUARIOS # @add_metadata() # def get(userId, fields=None, *args, **kwargs): # #get_task = current_app.tasks.get_users_from_twitter.delay() # get_task = current_app.tasks.execute_metrics.delay() # return {'res...
1,375
473
import logging from time import sleep from cct.case import Case logger = logging.getLogger(__file__) class create_snapshot(Case): def pre_test(self): logger.info ('doing something before create snapshot') sleep(3) def process(self): logger.info('create snapshot') sleep(5)...
395
115
raise DeprecationWarning("""DEPRECATED: After Popular request and decision from the BDFL: `IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell` during the beta cycle (after IPython 5.0.beta3) Sorry about that. This file will be removed in 5.0 rc or final. """)
296
99
lista = [] for n in range(0, 5): lista.append(int(input(f'Digite um valor para a posição {n}: '))) print('=-=' * 10) print(f'Você digitou os valores {lista}') maior = lista[0] menor = lista[0] for n in lista: if maior < n: maior = n if menor > n: menor = n print(f'O maior valor digitado foi...
591
223
# ------------------------------------------------------------------------------ # CodeHawk Binary Analyzer # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2016-2020 Kestrel Technology LLC # Copyright (c) 2020 Henny Si...
6,461
2,100
from asyncio import sleep from vkbottle.exceptions import VKError from vkbottle.framework.blueprint.user import Blueprint user = Blueprint( name='access_token_error_blueprint' ) @user.error_handler.error_handler(5) async def rps_handler(e: VKError): exit(1)
283
106
import challenges import unittest class RottingOrangesTests(unittest.TestCase): def test_time_to_rot(self): """ Graph BFS problem. Tells the time taken for oranges to all rot. Test cases from LeetCode. """ # Test Cases oranges1 = [ [2,1,1], [1...
2,135
778
#!/usr/bin/env python3 # Day 6: Find All Duplicates in an Array # # Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements # appear twice and others appear once. # Find all the elements that appear twice in this array. # Could you do it without extra space and in O(n) runtime? class Solution: ...
1,293
367
"""TiledImageVisual class A visual that draws tiles using a texture atlas. """ from typing import List, Set import numpy as np from ...layers.image.experimental.octree_util import OctreeChunk from ..vendored import ImageVisual from ..vendored.image import _build_color_transform from .texture_atlas import TextureAtla...
10,519
3,123
import tensorflow as tf x = tf.constant(35, name='x') print(x) y = tf.Variable(x+5, name='y') with tf.Session() as session: merged = tf.summary.merge_all() writer = tf.summary.FileWriter("output", session.graph) model = tf.global_variables_initializer() session.run(model) print (session.run(y)) ...
339
119