content stringlengths 5 1.05M |
|---|
import os
import bpy
from src.loader.LoaderInterface import LoaderInterface
from src.utility.Utility import Utility
class ReplicaLoader(LoaderInterface):
""" Just imports the objects for the given file path
The import will load all materials into cycle nodes.
**Configuration**:
.. list-table::
... |
#!usr/bin.env python3
# Ex. 1: Two words are anagrams if you can rearrange the letters from one
# to spell the other. Write a function called is_anagram that takes two
# strings and returns True if they are anagrams.
def is_anagram(w1, w2):
if sorted(w1) == sorted(w2):
return True
else:
return False
print is_... |
#!/usr/bin/env python3
"""
File: classify_gender.py
------------------------
Script for classifying gender using face embeddings.
Example
-------
in_path: output_dir
out_path: output_dir
where 'output_dir' contains video output subdirectories
outputs
output_dir/
├── video1
... |
notification_dict = {}
def register_notification_class(notification_class):
"""
register_notification_class
"""
notification_dict[notification_class.__name__] = notification_class
def get_notification_class(notification_class_name):
if notification_class_name not in notification_dict:
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-09 16:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('extravehicular', '0001_initial'),
]
operations = [... |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import tensorflow as tf
from data import load_dataset
from models import knowledge_distillation_models
from tensorflow.python.keras.optimizers import SGD
net_size = 6
net_type = "resnet"
weights_file = "/Users/blakeedwards/Desktop/remote-files/ES... |
from dataclasses import dataclass, field
from pandas import DataFrame, Timedelta
from math import floor, ceil
import frontur_utilities.constants as const
@dataclass(unsafe_hash=True)
class Flight:
flight_entry: DataFrame = field(repr=False, hash=False)
seats_used: float = field(default=.8, repr=False, metadata... |
import tensorflow as tf
import constants
import data.preprocessing.preprocessing as preprocessing
import helpers
class Dataset:
def __init__(self, dataset_name: str, tiny: bool = True):
if dataset_name == '':
self.dataset_name = 'FAKE'
self.n_classes = 80
self.tiny = t... |
import asyncio
from dffml import (
MeanSquaredErrorAccuracy,
Features,
Feature,
train,
accuracy,
predict,
)
from myslr import MySLRModel
async def main():
# Configure the model
model = MySLRModel(
features=Features(Feature("Years", int, 1)),
predict=Feature("Salary", ... |
from cardboard import types
from cardboard.ability import (
AbilityNotImplemented, spell, activated, triggered, static
)
from cardboard.cards import card, common, keywords, match
@card("Awakener Druid")
def awakener_druid(card, abilities):
def awakener_druid():
return AbilityNotImplemented
retur... |
# Copyright (c) 2019 SSL-Roots
#
# 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, copy, modify, merge, publish, distribut... |
# Generated by Django 3.1 on 2021-12-07 13:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0011_auto_20211207_0821'),
]
operations = [
migrations.RenameField(
model_name='newuserinfo',
old_name='IMS_Member_ID... |
import numpy as np
import numpy.random as npr
def radixsort(lst):
"""Integer only"""
finished = False
low_order = 1
while not finished:
buckets = [[] for _ in range(10)]
for elem in lst:
digit = (elem // low_order) % 10
buckets[digit].append(elem)
j = 0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.
#
def test_query_large_result_set(conn_cnx, db_parameters):
"""
[s3] Get Large Result set
"""
number_of_rows = 50000
with conn_cnx(
user=db_parameters['s3_user'],
... |
from ...core.utils import dictionary, py3, general
from ...core.devio import data_format, interface
from ...core.dataproc import image as image_utils
import numpy as np
import contextlib
import time
import collections
from . import IMAQdx_lib
lib=IMAQdx_lib.lib
try:
lib.initlib()
except (ImportError, OSError):
... |
SERVER_ERROR_500 = ({"message": "An error occured."}, 500)
NOT_FOUND_404 = ({"message": "Resource could not be found."}, 404)
NO_INPUT_400 = ({"message": "No input data provided."}, 400)
INVALID_INPUT_422 = ({"message": "Invalid input."}, 422)
ALREADY_EXIST = ({"message": "Already exists."}, 409)
DOES_NOT_EXIST = ({"m... |
from django.urls import path
__all__ = [
"urlpatterns",
]
from trench.views import (
MFAConfigView,
MFAListActiveUserMethodsView,
MFAMethodActivationView,
MFAMethodBackupCodesRegenerationView,
MFAMethodConfirmActivationView,
MFAMethodDeactivationView,
MFAMethodRequestCodeView,
MFA... |
import sys
import pathlib
def setup():
BASE_PATH = pathlib.Path(__file__).parent.parent
base_path = BASE_PATH.absolute().as_posix()
sys.path.append(base_path)
|
import time
import pandas as pd
from options.train_options import TrainOptions
from utils import create_dataset
if __name__ == '__main__':
opt = TrainOptions().parse() # training options
dataset = create_dataset(opt) # initialize and preprocess dataset
dataset_size = len(dataset)
... |
#
# PySNMP MIB module ADTRAN-AOS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:58:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-09-05 10:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20160317_2129'),
]
operations = [
migrations.AddField(
... |
""" For quickly writing key cluster properties to previously opened output files
"""
__author__ = "Jeremy J Webb"
__all__ = [
"extrct_out",
"rho_prof_out",
"alpha_prof_out",
"sigv_prof_out",
"eta_prof_out",
"snapout",
"fortout",
"gyrout",
]
import numpy as np
from galpy.util import bov... |
def add(n):
def inner(x):
return x + n
return inner |
r"""
Isogenies
An isogeny `\varphi: E_1\to E_2` between two elliptic curves `E_1` and
`E_2` is a morphism of curves that sends the origin of `E_1` to the
origin of `E_2`. Such a morphism is automatically a morphism of group
schemes and the kernel is a finite subgroup scheme of `E_1`. Such a
subscheme can either be gi... |
# -*- encoding: utf-8 -*-
"""
mkarate度数横着的柱状图
"""
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import seaborn as sns
from model.multiscale_HSD import MultiHSD
from tools.hierarchy import read_hierarchy
def fetch_data():
# 获取mkarate节点度数
# 邻域(4-hop)节点总个数 vs 直接邻居个数
graph = nx.... |
#!/usr/bin/python
"""Example script for SCP write"""
from __future__ import print_function
import argparse
import socket
import os
import sys
from datetime import datetime
from ssh2.session import Session
parser = argparse.ArgumentParser()
parser.add_argument('source', help="Source file to copy")
parser.add_argu... |
# Copyright 2014 NeuroData (http://neurodata.io)
#
# 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 ag... |
#!/usr/bin/env python3
from pylsl import StreamInlet, resolve_byprop
# first resolve an EEG stream on the lab network
print("looking for an Empatica E4 stream...")
streams = resolve_byprop('type', 'wristband')
# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])
while True:
# get a new s... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from audio_processing import dynamic_range_compression
from audio_processing import dynamic_range_decompression
from stft import STFT
from pytorch_revgrad import RevGrad
class LinearNorm(torch.nn.Mod... |
'''
$Author: yanfei.shi@hp.com $
$Date: 2013-10-14 08:12:13 -0500 (Mon, 14 Oct 2013) $
$Header: https://svn02.atlanta.hp.com/local/ic4vc-dev/server/trunk/src/portlets/network.py 5942 2013-10-14 13:12:13Z yanfei.shi@hp.com $
$Id: network.py 5942 2013-10-14 13:12:13Z yanfei.shi@hp.com $
$Revision: 5942 $
'''
'''
... |
"""Support for MyBMW button entities."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
import logging
from typing import TYPE_CHECKING, Any
from bimmer_connected.vehicle import MyBMWVehicle
from bimmer_connected.vehicle.remote_services import Remo... |
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.signals import request_finished
from django.utils.safestring imp... |
#######################
# Dennis MUD #
# alter_item.py #
# Copyright 2018-2020 #
# Michael D. Reiley #
#######################
# **********
# 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 t... |
#!usr/bin/python
# -*- coding:utf8 -*-
# Feature: Keyword only arguments
# 限定关键字参数需要指定参数名传入
def add(a, b, *, c):
return a + b + c
print(add(1, 2, c=3)) |
# Copyright (C) 2017-2019 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# 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 th... |
# -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class AuthorizeController(Controller):
def get(self):
"""
.. test::
expect(10, code=200, text='unauthorized')
expect(21, code=200, text='testuser')
expect(23, code=20... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.mplot3d import Axes3D
from scipy import integrate
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# MISCELLANEOUS ... |
# Kontsioti, Maskell, Dutta & Pirmohamed, A reference set of clinically relevant
# adverse drug-drug interactions (2021)
# Creates a single output file for single-drug ADRs, indications and negative controls
## BNF - ADRs
single_drug_adr_bnf = pd.read_csv(
"event_mapping/output/bnf_single_mapped_with_eventnames.cs... |
import math
import random
import pygame
from pygame import mixer
pygame.init() # initialize pygame
total_bullet = 0
total_score = 0
enemy_killed = 0
textX = 10
textY = 10
height = 600
width = 800
flag = False
player_life = 5
armour_health = 12
GREEN = (0, 255, 0)
RED = (255, 0, 0)
screen = pygam... |
"""Main function."""
import argparse
def cli():
"""CLI function to parse CLI arguments.
Returns:
args: dict -- CLI arguments
"""
parser = argparse.ArgumentParser(description='CVM crawler CLI')
# name
parser.add_argument('name', type=str, nargs='?', default='World',
... |
import datetime
import netCDF4
import numpy as np
from random import randint
from PIL import Image
from PIL import ImageDraw, ImageFont
font = ImageFont.truetype("../fonts/FreeSans.ttf", 12)
fileOutDir="../datasets"
dimsset = {
'netcdf_5dims/netcdf_5dims_seq1/nc_5D_20170101000000-20170101001000.nc':{
'time':{
... |
# --------------------------------------------------------
# OpenVQA
# Written by Yuhao Cui https://github.com/cuiyuhao1996
# --------------------------------------------------------
import os
class PATH:
def __init__(self):
self.init_path()
# self.check_path()
def init_path(self):
... |
import argparse
from keras.preprocessing.image import ImageDataGenerator
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-w', '--weight', type=str, help='weight h5 file')
parser.add_argument('-v', '--validation', type=str, help='validation/test file')
args = parser.parse_ar... |
from mdutils.mdutils import MdUtils
import os
import argparse
import glob
from pathlib import Path
import pypandoc
import json
import tempfile
from pyveg.src.azure_utils import download_rgb, download_summary_json
def get_collection_and_suffix(collection_name):
"""
Lookup collection and suffix based on the na... |
from os.path import isfile, getsize
import json
from threading import Lock
# A database alternative for saving queues
# queues and queue of each download are saved as 2 files "QUEUES" and "DOWNLOAD_QUEUE"
# files are read on launch and written when changed
# data and files are protected from other threads by lock
# if... |
import random
print("H A N G M A N")
words = ['python', 'java', 'kotlin', 'javascript']
word = ""
status = ""
def reveal_letter(_guess):
global status
out = ""
for index, letter in enumerate(word):
if letter == _guess:
out = out + _guess
else:
out ... |
#方差选择法
#使用方差选择法,先要计算各个特征的方差,然后根据阈值,选择方差大于阈值的特征。使用feature_selection库的VarianceThreshold类来选择特征的代码如下:
from sklearn.feature_selection import VarianceThreshold
#方差选择法,返回值为特征选择后的数据 #参数threshold为方差的阈值
from sklearn.datasets import load_iris
iris = load_iris()
#print(VarianceThreshold(threshold=3).fit_transform(iris.data))
sele... |
import segfault
segfault.segfault()
|
# classes for plotting
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from pymatgen.core.periodic_table import Element
mpl.rcParams["savefig.directory"] = os.chdir(os.getcwd())
mpl.rcParams["savefig.format"] = 'pdf'
#TODO: clean this class a bit
class Plotte... |
from graphs import Graph
def printGraph(graph):
print(graph.adjancencyList)
print()
def testAddVertex():
graph = Graph()
graph.addVertex("A")
graph.addVertex("B")
graph.addVertex("C")
printGraph(graph)
return graph
def testAddEdge():
graph = testAddVertex()
graph.addEdge("A... |
from pushpy_examples.client.ex_push_manager import ExamplePushManager
m = ExamplePushManager()
m.connect()
local_tasks = m.local_tasks()
# execute a simple lambda on the host
print(local_tasks.apply(lambda: 1 + 1))
def do_pi(k):
import math
return math.pi * k
repl_code_store = m.repl_code_store()
# stor... |
n=int(input())
ans=0
for i in range(n):
x=[*map(int,input().split())]
if len(set(x))==1:
ans=max(ans,50000+x[0]*5000)
elif len(set(x))==2:
if x.count(x[0])==3: key=x[0]
elif x.count(x[1])==3: key=x[1]
elif x.count(x[2])==3: key=x[2]
elif x.count(x[3])==3: key=x[3]
else:
temp=2000
for _ in set(x): t... |
"""
A callback to register for a :class:`~msl.equipment.resources.thorlabs.kinesis.motion_control.MotionControl`
message queue.
.. code-block:: python
from msl.equipment import Config
from msl.equipment.resources.thorlabs import MotionControlCallback
@MotionControlCallback
def msg_callback():
prin... |
from enum import Enum
class Precision(Enum):
NANO_SECONDS = 9
SECONDS = 0
|
#! /usr/bin/env python
# Copyright (C) 2022 Pedro Ilídio <ilidio@alumni.usp.br>
# License: 3-clause BSD
from setuptools import setup, Extension, find_packages
from pathlib import Path
from Cython.Build import cythonize
import numpy
PATH_ROOT = Path(__file__).parent
README = (PATH_ROOT/"README.md").read_text()
# Get _... |
###################################################################################
#
# Copyright (C) 2017 MuK IT GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation,... |
from time import sleep
from unittest import TestCase, skip
import mockserver as mk
from common.message_registrar import MessageRegistrar
from common.queue_pusher import QueuePusher
import json
_predefined_message = {"message_type": "error",
"message": {"chat_id": 12, "text": "Hello"}}
class T... |
from pathlib import Path
from types import MethodType
from typing import Dict, Iterable, Tuple, Callable
import torch
from homura.callbacks import Callback
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from .containers import Map
from .miscs import check_path
from .runner import R... |
from marko.parser import Parser # type: ignore
from marko.block import Heading, Paragraph, CodeBlock, List # type: ignore
from marko.inline import CodeSpan # type: ignore
from langcreator.common import Generators, InputOutputGenerator, tag_regex, get_tags, builtin_generators
import collections
import re
def parse(... |
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from typing import Any, Dict, Optional
from discord.ext.commands import Bot
__all__ = ("CommanderBotBase",)
class CommanderBotBase(ABC, Bot):
@property
@abstractmethod
def started_at(self) -> datetime:
...
@propert... |
from collections import OrderedDict
expected = [
OrderedDict(
[
("title", u"Appendix 5"),
(
"content",
[
OrderedDict(
[
("type", "section"),
("id", u"s... |
# Generated by Django 3.0.5 on 2020-05-15 05:44
import datetime
from django.db import migrations, models
import django.utils.timezone
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20200514_1833'),
]
operations = [
migra... |
#
# 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 us... |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: onos/ransim/metrics/metrics.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import AsyncIterator, Dict, List
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
import grpclib
class EventType... |
import configparser
from os.path import expanduser
from os import environ
if 'PYBLIOMETRICS_CONFIG_FILE' in environ:
CONFIG_FILE=environ['PYBLIOMETRICS_CONFIG_FILE']
else:
CONFIG_FILE = expanduser("~/.scopus/config.ini")
try:
config = configparser.ConfigParser()
config.optionxform = str
config.rea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual("foo".upper(), "FOO")
if __name__ == "__main__":
unittest.main()
# vim:set et sts=4 ts=4 ... |
#!python3
import fnmatch
from setuptools import setup
from setuptools.command.build_py import build_py as build_py_orig
import codecs
import os.path
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
def... |
# This script is runs S2S-LHSPA1-{2,3,4,5}{+Type} models.
from typing import *
from seutil import IOUtils
from shared import *
import argparse
import os
import yaml
parser=argparse.ArgumentParser()
parser.add_argument('-mode', '--mode', required=True,
default='train',
type=st... |
from django.db import models
# Create your models here.
class BookInventory(models.Model):
author = models.CharField(max_length=50, default='Anonymous')
title = models.CharField(max_length=250, default="No Title")
number_of_pages = models.IntegerField()
published_date = models.DateField(default='19... |
import os
from pathlib import Path
from piper.cli.base import PiperCommand
from piper.config.pipe import Pipe
from piper.tools.venv import Virtualenv
class Setupper(PiperCommand):
def _phase_name(self) -> str:
return "setup"
def _manage(self, pipe: Pipe):
# Prepare the requi... |
"""Implementation of the 'trim' command.
"""
from collections import Sequence, defaultdict
import logging
import os
import sys
import textwrap
from atropos.commands.base import (
BaseCommandRunner, Summary, Pipeline, SingleEndPipelineMixin,
PairedEndPipelineMixin)
from atropos.commands.stats import (
Single... |
# Copyright 2018 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... |
from collections import defaultdict
from itertools import chain
from django.http import JsonResponse
from django.views import View
from dashboard.es_models import TripRecord, DayCounter
from utils.es_utils import EsAggBuilder
from elasticsearch_dsl import Q
from utils.locations import LOCATION_DICT
from utils.messag... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .auto_provisioning_group import *
from .auto_snapshot_policy import *
from .command im... |
import pytest
from model_bakery import baker
from pypro.modulos import facade
from pypro.modulos.models import Modulo
@pytest.fixture
def modulos(db):
titulos = ['antes', 'depois']
return [baker.make(Modulo, titulo=t) for t in titulos]
def test_listar_modulos_ordenados(modulos):
assert list(sorted(modu... |
import json
class TestUserResourceEndpoints:
def test_user_login_successfull(self, client, new_user):
""" Test for a successful user login """
response = client.post(
"/api/v1/user/login",
data=json.dumps(
{
"email": new_user.email,
... |
# Generated by Django 2.0 on 2018-05-18 03:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dal', '0006_auto_20180517_0815'),
]
operations = [
migrations.AddField(
model_name='quickloginrecord',
name='update_ti... |
import matplotlib.pyplot as plt
import pandas as pd
import os
filename = os.path.dirname(os.path.abspath(__file__)) + "/data/" + "data.csv"
df = pd.read_csv(filename)
df.plot(x='t')
plt.show()
|
# type: ignore
# ^ ignore typing because legacies were entirely
# copied from vkbottle 2.x without quality insurance
from typing import List
from warnings import warn
from vkbottle.modules import json
def keyboard_gen(pattern: List[List[dict]], one_time: bool = False, inline: bool = False):
""" Simple keyboard ... |
from Config import Config
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
class Telegram:
def __init__(self, fac... |
import sys
class Horse(object):
"""
given a string like: neineighghneigh, count the number of horses (neigh)
"""
def countHorse(self, s):
dic = {val: idx for idx, val in enumerate("neigh")}
counts = [0, 0, 0, 0, 0]
ans = 0
for idx, ch in enumerate(s):
counts[... |
from django.conf import settings
from django.urls import path
from jackpot import views
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
from . views import freetips, singlebet, results
app_name = 'jackpot'
urlpatterns = [
path('singlebet/', views.singlebet, name='si... |
#!/usr/bin/python3
import os
import sys
from getpass import getuser
from shutil import copy2
from PIL import Image
from datetime import datetime, timedelta
PATH_SDCARD = '/media/' + str(getuser()) + '/disk'
PATH_SERVIDOR = '/home/calmanet/arquivos/'
HTML_INDICE = PATH_SERVIDOR + 'indice_de_fotos.html'
THUMBS_HTML = '... |
#!/localdisk/python3-venv/bin/python
import cv2
import matplotlib.pyplot as plt
import numpy as np
def canny(image):
gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
canny = cv2.Canny(blur, 50, 150)
return canny
def display_line(image, lines):
line_image = np.zeros_like(image... |
# Copyright 2016 Google Inc. 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 applicable law or a... |
# Generated by Django 2.1.7 on 2019-09-30 06:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settin... |
# Source : https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
# Author : Fish.Yu
# Date : 2017-12-26
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def aver... |
from .scraper import Scraper
from .quoras import Quoras
from .browser import Browser
|
"""
Question: Best Time to Buy and Sell Stock II
Difficulty: Medium
Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Ref: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
You are given an integer array prices where prices[i] is the price of a given stock on the... |
import string
alphabetList = list(string.ascii_lowercase)
def countchar(x):
lst = [0] * 26
for i in range(len(x)):
# confirm number only
if x[i] >= 'a' and x[i] <= 'z':
# ord function to get the value of the alphabet a = 97 b = 98 c = 99.
# from finding the different bet... |
from django.test import TestCase
from dojo.tools.aws_prowler.parser import AWSProwlerParser
from django.utils import timezone
from dojo.models import Test, Engagement, Product, Product_Type, Test_Type
class TestAwsProwlerParser(TestCase):
def setup(self, testfile):
product_type = Product_Type(critical_pr... |
"""
mark domains/boundaries with dolfin MeshFunctions
"""
from dolfin import *
from importlib import import_module
from math import sqrt, pow
synonymes = {
"fluid":{"bulkfluid","pore"},
"pore": "porecenter",
"sin":"membrane",
"molecule":"dna",
"moleculeb":"dnab",
"solid":{"dna", "membrane"},
... |
import RPi.GPIO as GPIO
from hx711 import HX711
from Speaker import Speaker
class Scale:
def __init__(self):
self.hx =HX711(24, 23)
self.hx.set_reading_format("MSB", "MSB")
self.hx.set_reference_unit(255) # unit needs updating
self.hx.reset()
self.hx.tare()
self.limit = 1500 # trash limit
def checkWeigh... |
from compare import expect
from nose.plugins.attrib import attr
from simplads.simplad_monad.simplad_base_helper import Bound
import unittest
from simplads import Bundle
from simplads import MaybeSimplad, MaybeDeltaMaker
from simplads import WriterDeltaMaker
from simplads import ReaderDeltaMaker
from simplads import f... |
def clear():
import os
try:
os.system('clear')
except:
os.system('cls')
def pause():
input("Pressione ENTER para continuar: ")
def linha(char='-', tam=50):
return char * tam
def cabecalho(txt: str):
from termcolor import colored
print(linha())
... |
'''
Random exceptions for the program
'''
from paramiko.ssh_exception import AuthenticationException
class InvalidDetfile(Exception):
'''
We need a detfile
'''
pass
class NoConnection(Exception):
'''
We need a detfile
'''
pass
class HostNotFound(Exception):
'''
Thrown whenev... |
"""
Copyright (c) 2021 Elix, Inc.
"""
from .abstract_explainer import AbstractExplainer
from .d_mpnn import DirectedMessagePassingNetwork
from .gcn import GraphConvNetwork
|
from datetime import datetime
from casexml.apps.stock.const import TRANSACTION_TYPE_LA, SECTION_TYPE_STOCK
from casexml.apps.stock.models import StockTransaction, StockReport
from corehq.apps.commtrack.models import StockState
from corehq.apps.products.models import SQLProduct
from custom.ilsgateway.tanzania.handlers.k... |
# -*- coding: utf-8; -*-
from setuptools import setup
setup(name='emojipy',
version='0.1',
description='Python wrapper for emojione',
author='Kaviraj Kanagaraj',
author_email='kaviraj@launchyard.com',
packages=['emojipy',],
test_suite='emojipy.tests',
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.