content stringlengths 5 1.05M |
|---|
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... |
import pygame
from game import Game
# print(pygame.font.get_fonts())
def main():
g = Game()
# g.disspiate() # deubg
g.start()
if __name__ == "__main__":
main() |
# 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! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from time import perf_counter_ns
from nubia.internal.typing import argument, command
from bitarray import bitarray
from bitarray.util import int2ba, ba2int
from tausworthe import TausworthePRN
import matplotlib.pyplot as plt
from numpy import cos, histogram, log, pi, sin, sqrt
SEED_DEFAULT = 42424242424242
# Number o... |
#!/usr/bin/env python3
# Automatically generated file by swagger_to. DO NOT EDIT OR APPEND ANYTHING!
"""Implements the client for test."""
# pylint: skip-file
# pydocstyle: add-ignore=D105,D107,D401
import contextlib
import json
from typing import Any, BinaryIO, Dict, List, MutableMapping, Optional
import requests
i... |
from python_helper import log
from globals import newGlobalsInstance
globalsInstance = newGlobalsInstance(
__file__,
successStatus = True,
errorStatus = True,
infoStatus = True,
# debugStatus = True,
failureStatus = True
)
log.info(__name__, 'Importiong libraries')
import time
import numpy as ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import tensorflow.compat.v1 as tfv1
from google.protobuf import text_format
def main():
# Load and export as string
with tfv1.gfile.FastGFile(sys.argv[1], "rb") as fin:
graph_def = tfv1.GraphDef()
graph_def.ParseFromString(fin.read())
... |
# -*- coding: utf-8 -*-
from ..scraper import make_scraper, _ParserScraper
def add(name, relativeUrl):
attrs = dict(
name=name,
url='http://www.nitrocosm.com/go/' + relativeUrl,
imageSearch='//img[@class="gallery_display"]',
prevSearch='//a[@class="nav_btn_previous"]'
)
glo... |
import demistomock as demisto
from CommonServerPython import *
def compare(left, right):
return {
'ListCompare':
{
'LeftOnly': [x for x in left if x not in right],
'RightOnly': [x for x in right if x not in left],
'Both': [x for x in left if x in... |
#!/usr/bin/env python3
"""Script to monitor and display car battery state."""
from time import sleep
from datetime import datetime
from smbus import SMBus
import argparse
import subprocess
MIN_VOLTAGE = 3.3 * 3
MAX_VOLTAGE = 4.2 * 3
BAT_LOW_VOLTAGE = 3.6 * 3
BAT_VLOW_VOLTAGE = 3.5 * 3
BAT_CRIT_VOLTAGE = 3.35 * 3
VOLT... |
#-*-coding:utf-8;-*-
#qpy:2
#qpy:console
from binascii import b2a_hex
import socket, struct
from collections import namedtuple
import lytro
magic = 0xfaaa55af
Response = namedtuple('Response', ['magic', 'size', 'seq', 'command'])
class IpTarget(lytro.Target):
def __init__(self, address, timeout=1):
self.... |
import logging
import os
import shutil
import tempfile
import uuid
from pathlib import Path
from typing import Callable, Tuple, List, Text, Set, Union, Optional, Iterable
from rasa.shared.data import TRAINING_DATA_EXTENSIONS
from rasa.shared.nlu.training_data import loading as nlu_loading
logger = logging.getLogger(_... |
from .test_get_all_cars_with_avg_rating import GetAllCarsWithAvgRatingSelectorTest
from .test_get_all_cars_popularity import GetAllCarsPopularityTest
from .test_get_models_for_make import GetModelsForMakeTest
|
import pandas as pd
wb = pd.read_excel(
'/home/rogeriogama/Área de Trabalho/Projetos/tese/Dados/sigeo_dado.xlsx')
df = pd.DataFrame(wb)
df.to_csv('sigeo_dado.csv', sep=';', index=False)
|
# -*- coding: utf-8 -*-
import json
import unittest
import uuid
from datetime import datetime
from stix_shifter_modules.infoblox.entry_point import EntryPoint
class TestResultTranslatorMixin:
@staticmethod
def get_dialect():
raise NotImplementedError()
@property
def data_source(self):
... |
#
# 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... |
# -*- coding: utf-8 -*-
"""
chemdataextractor.doc
~~~~~~~~~~~~~~~~~~~~~
Document processing.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .document import Document
from .text import Text, ... |
import torch
from torch2trt_dynamic.torch2trt_dynamic import *
def get_intwarper_trt(other, ctx):
if isinstance(other, IntWarper):
return other._trt
elif isinstance(other, int):
return ctx.network.add_constant((1,), np.array([other], dtype=np.int32)).get_output(0)
else:
ret... |
#! /usr/local/bin/python3
from my_nba.client import NBAClient
from my_nba.downloaders.player import PlayerDownloader
from my_nba.downloaders.team import TeamDownloader
from my_nba.downloaders.scoreboard import ScoreboardDownloader
import logging
import argparse
# TODO: logging include datetime
class MyNBA():
def... |
"""
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The soluti... |
import gedit
from fuzzyopen import FuzzyOpenPluginInstance
# STANDARD PLUMMING
class FuzzyOpenPlugin( gedit.Plugin ):
DATA_TAG = "FuzzyOpenPluginInstance"
def __init__( self ):
gedit.Plugin.__init__( self )
def _get_instance( self, window ):
return window.get_data( self.DATA_TAG )
def _set_instance(... |
"""
This script is strictly for debugging the functions in
'reformat_exp_data.py' and is __not__ meant to be included
in tkinter bundles/the app itself (see README file for info on that).
"""
import reformat_exp_data
test_input_dir = (
'debug_data'
)
test_output_dir = (
'debug_data/debug_data_output'
)
reform... |
import logging
from .. import entities, repositories, exceptions, miscellaneous, services
logger = logging.getLogger(name=__name__)
class Pipelines:
"""
Pipelines Repository
"""
def __init__(self, client_api: services.ApiClient, project: entities.Project = None):
self._client_api = client_ap... |
from rest_framework import generics
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework import status
from xos.apibase import XOSRetrieveUpdateDestroyAPIView, XOSListCreateAPIView
from rest_framework import viewsets
from django.conf.urls import patterns, url
from xos.... |
from abc import ABC, abstractmethod
class IContent:
def format(self, format, content=None, available_formats={}):
if not format.lower() in available_formats:
raise TypeError(f"Does not support {format}")
if not content:
raise TypeError("Must provide content")
retur... |
# Copyright 2016 Pinterest, Inc.
#
# 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 writi... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#############################################
# File Name: setup.py
# Author: rarnu
# Mail: rarnu1985@gmail.com
# Created Time: 2021-10-18 10:23:35
#############################################
from setuptools import setup, find_packages
setup(
name = "isyscore",
... |
{"filter":false,"title":"urls.py","tooltip":"/nodasf/urls.py","undoManager":{"mark":100,"position":100,"stack":[[{"start":{"row":24,"column":53},"end":{"row":24,"column":54},"action":"insert","lines":[","],"id":398}],[{"start":{"row":24,"column":54},"end":{"row":24,"column":55},"action":"insert","lines":[" "],"id":399}... |
from macaque import cli
cli.cli()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 15:19:11 2019
@author: Austin Hsu
"""
import torch
from torch import nn
from torch.autograd import Variable
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import torch.utils.data as data_utils
import numpy as np
import scipy.ndimage
i... |
from ._keyboard import get_key
def get_int_from_user(message, min_, max_) -> int:
"""
Return an integer in range [a, b] (both included) input by user.
"""
error_msg = 'invalid input, try again'
while True:
print(message)
inp = input(f' ({min_}-{max_})>')
try:
in... |
from data.s2 import read_all
from data import batch_jsonl_parsed, upload_parallel
from solr.instances import get_localhost_session
import json
"""
export interface Document {
id: string;
year?: number;
s2Url: string; -> source_url
journalVolume: string; -> volume
journal... |
"""Added Shopitem Vote model
Revision ID: 67cef492a609
Revises: ff8f2393e045
Create Date: 2018-03-28 01:22:36.116246
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '67cef492a609'
down_revision = 'ff8f2393e045'
branch_labels = None
depends_on = N... |
import argparse
import os
import pickle
from typing import Tuple
import torch
from torch import nn
import simulation.utils.machine_learning.data as ml_data
from simulation.utils.machine_learning.cycle_gan.configs.test_options import (
CycleGANTestOptions,
WassersteinCycleGANTestOptions,
)
from simulation.util... |
import argparse
import glob
from pathlib import Path
import mayavi.mlab as mlab
import numpy as np
import torch
from pcdet.config import cfg, cfg_from_yaml_file
from pcdet.datasets import DatasetTemplate
from pcdet.datasets import KittiDataset
from pcdet.models import build_network, load_data_to_gpu
from pcdet.utils ... |
# Copyright 2018 The Cornac 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 applicable ... |
from django.contrib import admin
from imagekit.admin import AdminThumbnail
from .models import Icon
@admin.register(Icon)
class IconAdmin(admin.ModelAdmin):
list_display = ('name', 'icon_thumbnail')
icon_thumbnail = AdminThumbnail(image_field='thumbnail')
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
# DO NOT EDIT! This file is automatically generated
import datetime
import enum
import typing
import attr
from commercetools.types._base import PagedQueryResponse, Update, UpdateAction
from commercetools.types._common import Reference, ReferenceTypeId, Resource
if typing.TYPE_CHECKING:
from ._common import Addr... |
import numpy as np
import tensorflow as tf
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
# Store the MNIST data in a folder
# one_hot = True -> see explanation of one hot
mnist = input_data.read_data_sets("mnist_data/", one_hot=True)
# For this example, only 5000 images are... |
import numpy as np
from ev3sim.devices.base import IDeviceInteractor, Device
from ev3sim.devices.compass.base import CompassSensorMixin
from ev3sim.objects.utils import local_space_to_world_space
from ev3sim.simulation.loader import ScriptLoader
class CompassInteractor(IDeviceInteractor):
name = 'COMPASS'
de... |
import numpy as np
from numba import njit, prange
from tssearch.utils.preprocessing import standardization
@njit(parallel=True, fastmath=True)
def _cost_matrix(x, y):
"""
Parameters
----------
x: nd-array
Time series x (query).
y: nd-array
Time series y.
Returns
-------
... |
# -*- coding: utf-8 -*-
from lxml import etree
from threaded_crawler import threaded_crawler
def scrape_callback(url, html):
if url.endswith('.xml'):
# Parse the sitemap XML file
tree = etree.fromstring(html)
links = [e[0].text for e in tree]
return links
else:
# Add s... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListLogStreamResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
... |
from urllib.parse import parse_qsl
def parse_qs_single(qs):
return dict(parse_qsl(qs))
def wnlemma_to_analy_lemma(wnlemma):
return wnlemma.lower().replace("_", " ").strip("-")
|
# ------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
# ------------------------------------------------------------------------------
# Copyright (C) 2019 EOX IT Services GmbH
#
# Permission... |
from typing import List
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
res = set()
for word1 in words:
for word2 in words:
if word1 != word2 and word1 in word2:
res.add(word1)
... |
import json
import re
from localstack.services.apigateway.integration import ApiGatewayVtlTemplate
from localstack.utils.aws.templating import render_velocity_template
# template used to transform incoming requests at the API Gateway (forward to Kinesis)
APIGW_TEMPLATE_TRANSFORM_KINESIS = """{
"StreamName": "stre... |
class Solution(object):
def __init__(self, w):
"""
:type w: List[int]
"""
self.total = 0
self.res = []
for i in w:
self.total += i
self.res.append(self.total)
def pickIndex(self):
"""
:rtype: int
"""
target = random.randint(0,self.total-1)
begin,end = 0,len(self.res)-1
while begin<e... |
import unittest
from ligature.recordset import RecordSet
from ligature.examples import simpleRecordSet, simpleAddition
from ligature.calculations.cluster import Cluster
class ClusterTestCase(unittest.TestCase):
def test_basic(self):
function = lambda a,b: a+b
srs = RecordSet(simpleRecordSet)
c = Clust... |
from pydantic import Field
from typing import Optional, List, Dict
from sirena_client.base.models.base_client_request import RequestModelABC
class GetOrder(RequestModelABC):
rloc: str = Field(description="Номер PNR")
last_name: str = Field(description="Фамилия любого из пассажиров")
version: Optional[in... |
from DetectingLoops import *
class Function(object):
def __init__(self, name, start_line_text, start_line_no, end_line_text, end_line_no):
self.name = name
self.start_line_text = start_line_text
self.end_line_text = end_line_text
self.start_line_no = start_line_no
self.end_... |
from output.models.nist_data.atomic.g_day.schema_instance.nistschema_sv_iv_atomic_g_day_max_exclusive_4_xsd.nistschema_sv_iv_atomic_g_day_max_exclusive_4 import NistschemaSvIvAtomicGDayMaxExclusive4
__all__ = [
"NistschemaSvIvAtomicGDayMaxExclusive4",
]
|
# -*- coding: utf-8 -*-
from pynetworking.Feature import Feature
from pprint import pformat
import re
import json
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
class ats_mac(Feature):
"""
mac feature implementation for ATS
"""
... |
from .rust import (
rfib,
busy_fib,
hello_rust,
)
def fib(n: int) -> int:
return rfib(n)
def hello(input_text: str) -> None:
hello_rust(input_text)
|
from twisted.python import log
from django.conf import settings
from django.core import management
from django.core.management import call_command
from django.db import connection
from django.db import transaction, DEFAULT_DB_ALIAS
real_commit = transaction.commit
real_rollback = transaction.rollback
# real_enter_tr... |
# Copyright 2019 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... |
from setuptools import setup
from setuptools_rust import RustExtension
setup(
rust_extensions=[RustExtension("word_count.word_count", debug=False)],
)
|
import pytest
import respo
from tests.test_django_field.some_app.models import ExampleModel
@pytest.mark.django_db
def test_simple_model_creation_and_save():
respo_client = respo.RespoClient()
model = ExampleModel(respo_field=respo_client)
model.save()
model: ExampleModel = ExampleModel.objects.get(r... |
# Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
name: wordpress display-widgets插件后门漏洞
referer: http://www.nsfocus.com.cn/upload/contents/2017/09/20170915174457_73771.pdf
author: Lucifer
description: wordpress display-widgets Version 2.6.1——Version 2.6.3.1 geolocation.php存在后门。
'''
import sys
import requests
class w... |
"""Variables
@see: https://docs.python.org/3/tutorial/introduction.html
@see: https://www.w3schools.com/python/python_variables.asp
@see: https://www.learnpython.org/en/Variables_and_Types
Python is completely object oriented, and not "statically typed".
You do not need to declare variables before using them, or decl... |
from .endpoint import AiopikaEndpoint
from .exceptions import RoutingException
class Method(object):
"""
Class for storage handler endpoints and his identifier. This is analog of HTTP Route class.
"""
def __init__(self, handler: AiopikaEndpoint, identifier: str):
"""
Initialize of Met... |
from wx import *
from txt_constants import *
import sys
import os
import re
from datetime import datetime
class TextEditor(App):
def __init__(self):
super(TextEditor, self).__init__()
self.file_name = sys.argv[1]
self.data = ""
self.get_file_data()
self.window = self.create... |
import io
from typing import Iterable, Sequence
import click
from sqlalchemy.orm import joinedload
from aspen.config.config import Config
from aspen.database.connection import (
get_db_uri,
init_db,
session_scope,
SqlAlchemyInterface,
)
from aspen.database.models import Sample, UploadedPathogenGenome
... |
import json
from pymongo import MongoClient
# import json file
def import_json(name):
with open('data_files/' + name) as mydata:
d = json.load(mydata)
return d
# insert data into mongoDB
def insert_data():
# get the json file containing the data
myTripAdvisorRestaurants = import_json('tripadvisor_restaurants.... |
# DomirScire
def mysum(*numbers):
output = 0
for number in numbers:
output += number
return output
if __name__ == "__main__":
print(mysum(10, 20, 30, 40))
|
# -*- coding:utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals,
)
import json
import django
from django.core import checks
from django.db.models import Field, IntegerField, Transform
from django.utils import six
from django_mysql import forms
from django_mysql.checks ... |
import os
import time
import warnings
from dash.testing.application_runners import import_app
def take_snapshot(dash_duo, name):
target = "/tmp/dash_artifacts" if not dash_duo._is_windows() else os.getenv("TEMP")
try:
os.makedirs(target, exist_ok=True)
except OSError:
warnings.warn("Unab... |
from tqdm import tqdm
import torch
from protonets.utils import filter_opt
from protonets.models import get_model
def load(opt):
model_opt = filter_opt(opt, 'model')
model_name = model_opt['model_name']
del model_opt['model_name']
return get_model(model_name, model_opt)
def evaluate(model, data_loa... |
# This code is licensed under the MIT License (see LICENSE file for details)
from PyQt5 import Qt
class ColorDelegate(Qt.QStyledItemDelegate):
def createEditor(self, parent, option, midx):
if midx.isValid():
e = Qt.QColorDialog(parent)
e.setOption(Qt.QColorDialog.ShowAlphaChannel)
... |
from setuptools import find_packages, setup
setup(name="nnlib",
version="0.1",
description="These are various functions and tools around deep learning with fastai, tensorrt, labeling and so one.",
author="Johannes Metzler",
author_email='johannes.metzler@gmail.com',
platforms=["Any"]... |
from collections import Counter
class Solution:
def contains(self, set1: Counter, set2: Counter) -> bool:
for k in set2:
if set1[k] < set2[k]:
return False
return True
def helper(self, words: List[Counter], start: int, letters: Counter, score: List[int]) -> int:
... |
import os
import imp
import json
import codecs
import logging
def relative_path_to_abs(reference_path, relative_path):
# If reference path is a file eg. plugin json file get dirname
# and add the relative path to it
if os.path.isfile(reference_path):
reference_path = os.path.dirname(reference_path... |
import asyncio
import copy
import csv
import math
import queue
import threading
import uuid
import warnings
from datetime import datetime
from typing import List, Optional, Union, Callable, Coroutine, Iterable
import pandas
import pytz
from .dtypes import _termination_obj, Event
from .flow import Flow, Complete
from ... |
#!/usr/bin/env python
import subprocess
import json
urls = [
"https://www.apple.com/v/home/f/images/heroes/iphone-se/hero__dvsxv8smkkgi_large.jpg",
"https://www.apple.com/v/home/h/images/heroes/iphone-11-spring/hero__dvsxv8smkkgi_large.jpg",
"https://www.apple.com/v/home/h/images/heroes/iphone-11-pro-spring/hero__dvs... |
from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from django.conf import settings
from public_chat.models import PublicChatRoom
DEBUG = False
def public_chat_view(request, room_id):
context = {}
try:
room = PublicChatRoom.objects.get(id=room_id)
co... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2015 Dr. Ralf Schlatterbeck All rights reserved
# Reichergasse 131, A--3411 Weidling, Austria. rsc@runtux.com
# #*** <License> ************************************************************#
# This module is part of the package GTW.OMP.PAP.
#
# This module is licensed under th... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import warnings
import numpy as np
from niftynet.layer.base_layer import RandomisedLayer
warnings.simplefilter("ignore", UserWarning)
warnings.simplefilter("ignore", RuntimeWarning)
class RandomFlipLayer(RandomisedLayer):
"""
A... |
from models import *
from utils import *
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import json
import time
from time import sleep
import sys
import random
import os
from sklearn.metrics import f1_score
class Trainer:
def __init__(self, da... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
__all__ = ["LEFT_MENUS", "PRIVILEGE_PAGE_SIZE", "ACTIVE_WHEN_ADDED", "SITE_NAME",
"ACCESSIBLE_APPS", "GROUP_CACHE_KEY", "PERMISSION_CACHE_KEY"]
LEFT_MENUS = [
{"name": _("Permission Cente... |
import typing as t
from abc import ABC, abstractmethod
from flask import Request, Response
class BaseHTTPMiddleware(ABC):
"""
BaseHTTPMiddleware
A base class to create an HTTP Middleware by using dispatch function.
Inherit this class to make it
"""
@abstractmethod
def __init__(self):
... |
import csv
import cpsc2018
import os
import argparse
import numpy as np
import sys
'''
cspc2018_challenge score
Written by: Xingyao Wang, Feifei Liu, Chengyu Liu
School of Instrument Science and Engineering
Southeast University, China
chengyu@seu.edu.cn
'''
'''
Score the predic... |
# -*- encoding: utf-8 -*-
# Variables Flask
HOST = "127.0.0.0"
DEBUB = True
BCRYPT_LEVEL = 12
PORT = 5000
SECRET_KEY = 'Secret Key Default'
# Logging
LOG_PATH=logs/error.log
LOG_LEVEL=debug
# Variables SQLALCHEMY
SQLALCHEMY_ECHO = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
# Variable de conexión de SQLALCHEMY
SQLA... |
from __future__ import print_function
from __future__ import absolute_import
from .tesisfunctions import brightness,retinalmask,IMAGEPATH
import glob
import cv2
imlist= glob.glob("im*.jpg")
imlist.extend(glob.glob("good_*.jpg"))
for fn in imlist:
try:
img = cv2.imread(fn)
name = "masked_"+fn
... |
# Generated by Django 3.1.7 on 2021-05-09 21:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('connections', '0002_auto_20201224_1619'),
]
operations = [
migrations.AlterModelOptions(
name='controllersession',
options={... |
from HTMLParser import HTMLParser
filename = "bookmarks_10_13_16.html"
text = open(filename)
data = text.read()
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if len(attrs) != 0:
print "Encountered a attribute:", attr... |
__version__ = '35.4.0'
|
'''
Code inspired from the official repository https://github.com/cg563/simple-blackbox-attack
'''
import torch
import cv2
import matplotlib.pyplot as plt
import logging as log
def simba(x, y, model, num_iters=10000, epsilon=0.1):
num_pixels = x.reshape(1, -1).size(1)
# get a random permutation o... |
import logging
import serial.tools.list_ports
from message_handler import MessageHandler
from transceiver import Transceiver
class TransceiverManager:
def __init__(self, handler: MessageHandler, port_filter='/dev/ttyUSB[0-9]+'):
self.log = logging.getLogger('manager')
self.handler = handler
... |
"""600. Smallest Rectangle Enclosing Black Pixels
"""
class Solution:
"""
@param image: a binary matrix with '0' and '1'
@param x: the location of one of the black pixels
@param y: the location of one of the black pixels
@return: an integer
"""
def minArea(self, image, x, y):
# write... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
from setuptools import setup
setup(name='Deviency_Score', version='0.1', packages=['Deviency_Score'])
|
from django.contrib import admin
from core.models import Trial
class TrialAdmin(admin.ModelAdmin):
pass
admin.site.register(Trial, TrialAdmin)
# Register your models here.
|
'''connector.py'''
import csv
with open("albums.csv") as albums:
albums_dict = {} # Using dictionary to match key:value pairs
file = csv.reader(albums)
for line in file:
if line[1] not in albums_dict.keys():
albums_dict[line[1]] = line[0]
with open("artists.csv") as artists:
artis... |
from parafermions.MPO import MPO
import time
import numpy as np
import scipy as sp
class CommutatorOp(MPO):
"""
Class for MPO representations of commutators.
"""
def __init__(self, N, t, D, mu, U, Nw, Pw, dtype=np.dtype('complex128')):
"""
Constructor of MPO commutator class.
... |
# Python3 version of code
import bbplotter
import json
# global dictionaries
# pdict: conversion of json file to dictionary of players and their batted ball numbers
# stat_dictionary: stores certain playerbase stats, i.e. number of players in pdict
# axes_dictionary: player[key] -> string, where string is full name of... |
from machine import Pin
from time import sleep
# GP4 - IN
relay_pin = Pin(4, Pin.OUT)
while True:
print("turn on relay!")
relay_pin.value(1)
sleep(5)
print("turn off relay!")
relay_pin.value(0)
sleep(5) |
import dask
from dask.threaded import *
from contextlib import contextmanager
from dask.utils import raises
from operator import add, mul
fib_dask = {'f0': 0, 'f1': 1, 'f2': 1, 'f3': 2, 'f4': 3, 'f5': 5, 'f6': 8}
def test_start_state():
dsk = {'x': 1, 'y': 2, 'z': (inc, 'x'), 'w': (add, 'z', 'y')}
result = ... |
from sys import stdin
bottom = int(stdin.readline())
top = stdin.readline().split()
first = 0
for n in top:
if n != "-1":
first += int(n)
else:
bottom -= 1
print float(first) / float(bottom)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.