content
stringlengths
5
1.05M
from . import translate_enhe
from flask import render_template, request, redirect, url_for from . import app from .models import User, Post, Comment, Vote, Category from peewee import fn, JOIN from flask_security import login_required, current_user @app.route('/') @app.route('/index') def index(): return render_template('index.html', title=...
import pandas as pd import numpy as np # Return Series with specified index labels removed # Remove elements of a Series based on specifying the index labels. When using a # multi-index, labels on different levels can be removed by specifying the level s = pd.Series(data=np.arange(1, 4), index=list('ABC')) print("<--...
# -*- coding:utf-8 -*- from django import template from django.utils.html import format_html import logging from django.db.models.loading import get_model from django.core.urlresolvers import reverse from physical.models import Environment register = template.Library() MB_FACTOR = 1.0 / 1024.0 / 1024.0 LOG = logging...
# -*- coding: utf-8 -*- # Created by restran on 2017/7/17 from __future__ import unicode_literals, absolute_import import re from optparse import OptionParser """ https://github.com/abpolym/crypto-tools/tree/master/find-coding-scheme """ parser = OptionParser() parser.add_option("-d", "--data str", dest="data_str", ...
""" AST and parsing related functions. """ import collections import itertools import functools import string import sys import textwrap import logging import pyparsing as p from . import runtime from . import exceptions from . import schema from . import functions from . import framework from . import astracing cl...
""" Flood-Proofs - S3M static-data prep __date__ = '20211213' __version__ = '2.0.0' __author__ = 'Francesco Avanzi (francesco.avanzi@cimafoundation.org', 'Fabio Delogu (fabio.delogu@cimafoundation.org', __library__ = 's3m' General command line: python3 S3M_StaticDataprep.py -settings_file "S3M_StaticDatapr...
import time import logging import fire import numpy as np from tqdm import tqdm from torch.utils.data import DataLoader import models import utils from dataset import ImageDataset logging.getLogger().setLevel(logging.INFO) def run(model_name, output_dir, dataname, data_dir='./data', batch_size=16, test_run=-1): ...
import sys import h5py import argparse import numpy as np def parse_arguments(): parser = argparse.ArgumentParser( description=__doc__, # printed with -h/--help formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument('FILE', help="Input .h5 dataset") parser.add_argu...
import datetime import os import warnings import xml.etree.ElementTree as ET import zipfile import numpy as np import shapely import isce3 from nisar.workflows.stage_dem import check_dateline from s1reader.s1_burst_slc import Doppler, Sentinel1BurstSlc # TODO evaluate if it make sense to combine below into a class d...
from . import ( abbreviations, array_param, macro_files, matrix_op, parameter_definition, process_controls, )
from django.db import models class SequenceManager(models.Manager): def get_queryset(self): return super().get_queryset().order_by('sequence') class SequenceModel(models.Model): sequence = models.PositiveSmallIntegerField( editable=False, null=False) objects = models.Manager() ...
import sys import re import os import copy import json import yaml import subprocess import logging import collections from operator import methodcaller class Utils: name = 'utils' _instance = None def __new__(cls, log_level=logging.INFO, log_format=None): if cls._instance is None: cl...
# ##### 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...
def search(graph, start, goal, search_strategy): """ Generic graph searching algorithm from the book Artificial Inteligence: Foundations of computational agents Figure 3.4 p86 Keyword arguments: graph -- A dict that represents the graph start -- the start node goal -- the end node s...
import os, sys import logging, traceback grey = "\x1b[38;21m" green = "\x1b[32;21m" yellow = "\x1b[33;21m" red = "\x1b[31;21m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" prefix = "[Atlas] " class ColorFormatter(logging.Formatter): def __init__( self, format="%(asctime)s - %(name)s - %(levelname)...
"""unit test case for frcnn util.""" from unittest.mock import MagicMock, patch import numpy as np import torch from datasetinsights.data.bbox import BBox2D from datasetinsights.estimators.faster_rcnn import ( FasterRCNN, _gt_preds2tensor, canonical2list, convert_bboxes2canonical, gather_gt_preds...
from collections import OrderedDict, defaultdict # Python 3 specific from collections.abc import Sequence, Mapping def test(*args): pass class MySequenceABC(Sequence): pass class MyMappingABC(Mapping): pass class MySequenceImpl(object): def __getitem__(self, key): pass def __len__(self...
# Generated by Django 3.1 on 2021-06-27 19:25 from django.db import migrations, models import filer.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MyFile', fields=[ ('id', ...
# Decision Tree base class import numpy as np import os import subprocess class Decision_tree: def __init__(self): self.root = None self.nodes = -1 self.lc_nodes = -1 self.Xnames = None self.Ynames = None def ready(self): return (self.root is not None) def fit(self, dataset): pa...
import socket import pickle HEADER_LENGTH = 10 class Server: def __init__(self, port, address=None): self.port = port if address is None: address = socket.gethostbyname(socket.gethostname()) def receive_packet(client_socket): pass
""" A synchronous and asynchronous API wrapper for the [UberDuck](https://uberduck.ai) text-to-speech service with 100% coverage and top-notch utilities. Copyright 2022-present ImNimboss Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (t...
#!/usr/bin/env python from os.path import realpath import os from waflib.Configure import conf import clibtool tooldir = os.environ['WAF_TOOLDIR'] fragment= """ #include "numini/reader.hxx" int main() { numini::Reader ini; } """ def options(opt): opt.load('yaml-cpp', tooldir=tooldir) clibtool.options(o...
import urllib2 import sys import unicodedata def fetch_rst(url): print 'Fetching %s..' % url req = urllib2.Request(url) fd = urllib2.urlopen(req, timeout=30) body = fd.read() body = body.replace("\r\n", "\n") body = body.decode('utf8', 'ignore').encode('ascii', 'ignore') pos = body.find("{{{") if pos >= 0...
from .. import Seclytics from optparse import OptionParser from texttable import Texttable from pprint import pprint if __name__ == '__main__': # pass in the access_token via commandline parser = OptionParser() parser.add_option("--access_token", action="store", type="string", dest="a...
import re # TODO: strip white space and punctuation from body freenode_OnlineCop_re = re.compile(r""" ^\s* (?P<leading_number>[0-9.]+|\([a-z0-9A-Z]+\))? \s* (?P<title> (?:[^\d.;?\n]+ | \d+(?:\.\d+(?:[0-9]+\.)*)? )* # Non-digits ) (?P<punctuation>[.;?,]|$)(?P<body>.*?$) """, re.MULTILINE | re.VERBOSE) # _{16}\...
VERSION = "1.44"
import sys from oslo_config import cfg from oslo_log import log as logging from nova import utils from nova import config from nova import objects from nova import version from nova.daolicloud import service from nova.openstack.common.report import guru_meditation_report as gmr CONF = cfg.CONF def main(): confi...
import django.core.files.storage from django.db import migrations, models import mayan.apps.document_signatures.models class Migration(migrations.Migration): dependencies = [ ('document_signatures', '0006_auto_20160326_0616'), ] operations = [ migrations.AlterField( ...
from django.contrib import admin from website.models import Contact # Register your models here. admin.site.register(Contact)
import os.path from urllib.parse import urlencode from django.contrib.auth import get_user_model from django.contrib.postgres.fields import JSONField from django.db import models User = get_user_model() class Upload(models.Model): """ An abstract model intended to be subclassed by the project to further...
import cpp_module.cppcore as cpp from demo_helpers import play_blackjack def demo_main(): bet_money = 1000 game = cpp.Game( cpp.Table(cpp.Hand(), cpp.Hand(), cpp.StandardDeck(True), bet_money) ) while True: result = play_blackjack(game) if result == cpp.GameState.dealer_win: ...
# -*- coding: utf-8 -*- class GildedRose(object): def __init__(self, items): self.items = items def __decrease_quality(self, item, amount): for i in range(amount): if item.quality > 0: item.quality = item.quality - 1 def __increase_quality(self, item, amount):...
from typing import List, Union import numpy as np import pandas as pd from sklearn.base import BaseEstimator, RegressorMixin from statsmodels.gam.api import BSplines, CyclicCubicSplines, GLMGam class GAM(RegressorMixin, BaseEstimator): """Generalized Additive Models :param splines: type of spline functions ...
""" A plugin for setuptools to delete all build products - especially useful for binary extensions, """ from __future__ import absolute_import __version__ = '0.1' __author__ = 'Gabi Davar' __all__ = ['DistCleanCommand'] import os from os.path import abspath, join, normcase, relpath import fnmatch import setuptools ...
import torch class SEBlock(torch.nn.Module): def __init__(self,inplanes,redr,poolflag = 'avg'): super(SEBlock,self).__init__() if poolflag == 'max': self.pool = torch.nn.AdaptiveMaxPool2d((1,1)) if poolflag == 'avg': self.pool = torch.nn.AdaptiveAvgPool2d((1,...
from pyglet.window.key import *
#!/usr/bin/env python from tools.multiclass_shared import prepare_data [traindat, label_traindat, testdat, label_testdat] = prepare_data(False) parameter_list = [[traindat,testdat,label_traindat,label_testdat,2.1,1,1e-5],[traindat,testdat,label_traindat,label_testdat,2.2,1,1e-5]] def classifier_multiclasslinearmachi...
import logging import queue import threading from time import sleep from searchzone.tasks.helper import read_file_and_add_to_queue from searchzone.elastic.appsearch import AppSearchConnector from searchzone.tasks.update import outdated from searchzone.tasks.new import new from searchzone.tasks.diff import diff from se...
# script to: # write trajectory .dat file to .tfrecord # compute average velocity and average acceleration for entire system # return max bounding box dimensions # save backbone and normal versors as step context? import argparse import functools import os import json import math import pickle import random import te...
from typing import Optional, List from sqlalchemy.orm import Session from app.crud.base import CRUDBase from app.models.tag import Tag from app.schemas.tags import TagCreate, TagUpdate class CRUDTag(CRUDBase[Tag, TagCreate, TagUpdate]): def get_by_name(self, db: Session, *, name: str) -> Optional[Tag]: ...
import os, tqdm, time import numpy as np import torch import torch.nn.functional as F import torchvision.utils as vutils from tensorboardX import SummaryWriter import lib from lib import utils def summary_grid_image(logger, x, name, step): if x.max() > 1: x = (x - x.max()) / (x.max() - x.min()) else: ...
import cv2 import numpy as np import argparse import pandas as pd edge_rate = 0.05 parser = argparse.ArgumentParser() parser.add_argument('--imgfile', default='',type=str, help = 'The file name of the orignial image file') parser.add_argument('--txtfile', default='', type=str, he...
''' The purpose of this test is to step through multiple tuning states to try to identify the breakdown voltage at each, and which levels may be broken. The target operating voltage will be 470 V for each level. T. Golfinopoulos, 8 June 2015 ''' from MDSplus import * from numpy import * from time import sleep s0=115...
import datetime import json import os import time import snap from db_interface import get_edge_number, get_all id_pkg_dict = {} def get_id_from_package(graph, package): node_id = id_pkg_dict.get(package, -1) if node_id == -1: node_id = graph.AddNode(-1) id_pkg_dict[package] = node_id ...
from enum import Enum, auto class velocityUnits(Enum): kRPM = auto() kRPS = auto() kEncoderTicksPer100 = auto() class positionUnits(Enum): kEncoderTicks = auto() kRotations = auto()
from typing import Union def push_regionprops_column(regionprops : Union[list, dict], column : str): from .._tier0 import push import numpy as np if isinstance(regionprops, dict): return push(np.asarray([regionprops[column]])) else: if hasattr(regionprops[0], 'original_label'): ...
""" Cisco_IOS_XE_ip_sla_oper This module contains a collection of YANG definitions for monitoring of IP SLA statistics of a Network Element. Copyright (c) 2016\-2017 by Cisco Systems, Inc. All rights reserved. """ from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, Y...
import json import pytest from sqlalchemy.sql import text as sa_text from sqlalchemy.orm.session import sessionmaker from opencdms.models.climsoft import v4_1_1_core as climsoft_models from apps.climsoft.db.engine import db_engine from apps.climsoft.schemas import paperarchivedefinition_schema from datagen.climsoft imp...
#!/usr/bin/env python import sys for line in sys.stdin: # extract data key, val = line.strip().split('\t', 1) # passenger_count try: key = int(val.split(',')[3]) except ValueError: continue # print print '%s\t%s' % (key, 1) ''' cd ~/hw1/Task2-c/ rm -rf NumberPassengersSam...
''' GeoParser admin core Utility - Store information about index configuration - id - domain-name - indexes - list of indexes for this domain. - core_names - list of cores for those indexes. - point_list - list of num of points points found - idx_size_list - list of size of target index - idx_field_list - csv...
def reverse(text): reversedText = "" for i in range(len(text) - 1, -1, -1): reversedText += text[i] return reversedText def mirror(text): mirroredText = text + reverse(text) return mirroredText print(mirror("Python"))
def pretty_printing(root, level): ''' Prints the Abstract Syntax Tree out using the stringify methods available on the model classes. ''' pretty = '%s%s' % (''.join(['\t' for x in range(level)]), root.constraint) print(pretty) level += 1 if root.l_child: pretty_printing(root.l_c...
import ast import re from scipy.spatial import KDTree from webcolors import ( CSS3_HEX_TO_NAMES, hex_to_rgb, ) def convert_rgb_to_names(str_rgb): css3_db = CSS3_HEX_TO_NAMES names = [] rgb_values = [] for color_hex, color_name in css3_db.items(): names.append(color_name) rgb_va...
''' Convert Canvas output to a common format ''' import myvcf import SV import os import sys import re class Canvas: @staticmethod def doparse ( canvas_data ): # Y 59020307 Canvas:GAIN:Y:59020308-59028273 N <CNV> 2 q10;L10kb SVTYPE=CNV;END=59028273;CNVLEN=7966 RC:BC:CN:MCC 364:6:7:5 E=canvas_data #if type (ca...
# Tested on python3.6 import grpc from concurrent import futures import time import logging import network_analytics_pb2 import network_analytics_pb2_grpc import bipartite_graphs SLEEP_TIME = 86400 # One day class NetworkAnalytics(network_analytics_pb2_grpc.NetowrkAnalyticsServicer): def BipartiteGraph(self...
import psutil import gc import numpy as np import time class MemReporter: def __init__(self, comm=None): self.comm = comm self.timer = time.time() def run(self, msg=""): """ Gather and report the amount of allocated, free and swapped system memory """ vmem = psutil.vir...
# As a young traveler, you gather items and craft new items. # You will receive a journal with some Collecting items, separated with ", " (comma and space). # After that, until receiving "Craft!" you will be receiving different commands. # Commands (split by " - "): # • "Collect - {item}" – Receiving this command, yo...
__all__ = [ "PlottingTools", "RateSpecClass", "RateSpecTools", "CurveFitting" ]
from PIL import Image from bitstring import Bits from StegoImage.BaseStegoImage import BaseStegoImage class StegoBinaryStore(BaseStegoImage): def __init__(self, nbr_of_planes=3): super().__init__(nbr_of_planes) def _insert_header(self, data_size): header = Bits(uint=data_size, length=self._h...
# This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE from __future__ import print_function import multiprocessing class FakeAsyncResult(object): def __init__(self, X): self.X = X def wait(self, *a): pass def get(self, *a): ret...
import requests from questions_three.vanilla import Structure class GraphqlResponse: def __init__(self, requests_response): if not isinstance(requests_response, requests.Response): raise TypeError("Refusing to work until given a requests.Response") self.http_response = requests_respon...
import pytest from recognizers_text import Culture from recognizers_number_with_unit.number_with_unit import NumberWithUnitRecognizer, NumberWithUnitOptions from recognizers_number_with_unit.number_with_unit.models import DimensionModel, AbstractNumberWithUnitModel, ExtractorParserModel from recognizers_number_with_uni...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from ..registry import registry FILTER_CHOICES = registry.get_filter_choices() class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( ...
# LSTM for international airline passengers problem with regression framing import numpy import matplotlib.pyplot as plt import pandas import math from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import m...
from flask import Flask application = Flask(__name__) from bs4 import BeautifulSoup import requests from flask import jsonify coins = ["ETH","BTC","LTC","XRP","OMG","REQ","ZRX","GNT","BAT","AE","TRX","XLM","NEO","GAS","XRB","NCASH","EOS","CMT","ONT","ZIL","IOST","ACT","ZCO","SNT","POLY","ELF","REP","QKC","XZC","BCHABC...
""" Jupyter shell API ~~~~~~~~~~~~~~~~~ """ from contextlib import contextmanager, closing, redirect_stderr, redirect_stdout from io import StringIO import os import re import shutil import sys import tempfile from IPython import InteractiveShell def pop_until_match(items, pattern): """Pop from list.""" ...
# # check-attendance.py # # This code checks interaction by students with a particular # course over a period of time. # # course_id = 34797 course_id = 35270 year = 2018 # # import sys sys.path.append("../module/") import PyCAPI import datetime import json import uob_utils import matplotlib import matplotlib.pyplot...
import os import logging from datetime import datetime LOGS_DIR = '_logs' def _trigger_formatter(): _datefmt = '%b %d %H:%M:%S' _fmt = '%(asctime)s | %(levelname)8s | %(processName)s | %(message)s' return logging.Formatter(fmt=_fmt, datefmt=_datefmt) def _metrics_formatter(): return logging.Formatte...
import pytz from collections import OrderedDict from datetime import datetime from seraphsix.constants import DATE_FORMAT, DATE_FORMAT_TZ from seraphsix.models.database import ClanMember, Member def merge_dicts(a, b, path=None): # Merge dict `b` into dict `a` if path is None: path = [] for key i...
import mdformat import mdformat_black def test_format_python(): assert mdformat_black.format_python("print(\n''\n)", "") == 'print("")\n' def test_mdformat_integration(): unformatted_md = """~~~python def hello(): print( 'Hello world!' ) ~~~ """ formatted_md = """```python def hello(): ...
# encoding: utf-8 import pytest from marrow.mongo import Document, Field, Index @pytest.fixture def coll(connection): return connection.test.collection class Sample(Document): field = Field('field_name') other = Field('other_field') _field = Index('field', background=False) _inverse = Index('-field', backgro...
import os # ------------- YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY")
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: lndgrpc/compiled/verrpc.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _m...
import os import base64 import pydenticon import pandas import blabel SAMPLES_DIR = os.path.join("tests", "data", "samples") def get_template_and_style(folder_name): folder = os.path.join(SAMPLES_DIR, folder_name) template = os.path.join(folder, "item_template.html") style = os.path.join(folder, "style...
from osp.corpus.syllabus import Syllabus def test_log_path(mock_osp): """ Syllabus#log_path should return the .log file path. """ path = mock_osp.add_file() syllabus = Syllabus(path) assert syllabus.log_path == path+'.log'
import pygame, os from settings import * class Weapon: def __init__(self, x, y, name): self.img = pygame.transform.scale2x(pygame.image.load(os.path.join(f"assets/img/weapons/{name}", f"{name}.png"))) self.rect = pygame.Rect(x, y, self.img.get_width(), self.img.get_height()) self.counter_i...
# -*- coding: utf-8 -*- # @Time : 2021/12/1 23:30 # @Author : rhming # 沃阅读: 每日阅读抽奖大活动 import os,sys import requests,login,logging,urllib.parse,util,re,execjs,time,random,re class woread_task: def run(self, client, user): self.client,self.user=client,user self.session=requests.session(...
import pytest import packerlicious.provisioner as provisioner class TestConvergeProvisioner(object): def test_required_fields_missing(self): b = provisioner.Converge() with pytest.raises(ValueError) as excinfo: b.to_dict() assert 'required' in str(excinfo.value) def tes...
__author__ = 'koitaroh' # convert_topic_to_grid.py # Last Update: 2016-08-13 # Author: Satoshi Miyazawa # koitaroh@gmail.com # Convert tweets to population density array p[t, x, y] import csv import numpy import pickle import os import datetime import sqlalchemy import gensim # Logging ver. 2016-07-1...
import sys import shapefile import httplib import urllib import base64 if (len(sys.argv) == 1): print "<folder> <port> <username>:<password> <geo index name>" sys.exit(0) auth = 'Basic ' + base64.encodestring(sys.argv[3]).rstrip() conn = httplib.HTTPConnection("localhost", sys.argv[2]) # conn.set_debuglevel(...
# Implementation of a binary search tree (BST) data structure # By: Jacob Rockland # node class for BST class Node(object): # initializes node def __init__(self, key, data = None): self.key = key if data is None: self.data = key else: self.data = data se...
import requests import json def get_type_of_instance(qid): def get_label(response): label = None response = json.loads(response) id_num = [k for k in response["entities"].keys()][0] languages = [k for k in response["entities"][id_num]["labels"].keys()] for lang in languages: if "fr" == lang: label = ...
import os from itertools import combinations import numpy as np import rospkg from proseco.testing.tester import TestFailedError from proseco.utility.visualize_proseco_data import calculateStartPosPolygon from shapely.geometry import MultiPoint from proseco.utility.io import load_data if __name__ == "__main__": ...
from django.shortcuts import render from django.http import HttpResponse from .forms import QueryForm from .TwitterAPI import searchTimeLine, usernameExist # Create your views here. def index(request): print(request.) # blank form form = QueryForm() # if POST request (form submitted) if request.m...
# Copyright (C) 2021-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import pytest from ote_sdk.entities.url import URL from ote_sdk.tests.constants.ote_sdk_components import OteSdkComponent from ote_sdk.tests.constants.requirements import Requirements @pytest.mark.components(OteSdkComponent.OTE_SDK)...
from django.apps import AppConfig class FunwithmathConfig(AppConfig): name = 'funwithmath'
#!/usr/bin/python import os import re import time import dotenv import requests dotenv.load_dotenv() SQEXID = os.getenv("SQEXID") PASSWORD = os.getenv("PASSWORD") CHARACTER_ID = os.getenv("CHARACTER_ID") RETAINER_COUNT = os.getenv("RETAINER_COUNT") RETAINER_ID = list() for x in range(1, int(RETAINER_COUNT) + 1): ...
import pandas as pd import numpy as np import pyaf.ForecastEngine as autof import pyaf.Bench.TS_datasets as tsds import pyaf.Bench.GenericBenchmark as tBench import warnings #%matplotlib inline tester1 = tBench.cGeneric_Tester(tsds.load_FPP2_datsets() , "FPP2_BENCH"); with warnings.catch_warnings(): warnings.si...
from ..utils import mol_converter from ..typing import SpectrumType def clean_inchis(spectrum_in: SpectrumType, rescue_smiles=True) -> SpectrumType: """Make inchi style more consistent and wrongly given smiles. Args: ---- spectrum_in: matchms.Spectrum() Input spectrum. rescue_smiles: bool...
# pylint: disable=invalid-name from __future__ import ( annotations, ) from collections import ( UserDict, ) from contextlib import ( suppress, ) from gremlinx.utils import ( statics, ) from gremlinx.utils.classes import ( GraphTraversalBase, SourceType, ) from gremlinx.utils.exceptions import ...
from functools import lru_cache import re from tool.runners.python import SubmissionPy class ThoreSubmission(SubmissionPy): def run(self, s): """ :param s: input in string format :return: solution flag """ rule_lines, messages = s.split("\n\n") rules = self.parse_r...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/python/tpu/tensor_tracer.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _mess...
import re import os from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc import csv from product_spiders.items import Product, ProductLoader class VanC...
n = int(input()) v = list(map(lambda x: 1 if x == 'M' else -1, input())) curr = 0 ans = 0 while ans < len(v)-1: if abs(curr + v[ans+1]) < abs(curr + v[ans]): v[ans], v[ans+1] = v[ans+1], v[ans] if abs(curr + v[ans]) > n: break curr += v[ans] ans += 1 if abs(curr + v[ans]) <= n: ans ...
import json import random from collections.abc import Sequence from functools import lru_cache from pathlib import Path from typing import Union import typing from torch import Tensor from examples.data_utils import split_train_dataset, get_next from examples.data_utils import get_mnist_digits from deepstochlog.cont...
from hashlib import md5 def main(salt,zeroes,nbr=0): md5_hash = '' while md5_hash[0:zeroes] != '0'*zeroes: nbr += 1 md5_hash = md5((salt+str(nbr)).encode('utf-8')).hexdigest() return nbr print(main('bgvyzdsv',5)) # pt1 print(main('bgvyzdsv',6)) # pt2
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance # with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accom...
from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException """ The combined script for extracting MSKCC data class MSKCC_URL: extracting MSKCC data by alphabetic listing, then load each page and extract all herbs from [A-Z] class...
import re import sys # defining variable chk_table = [] filepath = sys.argv[2] # getting the correct chk table with open(sys.argv[1] + '.chk','r') as fp: chk_table = fp.readlines() fp.close() # Identify pattern inst = re.compile(r"\b0x[a-f0-9]{0,4}977$") # insert it to the chk instruction (predefined layout) ...