content stringlengths 5 1.05M |
|---|
import os
import string
import re
import argparse
import json
import time
import hashlib
import snowflake.connector
import warnings
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptograp... |
# Create a program that writes 'Hello World!' on the screen.
|
from setuptools import Extension, setup
from torch.utils import cpp_extension
# `cpp_extension` is equivalent to:
# Extension(
# name='lltm_cpp',
# sources=['lltm.cpp'],
# include_dirs=cpp_extension.include_paths(),
# language='c++')
setup(name='lltm_cpp',
ext_modules=[cpp_extension.CppExtension('l... |
# python3
import sys
n, m = map(int, sys.stdin.readline().split())
lines = list(map(int, sys.stdin.readline().split()))
rank = [1] * n
parent = list(range(0, n))
ans = max(lines)
def getParent(table):
if table != parent[table]:
parent[table] = getParent(parent[table])
return parent[table]
def merge(... |
from .darts_backbone import *
|
import unittest
import cal_complejos
import simulacion_cuantica as sim
class testNumerosComplejosCal(unittest.TestCase):
def testSuma(self):
a = (12,11)
b = (20,3.5)
self.assertEqual(cal_complejos.suma(a,b),(32,14.5))
self.assertFalse(cal_complejos.suma(a,b)==(50,14... |
# -*- coding: utf-8 -*-
'''
Read and Write files to disk and return the relative path data for the index
'''
# Import python libs
import os
import io
import binascii
# Import alder libs
import alder.aid.rand
def _file_loc(files_dir):
while True:
fn_ = os.path.join(files_dir, alder.aid.rand.rand_hex_str(24... |
#Desafio 011
ap = int(input('Altura da parede: '))
lp = int(input('Largura da parede: '))
A = ap*lp
lt = A/2
print('A área da parede é {}\nA quantidade de tinta nescessaria é: {}'.format(A, lt))
|
# -*- coding: utf-8 -*-
from string import Template
from pastepwn.util import DictWrapper
class TemplatingEngine(object):
"""Wrapper class around the python templating feature"""
@staticmethod
def fill_template(paste, analyzer_name, template_string, matches=None, **kwargs):
"""
Returns a... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-07-01 18:19
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... |
# Copyright 2018 ZTE Corporation. 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 ... |
#
#
# #
# I do not condone using this program nefariously.
# I am in no ways managing, nor taking responsibility for the extended usage of this project.
# It was used as an educational aiding project, and as a result, I believe that educationally
# I believe similar functionality should be natively implemented in... |
from __future__ import annotations
import math
from typing import List, Union
import stargazing.data.database as database
from stargazing.utils.format_funcs import format_project_time
class Project():
"""A named project counting total pomodoro time.
@param name: Display name for the project"""
def __in... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
from typing import Dict, List, Tuple
import caffe2.proto.caffe2_pb2 as caffe2_pb2
import numpy as np
from caffe2.python import core, schema, workspace
from ml.rl.caffe_utils import C2
from ml.rl.preprocessing... |
import datetime as dt
import logging
from dataclasses import dataclass
import requests
from .const import *
from .Token import Token
from .Vehicle import Vehicle
_LOGGER = logging.getLogger(__name__)
@dataclass
class ClimateRequestOptions:
set_temp: float = None
duration: int = None
defrost: bool = No... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Selector
import time
from ljcrawl.items import LjcrawlItem
class LianjiacrawlSpider(scrapy.Spider):
name = "lianjiacrawl"
allowed_domains = ["bj.lianjia.com"]
start_urls = ['http://bj.lianjia.com/']
# https: // bj.lianjia.com / zufang / pg1 /
... |
ffrom unittest import TestCase
import os
import requests
class TestHttpSystem(TestCase):
def test_no_args(self):
BASE_URL = os.getenv('BASE_URL', 'https://us-central1-xadrex-explorer.cloudfunctions.net/hello_http')
assert BASE_URL is not None
res = requests.get(f"{BASE_URL}/hello_http")
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.store, name='store'),
path('cart/', views.cart, name='cart'),
path('checkout/', views.checkout, name='checkout'),
path('product/<int:id>/', views.product, name='product'),
path('orders/', views.orders, name='orders'),
... |
import numpy as np
from time import time
#Day 25: Sea Cucumber
#bad, but still acceptable, performance ( about 5 s)
def preprocess(inp = '..//input files//input_d25.txt'):
'''
input: AoC txt file
output: np.array representing the snails
'''
with open(inp, 'r') as fob:
... |
from reports.core.main import ReportBuilder |
# coding: utf-8
"""
============================
Train an Acoustic Classifier
============================
Train an acoustic classifier on speech or noise features.
To see how soundpy implements this, see `soundpy.models.builtin.envclassifier_train`.
"""
##############################################################... |
# flake8: noqa
import pytest
import embedding.training_process
import numpy
import tempfile
from pathlib import Path
import unittest
import ai_training as ait
pytestmark = pytest.mark.asyncio
async def mock_w2v_call(payload, endpoint='words'):
if endpoint == "words":
return {'vectors': {"word1": [1.1, 1... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from run_bwc_test import BundleManifest,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .utils.loader import get_schema # noqa
from .utils.cursor_pagination import CursorPaginator # noqa
from .utils.exceptions import ERROR_CODED_EXCEPTIONS, GQLExecutionUserError, GQLExecutionUserErrorMultiple # noqa
from .utils.roles import REQUIRE_RO... |
#!/usr/bin/python
def uppercase(fun):
def wrapper():
res = fun()
modified = res.upper()
return modified
return wrapper
@uppercase
def gen_message():
return 'Hello there!'
msg = gen_message()
print(msg)
|
"""
Copyright 2008 Lode Leroy
This file is part of PyCAM.
PyCAM 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.
PyCAM is distributed in th... |
from sympy import *
from sympy.polys.orderings import monomial_key
x, y = symbols('x y')
print(groebner([x**2 + 2*y**2 - 3, x**2 + x*y + y**2 - 3], x, y, order='lex'))
print(groebner([x**2 + 2*y**2 - 3, x**2 + x*y + y**2 - 3], y, x, order='lex'))
|
def parse_url_and_method(resource):
index = resource.rindex('/')
(url, method) = (resource[:index], resource[index + 1:])
return (url, method)
def register_resources():
END_COMMAND = 'END'
resources = {}
while True:
line = input()
if line == END_COMMAND:
break
... |
from google.cloud import storage
'''
cf.) [API Doucument](https://googleapis.dev/python/storage/latest/blobs.html)
'''
class GCSUtils(object):
def __init__(self):
self.storage_client = storage.Client()
def create_bucket(self, bucket_name):
bucket = self.storage_client.create_bucket(bucket_na... |
import cv2
image = cv2.imread('1.jpg')
# Remove vertical and horizontal lines
kernel_vertical = cv2.getStructuringElement(cv2.MORPH_RECT, (1,50))
temp1 = 255 - cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel_vertical)
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))
temp2 = 255 - cv2.morphologyEx... |
"""
Package containing binaries needed for the FiftyOne Desktop App.
"""
import os
FIFTYONE_DESKTOP_APP_DIR = os.path.join(
os.path.abspath(os.path.dirname(__file__)), "bin"
)
|
import datetime
from pathlib import Path
class Logger:
def __init__(self):
self.development = False
self.__logging = False
self.__logFile = ''
def activate(self, path, name, overwrite_sensitive=True):
"""
Activate the action log. Required are a path and a name for the ... |
# @Title: 买卖股票的最佳时机 II (Best Time to Buy and Sell Stock II)
# @Author: 18015528893
# @Date: 2021-02-01 22:13:04
# @Runtime: 48 ms
# @Memory: 17.7 MB
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0, 1] for _ in range(n+1)]
dp[0][0] = 0
dp[0][1... |
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
from tokens import PYT_LOGIN, PYT_PASSWORD
import unittest
class test_pyt(unittest.TestCase):
def setUp(self):
self.wd = WebDriver()
self.wd.implicitly_wait(30)
def test_test_pyt(self):
wd = self.w... |
from keylayoutelement import KeyLayoutElement
class MetaData:
def __init__(self):
self.version = 2
self.size_unlimited = True
self.root = KeyLayoutElement('/')
self.root.runtimeSetup()
def findNode(self, name):
if name == "/":
return self.root
tokens = name.split("/")
return self.root.pathWalk(to... |
class LeagueGame:
def __init__(self, data):
self.patch = data['patch']
self.win = data['win']
self.side = data['side']
self.opp = data['opp']
self.bans = data['bans']
self.vs_bans = data['vs_bans']
self.picks = data['picks']
self.vs_picks = data['vs_picks']
self.players = data['players']
class Lea... |
import typing
from abc import ABC, abstractmethod
__all__ = ("AES_SIV_Encryptor",)
class EncryptorInterface(ABC):
"""An interface for providing encryption/decryption methods for session data."""
@abstractmethod
def __init__(
self,
secret: str,
iv: typing.Optional[bytes] = None,
... |
from __future__ import absolute_import
from nose.tools import raises
from plotly.graph_objs import (Data, Figure, Layout, XAxis, YAxis)
import plotly.tools as tls
@raises(Exception)
def test_non_integer_rows():
tls.get_subplots(rows=2.1)
@raises(Exception)
def test_less_than_zero_rows():
tls.make_subplots... |
msg = 'CADASTRE UMA PESSOA'
totmais18 = 0
tothomens = 0
totmmenos20 = 0
while True:
print('-'*40)
print(f'{msg:^40}')
print('-' * 40)
while True:
idade = int(input('Idade: '))
if idade > 0:
break
while True:
sexo = str(input('Sexo[M/F]: ')).upper().st... |
from six import StringIO
from conans import ConanFile, tools
class TestPackageConan(ConanFile):
settings = "os", "arch", "build_type", "compiler"
def test(self):
if not tools.cross_building(self):
output = StringIO()
self.run("innoextract --version", output=output,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from pprint import pprint
import shapefile
from geojson import Feature, FeatureCollection
from shapely.geometry import asShape, MultiPolygon, Polygon, mapping, shape
from shapely.ops import polygonize
from shapely.wkt import dumps
from geojson import FeatureColl... |
import unittest
from records_mover.url.filesystem import FilesystemFileUrl
from records_mover.records.targets.data_url import DataUrlTarget
from records_mover.records.records_format import DelimitedRecordsFormat
class TestDataUrlTarget(unittest.TestCase):
def test_gzip_compression_inferred_no_records_format(self)... |
from rlbot.agents.executable_with_socket_agent import ExecutableWithSocketAgent
class JavaBot(ExecutableWithSocketAgent):
def get_port(self):
return 24008
def build_add_command(self) -> str:
# TODO: pull the RLBot port from somewhere instead of hard coding
return f"addsocket\n{self.na... |
# -*- coding: utf-8 -*-
"""
@brief test log(time=52s)
"""
import sys
import os
import unittest
import shutil
import warnings
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder, skipif_circleci
from pyquickhelper.ipythonhelper import execute_notebook_list, execute_notebook_li... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.runner import BaseModule
from ..builder import NECKS
@NECKS.register_module()
class DenseCLNeck(BaseModule):
"""The non-linear neck of DenseCL.
Single and dense neck in parallel: fc-relu-fc, conv-relu-conv.
Borrowed from the... |
"""
Search.
"""
import random
def binary_search(array, val):
"""Binary search."""
sorted_array = sorted(array)
i = 0
j = len(array) - 1
while i <= j:
mid = (i + j) // 2
if sorted_array[mid] == val:
return mid
if sorted_array[mid] < val:
i = mid + 1
... |
"""Pytest Fixtures used for testing Pytelliot"""
import os
import pytest
from brownie import chain
from chained_accounts import ChainedAccount
from chained_accounts import find_accounts
from telliot_core.apps.telliot_config import TelliotConfig
@pytest.fixture(scope="session", autouse=True)
def rinkeby_cfg():
"... |
from expression import *
from move import changeDegree
#start
changeDegree([4],[70])
changeDegree([2],[60])
changeDegree([8],[120])
changeDegree([6,10],[80,30])
time.sleep(2)
#stop
changeDegree([6,10],[init[6],init[10]])
changeDegree([8],[init[8]])
changeDegree([2],[init[2]])
changeDegree([4],[init[4]])
|
import argparse
import importlib
import json
import math
import os
import matplotlib
import numpy as np
import tensorflow as tf
import utils
from config_rnn import defaults
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# -----------------------------------------------------------------------------
parser = ... |
from __future__ import absolute_import, print_function, division
from tempfile import NamedTemporaryFile
import csv
from petl.compat import PY2
import petl as etl
from petl.test.helpers import ieq, eq_
def test_basics():
t1 = (('foo', 'bar'),
('A', 1),
('B', 2))
w1 = etl.wrap(t1)
... |
#!/usr/bin/env python3
from collections import namedtuple
import sys
import time
from PIL import Image # Requires the Pillow library
DISP_WIDTH = 150
DISP_HEIGHT = 16
Vector = namedtuple('Vector', 'x y')
if len(sys.argv) == 1:
print('Usage: %s <image 1> [<image 2> <image 3> ...]' % sys.argv[0], file=sys.stderr)
... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
#end_pymotw_header
import profile
def fib(n):
# from literateprograms.org
# http://bit.ly/hlOQ5m
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
d... |
import logging
import pprint
from dbnd.api.tracking_api import TrackingAPI
logger = logging.getLogger(__name__)
class ConsoleDebugTrackingChannel(TrackingAPI):
"""Json API client implementation."""
def __init__(self, print_func=None):
super(ConsoleDebugTrackingChannel, self).__init__()
sel... |
#!/usr/bin/python
import os, sys, operator, socket, subprocess, threading, time, pexpect, netifaces
#logging
# from __future__ import absolute_import
# from __future__ import print_function
# from __future__ import unicode_literals
import pexpect
import re
#logger = logging.getLogger('simple_example')
#logger.setLeve... |
# -*- coding: utf-8 -*-
__author__ = "苦叶子"
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
# 切换至默认的frame上下文环境
def switch_default_frame(driver):
driver.switch_to.default_content()
# 定位下alert_id按钮
ele = driver.find_element_by_id("alert_id")
print(ele... |
import os
import requests
import json
import datetime
import time
from common.config import korea_timezone
minute_to_arrival = {
'한대앞': 0, '중앙': 2, '고잔': 4, '초지': 6.5, '안산': 9, '신길온천': 12.5, '정왕': 16, '오이도': 19, '달월': 21, '월곶': 23,
'소래포구': 25, '인천논현': 27, '호구포': 29, '상록수': 2, '반월': 6, '대야미': 8.5, '수리산': 11.5,... |
# Copyright 2019, The TensorFlow Federated Authors.
#
# 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 o... |
from enum import Enum, IntEnum
import os
from typing import Any, List, Optional
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
class Type(IntEnum):
SEDAN = 0
HATCHBACK = 1
COUPE = 2
SUV = 3
CONVERTIBLE = 4
PICKUP = 5
MINIVAN = 6
WAGON = 7
BUS = 8
... |
import tensorflow as tf
import numpy as np
import glob
import os
import json
from datetime import datetime, date, time
import cv2
import sys
import getopt
############################################################
#
# reference:
# * https://github.com/Newmu/dcgan_code.git
# * https://github.com/soumith/dcgan.torch... |
# Copyright 2019 Nicole Borrelli
#
# 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... |
#!/usr/bin/python3
import glob
import os
import re
import csv
# The file path is given where all the uniprot text files are kept
#one example file given as uniprot_file
list_files = glob.glob("/home/suresh/uniprot/" + "*." + "txt")
# This is to create a file
writefile = open("required_file_new.txt", "w")
# These str... |
"""
Dialog for exporting clip; shows message depending on available encoder.
"""
from sleap.gui.dialogs.formbuilder import FormBuilderModalDialog
class ExportClipDialog(FormBuilderModalDialog):
def __init__(self):
from sleap.io.videowriter import VideoWriter
super().__init__(form_name="labeled_c... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets
from torchvision import transforms
import torchvision
import math
import random
import numpy as np
import torch.optim.lr_scheduler as lrs
import datas
from utils import *
def paded_... |
#
#
# This source file is part of ELINA (ETH LIbrary for Numerical Analysis).
# ELINA is Copyright © 2019 Department of Computer Science, ETH Zurich
# This software is distributed under GNU Lesser General Public License Version 3.0.
# For more information, see the ELINA project website at:
# http://elina.ethz.ch
#... |
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print "you have %d cheeses" % cheese_count
print "and %d boxes of crackers" % boxes_of_crackers
print "give them parameters"
cheese_and_crackers(23,21)
print "or use variables"
cheese_amount = 44
cracker_boxes = 19
cheese_and_crackers(cheese_amount,c... |
# Generated by Django 3.0.8 on 2022-01-03 10:33
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_US... |
"""Append a message directly to a user's mailbox."""
import sys
import time
from argparse import ArgumentParser, FileType, Namespace
from typing import Tuple
from .command import ClientCommand
from ..grpc.admin_grpc import AdminStub
from ..grpc.admin_pb2 import AppendRequest, AppendResponse
class AppendCommand(Clie... |
import sqlalchemy as sa
from marshmallow import fields
import tests.test_app.models as m
from awokado import custom_fields
from awokado.consts import CREATE, READ, UPDATE, BULK_UPDATE, DELETE
from awokado.meta import ResourceMeta
from awokado.request import ReadContext
from awokado.resource import BaseResource
class... |
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import os
import json
class Spotify:
def __init__(self, id, secret):
self.id = id
self.secret = secret
def get_playlists(self):
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=self.id,
... |
import torch.nn as nn
import torch.nn.functional as F
s = 2 # "same" padding
class model1(nn.Module):
def __init__(self):
super(model1, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 5, padding = s)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 16, 5, padding = s)
... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2017 the Critic contributors, Opera Software ASA
#
# 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/LI... |
def counter(string):
"""
Calculate count of elements in string.
"""
result = [f'Count of {elem} = {string.count(elem)}\n'for elem in set(string)]
return "".join(result) |
import numpy
def create_dummy_dataset():
data = numpy.asarray([
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
],
dtype=numpy.float64
)
labels = numpy.asarray([0, 0, 1], dtype=numpy.uint8)
print(f'writing data:\n{data}')
numpy.save('data/dummy.npy',... |
import logging
import os
import numpy as np
from netCDF4 import Dataset
def get_logger(name, level='debug', log_file='log.txt'):
"""
Retrieve the logger for SWIFLow with coloredlogs installed in the
right format
"""
# Setup logging
log_level = level.upper()
level = logging.getLevelName(lo... |
def factorial_division(num1,num2):
factorial1 = 1
factorial2 = 1
for number in range(1, num1 + 1):
factorial1 *= number
for number1 in range(1, num2 + 1):
factorial2 *= number1
result = factorial1 / factorial2
return result
a = int(input())
b = int(input())
outcome... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""HiPS tile drawing."""
from .paint import *
from .ui import *
from .healpix import *
|
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
#!/usr/bin/env python
#
#The MIT CorrelX Correlator
#
#https://github.com/MITHaystack/CorrelX
#Contact: correlX@haystack.mit.edu
#Project leads: Victor Pankratius, Pedro Elosegui Project developer: A.J. Vazquez Alvarez
#
#Copyright 2017 MIT Haystack Obse... |
from .base import *
import mongoengine
import logging
########## DEBUG CONFIGURATION
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
########## END DEBUG CONFIGURATION
########## FULL URL CONFIGURATION FOR UNIT & INTEGRATION TESTS
IEC_LOOKUP_URL = 'http://127.0.0.1:8000/iec/api/v1/looku... |
import asyncio
import aiopg
import hashlib
from . import core
from . import nwdb
@asyncio.coroutine
def send(client, email, subject, body):
"""
Schedule an email to be sent.
"""
with (yield from nwdb.connection()) as conn:
member_id = None
if "member_id" in client.session:
... |
# Copyright 1996-2020 OpenDR European Project
#
# 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 agree... |
# coding: utf-8
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter import unicodehelper
from rpython.rlib.rstring import StringBuilder
class W_FString(W_Root):
def __init__(self, unparsed, raw_mode):
assert isinstance(unparsed, s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
from pathlib import Path
from enum import Enum
from . import settings
from . import utils
from . import exceptions
from . import pygittools
from . import wizard
from . import logger
from . import reltools
_logger = logger.get_logger(__nam... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#import cv2
#import numpy as np
#import os
from flask import Flask, flash, request, redirect, url_for, render_template , abort
#from flask import session as login_session
#from werkzeug.utils import secure_filename
#import re, time, base64
#from PIL import Image
... |
from distutils.core import setup
setup(
name = 'hatebase',
packages = ['hatebase'],
package_dir = {'hatebase': 'hatebase'},
package_data = {'hatebase': ['__init__.py', 'tests/__init__.py', 'tests/test.py']},
version = '0.5',
description = "Python Version of Andrew Welter's Hatebase Wrapper, based on Daniel... |
#!/usr/bin/env python
import sys
import os
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
apikey=os.getenv('EXOSCALE_API_KEY')
secretkey=os.getenv('EXOSCALE_SECRET_KEY')
Driver = get_driver(Provider.EXOSCALE)
conn=Driver(key=apikey,secret=secretkey)
#Convenience funct... |
# Copyright 2018 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... |
def has_permission(user, _):
"""
:param user: {'id': str, 'creation_date': float, 'groups': [str], 'email': str, ..+}
:param _: Void
:return: bool, determines if system has permission to write index for a database row item.
For example, if you want to index 'name' and 'phone', You should write like ... |
import mock
from testify import TestCase
from testify import setup
from testify.assertions import assert_equal
from tron import eventloop
class UniqueCallTestCase(TestCase):
@setup
def setup_monitor(self):
self.func = mock.Mock()
self.callback = eventloop.UniqueCallback(5, self.func)
... |
# -*- encoding:utf-8 -*-
import unittest
from py_nifcloud import ComputingClient
from bs4 import BeautifulSoup
class TestNifCloudClientRequest(unittest.TestCase):
@classmethod
def setUpClass(cls):
sut = ComputingClient(region_name="jp-east-1")
cls.params = {
'Action': 'DescribeRe... |
#Somatorio de respostas das perguntas repetidas
s = 0
for c in range (0,3):
n = int(input('Digite o valor que será somado: '))
s = s+n #Tambem pode ser S +=n
print(' A soma é {}'.format(s)) |
"""
7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure the sandwich 'pastrami' appears in the
list at least three times. Add code near the beginning of your program to print a message saying the deli has run out of
pastrami, and then use a while loop to remove all occurrences of 'pastrami' f... |
from __future__ import print_function
import sys
sys.path.append('/usr/lib/python2.7') # smb
import cv2
import os
import numpy as np
import cPickle as pickle
import timeit
import time
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils, Li... |
# -*- coding: utf-8 -*-
from django.conf.urls import include, url
urlpatterns = [
url(r'^yubin/', include('django_yubin.urls')),
]
|
"""notify.py
Example notification script for fishing_report.py
"""
from configparser import ConfigParser
import urllib.request
import urllib.parse
def notify(notify_dict, config_file="config.ini"):
config = ConfigParser()
config.read(config_file)
notify_config = config["NOTIFY"]
user = notify_config... |
import discord
from discord.ext import commands
from bs4 import BeautifulSoup
class Youtube:
def __init__(self, bot):
self.bot = bot
self.uri = 'https://youtube.com/results'
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 '
... |
#!/usr/bin/env python
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_argspec
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_auth_client
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import h... |
#!/usr/bin/env python
# pylint: disable=protected-access,redefined-outer-name,too-many-arguments
"""ImageConfig tests."""
import json
import logging
from copy import deepcopy
from typing import List
import pytest
from docker_registry_client_async import FormattedSHA256
from pytest_gnupg_fixtures import GnuPGKeypa... |
from __future__ import absolute_import
########################################################################
# File based on https://github.com/Blosc/bcolz
########################################################################
#
# License: BSD
# Created: October 5, 2015
# Author: Carst Vaartjes - cva... |
from sklearn.metrics import mean_squared_error
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from math import sqrt
import numpy as np
from P2_get_data import get_data
epochs = 150
batch_size = 100
time_steps = 3
def LSTM_train(x_... |
#!/usr/bin/env python
from .browse import SearchCriteria, AlbumMetadata, AlbumImage
from .group import Group, GroupPlayer
from .media import MediaItem
from .player import Player, QuickSelect, PlayMode
from .source import Source
from . import heos
__all__ = [
'SearchCriteria', 'AlbumMetadata', 'AlbumImage',
'Gr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.