content stringlengths 5 1.05M |
|---|
import pytest
# Using https://iancoleman.io/bip39/ and https://jlopp.github.io/xpub-converter/
# mnemonic = "ghost ghost ghost ghost ghost ghost ghost ghost ghost ghost ghost machine"
# m/44'/0'/0'
@pytest.fixture
def ghost_machine_xpub_44():
xpub = "xpub6CGap5qbgNCEsvXg2gAjEho17zECMA9PbZa7QkrEWTPnPRaubE6qKots... |
DATA_ID = 13
|
from __future__ import unicode_literals
from django.apps import AppConfig
class MediumEditorConfig(AppConfig):
name = 'mediumeditor'
|
import jax.lax as lax
import jax.numpy as jnp
from hparams import HParams
try:
from .losses import KLDivergence
except (ImportError, ValueError):
from model.losses import KLDivergence
hparams = HParams.get_hparams_by_name("efficient_vdvae")
class KLDivergenceStats(KLDivergence):
def _get_kl_loss(self,... |
from autovalidate.reporters.core import Reporter, reporter
@reporter('dot')
class DotReporter(Reporter):
def report(self, result):
self.write('.' if result.valid else 'F')
def summarize(self):
self.write('\n')
super(DotReporter, self).summarize()
|
# -----------------------------------------------------------------------------
# Name: parser.py
# Purpose: Framework for analyzing the syntactic structure
# of simple tonal lines
#
# Author: Robert Snarrenberg
# Copyright: (c) 2021 by Robert Snarrenberg
# License: BSD, see lic... |
"""Class implementation for the mouse event.
"""
from typing import Generic
from typing import TypeVar
from apysc._event.event import Event
from apysc._event.prevent_default_interface import PreventDefaultInterface
from apysc._event.stop_propagation_interface import StopPropagationInterface
from apysc._type.... |
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from ..serializers.profile import ProfileSerializer
@api_view(["GET", "PA... |
from confusables import confusable_regex
import datetime
import json
import os
import re
import requests
API_BASE_URL = os.environ["API_BASE_URL"]
CLIENT_KEY = os.environ["CLIENT_KEY"]
class BanInstance:
def __init__(self, banJson, current_time, timeout_duration, session):
self._session = session
self.ban_i... |
import cgi
import logging
import urllib.parse
from pathlib import Path
from pathvalidate import sanitize_filename
from alteia.core.utils.typing import ResourceId, SomeResourceIds
LOGGER = logging.getLogger(__name__)
def extract_filename_from_headers(headers: dict) -> str:
h = headers['content-disposition']
... |
import os
from flask import Flask, redirect, url_for, request, render_template, session, make_response
from pymongo import MongoClient
import requests
app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]
app.api_backend_host = os.environ["BACKEND_HOST"]
app.api_backend_wcs_host = os.environ["BACKEND_HO... |
# -*- coding: utf-8 -*-
import json
from quantized_mesh_tile.global_geodetic import GlobalGeodetic
# Zoom 0 to 8
globalTilesConfig = [
[
{"startX": 0, "startY": 0, "endX": 1, "endY": 0}
],
[
{"startX": 0, "startY": 0, "endX": 3, "endY": 1}
],
[
{"startX": 0, "startY": 0, "e... |
import sys
import random
#for random sequence
'''
cdna =[]
x=0
n=['A', 'C', 'G', 'T']
y = random.randrange(1, 50)
while x < y:
rdna = random.choice(n)
for i in range(0, random.randrange(1, y/4)):
cdna.append(rdna)
x= len(cdna)
'''
corrupteddna="AAATAAAGGGGCCCCCTTTTTTTCC"
cdna ... |
from load import *
import ReadFile
import WriteFileAll
import sys
'''
@author
Guangxu Jin, wake forest school of medicine.
Processing covid hits
'''
####input and output
#cov_hits=config.cov_hits #"/home/guangxujin/covid-19/SARS-COV2_raw/1_US_WI_blast_1000/*blast"
cov_hit=sys.argv[1]
gc_out=sys.argv[2]
#data=ReadFi... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import netaddr
from netaddr import IPNetwork
# iplist =[
# IPNetwork('10.105.205.8/29'),
# IPNetwork('10.105.205.16/28'),
# IPNetwork('10.105.205.32/27'),
# IPNetwork('10.105.205.64/26'),
# IPNetwork('10.105.205.128/26'),
# IPNetwork('10.105.205.1... |
#vigenere
#string="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key=input()
d={
'A':0,
'B':1,
'C':2,
'D':3,
'E':4,
'F':5,
'G':6,
'H':7,
'I':8,
'J':9,
'K':10,
'L':11,
'M':12,
'N':13,
'O':14,
'P':15,
'Q':16,
'R':17,
'S':18,
'T':19,
'U':20,
'V':21,
... |
import scipy.io.wavfile as wav
import numpy as np
import os
import pydub
import tempfile
import scipy
import random
from python_speech_features import logfbank
from lib.tools_math import *
def changeRateTo16000(filepath):
if filepath[-4:].lower() =='.wav':
sound = pydub.AudioSegment.from_wav(filepath)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains all the exceptions thrown by the package.
There are two base types for exceptions: TemplateError and ValidationError
"""
from __future__ import unicode_literals
class TemplateError(Exception):
"""
TemplateError are errors thrown at the i... |
apple $3 each lb |
import logging
from abc import ABCMeta
from models.yarn.objects import YarnResource, YarnRunningContainer, YarnContainerType
from schedulers.yarn import YarnRegularScheduler, YarnFairScheduler, LOG, MEM_INCREMENT, YARN_MIN_ALLOCATION_MB
from stats.decisions import YarnFairSchedulerElasticStats
from utils import round_... |
from recipes.apis import RecipesAPIFactory as RecipesAPI |
from typing import overload
import numpy as np
from scipy.optimize import bisect, root
from scipy.stats import norm
from blackscholes.base import PricingMetaClass, PricingModelBase
def gen_getter(key:str):
def getter(self):
self._update_values()
return getattr(self, f"_{key}")
return getter
... |
#one hot encoding
import numpy as np
samples = {'Jupiter has 79 known moons .', 'Neptune has 14 confirmed
moons !'} # Sample set for our example
# Create an empty dictionary
token_index = {}
#Create a counter for counting the number of key-value pairs in the
token_length
counter = 0
# Select the eleme... |
'''
A convex polygon is a simple polygon in which no line segment
between two points on the boundary ever goes outside the
polygon. Equivalently, it is a simple polygon whose interior is a
convex set. In a convex polygon, all interior angles are less than or
equal to 180 degrees, while in a strictly convex polygon all ... |
'''
Stage 1 involves selected the major cryptos
based on a criteria of exceedance of market capitalization above $4bn
Don't forget to set the folder in which this script is held in
as the current working folder before running the script
'''
# import needed libraries
import pandas as pd
import time
from tqdm import tq... |
TURRET_CONFIG = {
'baudrate':9600,
'serialPort':'/dev/ttyUSB0',
'useSSL': False,
'validationBypass': True,
'noTurret',False,
'password': "Z",
'webSocketPort': 9001,
'certFile': '/etc/uv4l/fullchain.pem',
'keyFile': '/etc/uv4l/privkey.key'
}
|
class Solution:
def XXX(self, root: TreeNode) -> int:
if not root:
return 0
left=self.XXX(root.left)
right=self.XXX(root.right)
return max(left,right)+1
|
# Verificando se algo é um objeto iterador
lista1 = [0, 1, 2, 3, 4, 5, 6]
print(hasattr(lista1, '__next__')) # Embora ela seja um objeto iterável, ela não é um iterador (False)
lista2 = [0, 1, 2, 3, 4, 5]
lista2 = iter(lista2) # Transformo a lista2 em um objeto iterador
print(hasattr(lista2, '__next__')) # True
#... |
SITE_URL = "http://127.0.0.1:8000/"
CREATE_USER_SUCCESS = "User created successfully."
USERS_GET_SUCCESS = "All users retrieved successfully."
UPDATE_USER_SUCCESS = "User updated successfully."
DELETE_USER_SUCCESS = "User deleted successfully."
GET_USER_SUCCESS = "User retrieved successfully."
USER_DOES_NOT_EXIST = "Us... |
import numpy as np
import mxnet as mx
import argparse
import cv2
import time
from core.symbol import P_Net20, R_Net, O_Net
from core.fcn_detector import FcnDetector
from core.detector import Detector
from tools.load_model import load_param
from core.MtcnnDetector20 import MtcnnDetector
def test_net(imgfile,prefix, ep... |
from .scrape_data import TransitData
|
target = 100
ns = range(1, target)
ways = [1] + [0]*target
for n in ns:
for i in range(n, target+1):
ways[i] += ways[i-n]
print(ways[100])
# https://blog.dreamshire.com/project-euler-76-solution/
|
import sys
import click
@click.group()
def cli():
pass
@click.command()
@click.option("--count", default=1, help="Number of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for _ ... |
from __future__ import print_function, division
from copy import deepcopy
import os
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
import rubin_sim.maf.metrics as metrics
import rubin_sim.maf.slicers as slicers
import rubin_sim.maf.stackers as stackers
import rubin_sim.maf.plots as plots
impor... |
# TODO: ugh:
import sys, pprint, os
sys.path.insert(1, '..')
sys.path.insert(1, '.')
sys.path.insert(1, os.path.join("..", "py"))
import h2o
import h2o_test_utils
from h2o_test_utils import ModelSpec
import os
import argparse
import time
import json
import requests
sys.path.insert(1, '../rest_tests')
##############... |
from typing import Optional
import pandas as pd
import numpy as np
from finstmt.exc import ForecastNotFitException
from finstmt.forecast.models.base import ForecastModel
class AverageModel(ForecastModel):
mean: Optional[float] = None
stderr: Optional[float] = None
def fit(self, series: pd.Series):
... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import federate_pb2 as federate__pb2
class FederateStub(object):
"""*
Federate service allows for P2P federation between Impervious nodes.
"""
... |
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
class Meta:
verbose_name_plural = 'Categories'
name = models.CharField(max_length=254)
friendly_name = models.CharField(max_length=254, null=True, blank=True)
def __str__(self):
... |
# encoding: UTF-8
# 首先写系统内置模块
import sys
from datetime import datetime, timedelta, time
from time import sleep
# 然后是第三方库模块(如PyQt4等)
import sip
from PyQt4 import QtCore
# 然后是自己编写的模块
from demoEngine import MainEngine
from strategyEngine import *
#####################################################... |
"""
Manage game statistics
Currently tracks:
- Possession
- Number of goals scored
- Pass accuracy
- Shot accuracy
"""
class Stats(object):
"""
Keep track of game statistics
"""
def __init__(self):
"""
Initializes the possession, pass accuracy and shot accuracy
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import shutil
import logging
import time
import traceback
from utilities import get_config
from utilities import tweet
from utilities import get_random_tweet_quote
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
... |
"""
The del keyword removes the specified index:
"""
thislist = ["apple", "banana", "cherry"]
del thislist[1]
print(thislist)
|
from Rationale_Analysis.models.saliency_scorer.base_saliency_scorer import SaliencyScorer
from allennlp.models.model import Model
@Model.register("wrapper")
class WrapperSaliency(SaliencyScorer) :
def score(self, **kwargs) :
output_dict = self._model['model'].forward(**kwargs)
output_dict = sel... |
import numpy as np
import time
import sys
import matplotlib.pyplot as plt
plt.style.use('ggplot')
# print(plt.style.available)
import sklearn.metrics
import torch
import torch.nn as nn
import torch.nn.functional as F
import sklearn.metrics
from skimage.metrics import structural_similarity as ssim
from skimage.metrics i... |
# Copyright 2019 The TensorFlow Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
aliases = {
# "Query" : "Replacement"
"luna": "princess luna",
"celestia": "princess celestia",
'chrysalis': "queen chrysalis"
}
|
###############################################################
# Name: main.py
# Purpose: Entry point for web2help
# Author: Luca Allulli (webmaster@roma21.it)
# Created: 2009-08-24
# Copyright: Luca Allulli (http://www.skeed.it/songpress.html)
# License: GNU GPL v2
#####################################... |
#!/usr/bin/env python
#coding=utf-8
from setuptools import setup, find_packages
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
import sys
if sys.version_info < (2, 6):
sys.exit('Python 2.5 or greater is re... |
import m5
from m5.objects import *
from m5.util import convert
import x86
from caches import *
class MySystem(LinuxX86System):
def __init__(self, opts):
super(MySystem, self).__init__()
self._opts = opts
self.clk_domain = SrcClockDomain()
self.clk_domain.clock = '3GHz'
... |
import datetime
import random
from django.core.exceptions import ValidationError
from django.utils import timezone
from model_mommy import mommy
from core.models import Reserva, Quarto
start_date = timezone.now()
end_date = start_date + timezone.timedelta(days=800)
quarto_list = Quarto.objects.all()
names = [
'... |
# mysql/enumerated.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re
from .types import _StringType
from ... import exc, sql, util
from ..... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('chatter', '0002_chat_name_text'),
]
operations = [
migrations.AddField(
model_name='chat',
name='dat... |
import numpy as np
def poisson_generator(rate, t_start=0, t_stop=1000.0):
"""
Returns a SpikeTrain whose spikes are a realization of a Poisson process
with the given rate (Hz) and stopping time t_stop (milliseconds).
Inputs:
rate - the rate of the discharge (in Hz)
t_st... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from chibi.atlas import Chibi_atlas
from chibi.file import Chibi_path
import unittest
from chibi_lxc.container import Container, Not_exists_error
class Centos_test( Container ):
name = 'centos_7_test'
provision_folders = {
'scripts': 'tests/scripts'
}
... |
# -*- coding: utf-8 -*-
"""Base code to load commands from xml and run them."""
from __future__ import annotations
import argparse
import datetime
from typing import List, Literal, TypedDict, Union
import wfc.wfc_control as wfc_control
import xml.etree.ElementTree as ET
import os
class RunInstructions(TypedDict):
... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
import librosa
import os
from model import vggish_rnn
# set CUDA visible devices
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
# set Flags
flags = tf.app.flags
# slim = tf.contrib.slim
flags.DEFINE_integer('num_batches'... |
import json
import logging
import os
from pathlib import Path
import random
import re
import shutil
from xml.dom import minidom
import yaml
from Cryptodome.PublicKey import RSA
from jinja2 import Environment, PackageLoader
import libvirt
from . import tools
from .exceptions import DeploymentDoesNotExists, VersionOSN... |
#!/usr/bin/env python3
""" Main File """
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
class PoliciesPanel(tk.LabelFrame):
"""process_panel
Create the Process Panel so that users can input Process Details.
:param parent:
The Parent parameter is the Main Window (root)
... |
from abc import abstractmethod
from textwrap import dedent
from typing import Optional, Iterable
import pytest
from hypothesis import given, settings, HealthCheck
from hypothesmith import from_grammar
from libcst import parse_module
from snakepack.analyzers import Analyzer
from snakepack.analyzers._base import Subjec... |
from dataclasses import dataclass
import vbancmd
from vbancmd import kinds
import random
import sys
# let's keep things random
kind_id = random.choice(tuple(kind.id for kind in kinds.all))
opts = {
"ip": "codey.local",
"streamname": "codey",
"port": 6990,
"bps": 0,
"sync": True,
}
vbans = {kind.i... |
# Title : Find the line number in which specified word exists.
# Author : Kiran Raj R.
# Date : 16/11/2020
user_input = input("Enter the word to search: ")
count = 0
occurance = []
with open('words.txt') as file:
for line in file:
count+=1
if user_input in line:
occurance.append(cou... |
from xtcocotools.coco import COCO
from xtcocotools.cocoeval import COCOeval
import numpy as np
gt_file = '../annotations/example_coco_val.json'
preds = '../annotations/example_coco_preds.json'
sigmas = np.array(
[.26, .25, .25, .35, .35, .79, .79, .72, .72, .62,.62, 1.07, 1.07, .87, .87, .89, ... |
from __future__ import print_function
import time
import os
os.chdir("d:/assignment")
import json
import matplotlib.pyplot as plt
import tensorflow as tf
from utils.classifiers.squeezenet import SqueezeNet
from utils.data_utils import load_tiny_imagenet
from utils.image_utils import SQUEEZENET_MEAN, SQUEEZENET_STD
from... |
import os
from datetime import datetime
from removebg import RemoveBg
from pyrogram import filters
from pyrogram.types import Message
from megumin import megux, Config
IMG_PATH = Config.DOWN_PATH + "dl_image.jpg"
@megux.on_message(filters.command("removebg", Config.TRIGGER))
async def remove_background(_, me... |
"""Convert a NT pathname to a file URL and vice versa."""
def url2pathname(url):
"""OS-specific conversion from a relative URL of the 'file' scheme
to a file system path; not recommended for general use."""
# e.g.
# ///C|/foo/bar/spam.foo
# and
# ///C:/foo/bar/spam.foo
# become... |
from mlapp.mlapp_cli.common.cli_utilities import to_lower, is_int, to_int, to_upper, is_positive, clean_spaces
steps = {
'number_of_steps': {
"display_name": "Choose how many pipeline steps to deploy",
"short_description": 'Press enter to set number of steps to 2',
"validations": [is_int, i... |
from olea.error_handler import OleaException
from common_errors import AccessDenied, NonExistedObj, DuplicateObj
__all__ = [
'AccessDenied', 'NonExistedObj', 'DuplicateObj', 'RolesExisted',
'InvalidSource', 'UnableToFetchTitle', 'IsBooked', 'BookedBefore',
'CancellingRejected'
]
class RolesExisted(OleaEx... |
# -*- coding: utf-8 -*-
import re
import scrapy
from locations.items import GeojsonPointItem
class UPSFreightServiceCenter(scrapy.Spider):
download_delay = 0.2
name = "ups_freight_service_centers"
item_attributes = { 'brand': "UPS Freight Service Centers" }
allowed_domains = ["upsfreight.com"]
st... |
#!/usr/bin/env python
# coding: utf-8
# ### *********** Atenção: ***********
# Utilize Java JDK 1.8 ou 11 e Apache Spark 2.4.2
# ****** Caso receba mensagem de erro "name 'sc' is not defined", interrompa o pyspark e apague o diretório metastore_db no mesmo diretório onde está este Jupyter notebook ******
# ## <fo... |
from tests.utils import W3CTestCase
class TestGridPositionedItemsImplicitGridLine(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'grid-positioned-items-implicit-grid-line-'))
|
from rest_framework import serializers
from vbb_backend.session.models import StudentSessionAssociation
from vbb_backend.users.models import Student
from vbb_backend.users.api.serializers.user import UserBareMinimumSerializer
class StudentSessionBaseSerializer(serializers.ModelSerializer):
id = serializers.UUIDF... |
# Copyright (c) 2020 fortiss GmbH
#
# Authors: Patrick Hart
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import tensorflow as tf
# tfa
from tf_agents.networks import actor_distribution_network
from tf_agents.networks import actor_distribution_r... |
#!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2018-2020 Florent Kermarrec <florent@enjoy-digital.fr>
# SPDX-License-Identifier: BSD-2-Clause
import os
import argparse
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex_boards.platforms import ae... |
# 艺气山直播:http://www.173.com/room/category?categoryId=11
import requests
class YQS:
def __init__(self, rid):
self.rid = rid
def get_real_url(self):
params = 'roomId={}'.format(self.rid)
with requests.Session() as s:
res = s.post('http://www.173.com/room/getVieoUrl', params... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def heavyside(x):
return 1 if x>0 else 0
def laing_chow(y, t, I1, I2):
"""Implements eqs (1-4) from Liang and chow in the format required by scipy.integrate.odeint.
y is assumed to be a list [u1, a1, u2, a2]
"... |
from unittest import mock
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from eventstore.forms import MomConnectImportForm
from eventstore.models import ImportRow, MomConnectImport
from registrations.models import ClinicCode
class MomConnectImportFormTests(TestCase):
... |
import logging
import re
import warnings
from typing import Dict, NamedTuple, Optional, Tuple, Union, cast
import transformers
from allennlp.common.checks import ConfigurationError
from transformers import AutoConfig, AutoModel
logger = logging.getLogger(__name__)
class TransformerSpec(NamedTuple):
model_name: ... |
import unittest
import solver
class TestSolution(unittest.TestCase):
def test_solve(self):
grid = [[1,2,3,4],[2,3,5,7],[3,4,5,6],[4,5,6,7]]
self.assertEqual(solver.solve(grid, 1), 7);
self.assertEqual(solver.solve(grid, 2), 6 * 7);
self.assertEqual(solver.solve(grid, 3), 7 * 6 * 7);
se... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class FlatButton(Component):
"""A FlatButton component.
Keyword arguments:
- children (a list of or a singular dash component, string or number; optional): This is what will be displayed inside the butt... |
"""
biopal quick start
Usage:
biopal-quickstart FOLDER
Arguments:
FOLDER Path to the folder to initialize
Options:
-h --help Show this screen
--version Show version
Details:
Initialize the folder with default input and configuration xml files:
Input_File.xml to be edite... |
"""Prepare input features for training neural vocoders
"""
import os
from concurrent.futures import ProcessPoolExecutor
from os.path import exists, join
import hydra
import numpy as np
from hydra.utils import to_absolute_path
from nnsvs.logger import getLogger
from nnsvs.multistream import get_static_features
from nns... |
from typing import Optional
from . import events
from .packet import QuicStreamFrame
from .packet_builder import QuicDeliveryState
from .rangeset import RangeSet
from .logger import QuicLoggerTrace
import logging
logger = logging.getLogger("client")
class QuicStream:
def __init__(
self,
stream_id... |
from .models import Page
def pages_processor(request):
pages = Page.objects.all().exclude(slug='home').order_by('title')
print pages
return {'pages': pages}
|
# coding: utf-8
# Copyright 2017 Google Inc. All rights reserved.
# Copyright 2017 Jim O'Regan
#
# 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-... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 19:38:37 2018
@author: markp
"""
import os
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptio... |
import urllib
from xml.etree.ElementTree import ElementTree
from django.conf import settings
key = getattr(settings, 'YANDEX_API_KEY')
api_url = 'http://cleanweb-api.yandex.ru/1.0/'
xml = ElementTree()
def check_spam(text):
text = unicode(text).encode('utf-8')
data = urllib.urlencode({'body-plain': text, 'k... |
import sys
import time
def bienvenida():
print "\n"
print "\033[94m /$$ /$$ /$$ /$$$$$$$ /$$$$$$$$ /$$ "
print "\033[94m| $$$ /$$$|__/ | $$__ $$ |__ $$__/ | $$ "
print "\033[94m| $$$$ /$$$$ /$$ /$$... |
#!/usr/bin/env python
import sys
def main(args):
print("args:", args)
if __name__ == '__main__':
main(sys.argv[1:])
|
from nose.tools import assert_equal, assert_is_none
from redict import ReDict, update_with_redict
class TestRedict:
@classmethod
def setup(cls):
d = {'.*foo.*': 1, '.*bar.*': 2, '.*baz.*': 3}
cls.rd = ReDict(d)
def test_get_no_match(self):
assert_is_none(self.rd.re_get('asdf_biz_a... |
from utils.common import LogManager
from utils.validators import ValidationException
def process_parameters(parameters: list) -> dict:
if parameters is None:
raise ValidationException("Parameters not defined")
result = {}
log_manager = LogManager()
for parameter in parameters:
field =... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_tracking.wandb.ipynb (unless otherwise specified).
__all__ = ['SaveModelAtEndCallback', 'log_dataset', 'UPITWandbCallback']
# Cell
import wandb
from fastai.vision.all import *
from fastai.callback.wandb import *
from fastai.callback.wandb import _format_metadata, _fo... |
import asyncio
from unittest import TestCase
from unit.elasticsearch.elasticsearch_test_utils import mock_search_client
from dp_conceptual_search.config import CONFIG
from dp_conceptual_search.search.client.search_client import SearchClient
from dp_conceptual_search.search.client.exceptions import RequestSizeExceede... |
# Copyright 2019 Kemal Kurniawan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#### search_test.py
#### made by Min-Seok Kwon
#### 2019-06-04 14:08:53
#########################
import sys
import os
SVRNAME = os.uname()[1]
if "MBI" in SVRNAME.upper():
sys_path="/Users/pcaso/bin/python_lib"
elif SVRNAME == "T7":
sys_path="/ms1/bin/python_lib"
el... |
""""""
from collections import namedtuple
def is_numeric(numstring):
try:
return isinstance(float(numstring),float)
except:
return False
def try_numeric(numstring):
"""Converts strings containing numbers into numbers, else returns the string
This is designed to help with the pr... |
import argparse
import logging
import sys
from pathlib import Path
from PlantStation.configurer import USER_CFG_PATH, GLOBAL_CFG_PATH
from .App import App
def run():
parser = argparse.ArgumentParser(description='Plantstation daemon')
parser.add_argument('-p', '--config-path', action='store', nargs=1, help='P... |
class wrapper:
def __init__(self,fn):
self.fn = fn
def __call__(self,*args):
return "(" + self.fn(*args) + ")"
def mydecorator(x):
print("decorating " + str(x))
return wrapper(x)
def describe():
return "world"
describe = mydecorator(describe)
print(describe())
|
#!/usr/bin/env python
import os
import json
def compile_problems_table():
""" supposed to run from /py directory """
os.chdir('../problemset')
compiled_problems_table = ""
for file in filter(lambda _: os.path.splitext(_)[1] == '.json', os.listdir()):
problem = json.loads(open(file, 'r', encodi... |
# Pedirle los datos al usuario
str1 = input("ingrese numero 1 ")
str2 = input("ingrese numero 2 ")
# Convertir los datos de cadena a numero
n1 = int(str1)
n2 = int(str2)
# Sumar los datos
suma = n1 + n2
goto 4
# print("El resultado es:" + str(suma))
print(f"El resultado es: {suma}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.