content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright 2021 Massachusetts Institute of Technology
#
# @file image_gallery.py
# @author W. Nicholas Greene
# @date 2020-07-02 23:44:46 (Thu)
import os
import argparse
def create_simple_gallery(image_dir, num_per_row=3, output_file="index.html", title="Image Gallery"):
"""Create a simple gallery with num_per_r... | python |
# %%
# Imports
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from torch.utils.data import Dataset, random_split
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
from... | python |
"""
Ejercicio 02
Escriba un algoritmo, que dado como dato el sueldo de un trabajador, le aplique un aumento del 15% si su salario bruto es inferior
a $900.000 COP y 12% en caso contrario. Imprima el nuevo sueldo del trabajador.
Entradas
Sueldo_Bruto --> Float --> S_B
Salidas
Sueldo_Neto --> Float --> S_N
... | python |
import os
import shutil
import cv2
import numpy as np
import pandas as pd
from self_driving_car.augmentation import HorizontalFlipImageDataAugmenter
IMAGE_WIDTH, IMAGE_HEIGHT = 64, 64
CROP_TOP, CROP_BOTTOM = 30, 25
class DatasetHandler(object):
COLUMNS = ('center', 'left', 'right', 'steering_angle', 'speed... | python |
# Copyright (c) 2021, Rutwik Hiwalkar and Contributors
# See license.txt
# import frappe
import unittest
class TestQMailScheduleRule(unittest.TestCase):
pass
| python |
#!/usr/bin/python
#eval p@20
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Usage:[pred]'
exit(0)
fi = open(sys.argv[1],'r')
K = 20
#precision@k
P = 0
unum = 943
rank = 0
for line in fi:
rank = int(line.strip())
if rank < K:
... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
import random
from typing import Optional, Tuple
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from densepose.converters.base import IntTupleBox
from .densepose_cse_base import De... | python |
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!') | python |
from django.db import models
class WelcomePage(models.Model):
"""
Welcome page model
"""
content = models.CharField(max_length=2000)
| python |
import uuid
import json
from textwrap import dedent
import hashlib
from flask import Flask, jsonify, request
from blockchain import Blockchain
# Using Flask as API to communicate with Blockchain
app = Flask(__name__)
# Unique address for node
node_identifier = str(uuid.uuid4()).replace("-", "")
# instantiate Blockc... | python |
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from py_muvr import FeatureSelector
from py_muvr.data_structures import (
FeatureEvaluationResults,
FeatureRanks,
InputDataset,
OuterLoopResults,
)
ASSETS_DIR = Path(__file__).parent / "assets"
@pytest.fixture(scope="sess... | python |
from djitellopy import Tello
tello=Tello()
tello.connect()
#tello.takeoff()
#
#move
#tello.move_up(100)
#tello.move_forward(50)
#tello.rotate_clockwise(90)
#tello.move_back(50)
#tello.move_up(50)
#
#tello.land()
import cv2
panel=cv2.imread('./DroneBlocks_TT.jpg')
cv2.imshow('tello panel', panel)
while True:
ke... | python |
import pytest
from lemur.auth.ldap import * # noqa
from mock import patch, MagicMock
class LdapPrincipalTester(LdapPrincipal):
def __init__(self, args):
super().__init__(args)
self.ldap_server = 'ldap://localhost'
def bind_test(self):
groups = [('user', {'memberOf': ['CN=Lemur Access... | python |
import pyglet
from inspect import getargspec
from element import Element
from processor import Processor
from draw import labelsGroup
from utils import font
class Node(Element, Processor):
'''
Node is a main pyno element, in fact it is a function with in/outputs
'''
def __init__(self, x, y, batch, c... | python |
from . import account
from . import balance
from . import bigmap
from . import block
from . import commitment
from . import contract
from . import cycle
from . import delegate
from . import head
from . import operation
from . import protocol
from . import quote
from . import reward
from . import right
from . import sof... | python |
# Copyright 2019 The Vitess 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 or agreed to i... | python |
# -*- coding: utf-8 -*-
# @Author: Amar Prakash Pandey
# @Co-Author: Aman Garg
# @Date: 25-10-2016
# @Email: amar.om1994@gmail.com
# @Github username: @amarlearning
# MIT License. You can find a copy of the License
# @http://amarlearning.mit-license.org
# import library here
import pygame
import time
import random... | python |
from django.urls import path
from django_admin_sticky_notes.views import StickyNoteView
urlpatterns = [
path("", StickyNoteView.as_view()),
]
| python |
import os
import pickle
import cv2
if __name__ == '__main__':
folder = './rearrangement-train/color/000001-2.pkl'
with open(folder, 'rb') as f:
tmp = pickle.load(f)
for i in range(3):
img = tmp[i, 0, ...]
cv2.imshow('haha', img)
cv2.waitKey(0)
| python |
def numRescueBoats(people, limit):
boats = 0
people.sort()
left = 0, right = len(people)-1
while left <= right:
if left == right:
boats += 1
break
current = people[left]+people[right]
if current <= limit:
left += 1
boats += 1
... | python |
from django.apps import AppConfig
from orchestra.core import accounts
class ContactsConfig(AppConfig):
name = 'orchestra.contrib.contacts'
verbose_name = 'Contacts'
def ready(self):
from .models import Contact
accounts.register(Contact, icon='contact_book.png')
| python |
from ... import UndirectedGraph
from unittest import TestCase, main
class TestEq(TestCase):
def test_eq(self) -> None:
edges = {
("a", "b"): 10,
("b", "c"): 20,
("l", "m"): 30
}
vertices = {
"a": 10,
"b": 20,
"z": 30
... | python |
from setuptools import setup, Extension, find_packages
import os
import glob
sources = []
sources += glob.glob("src/*.cpp")
sources += glob.glob("src/*.pyx")
root_dir = os.path.abspath(os.path.dirname(__file__))
ext = Extension("factorizer",
sources = sources,
language = "c++",
extra_compile_args =... | python |
import os
import datetime
try:
from PIL import Image, ImageOps
except ImportError:
import Image
import ImageOps
from ckeditor import settings as ck_settings
from .common import get_media_url
def get_available_name(name):
"""
Returns a filename that's free on the target storage system, and
av... | python |
# Generated by Django 1.11.23 on 2019-08-19 01:00
from django.conf import settings
from django.db import migrations
def set_site_domain_based_on_setting(apps, schema_editor):
Site = apps.get_model('sites', 'Site')
# The site domain is used to build URLs in some places, such as in password
# reset emails,... | python |
#!/usr/bin/env python
import csv
import re
from rdkit.Chem import AllChem
from rdkit import Chem
from rdkit import DataStructs
compounds = {}
def load_compounds(filename):
comps = {}
bad_count = 0
blank_count = 0
with open(filename) as csv_file:
csvr = csv.DictReader(csv_file, delimiter='\t... | python |
# Generated by Django 2.0.1 on 2018-01-23 11:13
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0013_auto_20170829_0515'),
]
operations = [
migrations.AlterField(
model_name='page',
... | python |
from metaflow import resources
from metaflow.api import FlowSpec, step
class ResourcesFlow(FlowSpec):
@resources(memory=1_000)
@step
def one(self):
self.a = 111
@resources(memory=2_000)
@step
def two(self):
self.b = self.a * 2
class ResourcesFlow2(ResourcesFlow):
pass
| python |
import struct
from slmkiii.template.input.button import Button
class PadHit(Button):
def __init__(self, data=None):
super(PadHit, self).__init__(data)
self.max_velocity = self.data(28)
self.min_velocity = self.data(29)
self.range_method = self.data(30)
def from_dict(self, data... | python |
"""Implementation of the MCTS algorithm for Tic Tac Toe Game."""
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import numpy.typing as npt
from mctspy.games.common import TwoPlayersAbstractGameState
from mctspy.tree.nodes import TwoPlayersGameMonteCarloTreeSearchNode
fr... | python |
from gettext import Catalog
from xml.etree.ElementInclude import include
from django.contrib import admin
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^catalog/', include(Catalog.urls)),
]
| python |
from phq.kafka.consumer import _latest_distinct_messages
from phq.kafka import Message
def test_latest_distinct_messages():
messages = [
Message(id='abc', payload={}),
Message(id='def', payload={}),
Message(id='xyz', payload={}),
Message(id='xyz', payload={}),
Message(id='a... | python |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Checks that gyp fails on static_library targets which have several files with
the same basename.
"""
import TestGyp
test = TestGyp.Tes... | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
pySnarlNetLib
author: Łukasz Bołdys
licence: MIT
Copyright (c) 2009 Łukasz Bołdys
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 w... | python |
from setuptools import setup
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="rubrix",
# other arguments omitted
descript... | python |
# Generated by Django 3.0.7 on 2021-01-19 13:36
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('payment_system', '0027_a... | python |
#!/usr/bin/env python3
"""
Author : kyclark
Date : 2018-11-02
Purpose: Rock the Casbah
"""
import argparse
import pandas as pd
import matplotlib.pyplot as plt
import sys
# --------------------------------------------------
def get_args():
"""get args"""
parser = argparse.ArgumentParser(
description... | python |
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
s = ''
for i in zip(*strs):
if len(set(i)) != 1:
return s
else:
s += i[0]
return s
if __name__ == '__main__... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: uber/cadence/api/v1/tasklist.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _messa... | python |
import string
def print_rangoli(n):
alpha = string.ascii_lowercase
L = []
for i in range(n):
s = "-".join(alpha[i:n])
L.append((s[::-1]+s[1:]).center(4*n-3, "-"))
print('\n'.join(L[:0:-1]+L))
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
# def print_rangoli(size... | python |
from pydantic import BaseModel
class PartOfSpeech(BaseModel):
tag: str
| python |
# coding:utf-8
import os
import json
import numpy as np
import torch.utils.data as data
from detectron2.structures import (
Boxes,
PolygonMasks,
BoxMode
)
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/annotations/instances_train2017.jso... | python |
#Need to prebuild in maya first
#RenderScript.py
#MayaPythonScript : RenderScript
#A script that can use python to automativly render the scene
import maya.cmds as cmds
import maya.cmds as mc
import maya.app.general.createImageFormats as createImageFormats
from mtoa.cmds.arnoldRender import arnoldRender
#Function : g... | python |
import torch
from torch import nn
from torch.nn import functional as F
def normalization(feautures):
B, _, H, W = feautures.size()
outs = feautures.squeeze(1)
outs = outs.view(B, -1)
outs_min = outs.min(dim=1, keepdim=True)[0]
outs_max = outs.max(dim=1, keepdim=True)[0]
norm = outs_max - outs_m... | python |
from .nucleus_sampling import top_k_top_p_filtering
from .transformer_decoder import TransformerDecoder | python |
# -*- coding: utf-8 -*-
from odoo import http
# class ControleEquipement(http.Controller):
# @http.route('/controle_equipement/controle_equipement/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/controle_equipement/controle_equipement/objects/', auth='public')
# ... | python |
import consts
quotes = []
fp = open(consts.quotes_file, "r")
for line in fp:
if line[0] == '*':
quotes.append(line[2:-1])
fp.close()
| python |
# Jogo da Forca versão 2
import tkinter as tk
import applic
window = tk.Tk()
applic.Application(window)
window.mainloop() | python |
# Copyright (c) 2020, NVIDIA 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 by appli... | python |
import pydocspec
from pydocspec import visitors
def dump(root:pydocspec.TreeRoot) -> None:
for mod in root.root_modules:
mod.walk(visitors.PrintVisitor())
# pydocspec_processes = {
# 90: dump
# }
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import mock
from click.testing import CliRunner
from elasticsearch_loader import cli
def invoke(content, *args, **kwargs):
if sys.version_info[0] == 2:
content = content.encode('utf-8')
runner = CliRunner()
with runner.isolated_filesystem... | python |
from dataclasses import dataclass
import os
from typing import Optional
@dataclass(frozen=True)
class ENV:
workspace_name: Optional[str] = os.environ.get('WORKSPACE_NAME')
subscription_id: Optional[str] = os.environ.get('SUBSCRIPTION_ID')
resource_group: Optional[str] = os.environ.get('RESOURCE_GROUP')
... | python |
# Learn more: https://github.com/Ensembl/ols-client
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
readme = f.read()
with open(os.path.join(os.path.dirname(__file__), 'LICENSE')) as f:
license_ct = f.read()
with open(os.path.join(... | python |
from vidispine.base import EntityBase
from vidispine.errors import InvalidInput
from vidispine.typing import BaseJson
class Search(EntityBase):
"""Search
Search Vidispine objects.
:vidispine_docs:`Vidispine doc reference <collection>`
"""
entity = 'search'
def __call__(self, *args, **kwarg... | python |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import copy
from datetime import datetime
from functools import partial
import os
from code import Code
import json_parse
# The template fo... | python |
from flask_jsondash import settings
def test_settings_have_url_keys_specified():
for family, config in settings.CHARTS_CONFIG.items():
assert 'js_url' in config
assert 'css_url' in config
def test_settings_have_urls_list_or_none():
for family, config in settings.CHARTS_CONFIG.items():
... | python |
number ="+919769352682 " | python |
import asyncio
import statistics
import time
from typing import Optional
import pytest
import pytest_asyncio
from janus import Queue as JanusQueue
from utils import create_kafka_event_from_dict, create_kafka_message_from_dict
from eventbus.config import (
ConsumerConfig,
HttpSinkConfig,
HttpSinkMethod,
... | python |
import numpy as np
import pandas as pd
import numba
import multiprocessing as mp
import itertools as it
import analyzer as ana
import concurrent.futures as fut
def calculate_pvalues(df, blabel, tlabel, mlabel, n, f=np.mean, **kwargs):
"""
Calculates the p value of the sample.
Parmas:
df --- (panda... | python |
"""Create openapi schema from the given API."""
import typing as t
import inspect
import re
from http import HTTPStatus
from functools import partial
from apispec import APISpec, utils
from apispec.ext.marshmallow import MarshmallowPlugin
from http_router.routes import DynamicRoute, Route
from asgi_tools.response impo... | python |
#!/usr/bin/env python
from setuptools import setup, find_packages
import versioneer
setup(name='hiwenet',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Histogram-weighted Networks for Feature Extraction and Advance Analysis in Neuroscience',
long_descriptio... | python |
import os
import time
def main():
try:
os.remove("/etc/pmon.d/neutron-avs-agent.conf")
except:
pass
while True:
time.sleep(100)
if __name__ == "__main__":
main()
| python |
from rest_framework import serializers
from paste import constants
from paste.models import Snippet
class SnippetSerializer(serializers.ModelSerializer):
"""Snippet model serializer."""
class Meta:
model = Snippet
fields = '__all__'
read_only_fields = ['owner']
def create(self, ... | python |
""" Seeking Alpha View """
__docformat__ = "numpy"
import argparse
from typing import List
import pandas as pd
from datetime import datetime
from gamestonk_terminal.helper_funcs import (
check_positive,
parse_known_args_and_warn,
valid_date,
)
from gamestonk_terminal.discovery import seeking_alpha_model
... | python |
import os
import ntpath
from preprocessing.segmentation import segment
from preprocessing.augment import augment
from CNN.recognize_character import recognize
from Unicode.seqgen import sequenceGen
from Unicode.printdoc import unicode_to_kn
def segmentation_call(image):
rootdir = 'web_app/hwrkannada/hwrapp/stat... | python |
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from authors.apps.authentication.models import User
class ReadStats(models.Model):
"""
Users read statistics
"""
user = models.OneToOneField(User, on_delete=models.CASCADE, db_index=Tr... | python |
import matplotlib.pyplot as plt
from flask import Flask
from flask_cors import CORS
from api.v1 import api_v1
app = Flask(__name__, static_url_path='', static_folder='frontend')
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app.register_blueprint(api_v1, url_prefix='/api/v1')
app.config.SWAGGER_UI_DOC_EXP... | python |
from datetime import datetime
from django.utils import timezone
import factory
from .. import models
from faker.generator import random
random.seed(0xDEADBEEF)
class BundleFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Bundle
easydita_id = factory.Faker('first_name')
ea... | python |
from argparse import ArgumentParser
from irun.compiler import compile_node, construct
from irun.parser import parse
def compile_irun(source):
tree = parse(source)
rql_context = compile_node(tree)
return construct(rql_context)
def main(argv=None):
parser = ArgumentParser()
parser.add_argument("-... | python |
import torch
from torch.autograd import Variable
import render_pytorch
import image
import camera
import material
import light
import shape
import numpy as np
resolution = [256, 256]
position = Variable(torch.from_numpy(np.array([0, 0, -5], dtype=np.float32)))
look_at = Variable(torch.from_numpy(np.array([0, 0, 0], dt... | python |
f=open("./CoA/2020/data/02a.txt","r")
valid=0
for line in f:
first=int(line[:line.index("-")])
print(first)
second=int(line[line.index("-")+1:line.index(" ")])
print(second)
rule = line[line.index(" ")+1:line.index(":")]
print(rule)
code = line[line.index(":")+2:]
print(code)
if code... | python |
## An implementation of the credential scheme based on an algebraic
## MAC proposed by Chase, Meiklejohn and Zaverucha in Algebraic MACs and Keyed-Verification
## Anonymous Credentials", at ACM CCS 2014. The credentials scheme
## is based on the GGM based aMAC. (see section 4.2, pages 8-9)
from amacs import *
from ge... | python |
import pygame
import math
from Tower import *
pygame.init()
class T_SuperTower(Tower):
def __init__(Self , sc , Images):
Self.L1 = Images
Self.image = Self.L1[0]
Self.level = 5
Self.range = 100
Self.damage = 100
Self.x = 0
Self.y = 0
Self.bulletx ... | python |
import os
import tempfile
class Config:
IS_TRAIN = True # Set whether you want to Train (True) or Predict (False)
TICKER = 'EURUSD'
num_of_rows_read = 1000 # If set 0 then all the rows will be read
# Set MySQL inputs if True
IS_MYSQL = False
MYSQL_USER = 'Write your user name'
MYSQL_PASSWORD = 'Write your... | python |
from typing import Any
class TonException(Exception):
def __init__(self, error: Any):
if type(error) is dict:
error = f"[{error.get('code')}] {error.get('message')} " \
f"(Core: {error.get('data', {}).get('core_version')})"
super(TonException, self).__init__(error)
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import Flask
'''
Created on Nov 22, 2016
@author: jmartan
'''
import os,signal
import requests
import argparse
import uni_func
import atexit
import unicornhat
def update_widget(codec_ip, username, password, widget_id, value, unset=False):
# "unset" is needed in a si... | python |
from slackbot.bot import Bot
from slackbot.bot import respond_to
import re
import foobot_grapher
def main():
bot = Bot()
bot.run()
@respond_to('air quality', re.IGNORECASE)
def air_quality(message):
attachments = [
{
'fallback': 'Air quality graph',
'image_url': foobot_grapher.getSensorReadings(Fal... | python |
"""
Дан список, заполненный произвольными целыми числами. Найдите в этом списке два числа, произведение которых
максимально. Выведите эти числа в порядке неубывания. Решение должно иметь сложность O(n), где n - размер списка. То
есть сортировку использовать нельзя.
"""
a = list(map(int, input().split()))
negative_max =... | python |
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.http import HttpResponse, HttpRequest
from zilencer.models import RemotePushDeviceToken, RemoteZulipServer
from zerver.lib.exceptions import JsonableError
from zerver.lib.push_notifications import send_android_push_notif... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class InjaConan(ConanFile):
name = "inja"
version = "2.1.0"
url = "https://github.com/yasamoka/conan-inja"
description = "Template engine for modern C++, loosely inspired by jinja for Python"
licens... | python |
class Learner(object):
def log_update(self, o, a, r, op, logpb, dist, done):
self.log(o, a, r, op, logpb, dist, done)
info0 = {'learned': False}
if self.learn_time(done):
info = self.learn()
self.post_learn()
info0.update(info)
info0['learned'... | python |
import os
import shutil
import json
print("[+] Cleaning...")
with open("tree.json", "r") as f:
json_str = f.read()
json_data = json.loads(json_str)
f.close()
for (path, dirs, files) in os.walk(os.curdir):
if path not in json_data["dirs"]:
shutil.rmtree(path)
else:
for f in files:
f = f"{path}{os.sep}{f}"... | python |
# BT5071 pop quiz 2
# Roll Number: BE17B037
# Name: Krushan Bauva
def bubble(A):
n = len(A)
if n%2 == 1:
A1 = A[0:n//2+1]
A2 = A[n//2+1:n]
else:
A1 = A[0:n//2]
A2 = A[n//2:n]
n1 = len(A1)
for i in range(n1-1, 0, -1):
for j in range(i):
if A1[j]>A1... | python |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth.models import Permission, User
from django.db import models
from localflavor.us.models import USStateField
from phonenumber_field.modelfields import PhoneNumberField
from multiselectfield import MultiSelectField
from endor... | python |
# -*- coding: utf-8 -*-createacsr_handler
from __future__ import unicode_literals
import json
import logging
import os
import uuid
import time
import secrets
import cryptography
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.p... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from credocommon.models import Detection
from credocommon.helpers import validate_image, rate_brightness
class Command(BaseCommand):
help = "Validate detections"
def handle(self, *args, **opt... | python |
"""Implement an error to indicate that a scaaml.io.Dataset already exists.
Creating scaaml.io.Dataset should not overwrite existing files. When it could
the constructor needs to raise an error, which should also contain the dataset
directory.
"""
from pathlib import Path
class DatasetExistsError(FileExistsError):
... | python |
from datetime import datetime
from django.views.generic.edit import BaseCreateView
from braces.views import LoginRequiredMixin
from .base import BaseEditView
from forum.forms import ReplyForm
from forum.models import Topic, Reply
class ReplyCreateView(LoginRequiredMixin, BaseCreateView):
model = Topic
form_... | python |
"""
See the problem description at: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/
"""
class Solution:
def minAddToMakeValid(self, S: str) -> int:
"""
Time complexity : O(n)
Space complexity: O(1)
"""
score1 = score2 = 0
for char in S... | python |
from tests.seatsioClientTest import SeatsioClientTest
from tests.util.asserts import assert_that
class ListAllTagsTest(SeatsioClientTest):
def test(self):
chart1 = self.client.charts.create()
self.client.charts.add_tag(chart1.key, "tag1")
self.client.charts.add_tag(chart1.key, "tag2")
... | python |
"""empty message
Revision ID: 20210315_193805
Revises: 20210315_151433
Create Date: 2021-03-15 19:38:05.486503
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "20210315_193805"
down_revision = "20210315_151433"
branch_labels = None
depends_on = None
def upgra... | python |
def parse_full_text(status):
"""Param status (tweepy.models.Status)"""
return clean_text(status.full_text)
def clean_text(my_str):
"""Removes line-breaks for cleaner CSV storage. Handles string or null value.
Returns string or null value
Param my_str (str)
"""
try:
my_str... | python |
#!/usr/bin/env python
"""Command line utility to serve a Mapchete process."""
import click
import logging
import logging.config
import os
import pkgutil
from rasterio.io import MemoryFile
import mapchete
from mapchete.cli import options
from mapchete.tile import BufferedTilePyramid
logger = logging.getLogger(__name_... | python |
from .dualconv_mesh_net import DualConvMeshNet
from .singleconv_mesh_net import SingleConvMeshNet
| python |
from __future__ import print_function
import json
import urllib
import boto3
print('*Loading lambda: s3FileListRead')
s3 = boto3.client('s3')
def lambda_handler(event, context):
print('==== file list in bucket ====')
AWS_S3_BUCKET_NAME = 'yujitokiwa-jp-test'
s3_resource = boto3.resource('s3')
bucke... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 21:05:47 2020
@author: Richard
"""
from newsapi import NewsApiClient
newsapi = NewsApiClient(api_key='0566dfe86d9c44c6a3bf8ae60eafb8c6')
all_articles = newsapi.get_everything(q='apple',
from_param='2020-04-01',
... | python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas_datareader import data as web
from datetime import datetime, timedelta
from yahoo_finance import Share
from math import ceil, floor
from collections import deque
class Stock():
""" Historical data of a Stock
Attribute... | python |
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
size = 1000
x = np.random.randn(size)
y = 1.051 * x + np.random.random(size)
plt.plot(x,y,'*',color='black',label="Dado original")
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Regressão Linear')
slope, intercept, r_value, p_value, std_err = s... | python |
"""
Contains functions to assist with stuff across the application.
ABSOLUTELY NO IMPORTS FROM OTHER PLACES IN THE REPOSITORY.
Created: 23 June 2020
"""
| python |
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (C) 2015 by Brian Horn, trycatchhorn@gmail.com.
#
# 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 w... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.