content stringlengths 5 1.05M |
|---|
# 167. Two Sum II - Input array is sorted - LeetCode
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 1... |
import logging
def column_headers(header_row):
logging.info(f"Validating header row, headers: {header_row}")
header_list = header_row.split(",")
try:
valid = True
if header_list[0] != "code":
logging.info(f"got in code: {header_list[0]}")
valid = False
if ... |
import json
from config import TEXT_LANGUAGE
from game.roles.villager import Villager
from game.roles.werewolf import Werewolf
from game.roles.guard import Guard
from game.roles.seer import Seer
from game.roles.lycan import Lycan
from game.roles.betrayer import Betrayer
from game.roles.superwolf import Superwolf
from ... |
t = c = i= 0
menor = ''
while True:
n = str(input('Nome: ')).capitalize()
p = float(input('Preço: R$ '))
t += p
if i == 0:
m = p
menor = n
i += 1
if p > 1000:
c += 1
if p < m:
menor = n
op = ' '
while op not in 'sn':
op = str(input('Quer co... |
# -*- coding: utf-8 -*-
"""
Some generic laguage level utilities for internal use.
"""
import collections
import functools
import sys
import warnings
from typing import (
AbstractSet,
Any,
Callable,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Seque... |
""" --- The Angles of a Triangle --- Elementary
You are given the lengths for each side on a triangle.
You need to find all three angles for this triangle. If the given side
lengths cannot form a triangle (or form a degenerated triangle),
then you must return all angles as 0 (zero). The angles should be
represented as... |
# -*- coding: utf-8 -*-
""" doScan.py
The core interface that takes minimal text description of scan and does IPC with hardware system
This is the common entry into the hardware interface and uses a minimal text desc file containing three
blocks: [Major], [Minor], [Interface]. This routine can be called independently... |
import logging
from django.core.management.base import BaseCommand, CommandError
from plyara import Plyara
from rules.models import YaraRule
# Configure Logging
logging.basicConfig(level=logging.INFO)
class Command(BaseCommand):
help = 'Recalculate the logic hashes of the entire rule corpus'
def handle(se... |
import pandas as pd
import numpy as np
class ExternalData():
def __init__(self, csv, mol_names, exclude=[]):
self.csv = csv
self.mol_names = mol_names
self.exclude = exclude
def fit(self, molecules):
return molecules
def fit_transform(self, molecules, labels):
... |
import mailroom_stuff.Front_End
if __name__ == '__main__':
mailroom_stuff.Front_End.main()
|
from flask_script import Manager,Shell,Server
from app import create_app ,db
from app.models import User
from flask_migrate import Migrate, MigrateCommand
app=create_app('production')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
manager.add_command('Server',Server)
@mana... |
#!/usr/bin/env python
import socket
import sys
import os
sys.path.append('./src')
from multi_detector import MultiDetector
libpath = "../lib/linux/libnyumaya.so"
hotword_graph="../models/Hotword/marvin_big_0.3.tflite"
hotword_labels="../models/Hotword/marvin_labels.txt"
action_graph="../models/Command/on_off_big_0... |
#!/usr/bin/env python
""" This code implements a ceiling-marker based localization system.
The core of the code is filling out the marker_locators
which allow for the specification of the position and orientation
of the markers on the ceiling of the room """
import rospy
from ar_pose.msg import ARMarkers
... |
import os
from typing import Any, Dict, Optional
import httpx
import pytest
from fastapi import status
from tortoise import Tortoise
from chapter6.tortoise_relationship.app import app
from chapter6.tortoise_relationship.models import (
CommentDB,
CommentTortoise,
PostDB,
PostTortoise,
)
DATABASE_FIL... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Test Project fro machine learning',
author='Vipin',
license='MIT',
)
|
# Generated by Django 2.1 on 2020-01-10 00:07
from django.db import migrations
import pyuploadcare.dj.models
class Migration(migrations.Migration):
dependencies = [
('rate', '0002_auto_20200109_1306'),
]
operations = [
migrations.AddField(
model_name='profile',
n... |
from .music import * |
# -*- coding: UTF-8 -*-
import torbjorn as tbn
from .an2cn import An2Cn
from .cn2an import Cn2An
ac = An2Cn()
ca = Cn2An()
an = 9876543298765432
cn = "九千八百七十六万五千四百三十二亿九千八百七十六万五千四百三十二"
@tbn.run_time
def run_cn2an_ten_thousand_times():
for _ in range(10000):
result = ca.cn2an(cn)
assert result ==... |
import warnings
from ..utility.strcmpi import *
from ..utility.debug_message import *
from .fileparts import *
def _open_file(filename, defaultExt, permission, fileDataFcn, verbose=False):
"""
Opens a given file and executes the specified function over its data
Parameters
---------... |
numbers = ["886"]
def parse_phone_number(phone_number):
# 国内号码不按照国际号码方式处理,直接返回手机号,这样亿美才能发送成功
if phone_number.startswith("+86"):
return phone_number[3:]
real_phone_number = None
for number in numbers:
p = "+" + number
if phone_number.startswith(p + "0"):
real_phone... |
# common conversion point stacking
# import modules
import sys
from geographiclib.geodesic import Geodesic as geo
import numpy as np
# from matplotlib.mlab import griddata
import scipy
import scipy.ndimage
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import num... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\aging\aging_data.py
# Compiled at: 2019-04-30 00:16:35
# Size of source mod 2**32: 7516 bytes
f... |
"""Tests for web app requests"""
from unittest import TestCase
import sodar_taskflow
from apis.irods_utils import init_irods, cleanup_irods_data
class AppTestBase(TestCase):
"""Base test class for web app"""
def setUp(self):
# Init iRODS connection
self.irods = init_irods(test_mode=True)
... |
from django.db import models
from django.urls import reverse
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('Date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = mode... |
#!/usr/bin/env python2
"""
os_path_test.py: Tests for os_path.py
"""
from __future__ import print_function
import unittest
from pylib import os_path # module under test
class OsPathTest(unittest.TestCase):
def testBasename(self):
self.assertEqual('bar', os_path.basename('foo/bar'))
if __name__ == '__main_... |
from abc import ABCMeta
class OgreMeshSerializerListener(metaclass=ABCMeta):
"""
This class allows users to hook into the mesh loading process and
modify references within the mesh as they are loading. Material and
skeletal references can be processed using this interface which allows
f... |
import os
import dill
import numpy as np
from math import pi, exp, atan, sqrt, acos
def angle(x, y):
"""calculates the angle of (x,y) with respect to (0,0)
:param x: x choordinate
:param y: y choordinate
:returns: the angle"""
at = atan(y/x)
if(x < 0): return at+pi
elif(y < 0): return at+2*pi
return at
de... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Adrien Vergé
#
# 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 pro... |
# Copyright (C) 2014 Universidad Politecnica de Madrid
#
# 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 la... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/david/projects/luxcorerender/LuxCore/src/pyluxcoretools/pyluxcoretools/pyluxcoremenu/menuwindow.ui',
# licensing of '/home/david/projects/luxcorerender/LuxCore/src/pyluxcoretools/pyluxcoretools/pyluxcoremenu/menuwindow.ui' applies.
#
#... |
from bflib.items.base import Item
from core import flags
from bfgame.factories.recipes import listing
from core.gameobject import GameObject
class ItemFactory(object):
name = "item"
type_map = Item
def __init__(self, game):
self.game = game
def create_new(self, base_item):
recipe = l... |
num = [1,2,3,4]
evens = list(filter(lambda x: x % 2 == 0, num))
print(evens)
|
from aclarknet.aclarknet.models import Client
from aclarknet.aclarknet.models import Service
from aclarknet.aclarknet.models import TeamMember
from aclarknet.aclarknet.models import Testimonial
from django.contrib import admin
class ClientAdmin(admin.ModelAdmin):
pass
class ServiceAdmin(admin.ModelAdmin):
p... |
import unittest
from pydantic import ValidationError
from mobile_handset_price_model.prediction.model import MobileHandsetPriceModel
from mobile_handset_price_model.prediction.schemas import MobileHandsetPriceModelInput, \
MobileHandsetPriceModelOutput, PriceEnum
class ModelTests(unittest.TestCase):
def tes... |
# stdlib
import itertools
from urllib import quote
from unittest import TestCase
import logging
import mock
import json
from utils.splunk.splunk import SplunkSavedSearch, SplunkInstanceConfig, SavedSearches
from utils.splunk.splunk_helper import SplunkHelper
class FakeInstanceConfig(object):
def __init__(self):... |
# -*- coding: utf-8 -*-
import logging
import os
from logging.handlers import RotatingFileHandler
from platform import uname
from plexapi.config import PlexConfig, reset_base_headers
from plexapi.utils import SecretsFilter
from uuid import getnode
# Load User Defined Config
DEFAULT_CONFIG_PATH = os.path.expanduser('~/... |
import sys
from cx_Freeze import setup, Executable
product_name = "Triangulation"
exe = Executable(
script = "main.py",
base = "Win32GUI",
targetName = "Triangulation.exe",
icon = "icon.ico",
shortcutName = "Triangulation",
shortcutDir = "ProgramMenuFolder"
)
build_exe_options = {"packag... |
import sys
sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python')
from CodeJam.Y12R5P1.kelvinlau.A import *
def func_87caa8d11eaf4a20affa21f893f4cbfc(infile):
n = int(infile.readline())
l = map(int, infile.readline().split())
return l
def func_38404980cd9d4ebb8816600eb7513... |
# -*- coding: utf-8 -*-
from app.api import HTTPStatus, Resource, api
from app.auth import auth
@api.response(code=HTTPStatus.UNAUTHORIZED.value, description="Unauthorized access")
class BaseController(Resource):
method_decorators = [auth.login_required]
|
# https://www.youtube.com/watch?v=XNKeayZW4dY
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
from tensorflow import keras
from tensorflow.keras import layers
print('You ... |
"""
Kaggle Challenge:
Modded version from
"http://www.kaggle.com/c/acquire-valued-shoppers-challenge/"
'Reduce the data and generate features' by Triskelion
"""
from datetime import datetime, date
from collections import defaultdict
data_dir = "../data/"
loc_offers = data_dir + "offers.csv"
loc_transactions = da... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import status, mixins, viewsets
from rest_framework.decorators import api_view
from rest_framework.decorators import action
#Serializers
from cride.maps.serializers import StopMo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import VERSION as DJANGO_VERSION
from django.db import migrations
def add_image_permissions_to_admin_groups(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')... |
#!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# Curious numbers in Z3
#
# From Martin Henz' collection of puzzles
# http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/#curious
# """
# Curious Numbers from "Amusements in Mathematics, Dudeney", number 114.
#
# The number 48 has this peculiarity, that if you add... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UserTestCase(IntegrationT... |
#Curso #7 Templates tags
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app = Flask(__name__, template_folder = 'prueba_template')
#para darle una carpeta en especifico
@app.route('/')
def index():
name = 'Sergio'
return render_template('index.html', nombre = name)
@app.route('... |
from output.models.ms_data.wildcards.wild_h003_xsd.wild_h003 import (
Bar,
Foo,
)
__all__ = [
"Bar",
"Foo",
]
|
import torch.nn as nn
import functools
import torch.nn.functional as F
import torch
from core.dataset.architecture.mobilespace import *
class MBSpaceController(nn.Module):
def __init__(self, n_conditions=1, n_unit=N_UNITS,
depths=DEPTHS, kernel_sizes=KERNEL_SIZES, expand_ratios=EXPAND_RATIOS,
... |
# Copyright (c) 2019 GalaxyLearning 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 appli... |
from django.apps import AppConfig
class TrantoolConfig(AppConfig):
name = 'transtool'
# todo check settings and show errors if there are any mistakes
|
from layout import fonts
import pygame
from utils import gen_text_object
class Button:
def __init__(self, display, x, y, w, h,
color_active, color_inactive, border_w, border_color, pressed_down_color, text_color_norm,
text_color_pressed, text='', action=None, jump_inc=0):
... |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了88.07% 的用户
内存消耗:13.4 MB, 在所有 Python3 提交中击败了42.98% 的用户
解题思路:
双指针
p指针用于记录位置,q指针寻找小于x的节点。
q指针找到<x的节点后,交换链表
"""
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
p, q = ListNode(0, next = head), head ... |
import logging
from typing import Any, Dict
import requests
LOG = logging.getLogger(__name__)
class Client:
CROSSWALK_ENDPOINT = '/crosswalks'
STATISTICS_ENDPOTIN = '/statistics'
TOKEN_ENDPOINT = '/login/access-token'
def __init__(self, base_url: str, username: str, passwd: str) -> None:
se... |
from tacred_enrichment.internal.ucca_enhancer import UccaEnhancer
from tacred_enrichment.internal.ucca_types import UccaParsedPassage
from tacred_enrichment.internal.dep_graph import Step, DepGraph
from tacred_enrichment.internal.ucca_types import is_terminal
class UccaEncoding(UccaEnhancer):
def enhance(self, t... |
from flask import jsonify
class InvalidSearchException(ValueError): pass
class InvalidRequestException(Exception):
def __init__(self, error_message, code=None):
self.error_message = error_message
self.code = code or 400
def response(self):
return jsonify({'error': self.error_message... |
from argparse import ArgumentParser
import pysam
def merge(input_path, output_path, custom_id='custom_id', line_length=80):
with open(output_path, 'w+') as out_f:
out_f.write(f'>{custom_id}\n')
data = ''
with pysam.FastxFile(input_path) as in_f:
for record in in_f:
... |
n=input()
if(len(n)<4):
print("NO")
else:
count=0
for i in range(0,len(n)):
if(n[i]=='4' or n[i]=='7'):
count=count+1
dig=0
flag=0
if(count==0):
print("NO")
else:
while count>0:
dig=count%10
if(dig!=4 and dig!=7):
fl... |
# Generated by Django 2.2.3 on 2019-07-12 14:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('TeamXapp', '0047_auto_20190712_1504'),
]
operations = [
migrations.AlterField(
model_name='allm... |
import os
import numpy
import math
import cv2
from skimage import io
from skimage import color
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from random import randint
class ClusterDataset(Dataset):
"""Camera localization dataset."""
def __cluster__(self, root_dir, num_exp... |
import pytest
from pretalx.common.forms.utils import get_help_text
@pytest.mark.parametrize('text,min_length,max_length,warning', (
('t', 1, 3, 't Please write between 1 and 3 characters.'),
('', 1, 3, 'Please write between 1 and 3 characters.'),
('t', 0, 3, 't Please write no more than 3 characters.'),
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
Provides a set of I/O routines.
.. include common links, assuming primary doc root is up one directory
.. include:: ../links.rst
"""
import os
import sys
import warnings
import gzip
import shutil
from packaging import version
... |
# stateio.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Supporting functions for accessing files from stateior via data commons.
https://github.com/USEPA/stateior
"""
import os
import pandas as pd
from esupy.processed_data_mgmt import download_from_remote, Paths,\
load_preprocessed_output
from flowsa.met... |
from sys import argv
import json
finalOutput = {"result": ""}
outputFile = argv[3]
if_spark = argv[4]
reviewFile = argv[1]
businessFile = argv[2]
nCates = int(argv[5])
def no_spark():
def LOAD_FILE(filePath):
output = []
with open(filePath) as file:
for line in file:
... |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import dj_database_url
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable f... |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from PIL import Image
import scipy.misc
import pandas as pd
import numpy as np
import random
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from glob import glob
from torch.util... |
"""
Define some reference aggregates based on *exact* site names
"""
import logging
import pandas as pd
from solarforecastarbiter import datamodel
from solarforecastarbiter.io import api
logger = logging.getLogger('reference_aggregates')
REF_AGGREGATES = [
{
'name': 'NOAA SURFRAD Average GHI',
... |
import sys
import unittest
import dask.array as da
import dask.distributed as dd
import numpy as np
import xarray as xr
# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
from src.geocat.comp import heat_index
else:
from geocat.comp import h... |
# INPUT
N = int(input())
A = [int(input()) for _ in range(N)]
# PROCESSES
"""
Critical observation:
To reach a value $V$, we must have come from a value SMALLER than $V$ AND that is before it.
Assuming that ALL values before $V$ have an optimal solution, we can find the optimal solution for $V$.
Define the DP ta... |
""" Simple mutually-recursive coroutines with asyncio. Using asyncio.ensure_future
instead of yield from allows the coroutine to exit and merely schedules the next
call with the event loop, allowing infinite mutual recursion. """
import asyncio
@asyncio.coroutine
def a(n):
print("A: {}".format(n))
asyncio.asy... |
from __future__ import unicode_literals
from collections import OrderedDict
from django import forms
from django.forms.widgets import Textarea
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
mark_safe_lazy = lazy(mark_safe... |
"""
Just another Python API for Travis CI (API).
A module which provides the tests of our requester module.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Project link:
https://github.com/funilrys/PyTravisCI
Project documentation:
https://pytravisci.readthedocs.io/en/latest/
License
::... |
#!/usr/bin/env python
from __future__ import print_function, division, absolute_import
import sys
from channelfinder import ChannelFinderClient, Channel, Property, Tag
import aphla as ap
#GET http://channelfinder.nsls2.bnl.gov:8080/ChannelFinder/resources/resources/channels?~name=SR*
cfsurl = 'http://web01.nsls2.bn... |
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class PinCard(models.Model):
token = models.CharField(max_length=32, db_index=True, editable=False)
display_n... |
#!/usr/bin/env python
"""The setup script."""
from setuptools import (
find_packages,
setup,
)
from authz import __version__
with open('README.md') as readme_file:
readme = readme_file.read()
requirements = ["casbin==1.9.3"]
test_requirements = ['pytest>=3', ]
setup(
author="Ezequiel Grondona",
... |
real = float(input('Quanto você tem na Carteira? R$'))
dolar = real / 5.11
euro = real / 5.76
print('Com R${:.2f} você pode comprar U$${:.2f} e €{:.2f} '.format(real, dolar, euro))
|
def fib(n):
if (n==0):
return 0
elif (n==1):
return 1
else:
x = fib(n-1) + fib(n-2)
return x
print(fib(6))
|
#!/usr/bin/python
from hashlib import sha1
from subprocess import check_output
import hmac
import json
import os
import sys
# Due to |hmac.compare_digest| is new in python 2.7.7, in order to be
# compatible with other 2.7.x version, we use a similar implementation of
# |compare_digest| to the Python implementation.... |
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'ix4hnvelil^q36!(bg#)_+q=vkf4yk)@bh64&0qc2z*zy5^kdz'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'user',
'job',
'ckeditor',
'django_filters',
'widget_tweaks',
'django.contrib.admin',
... |
import io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import time
class Analyzer:
'''Controls plotting of different object properties'''
def __init__(self):
self.plot_number = 1
self.xdata = []
self.reactors = []
self.reactor_numbe... |
from ..gl import AGLObject, GLHelper
from ...debugging import Debug, LogLevel
from ...constants import _NP_UBYTE
from ...autoslot import Slots
from OpenGL import GL
import numpy as np
import time
class TextureData(Slots):
__slots__ = ("__weakref__", )
def __init__(self, width: int, height: int):
self.width: int ... |
# This is a work in progress - see Demos/win32gui_menu.py
# win32gui_struct.py - helpers for working with various win32gui structures.
# As win32gui is "light-weight", it does not define objects for all possible
# win32 structures - in general, "buffer" objects are passed around - it is
# the callers responsibility to... |
import numpy as np
from numba import njit
@njit
def linspace(x1,x2,n):
'''
Jit compiled version of numpy.linspace().
'''
x = np.zeros(n)
x[0] = x1
x[-1] = x2
for i in range(1,n-1):
x[i] = x[0] + i*(x2-x1)/(n-1)
return x
@njit
def trapezoid(x,y):
'''
Jit compiled versio... |
from setuptools import setup, find_packages
setup(
name='k8sfoams',
version='1.0.2',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/mmpyro/k8s-pod-foamtree',
description='K8s pod foamtree visualizer',
author="Michal Marszale... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2019 Andreas Bunkahle
# Copyright (c) 2019 Bohdan Horbeshko
#
# 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 th... |
import threading
import datetime
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
import pandas as pd
import numpy as np
import time
from functools import reduce
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Ou... |
largura = float(input('Qual a largura da parede? '))
altura = float(input('Qual a altura da parede? '))
area = largura*altura
qtd_tinta = area/2
print(qtd_tinta) |
import os
from unittest.mock import call
import numpy as np
import pytest
import sparse
from histolab.slide import Slide
from histolab.tiler import RandomTiler, Tiler
from histolab.types import CoordinatePair
from ..unitutil import (
ANY,
PILImageMock,
SparseArrayMock,
function_mock,
initializer_... |
import numpy as np
import pandas as pd
import talib as ta
from cryptotrader.utils import safe_div
def price_relative(obs, period=1):
prices = obs.xs('open', level=1, axis=1).astype(np.float64)
price_relative = prices.apply(ta.ROCR, timeperiod=period, raw=True).fillna(1.0)
return price_relative
def momen... |
"""
@author : Krypton Byte
"""
import requests
def igdownload(url):
req=requests.get(url, params={"__a":1})
if ('graphql' in req.text):
media=req.json()["graphql"]["shortcode_media"]
if media.get("is_video"):
return {"status": True,"result":[{"type":"video", "url":media["video_url"]}... |
import requests
from bs4 import BeautifulSoup
#https://en.wikipedia.org/wiki/List_of_companies_operating_trains_in_the_United_Kingdom
def main():
urlList = ['https://twitter.com/ScotRail','https://twitter.com/LDNOverground','https://twitter.com/AvantiWestCoast','https://twitter.com/c2c_Rail','https://twitte... |
# coding: utf-8
nms = ['void',
'Front bumper skin',
'Rear bumper skin',
'Front bumper grille',
'network',
'Hood',
'Front fog lamp',
'Headlamp',
'Front windshield',
'Roof panel',
'Front fender',
'Rear fender',
'Front door shell outer plate',
'Rear door shell outer plate',
'Door glass front',
'Door glass rear',
'Rearvi... |
import httpretty
from tests import FulcrumTestCase
class MembershipTest(FulcrumTestCase):
@httpretty.activate
def test_search(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/memberships',
body='{"memberships": [{"id": 1},{"id": 2}], "total_count": 2, "current_page": 1, "tot... |
import pytest
from picorss.src.domain import entities
@pytest.fixture()
def rss_page() -> entities.RssPage:
return entities.RssPage(url="https://example.com")
def test_rss_page_has_url(rss_page: entities.RssPage) -> None:
assert rss_page.url
|
def process(self):
self.edit("LATIN")
self.replace("CAPITAL LETTER D WITH SMALL LETTER Z", "Dz")
self.replace("CAPITAL LETTER DZ", "DZ")
self.edit("AFRICAN", "african")
self.edit("WITH LONG RIGHT LEG", "long", "right", "leg")
self.edit('LETTER YR', "yr")
self.edit("CAPITAL LETTER O WITH... |
#!/usr/bin/env python3
# Write a program that computes typical stats
# Count, Min, Max, Mean, Std. Dev, Median
# No, you cannot import the stats library!
import sys
import math
units = []
#Create your list of integers/floating-point numnbers making sure to covert from strings
for i in sys.argv[1:]:
units.append(f... |
"""
Copyright (c) 2014, Samsung Electronics Co.,Ltd.
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 of conditions ... |
import os
from config.config import get_config
import shutil
def main():
config = get_config()
if not os.path.exists(config.dataset):
print(f"[!] No dataset in {config.dataset}")
return
for image_transfer in os.listdir(config.dataset):
print(image_transfer)
if not '2' in ... |
'''
Created on 2020-02-13
@author: wf
'''
from flask import Flask
from flask import render_template
from flask import request
from dgs.diagrams import Generators,Generator,Example
import os
from flask.helpers import send_from_directory
import argparse
import sys
from pydevd_file_utils import setup_client_server_paths
... |
import boto3
import codecs
import xmltodict
import re
class Example:
'''Represents a single source line and all corresponding target lines
we would like a Turker to evaluate.
'''
def __init__(self, source_line, key):
self.source_line = source_line # The single source line
self.target_lines = [] # Lis... |
def inputMatrix(m,n, vektori = False):
if vektori:
border = "border-right: 2px solid black; border-left: 2px solid black; border-top: none; border-bottom: none;"
else:
border = "border: none;"
tmp = ""
tmp+= """
<div class="container">
<div style="border-left: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.