content
stringlengths
5
1.05M
#!/usr/bin/env python import pytest from pytest import approx import igrf13 time = "2010-07-12" def test_igrf13(): mag = igrf13.igrf(time, 65, 85, 0, model=12) assert mag.north.item() == approx(9295.100256) assert mag.east.item() == approx(2560.199706) assert mag.down.item() == approx(59670.251893...
import logging import sdk_cmd import sdk_tasks import shakedown from tests import config log = logging.getLogger(__name__) def broker_count_check(count, service_name=config.SERVICE_NAME): def fun(): try: if len(sdk_cmd.svc_cli(config.PACKAGE_NAME, service_name, 'broker list', json=True)) == ...
# -*- coding: utf-8 -*- """ testunit 基础类 @Time : 2020/4/10 上午1:03 @File : testbase.py @author : pchaos @license : Copyright(C), pchaos @Contact : p19992003#gmail.com """ import unittest import datetime import QUANTAXIS as qa from .testbase import TestingBase class qaTestingBase(TestingBase): """unittest...
# -*- coding: utf-8 -*- import pytest import os import csv import tempfile from datetime import datetime from nart.writer.builtins.csvwriter import CSVWriter from nart.model.nartdata import NartData from nart.model.nartitem import NartItem @pytest.fixture def csvwriter_fixture(): """ csvrepo의 filepath를 생성하고,...
import torchvision.transforms as transforms config = { 'params': { "backbone": { "kernel_size": 3, "output_dim": 128, "input_dim": 3, "stride": 2, "padding": 1, "out_img_size": 16 }, "primary_capsules": { "k...
""" This file is part of tendril See the COPYING, README, and INSTALL files for more information """ import os import imp dirname, fname = os.path.split(os.path.abspath(__file__)) def import_(filename): (path, name) = os.path.split(filename) (name, ext) = os.path.splitext(name) (f, filename, data) = im...
# Copyright (C) 2021, Raffaello Bonghi <raffaello@rnext.it> # All rights reserved # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list...
import logging from typing import TYPE_CHECKING, Optional from web3.types import BlockIdentifier from rotkehlchen.assets.asset import Asset from rotkehlchen.constants.assets import A_ALETH, A_ETH, A_WETH from rotkehlchen.constants.ethereum import SADDLE_ALETH_POOL from rotkehlchen.constants.misc import EXP18 from rot...
from .version import __version__ # scTenifoldXct.__version__ from scTenifoldXct.core import scTenifoldXct from scTenifoldXct.visualization import get_Xct_pairs, plot_XNet from scTenifoldXct.merge import merge_scTenifoldXct
# Copyright 2014-2017 Lionheart Software LLC # # 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...
#!/usr/bin/env python # -*- coding: utf-8 -*- # check_apcaccess.py - a script for checking a APC UPS # using the apcaccess utility # # 2016 By Christian Stankowic # <info at stankowic hyphen development dot net> # https://github.com/stdevel # # Enhanced and error corrections by Chris Johnston 2017 # Tested on BX1300G ...
from tiltfile_runner import run_tiltfile_func from unittest.mock import Mock import unittest import pytest import yaml class DockerLocalTest(unittest.TestCase): def test_delegates_to_local_resource_for_build(self): local_resource = Mock() run_tiltfile_func("docker_task/Tiltfile", ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : embedding.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 10/03/2018 # # This file is part of NSCL-PyTorch. # Distributed under terms of the MIT license. import torch import torch.nn as nn __all__ = ['LearnedPositionalEmbedding'] class ...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.plant_heating_and_cooling_equipment import HeatPumpWaterToWaterEquationFitHeating log = logging.getLogger(__name__) class TestHeatPumpWaterToWaterEquationFitHeating(unittest.Tes...
#!/usr/bin/python """ Runs every day as crontab task to pull down previous day's log from Google app engine, and uploads it to S3. """ import os import sys import shutil import subprocess import string from pytz import timezone from datetime import datetime, timedelta settings = { 'appcfg' : '<path to ga...
#!/usr/bin/python # Copyright (c) 2017, 2018 Michael De La Rue # Copyright (c) 2017, 2018 Will Thames # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'communi...
# window.py # # Copyright 2020 Herpiko Dwi Aguno # # 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 3 of the License, or # (at your option) any later version. # # This program is d...
''' Module for performing Stable Matching it solves an instance of the stable marriage problem. This is used as a utility for Text-Media Matching ''' class StableMatcher: ''' Class to implement Stable matching This Class implements the stable matching using the gale shapley algorithm. ''' def __...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os csv_files = os.listdir(os.getcwd()) csv_files = [f for f in csv_files if "Line" in f and ".csv" in f] # Function to determine significance def isSignificant(xval,yval, xthr = 1, ythr = 2): if abs(xval) >= xthr and abs(yval) >= ythr: ...
x, y = map(int, input().split(" ")) if x == 0 and y == 0: print("origem") elif x > 0 and y > 0: print("1 quadrante") elif x < 0 and y > 0: print("2 quadrante") elif x < 0 and y < 0: print("3 quadrante") elif x > 0 and y < 0: print("4 quadrante") elif x == 0 and y != 0: print("Eixo y") eli...
from django.conf.urls import url from web.views import get_index, fetch urlpatterns = [ url(r'^$', get_index), url(r'^fetch/$', fetch), ]
#!/usr/bin/env python def part1(numbers, cards): for number in numbers: for card in cards: mark(card, number) if has_won(card): return score(number, card) def part2(numbers, cards): for number in numbers: iter_cards = cards.copy() for card in i...
import json import webapp2 from controllers.api.api_base_controller import ApiBaseController from consts.district_type import DistrictType from consts.event_type import EventType from datetime import datetime from database.district_query import DistrictsInYearQuery from database.event_query import DistrictEventsQuer...
# coding=utf-8 from sys import exit from pytun import * from scapy.all import * from MANGLE import * from FenrirFangs import * from Autoconf import * import socket import select import time from struct import * from binascii import hexlify,unhexlify class FENRIR: def __init__(self): if os.geteuid() != 0: exit(...
from click.testing import CliRunner import unittest from mock import patch, Mock, PropertyMock from floyd.cli.version import upgrade class TestFloydVersion(unittest.TestCase): """ Tests cli utils helper functions """ def setUp(self): self.runner = CliRunner() @patch('floyd.cli.version.pi...
# -*- coding: utf-8 -*- """ EnigmaLight Plugin by Speedy1985, 2014 https://github.com/speedy1985 Parts of the code is from DonDavici (c) 2012 and other plugins: all credits to the coders :-) EnigmaLight is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
#! /usr/bin/env python3 import os, sys, time, re pid = os.getpid() os.write(1, ("About to fork (pid:%d)\n" % pid).encode()) rc = os.fork() if rc < 0: os.write(2, ("fork failed, returning %d\n" % rc).encode()) sys.exit(1) elif rc == 0: # child os.write(1, ("Child: My pid==%d. Parent'...
import sys import math import random class leds: def __init__(self, call): self.call = call def show_next(self, color, index): data = [0x18, 0x05, 0x05, 0x02] if(color == "white"): data[2] = 0x01 elif(color == "red"): data[2] = 0x02 elif(color =...
#!/usr/bin/python from UcsSdk import * import time # This script shows how to monitor UCS Manager events and define your own call back to take specific action on the respective events. ucsm_ip = '0.0.0.0' user = 'username' password = 'password' def callback_all(mce): print 'Received a New Event with ...
import yaml import sys import os import time import re import copy import pprint """ For each possible rule path """ class ParserError(ValueError): pass class ParserError(ValueError): pass class Context(object): def __init__(self,level,name,parent=None): self.level = level self.name = ...
from typing import ClassVar, List, Tuple from urllib.parse import quote as http_quote from .base import BaseProtocol from ..types import IPAddressType # HTTP 1.1 only class HTTPProtocol(BaseProtocol[IPAddressType]): ports: ClassVar[Tuple[int, ...]] = (80,) _TYPES: ClassVar[List[bytes]] = [ b"*/*; q=0...
''' Leia a hora inicial e a hora final de um jogo. A seguir calcule a duração do jogo, sabendo que o mesmo pode começar em um dia e terminar em outro, tendo uma duração mínima de 1 hora e máxima de 24 horas. | Input Sample | Output Samples | | ------------ | ----------------------- | | 16 2 | O JOGO D...
# stdlib imports import logging from datetime import datetime, timedelta # third party imports from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import (Column, Integer, Float, String, DateTime, ForeignKey, Boolean) from sqlalchemy import create_engine from sqlalchemy.orm ...
# Copyright (c) Xidian University and Xi'an University of Posts & Telecommunications. All Rights Reserved import random from .nasbench_101_cell import Cell as Cell_101 from .nasbench_201_cell import Cell as Cell_201 from gnn_lib.data import Data from nas_lib.utils.utils_data import nas2graph from nas_lib.utils.predict...
''' Utility module. ''' import yaml import numpy as np swap = lambda x1, x2: (x2, x1) if x1 > x2 else (x1, x2) square = lambda x: x**2 def read_params(file) -> dict: ''' Read yaml file. Args: file (str): Path to the yaml file. Returns: dict: Contents of the yaml file. ''' ...
# -*- coding: utf-8 -*- """ Example code showing how to control Thorlabs TDC Motors using PyAPT V1.2 20141125 V1.0 First working version 20141201 V1.0a Updated to short notation 20150324 V1.1 Added more descriptions 20150417 V1.2 Implemented motor without serial Michael Leung mcleung@stanford.edu """ # Imp...
''' Дополните приведенный код, так чтобы он вывел сумму квадратов элементов списка numbers. numbers = [1, 78, 23, -65, 99, 9089, 34, -32, 0, -67, 1, 11, 111] ''' numbers = [1, 78, 23, -65, 99, 9089, 34, -32, 0, -67, 1, 11, 111] numbers2 = [] for i in range(len(numbers)): numbers2.append(numbers[i] ** 2) print(sum(n...
''' Copyright (C) 2015 Ryan Gonzalez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,...
# Generated by Django 2.2.24 on 2021-08-16 09:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('landing', '0103_policyarticle'), ] operations = [ migrations.AddField( model_name='section', name='prefix', ...
class Config: """Discriminator configurations. """ def __init__(self, steps: int): """Initializer. Args: steps: diffusion steps. """ self.steps = steps # embedding self.pe = 128 self.embeddings = 512 self.mappers = 2 # blo...
''' Simple program to gather all the internal and external links. NOT to be confused with inlinks and outlinks. Internal links are those links that point to another website within the same domain External links are those links that point to another website that does NOT share the same domain Reference link: https://www...
from setuptools import setup setup( name='simplejira', version='1.0', description='simplejira', author='Brandon Squizzato', author_email='bsquizza@redhat.com', url='https://www.github.com/bsquizz/simplejira', packages=['simplejira'], install_requires=[ 'jira', 'pyyaml', ...
import requests import jwt import binascii from base58 import b58decode_check from ecdsa import SECP256k1, VerifyingKey, SigningKey def submitTransaction(signedTransactionHex, nodeURL): endpointURL = nodeURL + "submit-transaction" payload = {'TransactionHex': signedTransactionHex} response = requests.post...
"""A module that provides methods for accessing the Auth API and providing the logged in user details.""" import http import json import logging import fastapi import fastapi.security import fastapi.security.http import requests from pydantic import BaseModel # pylint:disable=no-name-in-module import config logge...
""" Exercise 7 - Sequence Slicing Question: List slicing is important in various data manipulation activities. Let's do a few more exercises on that. Please complete the script so that it prints out the first three items of list letters. letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] Expected out...
#!/usr/bin/env python3 # (C) 2021 gomachssm import datetime __copyright__ = f'(C) {datetime.date.today().year} gomachssm' __version__ = 'dummy' # get from tag, matches v([0-9]+\.[0-9]+\.[0-9]+). __license__ = 'Apache License, Version 2.0' __author__ = 'gomachssm' __url__ = 'https://github.com/gomachssm/twsqlparser'...
import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import standard.analysis as sa from tools import nicename import tools import task import settings mpl.rcParams['font.size'] = 7 mpl.rcParams['pdf.fonttype'] = 42 mpl.rcParams['ps.fonttype'] = 42 mpl.rcParams['font.family'] = 'aria...
from django.shortcuts import render , reverse from django.http import HttpResponseRedirect # Create your views here. def home(request): return render(request , 'home.html')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Root __init__ """ __author__ = "Samuel Marks" __version__ = "0.0.7" __description__ = "CLI to replace HTTP GET on GitHub API with clones"
import logging from clx.analytics import detector_utils as du log = logging.getLogger(__name__) class DetectorDataset(object): """ Wrapper class is used to hold the partitioned datframes and number of the records in all partitions. """ def __init__(self, df, batch_size): """This function ins...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse from dataclasses import dataclass import os from datasets import registry as datasets_registry from foundations import desc fr...
import logging import numpy as np import paddle from ..common import get_logger from .var_group import * from .pruning_plan import * from .filter_pruner import FilterPruner __all__ = ['L1NormFilterPruner'] _logger = get_logger(__name__, logging.INFO) class L1NormFilterPruner(FilterPruner): def __init__(self, mo...
# Component to translate alias values into strings import os, re, logging, json from pathlib import Path, PosixPath, WindowsPath _ValAliases = {} # Keeps track of classes which have been registered def addAliasClass(aliasClass, tag=None): '''Add a class to the supported alias list so that the ValAlias.makeAlias m...
import json import multiprocessing import os import shutil from typing import Dict, List, Tuple import cv2 import numpy as np from flask import request from tensorpack.utils import logger from tqdm import tqdm from werkzeug import FileStorage from werkzeug.utils import secure_filename from zipfile import ZipFile from...
import numpy def print_table(table, path): f = open(path, 'w') for row in range(len(table)): for col in range(len(table[row])): f.write(str(table[row][col])) f.write(' ') print(table[row][col], end=' ') if col == len(table[row])-1: print("...
# -*- coding: utf-8 -*- # created: 2021-06-30 # creator: liguopeng@liguopeng.net import asyncio import logging import threading from abc import abstractmethod from datetime import datetime import paho.mqtt.client as mqtt from gcommon.server.server_config import ServerConfig from gcommon.utils import gtime logger =...
from scipy.optimize import minimize from numpy.random import random import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm, ticker from matplotlib.colors import LogNorm import numpy as np from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import py...
# Generated by Django 3.0.11 on 2020-11-11 20:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0003_auto_20201111_1505'), ] operations = [ migrations.AlterField( model_name='language', name='listing', ...
## Written by Daniel Buscombe, ## MARDA Science ## daniel@mardascience.com ##> Release v1.3 (July 2020) ###=================================================== # import libraries import sys, getopt, json, os # set to False if you wish to use cpu (not recommended) ##True or False USE_GPU = True # PREDICT = False # #...
"""Expected errors.""" import inspect import sys UNREPRODUCIBLE_SUGGESTION_TEXT = ( 'Here are things you can try:\n' '- Run outside XVFB (e.g. you will be able to see the launched program ' 'on screen.) with `--disable-xvfb`, which is especially useful for ' 'Chrome.\n' '- Run with the downloaded...
import tensorflow as tf import fire import json import os import numpy as np import tensorflow as tf from tensorflow.python.training.input import batch import model, sample, encoder import model import numpy as np import tensorflow as tf from tensorflow.contrib.training import HParams def interact_model( model_nam...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
from datetime import date, datetime from typing import Any, Dict from dateutil import relativedelta from django.db.models import Sum, Count from em.models import Account, Transaction class AccountHelper(object): date_fmt = '%m-%Y' day_fmt = '%Y-%m-%d' @staticmethod def get_spendings(overall_expns, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .type_convert import anything_to_string from .type_convert import anything_to_bytes from .spamc_header import SpamcHeader from .spamc_body import SpamcBody class SpamcProtocol(SpamcHeader, SpamcBody): def __init__(self): super().__init__() def cre...
#!/usr/bin/python # # coveragePlot.py # # This program generates genomic coverage plots # Chiu Laboratory # University of California, San Francisco # January, 2014 # # Copyright (C) 2014 Charles Y Chiu - All Rights Reserved # SURPI has been released under a modified BSD license. # Please see license file for details. ...
# ******************************************************************************* # Copyright (C) 2020-2021 INAF # # This software is distributed under the terms of the BSD-3-Clause license # # Authors: # Ambra Di Piano <ambra.dipiano@inaf.it> # **************************************************************************...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys class Calculator: def __init__(self, number1, number2): self.number1 = int(number1) self.number2 = int(number2) def add(self): print(self.number1 + self.number2) return self.number1 + self.number2 def subtract(self): print(self.number1 - self.number2)...
from flask import Blueprint bp = Blueprint('auth', __name__) from diploma.auth import auth, emails, forms, routes
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # """ This is the example of input record for the test_tranform_data. """ input_test_data = [ { "targetingCriteria": { "include": { "and": [ { "or": { ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from mm.utils.opengl import Render from mm.utils.mesh import generateFace from mm.models import MeshModel import numpy as np import matplotlib.pyplot as plt from skimage import io, img_as_float if __name__ == '__main__': # Load the first image from the video ...
import copy from cantoolz.module import CANModule class ecu_switch(CANModule): name = "CAN Switch" help = """ This module emulating CAN Switch. Init params (example): { 'Cabin': { # From Cabin interface 'OBD2':[ # To OBD2 allowed next ID 0x...
from collections import defaultdict start, end = 357253, 892942 num_digits = 6 def solve(start, end, strict=False): length = end - start count = 0 for i in range(length): number = start + i previous = number % 10 consecutives = defaultdict(int) for j in range(1, num_digit...
# ----------------------------------------------------------------------------- # NDN Repo getfile client. # # @Author jonnykong@cs.ucla.edu # @Date 2019-10-24 # ----------------------------------------------------------------------------- import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) imp...
import attr import logging from typing import Callable from mmds.exceptions import PackageNotFoundError try: from PIL import Image except: raise PackageNotFoundError("pillow", by="rgbs modality.") from .ts import TimeSeriesModality logger = logging.getLogger(__name__) dumb_image = Image.new("RGB", (32, 32))...
all_teams = ["ANC", "APO", "CSU", "GUC", "LTI", "MIN", "MRL", "NAI", "POS", "RI1", "RAK", "SOS", "ZJU"] semi_teams = ["APO", "CSU", "GUC", "MIN", "MRL", "POS", "SOS", "ZJU"] team_names = { # "BAS" : "Baseline (no agents)", "ANC" : "anct_rescue2013", "APO" : "Apollo-Rescue", "CSU" : "CSU-YUNLU", "GU...
import warnings class AppPlatformError(Exception): """ Raised by :meth:`Client.request()` for requests that: - Return a non-200 HTTP response, or - Connection refused/timeout or - Response timeout or - Malformed request - Have a malformed/missing header in the response. """ ...
import setuptools from glob import glob setuptools.setup( name="noteboard-extension", version='0.1.0', url="https://github.com/yuvipanda/noteboard", author="Yuvi Panda", description="Simple Jupyter extension to emit events about current notebooks to a noteboard server", data_files=[ ('s...
import os.path as osp import numpy as np class Dataset(object): def __init__(self, ids, labels, is_train=True, name='default'): self._ids = list(ids) self._labels = labels self.name = name self.is_train = is_train def get_data(self, id): activity = np.load(id) ...
import cv2 as cv import numpy as np import matplotlib.pyplot as plt #color spaces --> rgb spaces,grayscal img = cv.imread('photos/dog.jpg') cv.imshow('Dog',img) # plt.imshow(img) # plt.show() # point to note --> there is conversion of colour spaces in matplotlib # BGR to grayscale --> gray = cv.cvtColor(img,cv.COLO...
from rest_framework import serializers from users.models.organizations import Organization class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'domain')
import sys from data_wrapper.settings import MESSAGES class DataWrapper: def __init__(self, db=None, params=None, environment=None): if db: if db.lower() == 'mongodb': from data_wrapper.mongodb_wrapper import MongodbDbWrapper self.db = True self...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import re import shutil import subprocess import sys import tempfile from telemetry.internal.util import binary_manager class Min...
# ------------------------------------------------------------------------------ # Portions of this code are from # OpenPCDet (https://github.com/open-mmlab/OpenPCDet) # Licensed under the Apache License. # ------------------------------------------------------------------------------ import numpy as np import torch i...
import typing def printBinary(n: int) -> None: if n > 1: printBinary(n // 2) print(n % 2, end = "") def main() -> None: N = int(input("Input an integer:\n")) printBinary(N) return None main()
# Authors: David Alexander, Lance Hepler from __future__ import absolute_import, division, print_function from GenomicConsensus.arrow.utils import allSingleBaseMutations from GenomicConsensus.variants import Variant from GenomicConsensus.quiver.diploid import variantsFromAlignment import numpy as np import ConsensusC...
"""Tests for the /sessions/.../commands routes.""" import pytest from datetime import datetime from decoy import Decoy, matchers from fastapi import FastAPI from fastapi.testclient import TestClient from httpx import AsyncClient from typing import Callable, Awaitable from tests.helpers import verify_response from op...
import discord from discord.ext import commands import steam from steam import WebAPI, SteamID import keys ##TODO: convert to psql or something import pickle import asyncio import os import re ## Used to track the worst players in MM class PlayerTracker(commands.Cog): ## Init def __init__(self, bot): ...
__all__ = ['ioc_api', 'ioc_common', 'ioc_et', 'xmlutils']
import modin.pandas as pd import swifter # Do not remove - this modified bindings for modin import sys, os import datetime import csv import random import h5py import numpy as np import ipaddress import datetime as datetime def write_single_graph(f, graph_id, x, edge_index, y, attrs=None, **kwargs): ''' store...
# Class to generate batches of image data to be fed to model # inclusive of both original data and augmented data # https://gist.github.com/devxpy/a73744bab1b77a79bcad553cbe589493 # example # train_gen = PersonDataGenerator( # train_df, # batch_size=32, # aug_list=[ ...
from ._abstract import AbstractSearcher from ._result import RecipeLink, SearchResult import urllib.parse from typing import List class NyTimes(AbstractSearcher): def __init__(self): AbstractSearcher.__init__(self) @classmethod def host(cls): return "https://cooking.nytimes.com" d...
import json import requests import time import hmac import hashlib from requests.exceptions import HTTPError SDK_VERSION = '1.0.0' CLOCK_DRIFT = 300 class HTTPClient(object): def request(self, method, url, headers, data=None, auth=None): raise NotImplementedError('subclass must implement request') cl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import subprocess if subprocess.Popen(['./problem']).wait() != 0: print("Wow, you\'ve crushed this") flagfile = open('flag') if not flagfile: print("Flag is missing, tell admin") else: print(flagfile.read())
""" Sudo2 is for Loomgild.py """ import time from time import sleep # Command Functions def help(): print("Hello!") print("Welcome to Loomgild, a script that imitates a command line.") print("This is one of the few commands that you can use.") print("We will now load the commands you can use..") p...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Script to hold temporary routines created during the beamtime. Everything added here is star (*) imported into the IPython shell after the ``SplitAndDelay`` object has succesfully instantiated. Therefore, it is recommended to run the specific unit-test to quickly ensur...
from random import randint while True: print("----------\n[j] para jogar o dado\n[e] para fechar") res = str(input().replace(" ", "").lower()) if res == "j": print(f"\nvalor do dado: {randint(1, 6)}") if res == "e": break print("----------\n")
import contextlib import logging import os from pathlib import Path import shutil from subprocess import CalledProcessError, check_output import sys from tempfile import NamedTemporaryFile from typing import cast from spython.main import Client from lm_zoo import errors from lm_zoo.backends import ContainerBackend fr...
#importamos la libreria forms: from django import forms #creamos una lista de las posibles opciones del select: from .pqrsf import PQRSF_CHOICES #creamos la estructura dl formulario class ContactFrom(forms.Form): """creamos los campos""" email = forms.EmailField(label="correo electrónico", widget=forms.EmailInput(a...
def test_load(session, inline): inline("PASS")
TAG_MAP = { ('landuse', 'forest'): {"TYPE": "forest", "DRAW_TYPE": "plane"}, ('natural', 'wood'): {"TYPE": "forest", "SUBTYPE": "natural", "DRAW_TYPE": "plane"} } def find_type(tags): keys = list(tags.items()) return [TAG_MAP[key] for key in keys if key in TAG_MAP]