text stringlengths 2 999k |
|---|
""" Generate fake data.
Functions for generation some kind of fake datas. You can use ``mixer.fakers``
by manual, like this:
::
from mixer import fakers as f
name = f.get_name()
country = f.get_country()
url_gen = f.gen_url()(hostname=True)
urls = [next(url_gen) for _ in range(10)]
"""
from .... |
#!/usr/bin/env python2
import re
import os
import glob
import subprocess
import fileinput
os.chdir(os.path.join(os.path.dirname(__file__), '..'))
chart_version = '7.5.1'
versions = {
6: '6.8.6',
7: '7.5.1',
}
file_patterns = [
'*/examples/*/test/goss*.y*ml',
'*/examples/*/*.y*ml',
'helpers/examp... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Album'
db.create_table(u'chet_album', (
(u'id... |
def test():
assert "for ent in doc.ents" in __solution__, "Are you iterating over the entities?"
assert (
"print(ent.text, ent.label_)" in __solution__
), "Are you printing the text and the label?"
__msg__.good(
"Great work! So far, the model has been correct every single time. "
... |
# Module: Preprocess
# Author: Fahad Akbar <m.akbar@queensu.ca>
# License: MIT
import pandas as pd
import numpy as np
import ipywidgets as wg
from IPython.display import display
from ipywidgets import Layout
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn.impute._base import _BaseImputer
f... |
# -*- coding: utf-8 -*-
"""Invest in Great - Thank you for your message Page Object."""
import logging
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from directory_tests_shared import URLs
from directory_tests_shared.enums import PageType, Service
from pages imp... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
import random
import numpy as np
import torch
from .tools import parse_info_name
from ..utils.tensors import collate
from ..utils.misc import to_torch
from ..utils import rotation_conversions as geometry
POSE_REPS = ["xyz", "rotvec", "rotmat", "rotquat", "rot6d"]
class Dataset(torch.utils.data.Dataset):
def __... |
class Solution:
def numSteps(self, s: str) -> int:
dq = collections.deque(s)
cnt = 0
while len(dq) != 1 or dq[-1] == '0':
if dq[-1] == '0':
dq.pop()
else:
dq[-1] = '0'
i = len(dq) - 2
while i >= 0 and dq[... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class RequestGroup_ConditionSchema:
"""
A group of related requests that can ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from awx.main.models import Credential, CredentialType, Organization
@pytest.fixture
def cred_type():
# Make a credential type which will be used by the credential
ct = CredentialType.objects.create(
... |
"""A regression model to invert dcgan32 (image -> latent space vector
It is hardcoded but works
"""
import torch
class DCGAN32Inverter(torch.nn.Module):
def __init__(self, channels=32,dropout_rate=.3):
super(DCGAN32Inverter, self).__init__()
self.conv = torch.nn.Sequential(
torch.nn.C... |
"""Tests for cpas_toolbox.utils module."""
import inspect
import os
import pathlib
import pytest
from cpas_toolbox import utils
def test_str_to_object() -> None:
"""Test str_to_object function."""
a = 1
assert utils.str_to_object("a") is a
assert utils.str_to_object("utils") is utils
assert i... |
# Copyright (c) 2015, Scott J Maddox. All rights reserved.
# Use of this source code is governed by the BSD-3-Clause
# license that can be found in the LICENSE file.
'''
Copy the ifd.pyx template to fdint/_ifd.pyx
'''
import os
import sys
templates_dir = os.path.join(os.path.dirname(__file__), 'templates')
ifd_pyx_pat... |
# Copyright (c) 2019 Eric Steinberger
import torch
import torch.nn.functional as nnf
from PokerRL.rl import rl_util
from PokerRL.rl.neural.AvrgStrategyNet import AvrgStrategyNet
from PokerRL.rl.neural.NetWrapperBase import NetWrapperArgsBase as _NetWrapperArgsBase
from PokerRL.rl.neural.NetWrapperBase import NetWrap... |
#Cardi A's Code
#These import all of the nessisairy classes for the code to run.
from CharacterClasses import *
import time
#This is the enemys class. It contains a list of all of the enemys on the screen.
#It imports self wich acts as a globaliser for variables(so they can be shared inbetween all diferent functio... |
"""
Finding a discrete maximum entropy distribution
===============================================
Here we consider a simple convex optimization problem to illustrate how to use
**Cooper**. This example is inspired by `this StackExchange question
<https://datascience.stackexchange.com/questions/107366/how-do-you-solv... |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from abc import ABC, abstractmethod
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional
from urllib.parse import parse_qsl, urlparse
import pendulum
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources.strea... |
import os
import pickle as pkl
import numpy as np
from PIL import Image
from auto_tqdm import tqdm
from bokeh.layouts import column
from bokeh.layouts import row
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.models.glyphs import ImageURL
from bokeh.plotting import figure
from bokeh.plotting im... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class ExpandDimsOptions(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsExpandDimsOptions(cls, buf, offset):
n = fla... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: ToolkitEnv2
# language: python
# name: toolkite... |
import torch
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import time
import cv2
import numpy as np
import argparse
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import pandas as pd
from tqdm import tqdm
import tensorflow as t... |
from __future__ import print_function
from pyorbit.classes.common import np
from pyorbit.classes.model_container_emcee import ModelContainerEmcee
from pyorbit.classes.input_parser import yaml_parser, pars_input
from pyorbit.classes.io_subroutines import pyde_save_to_pickle,\
pyde_load_from_cpickle,\
emcee_save_... |
#
# Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
import json
from functools import wraps
from greengrass_common.env_vars import MY_FUNCTION_ARN
def mock(func):
"""
mock decorates _invoke_internal by checking if MY_FUNCTION_ARN is present
if MY_FUNCTION_ARN is present, t... |
from typing import Iterator
from pip._vendor.packaging.version import Version
from pytest import fixture, mark, raises
from pip._internal.exceptions import InvalidWheel
from pip._internal.network.lazy_wheel import (
HTTPRangeRequestUnsupported,
dist_from_wheel_url,
)
from pip._internal.network.session import ... |
#!/usr/bin/env python3
"""test_sequences.py
Unit test for the 'sequences' common module.
"""
__author__ = 'Curtis Belmonte'
import itertools
import unittest
from typing import Dict, List, Sequence
import common.sequences as seqs
class TestSequences(unittest.TestCase):
def test_arithmetic_product(self) -> Non... |
import operator
import functools
from lark import Lark, Transformer
from dae.variants.attributes import Inheritance
INHERITANCE_QUERY_GRAMMAR = r"""
reference: "reference"
mendelian: "mendelian"
denovo: "denovo"
possible_denovo: "possible_denovo"
omission: "omission"
possible_omission: "poss... |
"""Reference implementations of common operations."""
from itertools import product
from math import cos, pi, sin
from typing import List
import numpy as np
from ouster import client
def xyz_proj(metadata: client.SensorInfo,
scan: client.LidarScan) -> np.ndarray:
"""Computes a point cloud from a s... |
from typing import List, Optional, Union
from dataclasses import dataclass
from poker.processor import Approved, MyCards, SmallBlind, BigBlind, Folds, Calls, Raises, Checks, Wins, Shows, Quits
from poker.processor import Flop, Turn, River, Undealt, StandsUp, SitsIn, PlayerStacks, parser
from poker.base import calc_gini... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
import os
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtaildocs impor... |
#!/usr/bin/env python3
import math
def check_filename(filepath, extension=".txt"):
"""
Take a path to a file and ensure the filename has the right extension, else add the extension.
:param str filepath: The path to the file.
:param str extension: Extension for the given file. If wrong extension in file... |
from ProgressManager.RunTable.Models.RunProgress import RunProgress
from ConfigValidator.CustomErrors.ExperimentOutputErrors import ExperimentOutputFileDoesNotExistError
from ProgressManager.Output.OutputProcedure import OutputProcedure as output
from ProgressManager.Output.BaseOutputManager import BaseOutputManager
f... |
#-------------------------------------
# Project: Learning to Compare: Relation Network for Few-Shot Learning
# Date: 2017.9.21
# Author: Flood Sung
# All Rights Reserved
#-------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Blue Lynx and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestFitnessTrainingSession(unittest.TestCase):
pass
|
#coding:utf-8
import cv2
from functools import wraps
from pygame import mixer
import time
lastsave = 0
def counter(func):
@wraps(func)
def tmp(*args, **kwargs):
tmp.count += 1
global lastsave
if time.time() - lastsave > 3:
# this is in seconds, so 5 minutes = 300 seconds
... |
def ficha(nome='<Não informado>', pontos='0'):
print(f'O jogador {nome} fez {pontos} gol(s) no campeonato')
print('-'*45)
while True:
resp = ' '
jogador = str(input('Digite o nome do jagador: ')).strip().title()
gols = str(input('Quantos gols fez: ')).strip()
if jogador == '' and (gols == '' o... |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
"""HTTP related errors."""
from asyncio import TimeoutError
__all__ = (
'DisconnectedError', 'ClientDisconnectedError', 'ServerDisconnectedError',
'HttpProcessingError', 'BadHttpMessage',
'HttpMethodNotAllowed', 'HttpBadRequest', 'HttpProxyError',
'BadStatusLine', 'LineTooLong', 'InvalidHeader',
... |
#!/bin/python
"""
The MIT License (MIT)
Copyright (c) 2016 Saurabh Deochake
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, c... |
from django.shortcuts import render, redirect
from django.conf import settings
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.db.models import Case, When
from django.core.cache import cache
from django.core.cache import caches
try:
cache_alignment = caches['alignment... |
# project/server/auth/views.py
from flask import Blueprint, request, make_response, jsonify
from flask.views import MethodView
from project.server import bcrypt, db
from project.server.models import User
auth_blueprint = Blueprint('auth', __name__)
class RegisterAPI(MethodView):
"""
User Registration Resour... |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
################################... |
import os
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.36.0"
class AwsCSDKUtils(ConanFile):
name = "aws-c-sdkutils"
description = "aws c language sdk utility library."
topics = ("aws", "amazon", "cloud", "utility")
url = "... |
from enum import Enum, IntEnum
class DirectionX(IntEnum):
LEFT = 0
RIGHT = 1
class DirectionY(IntEnum):
REVERSE = 0
FORWARD = 1
class ActiveSensors(Enum):
NONE = (0, 0, 0, 0)
FAR_LEFT = (1, 0, 0, 0)
LEFT = (0, 1, 0, 0)
RIGHT = (0, 0, 1, 0)
FAR_RIGHT = (0, 0, 0, 1)
BOTH_MAIN... |
from rest_framework import serializers
from balance.models import Record
class BalanceSerializer(serializers.ModelSerializer):
class Meta:
model = Record
fields = (
'reward_type',
'coin_type',
'amount',
'description',
'user',
)
... |
import unittest
import getpass
from pprint import pprint
from libwebcq.CQ import CQ
from libwebcq.error import SessionError
from libwebcq.record import CustomerRecord, ModuleRecord, OwnerInfo, RecordType
cq = CQ('http://avclearquest.qlogic.org/cqweb/')
# Open a session befoer any network query.
cq.open_session()
try:
... |
import sys, os
#import logging
import unittest
from google.appengine.ext import ndb #, testbed
from google.appengine.api import datastore_errors
class TestCollection(unittest.TestCase):
# enable the datastore stub
nosegae_datastore_v3 = True
nosegae_memcache = True
#import model # does not work yet
def se... |
#AGC002f
def main():
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**6)
# map(int, input().split())
if __name__ == '__main__':
main() |
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from ...utils import get_model_consumer, normalize_yaml
pytestmark = [pytest.mark.conf, pytest.mark.conf_consumer, pytest.mark.conf_consumer_model]
def test():
consumer = get_model_co... |
"""
module for talking to the YubiHSM over a socket.
"""
# Copyright (c) 2011 Yubico AB
# See the file COPYING for licence statement.
__all__ = [
# constants
# functions
# classes
'YHSM_Stick_Client',
]
import sys
import re
import socket
import json
import pyhsm.util
import pyhsm.exception
CMD_WRIT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import re
import time
def find_num(major_el_name):
"""
Find the number of cations and the number of oxygen atoms of the principal element in the listing
:param major_el_name: Listing of principal elements
:return: N... |
# makes use of the previously created neutronics geometry (h5m file) and assigns
# actual materials to the material tags. Sets simulation intensity and specifies
# the neutronics results to record (know as tallies).
import openmc
import openmc_dagmc_wrapper as odw
import openmc_plasma_source as ops
# defines a simple... |
# ERFNet full model definition for Pytorch
# Sept 2017
# Eduardo Romera
#######################
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
# shuffle operation from https://github.com/jaxony/ShuffleNet/blob/master/model.py
def channel_shuffle(x, groups):
batchsi... |
"""
For this challenge, you are given two complex numbers, and you have to print the result of their addition, subtraction, multiplication, division and modulus operations.
The real and imaginary precision part should be correct up to two decimal places.
Input Format
One line of input: The real and imaginary part o... |
# Lecture 09_02 Exercise Objectives
# 01. Work with nested lists
# 02. Write function to extract locations
# 03. Write function to format location string
# 04. Control execution path from main() function
# 05. Implement accumulator pattern
# 06. Write for loops and conditional statements to filter data
# 08. Write exp... |
from dataclasses import dataclass, field
from enum import Enum, auto
class OrderStatus(Enum):
"""Order status"""
OPEN = auto()
PAID = auto()
CANCELLED = auto()
DELIVERED = auto()
RETURNED = auto()
@dataclass
class Order:
customer_id: int = 0
customer_name: str = ""
customer_addr... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.exception import SqlmapUnsupportedFeatureException
from plugins.generic.takeover import Takeover as GenericTakeover
class Takeover(GenericTakeover):
def __i... |
def som(a, b):
"""Print de som van de twee gegeven getallen
Args:
a (int): het eerste getal
b (int): het tweede getal
"""
pass
|
import os
from random import randint, seed
import numpy as np
import cv2
class MaskGenerator():
def __init__(self,
height, width, channels=3, rand_seed=None, filepath=None,
rotation=True, dilation=True, cropping=True, invert=False,
random_draws=70, target_ratio=None
):
"""Conv... |
import os
import platform
ext = ''
local_bins = False # change if wanting to test with local binary exes
if local_bins:
bin_path = os.path.join("..", "..", "bin")
if "linux" in platform.platform().lower():
pass
bin_path = os.path.join(bin_path, "linux")
elif "darwin" in platform.platform()... |
# qubit number=4
# total number=30
import cirq
import qiskit
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from ma... |
"""The avion component."""
|
# Generated by Django 2.0.1 on 2018-07-20 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Letter',
fields=[
('id', models.AutoField(a... |
import covid19pandas as cod
import matplotlib.pyplot as plt
ler = cod.get_deaths()
plt.pie(ler['3/30/20'],labels=ler['Country/Region'], autopct="%1.0f%%")
plt.show()
|
# -*- coding: utf-8 -*-
# pylint: disable=C0111,R0903
""" system module
adds the possibility to
* shutdown
* reboot
the system.
Per default a confirmation dialog is shown before the actual action is performed.
Parameters:
* system.confirm: show confirmation dialog before performing any action (default: true) ... |
from knn import * |
# Generated by Django 2.0.5 on 2018-06-17 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sum_v1', '0017_remove_file_upload_word_count'),
]
operations = [
migrations.AddField(
model_name='file_upload',
name... |
import sys
import matplotlib.pyplot as plt
import math
if len(sys.argv) < 1:
sys.exit("usage: %s [*.weights]" %sys.argv[0])
data_file = sys.argv[1]
data=[]
with open(data_file) as f:
line = next(f)
for x in line.split():
data+=[float(x)]
#print data
n, bins, patches = plt.hist(data, bins=math.sq... |
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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... |
from __future__ import absolute_import, division, print_function, unicode_literals
import six
from echomesh.expression.Envelope import Envelope
from echomesh.expression.ListExpression import ListExpression
from echomesh.expression.UnitExpression import UnitExpression
def expression(expr, element):
try:
i... |
# --------------------------------------------
# Setup file for the package
#
# Laurent Franceschetti (c) 2018-2020
# --------------------------------------------
import os
from setuptools import setup, find_packages
# --------------------
# Initialization
# --------------------
VERSION_NUMBER = '0.5.12'
# require... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
epsilon = 1e-16
def answer_loss(pred_ans,gt_ans,mask):
gt_ans = gt_ans.unsqueeze(1).expand_as(pred_ans)
loss = -(gt_ans*torch.log(torch.clamp(pred_ans,min=epsilon,max=1))).sum(-1)
loss = torch.mul(loss,mask).sum(-1)/mask.sum(... |
# coding: utf-8
# flake8: noqa
"""
Item Feed Service
<span class=\"tablenote\"><b>Note:</b> This is a <a href=\"https://developer.ebay.com/api-docs/static/versioning.html#limited\" target=\"_blank\"> <img src=\"/cms/img/docs/partners-api.svg\" class=\"legend-icon partners-icon\" title=\"Limited Release\" al... |
import logging
import platform
from time import time
import dials.algorithms.integration
from dials.algorithms.integration.processor import job
from dials.model.data import ImageVolume, MultiPanelImageVolume, make_image
from dials.util import log
from dials.util.mp import multi_node_parallel_map
from dials_algorithms_... |
"""
This component provides HA sensor support for Amcrest IP cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.amcrest/
"""
from datetime import timedelta
import logging
import voluptuous as vol
import homeassistant.helpers.config_validatio... |
import enum
from pipes.json_utils import dict_with_type,DictWrapper,ListWrapper
class TensorDataTypesConfig(object):
_types_map = {
'inputDataTypes': {'type': dict, 'subtype': None},
'outputDataTypes': {'type': dict, 'subtype': None},
}
_formats_map = {
}
def __init__(self
... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from __future__ import absolute_import, division, print_function
import os
import sys
from setuptools import find_packages, setup
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
_available_cuda_versions = [
"101",
... |
"""Alpha Omega United discord bot."""
|
# -*- coding: utf8 -*-
from __future__ import unicode_literals
import datetime
import smtplib
import unittest
from unittest import mock
from unittest.mock import mock_open, patch
from django.http import HttpRequest
from django.test import TestCase
from django.utils import timezone
import requests
from paying_for_co... |
from __future__ import absolute_import
from __future__ import unicode_literals
import hashlib
import hmac
import time
import uuid
import requests
from . import exceptions
class ExlibrisClient():
def __init__(self, key, secret):
self.key = key
self.secret = secret
self.start_url = 'https... |
import ctypes
import io
import logging
import random
from typing import Tuple
import sdl2
import sdl2.ext
from sdl2 import (
rw_from_object, # https://pysdl2.readthedocs.io/en/latest/modules/sdl2.html#sdl2.sdl2.rw_from_object
SDL_Window, SDL_Renderer,
SDL_Rect, # https://wiki.libsdl.org/SDL_Rect
SDL... |
"""
Tests that are syntactically impossible on python2.
"""
import unittest
from test._test_decorator_py2 import TestASTorator
try:
from test._test_decorator_py3 import TestASToratorPy3
except SyntaxError:
pass
if __name__ == '__main__':
unittest.main()
|
""" General Server side utilities
"""
from win32 import com as pythoncom
from . import policy
from win32 import error as winerror
from .exception import COMException
def wrap(ob, iid=None, usePolicy=None, useDispatcher=None):
"""Wraps an object in a PyGDispatch gateway.
Returns a client side PyI{iid} inte... |
#!/usr/bin/env python3
import argparse, csv, sys, time, collections
from common import *
if len(sys.argv) == 1:
sys.argv.append('-h')
parser = argparse.ArgumentParser()
parser.add_argument('filter_string', type=str)
parser.add_argument('tr_src_path', type=str)
parser.add_argument('va_src_path', type=str)
parser... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
def test_basic():
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
result = pos_tag(word_tokenize("John's big idea isn't all that bad."))
assert result == [('John', 'NNP'), ("'s", 'POS'), ('big... |
import inspect
import importlib
def load_class(cls):
""" Loads the given class from string (unless alrady a class). """
if inspect.isclass(cls):
return cls
module_name, class_name = cls.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, class_name, None)... |
# 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 u... |
import random
from worldSaver import getWorldAsString, saveWorld
import os
# constants - graphics
BLOCK_SIZE = 32 # 32x32 pixel per tile
GFX_DIRECTORY = r"gfx/"
GFX = dict()
for directory in filter(lambda x: os.path.isdir(os.path.join(GFX_DIRECTORY, x)), os.listdir(GFX_DIRECTORY)):
dir_c = os.path.join(GFX... |
# Run test API
import requests
import http
# import sys
PORT = '5022'
# Upload an unsupported file
print("Upload unsupported file")
url = 'http://0.0.0.0:'+PORT+'/v1/models' # API endpoint
filename = 'test.png'
file = open(filename, 'rb') # File to upload
try:
r = requests.post(url=url, files={'file': file})
e... |
#!/usr/bin/python
#Based on veproza proyect: https://gist.github.com/veproza/55ec6eaa612781ac29e7
import requests
#Edit me!!
print "Connecting to u-blox"
# alm is optional
r = requests.get("http://online-live1.services.u-blox.com/GetOnlineData.ashx?token=" + token +
";gnss=gps,glo,gal;datatype=eph,a... |
from tool.runners.python import SubmissionPy
class ThoreSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :return: solution flag
program = [int(i) for i in s.split(",")]
program[1] = 12
program[2] = 2
pc = 0
while program[pc... |
import random
from brownie import Sett
from typing import Any
from helpers.constants import MaxUint256
from helpers.sett.SnapshotManager import SnapshotManager
from .BaseAction import BaseAction
class DepositAndWithdrawAction(BaseAction):
def __init__(
self,
snap: SnapshotManager,
user: A... |
# proxy module
from __future__ import absolute_import
from blockcanvas.numerical_modeling.units.api import *
|
from urllib.parse import urlencode
import salt.utils.json
import salt.utils.yaml
from tests.support.cherrypy_testclasses import BaseToolsTest
class TestOutFormats(BaseToolsTest):
def __get_cp_config__(self):
return {
"tools.hypermedia_out.on": True,
}
def test_default_accept(self... |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import argparse
import os.path as osp
import sys
import time
from torch.utils.tensorboard import SummaryWriter
import torch
from ptflops import get_model_complexity_info
from scripts.default_config import (get_default_config,
... |
# https://leetcode.com/problems/word-break/
class Solution(object):
def wordBreak(self, s, wordDict):
"""
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictiona... |
from bballer import draft
from bballer.models.draft import PlayerInDraft
class TestDraft:
def test_draft(self):
d = draft.year(2003)
draft_pick = next(d)
assert isinstance(draft_pick, PlayerInDraft)
assert draft_pick.player.name == "LeBron James"
assert draft_pick.college i... |
from . import backend_inline, config # noqa
|
if __name__ == "__main__":
from autotrade.brain.ran_brain import RandomBrain
from autotrade.brain.indicator_brain import IndicatorBrain
from autotrade.brain.indicators.moving_avg import MACD, GoldenCross
from autotrade.eyes.human import HumanEyes
from autotrade.market.historic import HistoricMarket
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.