text
string
size
int64
token_count
int64
""" ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## AUTHOR = Vimal Paliwal <hello@vimalpaliwal.com> """ import sys import boto3 import click import threading from botocore.exceptions import ClientError from secureaws import ch...
8,550
2,723
import sys import argparse import euclides from PIL import Image import numpy as np from torchvision.transforms import functional as F def run_main(): parser = argparse.ArgumentParser(description='Find similar images in EuclidesDB.') parser.add_argument('--topk', dest='topk', type=int, required=True, ...
888
293
from .batch_filter import BatchFilter from gunpowder.ext import malis class RenumberConnectedComponents(BatchFilter): '''Find connected components of the same value, and replace each component with a new label. Args: labels (:class:`ArrayKey`): The label array to modify. ''' ...
868
243
# Generated by Django 3.0.4 on 2020-05-04 18:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20200323_0327'), ] operations = [ migrations.AlterField( model_name='movieentry', name='date_watch...
401
147
import logging import couchdb from collections import deque from threading import Thread from pylons import config from lr.lib import SpecValidationException, helpers as h from lr.lib.couch_change_monitor import BaseChangeHandler from lr.model import ResourceDataModel from couchdb import ResourceConflict from lr.lib.re...
3,534
1,047
# SPDX-License-Identifier: MIT from ...utils import * # System endpoints def msg_handler(message, regtype=None): def f(x): x.is_message = True x.message = message x.regtype = regtype return x return f class ASCMessage1(Register64): EP = 7, 0 class ASCBaseEndpoint: BAS...
1,432
477
import SimpleHTTPServer import SocketServer import sys from optparse import OptionParser class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): print self.path self.send_response(301) new_path = 'http://%s%s'%(o.ip, self.path) self.send_header('Location', new_path)...
710
250
from typing import List, Literal import pydantic class ConfigData(pydantic.BaseModel): UID: str COOKIE:str SCKEY:str SCTKEY:str BARK_KEY:str BARK_GROUP:str BARK_ICON:str BARK_ARCHIVE:str WW_ID: str WW_APP_SECRET: str WW_APP_USERID: str WW_APP_AGENTID: str WW_BOT_KEY...
943
439
import os from argparse import ArgumentParser from pathlib import Path from general_utils import split_hparams_string, split_int_set_str # from tacotron.app.eval_checkpoints import eval_checkpoints from tacotron.app import (DEFAULT_MAX_DECODER_STEPS, continue_train, infer, plot_embeddings, t...
6,479
2,256
# -*- coding: utf-8 -*- """ @author: Jim @project: tornado_learning @time: 2019/8/20 14:48 @desc: 上传文件 """ from __future__ import annotations from tornado_learning.handler import BaseHandler import os import uuid import aiofiles class UploadHandler(BaseHandler): async def post(self): ret_data = {}...
969
317
"""Main module """ # Standard library imports import string # Third party imports import numpy as np import justpy as jp import pandas as pd START_INDEX: int = 1 END_INDEX: int = 20 GRID_OPTIONS = """ { class: 'ag-theme-alpine', defaultColDef: { filter: true, sortable: false, resizab...
2,906
1,030
""" Unit tests for linked_queue.LinkedQueue """ from dloud_ads import linked_queue def test_dummy(): """ Test definition""" the_queue = linked_queue.LinkedQueue() assert the_queue.is_empty() assert not the_queue the_queue.enqueue(2) assert not the_queue.is_empty() assert len(the_queue) ...
811
324
import os import re # To use a consistent encoding from codecs import open as copen from os import path from setuptools import find_packages, setup here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with copen(path.join(here, 'README.rst'), encoding='utf-8') as f: long...
1,831
628
#*************************************************************** #* Name: LMS7002_BIAS.py #* Purpose: Class implementing LMS7002 BIAS functions #* Author: Lime Microsystems () #* Created: 2016-11-14 #* Copyright: Lime Microsystems (limemicro.com) #* License: #************************************************...
76,079
31,107
import time # Colors RED = (1,0,0) YELLOW = (1,1,0) GREEN = (0,1,0) CYAN = (0,1,1) BLUE = (0,0,1) PURPLE = (1,0,1) class BaseShape: # A list of instance attribute names, which are animatable objects animatable_attrs = [] # The time of the last animation update last_update = None # The nu...
1,299
435
rzymskie={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8} print(rzymskie) print('Jeden element slownika: \n') print(rzymskie['I'])
148
73
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from config.site_url import SiteUrl from urllib.request import urlopen from lxml.html import fromstring from random import randint from time import sleep # 余分な改行や文字列を削除し文字列に変換する関数 def conv(arg): arg = [item.strip().replace('    |', '') for item in arg] arg = ''.j...
1,791
940
import ctypes import ctypes.util libc = ctypes.CDLL(ctypes.util.find_library('c')) # Get network device's name def if_indextoname (index): if not isinstance (index, int): raise TypeError ('Index must be an integer.') libc.if_indextoname.argtypes = [ctypes.c_uint32, ctypes.c_char_p] libc.if_indexto...
1,077
412
import nltk,re,codecs from nltk.tokenize import word_tokenize,sent_tokenize from backNode import BackNode from nltk import Tree def trace_tree(trace): if trace.left==None and trace.right==None: return str(trace.root)+" "+str(trace.word) return "("+str(trace.root)+"("+str(trace_tree(trace.left))+")"+" "+"("+str...
3,677
1,733
"""Initialization package.""" from .api import Mullpy from .banner import banner __all__ = ['Mullpy', 'banner'] __version__ = '0.3.1'
135
51
import inspect import pathlib import sys import yuno # CONSTANTS TEST_OBJECT = { "a": 1, "b": 2, "c": 3, "test_dict": { "a": 1, "b": 2, "c": 3 }, "float": 1.1, "int": 1, "test_list": [1, 2, 3], "null": None, "string": "test", "boolean": True } TEST...
5,813
1,806
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """ {{cookiecutter.project_slug}}.cli ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {{ cookiecutter.project_short_description }} :copyright: © 2019 by the Choppy Team. :license: AGPLv3+, see LICENSE for more details. """ """Console script for {{cookiecutter.proje...
732
245
import unittest import src.classes.player as player class PlayersTest(unittest.TestCase): def test_to_string(self): self.assertTrue(str(player.Player()) == "Player(id=-1, name=UNDEFINED, is_adm=False, games=0, pitch=0.0, hold=0.0, passing=0.0, movement=0.0, attacking=0.0, rating=0.0)") def test_to_s...
891
381
from __future__ import annotations __all__ = ("executor",) import inspect import sys from asyncio import get_running_loop from concurrent.futures import Executor from functools import partial, wraps from typing import Awaitable, Callable, TypeVar, overload from asphalt.core import Context if sys.version_info >= (3,...
3,745
1,152
import jinja2 page = {} page['title'] = 'Shkola' page['item_path'] = '../src/' page['google_signin_client_id'] = "" page['google_site_verification'] = "" page['button'] = { 'width' : '137px', 'height' : '140px', 'font_size' : '111px', 'margin' : '10px', 'choices' : [] } page['button']['choices...
2,309
851
import logging import json import glob import pandas as pd import multiprocessing import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics...
19,771
6,240
# -*- coding: utf-8 -*- import time import json import random import string import asyncio import aiohttp from aiohttp.resolver import AsyncResolver from hashlib import md5 from urllib.parse import quote #-#from operator import itemgetter #-#from itertools import chain #-#from cStringIO import StringIO if __name__ == ...
25,321
8,870
# coding: utf-8 from __future__ import unicode_literals import time import logging import traceback from optparse import make_option import json from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django_fuzzytest.runner import FuzzyRunner logger = logging.getLogge...
1,565
473
#!/usr/bin/env python import glob import re import os import argparse import time import getpass import composition.support_functions.paths as paths import composition.support_functions.simfunctions as simfunctions from composition.support_functions.checkdir import checkdir def get_argdict(comp_data_dir, **args): ...
6,727
2,197
from typing import Union class ExcelTable: def _get_column(self, column_name:str, column_props:Union[dict, str]) -> dict: ''' Defaults to the title-cased `column_name`: my_favorite_color: 'My Favorite Color' For acronyms, abbreviations, provide the correct capitalization in t...
7,257
1,951
# Generated by Django 2.0.7 on 2018-07-06 19:23 from django.db import migrations, models import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('grading_system', '0002_student_email'), ] operations = [ migrations.RenameField( model_name='...
859
268
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
67,834
19,421
import unittest import django from django.test import TestCase from django.db import models from django.db.models.constants import LOOKUP_SEP from django_filters.utils import get_model_field, resolve_field from django_filters.exceptions import FieldLookupError from .models import User from .models import Article fr...
6,300
1,782
H, W = map(int, input().split()) A = [input() for _ in range(H)] if H + W - 1 == sum(a.count('#') for a in A): print('Possible') else: print('Impossible')
164
66
# coding=utf-8 #------------------------------------------------------------------------------# import os import time import fuse import errno from .item import RelFuseItem from .static_dir import StaticDirectory #------------------------------------------------------------------------------# class MountRoot(RelFuseIte...
2,188
525
import torch import onnx from torch import nn from onnxruntime.quantization import quantize_qat, quantize_dynamic, QuantType from .utils import Textual, DEFAULT_EXPORT class clip_converter(nn.Module): def __init__(self, model, visual_path: str = "clip_visual.onnx", textual_path: str = "clip_textu...
3,935
1,134
from datetime import datetime from kivy.app import App from kivy.factory import Factory from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.button import Button from electrum.gui.kivy.i18n import _ from electrum.bitcoin import Token from electrum.util import parse_token_URI, InvalidTokenURI fro...
6,493
1,914
import abc import base64 from datetime import date, datetime import dataclasses as dc from typing import Type as PyType, Any, Dict, Optional import marshmallow as ma import pickle import pluggy import statey as st from statey.syms import types, utils, Object class Encoder(abc.ABC): """ An encoder encodes d...
17,625
5,299
'''Functions related to the data loading and processing''' from transformers import (Wav2Vec2CTCTokenizer, Wav2Vec2FeatureExtractor, Wav2Vec2Processor) from datasets import (load_dataset as ds_load_dataset, Dataset, Dataset...
13,558
3,818
"""etravel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based...
1,604
509
import json import time from glob import glob from pathlib import Path from adet.data.video_data.util import * from PIL import Image, ImageFont, ImageDraw import os import random categories = ['airplane', 'ape', 'bear', 'bike', 'bird', 'boat', 'bucket', 'bus', 'camel', 'cat', 'cow', 'crocodil...
4,447
1,444
import numpy as np def fast_linear_interpolate(f, x): """ :param f: array of evenly spaced function values :param x: array of fractional positions to sample :type f: np.multiarray.ndarray :type x: np.multiarray.ndarray :rtype: np.multiarray.ndarray """ x0 = np.floor(x).astype(int) ...
1,342
504
from pydantic import BaseModel class BusinessRule(BaseModel): """This is a base class for implementing domain rules""" class Config: arbitrary_types_allowed = True # This is an error message that broken rule reports back __message: str = "Business rule is broken" def get_message(self) -...
492
143
""" Desafio 067 Problema: Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo. Resolução do problema: """ print('-' * 20) print(f'{" Tabuada v3.0 ":~^20}') pri...
627
267
""" pyexcel_xlsx ~~~~~~~~~~~~~~~~~~~ The lower level xlsx file format handler using openpyxl :copyright: (c) 2015-2019 by Onni Software Ltd & its contributors :license: New BSD License """ from pyexcel_io.io import get_data as read_data from pyexcel_io.io import isstream from pyexcel_io.io import ...
1,492
511
import numpy as np import tensorflow as tf from tensorflow.contrib import gan as tfgan from GeneralTools.graph_funcs.my_session import MySession from GeneralTools.math_funcs.graph_func_support import mean_cov_np, trace_sqrt_product_np from GeneralTools.misc_fun import FLAGS class GenerativeModelMetric(object): d...
12,775
4,268
import yaml class wsd(): def __init__(self, file, dict): self.file = file self.dict = dict def write_sd(self): with open(self.file, 'w') as f: f.write(yaml.dump(self.dict))
187
82
from getratings.models.ratings import Ratings class NA_Rengar_Mid_Aatrox(Ratings): pass class NA_Rengar_Mid_Ahri(Ratings): pass class NA_Rengar_Mid_Akali(Ratings): pass class NA_Rengar_Mid_Alistar(Ratings): pass class NA_Rengar_Mid_Amumu(Ratings): pass class NA_Rengar_Mid_Anivia(Ratings): ...
6,545
3,595
import logging import pytest from selene import Browser, Config from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager @pytest.fixture(scope='function') def browser_func(choose_driver): """Browser that closes after each test f...
3,372
975
from .evaluation import evaluation
34
7
import open3d as o3d import numpy as np from pclpy import pcl from tqdm import tqdm import os def o3d_meshes(dataset_name: str, path_to_data_folder='../../data'): """ Read in mesh (.ply, .stl, .off) files. The function assumes that each class of objects is in a separate folder and highly spefified for our...
7,034
2,539
import pymongo import random def create_database(db): user_collection = db['users'] user_collection.drop() user_collection = db['users'] post_collection = db['posts'] post_collection.drop() post_collection = db['posts'] comment_collection = db['comments'] comment_collection.drop() ...
9,523
3,195
""" Crie um programa que leia um a frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. ex: apos a sopa a sacada da casa a torre da derrota o lobo ama o bolo anotaram a data da maratona """ frase = input('Digite uma frase (sem acentos): ').replace(' ', '').upper() inverso = '' for c in range(len(fr...
530
212
from typing import Any, Callable import matplotlib.pyplot as plt from numpy import arange from .membership import Membership class BaseSet: def __init__( self, name: str, membership: Membership, aggregation: Callable[[Any, Any], Any], ): self.name = name self....
1,546
483
import numpy as np import chess import chess.engine from tkinter.filedialog import asksaveasfilename from parsing.math_encode import tensor_encode, tensor_decode from inference.infer_action import get_action class PlayLoop: __doc__ = ''' An interactive REPL environment for play with a trained chess AI ''...
9,911
2,827
from dataclasses import dataclass from typing import Generic, Mapping, TypeVar __all__ = ["Curve"] T = TypeVar("T") U = TypeVar("U") @dataclass class _Curve(Generic[T, U]): mapping: Mapping[T, U]
205
78
""" Get an Etree library. Usage:: >>> from anyetree import etree Returns some etree library. Looks for (in order of decreasing preference): * ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/) * ``xml.etree.cElementTree`` (built into Python 2.5) * ``cElementTree`` (http://effbot.org/zone/celem...
877
307
from abc import abstractmethod, ABC class Dispatcher(ABC): def __init__(self, dispatch_dict=None): self._dispatch_dict = dispatch_dict self._process_list = [] return def set_dispatch_dict(self, dispatch_dict): self._dispatch_dict = dispatch_dict @abstractmethod def d...
608
172
# -*- coding: utf-8 -*- """ Created on Wed Mar 25 11:01:41 2020 @author: liu """ from time import sleep import plot_TT from TimeTagger import createTimeTagger, freeAllTimeTagger, TimeDifferences # create a Time Tagger instance tagger = createTimeTagger() tagger.reset() # assign channels for measu...
766
333
# -*- coding: utf-8 -*- """ Created on Thu Nov 21 14:54:51 2019 @author: Ludovic.SPAETH """ from electroPyy.io.BaseRawIO import BaseRawIO from electroPyy.io.HdF5IO import HdF5IO from electroPyy.io.NeuroExIO import NeuroExIO from electroPyy.io.WinWcpRawIO import WinWcpRawIO
287
136
from .dynamic_graph_temporal_signal import * from .dynamic_graph_temporal_signal_batch import * from .static_graph_temporal_signal import * from .static_graph_temporal_signal_batch import * from .dynamic_graph_static_signal import * from .dynamic_graph_static_signal_batch import * from .train_test_split import *
317
100
# # 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 us...
3,605
1,145
__version__ = '0.1.3' __author__ = 'Miroslav Shubernetskiy' try: from .generics import * from .mixins import * except Exception: pass
147
55
# -*- coding: utf-8 -*- import pickle from sklearn.ensemble import RandomForestClassifier from base_shallow_classifier import BaseShallowClassifier class RFClassifier(BaseShallowClassifier): ''' Image classification using random forest classifier (RFC). Can reach 87.82% accuracy on test set of FashionM...
1,773
532
import os.path as osp from setuptools import setup, find_packages # todo: modify as we decide on versions, names, descriptions. readme MIN_PY_VER = '3.7' DISTNAME = 'recOrder' DESCRIPTION = 'computational microscopy toolkit for label-free imaging' with open("README.md", "r") as fh: LONG_DESCRIPTION = fh.read() ...
2,387
775
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import platform import sys from ctypes.util import find_library from ctypes import CDLL, CFUNCTYPE, POINTER, c_void_p, c_char_p, c_int, c_size_t, c_long from .. import _backend_config from .._ffi import FFIEngineError f...
6,457
2,693
# File: etl.py # Purpose: To do the `Transform` step of an Extract-Transform-Load. # Programmer: Amal Shehu # Course: Exercism # Date: Thursday 22 September 2016, 03:40 PM def transform(words): new_words = dict() for point, letters in words.items(): for letter in letters: ...
382
133
import psycopg2 from rest_framework import generics, permissions # from serializers import UserSerializer, UserFollowSerializer, UserSettingsSerializer from serializers import UserSerializer, UserFollowSerializer, UserSettingsSerializer from serializers import AllUsersSerializer, UserRegisterSerializer from userprofil...
2,983
845
# -*- coding:UTF-8 -*- from flask import Blueprint, current_app, request import pandas as pd from app.protocol import serialize from app.utils import Utils from app.database.crud import db_mgr from app.cache import redis_mgr api_v1 = Blueprint('api_v1', __name__) @api_v1.route('/show_raw_data', methods=['GET']) def ...
3,597
1,399
from oslo_log import log from oslo_config import cfg from report import storage from pecan import hooks LOG = log.getLogger(__name__) class RPCHook(hooks.PecanHook): def __init__(self, rcp_client): self._rpc_client = rcp_client def before(self, state): state.request.rpc_client = self._rpc_cl...
708
219
def have(subj, obj): subj.add(obj) def change(subj, obj, state): pass if __name__ == '__main__': main()
117
49
# Generated by Django 2.0.9 on 2018-11-25 11:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0011_auto_20181123_1446'), ] operations = [ migrations.RenameField( model_name='item', old_name='amount'...
548
184
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.0.1', description='compiling code for HSIP441 using python to explore the Neiss database', author='Garrett Eickelberg', license='MIT', )
262
83
from weibo import WeiboClient from weibo.watchyou import fetch_replies for r in fetch_replies(): # fetch_replies所依赖的weibo全局变量是在watchyou模块中存在的, 函数无法访问到这个模块中的全局变量 print(r['text'])
189
103
import datetime import json import os from unittest import TestCase, mock from urllib.parse import parse_qs, urlencode, urlparse, urlunparse from buildpack.infrastructure.database import ( UrlDatabaseConfiguration, get_config, ) from cryptography import x509 from cryptography.hazmat.primitives import hashes, s...
8,181
2,707
"""Implement the graph to traverse.""" from collections import Counter class Node: """Node class.""" def __init__(self, value, x, y): """Initialize node.""" self.x = x self.y = y self.value = value self.neighbors = [] def add_neighbor(self, n, weight): ""...
1,770
541
import json import gen.Types def loader(f): return json.load(open('../GenerateDatas/json/' + f + ".json", 'r'), encoding="utf-8") tables = gen.Types.Tables(loader) print(tables) r = tables.TbFullTypes.getDataList()[0].__dict__ print(r)
245
93
# ============================================================================ # FILE: kind.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ import json import typing from pathlib import Path from defx.acti...
10,255
3,398
# -*- coding: utf-8 -*- # @Author: Matthieu Petiteau # @Date: 2019-04-26 21:01:07 # @Last Modified by: Matthieu Petiteau # @Last Modified time: 2019-04-26 21:52:46 """Dispatch webhook event to specific actions.""" import json class Dispatcher: """Dispatch the different webhook events to the related functions...
3,659
1,179
# A bot that picks the first action from the list for the first two rounds, # and then exists with an exception. # Used only for tests. game_name = input() play_as = int(input()) print("ready") while True: print("start") num_actions = 0 while True: message = input() if message == "tourname...
790
226
# # Copyright 2020 Logical Clocks AB # # 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 ag...
2,027
616
import os.path from typing import List, Tuple from mapfmclient import MarkedLocation, Problem class MapParser: def __init__(self, root_folder: str): self.root_folder = root_folder def parse_map(self, name: str) -> Problem: with open(os.path.join(self.root_folder, name)) as file: ...
1,720
494
#!/usr/bin/python # Copyright (c) 2018, 2019, Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for ...
9,803
3,179
import sys if sys.version_info.major >= 3: import typing class BuiltinEnum: ANY = typing.Any BOOL = typing.NewType('Bool', bool) FLOAT = typing.NewType('Float', float) INT = typing.NewType('Int', int) PATH = typing.NewType('Path', str) STRING = typing.NewType('...
836
266
#!/usr/bin/env python3 import sys, os, re, html from flask import request, Response from sallybrowse.extensions import BaseExtension from subprocess import Popen, PIPE class Extension(BaseExtension): PATTERN = re.compile(r".*\.(pdf|xlsx|xls|docx|doc|ods|odt|xlt|ppt|pptx|odp|otp|ltx)$", re.IGNORECASE) PRIORITY = 100...
1,173
554
""" Created on Nov 30, 2021 @author: CyberiaResurrection """ import unittest import re import sys sys.path.append('../PyRoute') from Galaxy import Galaxy from Galaxy import Sector class testGalaxy(unittest.TestCase): """ A very simple, barebones test to check that Verge and Reft end up in their correct r...
4,713
1,563
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Firefox() driver.get('https://www.google.com') time.sleep(60) driver.close()
188
58
import pytest from dlms_cosem import enumerations, state from dlms_cosem.exceptions import LocalDlmsProtocolError from dlms_cosem.protocol import acse from dlms_cosem.protocol.acse import UserInformation from dlms_cosem.protocol.xdlms import Conformance, InitiateRequestApdu def test_non_aarq_on_initial_raises_protoc...
1,240
404
''' f we want to add a single element to an existing set, we can use the .add() operation. It adds the element to the set and returns 'None'. Example >>> s = set('HackerRank') >>> s.add('H') >>> print s set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) >>> print s.add('HackerRank') None >>> print s set(['a', 'c', 'e', '...
705
246
# 6. Продолжить работу над вторым заданием. Реализуйте механизм валидации вводимых пользователем данных. Например, для # указания количества принтеров, отправленных на склад, нельзя использовать строковый тип данных. # Подсказка: постарайтесь по возможности реализовать в проекте «Склад оргтехники» максимум возможностей...
2,331
858
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Optional from epicteller.core import redis from epicteller.core.model.credential import Credential class CredentialDAO: r = redis.pool @classmethod async def set_access_credential(cls, credential: Credential): await cls.r.pool.set(...
1,212
397
class LeagueGame: def __init__(self, data): self.patch = data['patch'] self.win = data['win'] self.side = data['side'] self.opp = data['opp'] self.bans = data['bans'] self.vs_bans = data['vs_bans'] self.picks = data['picks'] self.vs_picks = data['vs_picks'] self.players = data['players'] class Lea...
1,101
494
from common import * from model import vocab option = dict(edim=256, epochs=1.5, maxgrad=1., learningrate=1e-3, sdt_decay_step=1, batchsize=8, vocabsize=vocab, fp16=2, saveInterval=10, logInterval=.4) option['loss'] = lambda opt, model, y, out, *_, rewards=[]: F.cross_entropy(out.transpose(-1, -2), y, reduction='none')...
1,046
401
# Terminal_DA_AD.py # Circuit # D/A0---A/D0, D/A1---A/D1, # pot A---3.3V, potB---GND, pot wiper---A/D2 # Procedure # Run, then open REPL and then CTRL + D # Twist pot input while program runs to see ad2 vary # Notes # micro:bit ground is 0.4 V below cyber:bot board ground # micro:bit 3.3 V = 3.245 V WRT ...
1,713
1,060
import bpy from aiohttp import web import numpy as np from mathutils import Matrix, Vector import asyncio from cinebot_mini_render_server.blender_timer_executor import EXECUTOR routes = web.RouteTableDef() def delete_animation_helper(obj): if not obj.animation_data: return False if not obj.animation_...
4,781
1,559
roads_subset = roads[roads["frc_omschrijving"].isin(road_types)]
64
25
# -*- encoding: utf-8 -*- from utils import display_message, set_ams, start_loop, config_loop #config_loop(gui=True) from agent import Agent from messages import ACLMessage from aid import AID from protocols import FipaContractNetProtocol from filters import Filter from pickle import loads, dumps from time import slee...
4,176
1,349
from copy import deepcopy from numba import jit,njit import numpy as np import pymctdh.opfactory as opfactory from pymctdh.cy.sparsemat import CSRmat#,matvec @njit(fastmath=True) def matvec(nrows,IA,JA,data,vec,outvec): """ """ d_ind = 0 for i in range(nrows): ncol = IA[i+1]-IA[i] for...
9,320
3,218
# Copyright (c) 2020 DeNA Co., Ltd. # Licensed under The MIT License [see LICENSE for details] # kaggle_environments licensed under Copyright 2020 Kaggle Inc. and the Apache License, Version 2.0 # (see https://github.com/Kaggle/kaggle-environments/blob/master/LICENSE for details) # wrapper of Hungry Geese environment...
13,018
4,587
import numpy as np def normalize(image): mean = np.mean(image) meanSubtractedImage = image - mean return np.divide(meanSubtractedImage,np.power(np.sum(np.power(meanSubtractedImage,2)),0.5))
198
80