content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from flask_wtf import FlaskForm
from wtforms import DecimalField, StringField, SubmitField
from wtforms.validators import DataRequired
class UpdateRatingMovieForm(FlaskForm):
new_rating = DecimalField("Your Rating Out of 10 e.g. 7.5", validators=[DataRequired()])
new_review = StringField("Your Review", validat... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt._1btcxe import _1btcxe
class getbtc (_1btcxe):
def describe(self):
return self.deep_extend(super(getbtc, self).des... | nilq/baby-python | python |
from __future__ import print_function
from __future__ import absolute_import
import myhdl
from myhdl import instance
# @todo: move "interfaces" to system (or interfaces)
from ...cores.sdram import SDRAMInterface
from ...system import MemoryMapped
# @todo: utilize FIFOBus
from ...system import FIFOBus
def sdram_co... | nilq/baby-python | python |
array = []
for i in range (16):
# array.append([i,0])
array.append([i,5])
print(array) | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from Data_Structure.Linked_List import *
print("** Singly Linked List **")
list1 = Singly_Linked_List.Singly_Linked_List()
for i in range(1, 11):
list1.append(i)
print... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 26 05:59:46 2018
@author: zefa
"""
import os
import numpy as np
import cv2
MAX_HEIGHT = 720
def apply_mask(image, mask, color, alpha=0.5):
"""Apply the given mask to the image.
"""
for c in range(3):
image[:, :, c] = np.where(mask == 1,
... | nilq/baby-python | python |
from xicam.plugins.datahandlerplugin import DataHandlerPlugin, start_doc, descriptor_doc, event_doc, stop_doc, \
embedded_local_event_doc
import os
import fabio
import uuid
import re
import functools
from pathlib import Path
class EDFPlugin(DataHandlerPlugin):
name = 'EDFPlugin'
DEFAULT_EXTENTIONS = ['.... | nilq/baby-python | python |
import datetime as dt
def dt_to_str(dt_seconds):
"""
Converts delta time into string "hh:mm:ss"
"""
return str(dt.timedelta(seconds=dt_seconds))
| nilq/baby-python | python |
'''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from datetime import timedelta
import json
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout, login
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django... | nilq/baby-python | python |
#!/usr/bin/env python2.7
"""
Function-Class-Method browser for python files.
"""
# Copyright (c) 2013 - 2017 Carwyn Pelley
#
# 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 restricti... | nilq/baby-python | python |
#!/usr/bin/env python
"""
utils.py
"""
import os, warnings, numpy as np, pandas as pd
from glob import glob
from typing import List
from itertools import accumulate, chain, repeat
from .constants import FRAME, TRACK, TRACK_LENGTH, PY, PX
######################
## TRACKS UTILITIES ##
######################
def trac... | nilq/baby-python | python |
from django.conf import settings
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import TemplateView
from core.helpers import NotifySettings
from core.views import BaseNotifyFormView
from ukef.forms import UKEFContactForm
class HomeView(TemplateView):
t... | nilq/baby-python | python |
import stackprinter
def test_frame_formatting():
""" pin plaintext output """
msg = stackprinter.format()
lines = msg.split('\n')
expected = ['File "test_formatting.py", line 6, in test_frame_formatting',
' 4 def test_frame_formatting():',
' 5 """ pin p... | nilq/baby-python | python |
import sys
import getpass
from controllers.main_controller import MainController
from interface.main_menu import MainMenu
from utils.hospital_errors import *
from database_layer.database import *
from utils.hospital_constants import *
class StartMenu:
db = Database()
@classmethod
def run(cls):
pr... | nilq/baby-python | python |
import json # importing json module
class Utils:
def stringify(self, obj):
return json.dumps(obj)
def parseJson(self, string):
try:
return json.loads(string)
#pass
except:
return string
#pass
| nilq/baby-python | python |
from typing import List, Optional
from sqlalchemy import desc
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import select
from app.database.dbo.mottak import WorkflowMetadata as WorkflowMetadata_DBO
from app.domain.models.WorkflowMetadata import WorkflowMetadata, WorkflowMetad... | nilq/baby-python | python |
import pickle
pickle_in=open("instances_dev.pickle","rb")
data=pickle.load(pickle_in)
for i in range(10):
print(data[i])
| nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
from L1Trigger.VertexFinder.VertexProducer_cff import VertexProducer
L1FastTrackingJets = cms.EDProducer("L1FastTrackingJetProducer",
L1TrackInputTag = cms.InputTag("TTTracksFromTrackletEmulation", "Level1TTTracks"),
L1PrimaryVertexTag=cms.InputTag("VertexProducer", Ve... | nilq/baby-python | python |
import wikipedia
while True:
ans = input("Question: ")
wikipedia.set_lang("es")
print (wikipedia.summary(ans, sentences=2))
| nilq/baby-python | python |
import json
import sqlite3
#Initiating the database
connection=sqlite3.connect(database='roaster_db.sqlite')
curr=connection.cursor()#Cursor initiated
#Creating tables for the database
# Do some setup
curr.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
... | nilq/baby-python | python |
import glob
import os
import json
import dateutil.parser
import datetime
import re
COMPLETE_NUM_ACTIONS=18
TECHNICAL_DIFFICULTIES = '7h9r8g p964wg jcqf4w 9qxf5g'.split()
# Also exclude this person, who wrote about things other than restaurants.
TECHNICAL_DIFFICULTIES.append('49g68p')
INCOMPLETE_BUT_OK = 'hfj33r'.spli... | nilq/baby-python | python |
print('='*8,'Aluguel de Um Carro','='*8)
d = int(input('Por quantos dias o carro foi alugado?'))
km = float(input('Quantos km foram rodados com o carro?'))
pa = 60*d + 0.15*km
print('''O valor do aluguel a ser pago por este carro com {} dias alugados e {:.2f}km rodados sera de:
{}R${:.2f}{}.'''.format(d,km,'\033[32m',p... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains custom widgets to handle file/folder browser related tasks
"""
from __future__ import print_function, division, absolute_import
import os
import sys
import subprocess
from Qt.QtCore import Signal, Property, QSize
from Qt.QtWidgets import QSizeP... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""
tl_stock.py
Copyright (c) 2015 Rob Mason
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 t... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2017 Mobicage NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | nilq/baby-python | python |
import sys
sys.path.append('../')
import jupman
import local
def add(x,y):
#jupman-raise
return x + y
#/jupman-raise
def sub(x,y):
return help_func(x,y)
#jupman-strip
# stripped stuff is not present in exercises
def help_func(x,y):
return x - y
#/jupman-strip
#jupman-purge
# purged stuff n... | nilq/baby-python | python |
import pytest
import os
from matplotlib.testing.compare import compare_images
gold = "testing/gold"
scratch = "testing/scratch"
def compare( a, b ):
results = compare_images( a, b, 1 )
return (results is None)
def test_cinema_image_compare():
try:
os.makedirs(scratch)
except OSError as e... | nilq/baby-python | python |
from cloudshell_power_lib.Orchestration import power_off_resources_in_sandbox
from cloudshell.workflow.orchestration.sandbox import Sandbox
from cloudshell.workflow.orchestration.teardown.default_teardown_orchestrator import DefaultTeardownWorkflow
import cloudshell.helpers.scripts.cloudshell_dev_helpers as dev_helpers... | nilq/baby-python | python |
"""
The base fighter implementation
"""
from __future__ import absolute_import, print_function, division
from cagefight.cagefighter import CageFighter
import random
import math
class LightningFighter(CageFighter):
"""
Lightning ball wars fighter
"""
def __init__(self, world, fighterid):
self.... | nilq/baby-python | python |
from pydub import AudioSegment
import webrtcvad
import numpy as np
import speechpy
import torch
import torch.autograd as grad
import torch.nn.functional as F
from model.hparam import hp
import os
from model.frame import Frame
def get_logmel_fb(segment, len_window=25, stride=10, filters=40):
'''
Gives the ... | nilq/baby-python | python |
"""
Silly placeholder file for the template.
"""
def hello() -> str:
return "Hello {{cookiecutter.project_slug}}"
| nilq/baby-python | python |
"""
input:
1
5
1 5 2 3 4
output:
12
"""
def solve(N, a):
res = 0
for i in range(N - 1, 0, -1):
if a[i] < a[i - 1]:
a[i - 1] -= (a[i - 1] - a[i])
res += a[i]
return res + a[0]
T = int(input())
for _ in range(T):
N = int(input())
a = list(map(int, input().split()))
... | nilq/baby-python | python |
from streamsvg import Drawing
s = Drawing()
s.addNode("a")
s.addNode("b", [(0,4), (5,10)])
s.addNode("c", [(4,9)])
s.addNode("d", [(1,3)])
s.addLink("a", "b", 2, 2, color='blue', width=3)
s.addLink("b", "d", 2, 2, color='blue', width=3)
s.addLink("a", "c", 5, 5, color='blue', width=3)
s.addLink("b", "c", 6, 6, color... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# bifacial_radiance documentation build configuration file, created by
# sphinx-quickstart on Tuesday Sep 24 18:48:33 2019.
#
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
... | nilq/baby-python | python |
import os
from oletools.olevba3 import VBA_Parser
# Set this to True if you would like to keep "Attribute VB_Name"
KEEP_NAME = False
def parse(workbook_path):
vba_path = workbook_path + '.vba'
vba_parser = VBA_Parser(workbook_path)
vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_ma... | nilq/baby-python | python |
import django_filters
from django_filters import DateFilter, CharFilter
from .models import *
class Client_Filter(django_filters.FilterSet):
class Meta:
model = Client
fields = [
'name',
'address',
'phone_no'
]
class Staff_Filter(django_... | nilq/baby-python | python |
from airypi.remote_obj import RemoteObj
from flask import session, request
from airypi import utils
import json
import gpio
from airypi.callback_dict import CallbackDict
from airypi import event_loop
class Device:
RPI = 'RASPBERRY_PI'
ANDROID = 'ANDROID'
handler_for_type = {}
event_loop_f... | nilq/baby-python | python |
from math import exp
import numpy as np
import random
import time
class AnnealingSolver:
# 3*81: rows, cols, 3x3
optimal_energy = -243
# marks original values
def get_fixed_positions(self, sudoku):
original = []
for row in sudoku:
original.append([-1 if x > 0 else 0 for x... | nilq/baby-python | python |
""" UDF is called user define function
UDF is very useful when you want to transform your data frame, and there is no pre-defined
Spark sql functions already available.
To define a spark udf, you have three options:
1. use pyspark.sql.functions.udf, this works for select, withColumn.
udf(lambda_function, return_typ... | nilq/baby-python | python |
from flask.ext.restful import fields
from app import db
from . import User
class PlanEntry(db.Model):
eid = db.Column(db.Integer, primary_key=True)
plan_id = db.Column(db.Integer, db.ForeignKey('plan.pid'))
plan = db.relationship('Plan', back_populates='entries')
timestamp = db.Column(db.Time)
... | nilq/baby-python | python |
import pyttsx3
import time
CALLS = {
"F": "Step Forwards",
"B": "Step Bak",
"L": "Step Left",
"R": "Step Right",
"ROT": "About turn",
"CLAP": "Clapp"
}
class Caller:
def __init__(self):
self.engine = pyttsx3.init()
self.engine.setProperty("rate", 140)
def say_command... | nilq/baby-python | python |
from typing import List
from src import util
from PIL import Image, ImageDraw
from src.config import ConfigContentType
from .bounding_box import BoundingBox
from .effect_processor import EffectProcessor
from .text_procecssor import TextProcessor
from .shape_processor import ShapeProcessor
from src.font_scanner impo... | nilq/baby-python | python |
#Copyright (c) 2017 Andre Santos
#
#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, distribute... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-06 23:56
from __future__ import unicode_literals
import brazil_fields.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [... | nilq/baby-python | python |
from abc import abstractmethod
from typing import List, Dict
from src.bounding_box import BoundingBox
from src.utils.enumerators import BBType, BBFormat
import torch.nn.functional as F
class ModelEvaluator:
def __init__(self):
self._gt_bboxes = []
self._predicted_bboxes = []
self._img_cou... | nilq/baby-python | python |
import torch
from typing import List, Dict, Tuple, Iterable
from ray import tune
from torch import optim
from tqdm import trange
from G2G.model.graph_wrapper import GraphWrapper
from G2G.model.model import Predictor
from G2G.utils import get_all_combo, prepare_input, get_score
from G2G.decorators.decorators import logg... | nilq/baby-python | python |
print((2**int(input()))%(10**9+7)) | nilq/baby-python | python |
from utils.db.mongo_orm import *
class TestCase(Model):
class Meta:
database = db
collection = 'testCase'
# Common Fields
_id = ObjectIdField()
name = StringField()
description = StringField()
isDeleted = BooleanField(field_name='isDeleted', default=False)
status = Boolean... | nilq/baby-python | python |
# * Utils Function
from tools.Wave_Class import Wave
import math
def auto_frame_count(waves, h, w, tr):
max_time = 0.0
to_check = ((0, 0), (0, h), (0, w), (h, w))
for wave in waves:
temp_func = wave.distanceFunction()
for p in to_check:
temp_dist = temp_func(p[0], p[1])
... | nilq/baby-python | python |
# Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 18:24:57 2019
@author: jone
"""
#%% Simple Demo
import cv2
import numpy as np
# callback 함수
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img, (x, y), 100, (255, 0, 0), -1)
# 빈 이미지 생성
img = np.zeros((5... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import CTK
def commit():
print CTK.post
return {'ret': 'ok'}
def default():
submit = CTK.Submitter('/commit')
submit += CTK.RawHTML ("<h2>Can set, without initial value</h2>")
submit += CTK.StarRating ({'name': 'test_rate1', 'can_set': True})
submit += CTK.RawHTML ("... | nilq/baby-python | python |
import hashlib
# Status definitions and subdir names
STATUS = {"PENDING": "queue",
"STARTED": "inprogress",
"DONE": "results",
"ERROR": "errors"}
def get_id(doc):
"""
Calculate the id (hash) of the given document
:param doc: The document (string)
:return: a task id (hash... | nilq/baby-python | python |
from imported.submodules import submodulea
def bar():
print("imported.modulee.bar()")
submodulea.foo()
| nilq/baby-python | python |
from flask import Flask, render_template, jsonify, request, url_for
import json
app = Flask(__name__)
values_list = ['id', 'summary', 'host_is_superhost', 'latitude', 'longitude',
'property_type', 'room_type', 'accomodates', 'bathrooms',
'bedrooms', 'beds', 'security_deposit', 'cleaning_... | nilq/baby-python | python |
import cv2 as cv
import numpy as np
titleWindow = 'Introduction_to_svm.py'
print("Takes a moment to compute resulting image...")
# Set up training data
## [setup1]
labels = np.array([1, -1, -1, -1])
trainingData = np.matrix([[501, 10], [255, 10], [501, 255], [10, 501]], dtype=np.float32)
## [setup1]
# Train the SVM
##... | nilq/baby-python | python |
import cv2
import numpy as np
import copy
from shapes.shape import Shape
from shapes.ep import p2e, e2p, column
class BBox(Shape):
@classmethod
def from_region(cls, region):
yx = region.centroid()
tmp = cls(yx[1], yx[0], -np.rad2deg(region.theta_), 2 * region.major_axis_, 2 * region.minor_axi... | nilq/baby-python | python |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | nilq/baby-python | python |
from .effector import Effector
from .evidence import Evidence
from .gene import Gene
from .operon import Operon
from .organism import Organism
from .pathway import Pathway
from .publication import Publication
from .regulator import Regulator
from .regulatory_family import RegulatoryFamily
from .regulatory_interaction i... | nilq/baby-python | python |
"""
SHA-256 PRNG prototype in Python
"""
import numpy as np
import sys
import struct
# Import base class for PRNGs
import random
# Import library of cryptographic hash functions
import hashlib
# Define useful constants
BPF = 53 # Number of bits in a float
RECIP_BPF = 2**-BPF
HASHLEN = 256 # Number of bits in a... | nilq/baby-python | python |
#
# Copyright (c) 2020 Saarland University.
#
# This file is part of AM Parser
# (see https://github.com/coli-saar/am-parser/).
#
# 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://... | nilq/baby-python | python |
from django.db import IntegrityError
from django.db.models import Count, Q, IntegerField, CharField
from django.db.models.functions import Coalesce
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.per... | nilq/baby-python | python |
import os
from flask import Flask
from flask import render_template
from flask_assets import Environment
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from config.environments import app_config
db = SQLAlchemy()
def get_config_name():
return os.getenv('FLASK_CONFIG') or 'developme... | nilq/baby-python | python |
#
# Copyright (c) 2019 Juniper Networks, Inc. All rights reserved.
#
from cfgm_common.exceptions import BadRequest, NoIdError
from cfgm_common.exceptions import HttpError, RequestSizeError
from vnc_api.gen.resource_client import AccessControlList
from schema_transformer.resources._resource_base import ResourceBaseST
... | nilq/baby-python | python |
#
# ==================================
# | |
# | Utility functions for CBGB |
# | |
# ==================================
#
from collections import OrderedDict
from modules import gb
import importlib
import modules.active_cfg
cfg = importlib.im... | nilq/baby-python | python |
import numpy as np
from Bio.SVDSuperimposer import SVDSuperimposer
from sklearn.utils.validation import check_is_fitted
from sklearn.base import TransformerMixin, BaseEstimator
"""
BioPythonの関数をsklearnのモデルのように利用する関数/クラス群。
last update: 21 Jun, 2021
Authors: Keisuke Yanagisawa
"""
__all__ = [
"SuperImposer"
]
cl... | nilq/baby-python | python |
"""Build IDE required files from python folder structure from command line.
"""
import argparse
from ideskeleton import build
def main():
"""Build IDE files from python folder structure."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormat... | nilq/baby-python | python |
import pytest
from httpx import AsyncClient
from mock import patch
from models.schemas.status import StatusEnum
from resources import strings
pytestmark = pytest.mark.asyncio
@patch("api.routes.health.create_service_bus_status")
@patch("api.routes.health.create_state_store_status")
async def test_health_response_co... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/30 下午12:27
# @Title : 26. 删除排序数组中的重复项
# @Link : https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
QUESTION = """
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums =... | nilq/baby-python | python |
__package__ = 'archivebox.core'
import uuid
from django.db import models
from django.utils.functional import cached_property
from ..util import parse_date
from ..index.schema import Link
class Snapshot(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
url = models.... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# IMPORT STANDARD LIBRARIES
import re
_LINE_ENDER = re.compile(r'(?P<prefix>\s*).+(?::)(?:#.+)?$')
def _get_indent(text):
'''str: Find the indentation of a line of text.'''
return text[:len(text) - len(text.lstrip())]
def _add_indent(text, indent=1):
'''A... | nilq/baby-python | python |
#!/usr/bin/env python3
import csv
import typer
def read_csv(file_name: str):
print(f'FILE NAME {file_name}')
""" Opens a csv file and returns a list with the
contents of the first column (in reality returns a
list of all the rows contained in the file)
Args:
file... | nilq/baby-python | python |
import sys
import java.lang.Class
import org.python.core.PyReflectedFunction as reflectedfunction
import org.python.core.PyReflectedField as reflectedfield
import java.lang.reflect.Field as Field
import java.lang.reflect.Method as Method
import java.lang.annotation.Annotation as JavaAnnotation
from java.lang... | nilq/baby-python | python |
from ..model.elapsed_time_fractions import ElapsedTimeFractions
def calculate_time_fractions(elapsed_time_ns: int) -> ElapsedTimeFractions:
"""Elapsed time is in nanoseconds and should be calculated as difference between start and stop time using on the time.perf_counter_ns() function."""
microseconds, nanos... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import numpy as np
from PIL import Image
import torch
import torchvision
from platforms.platform import get_platform
class Datase... | nilq/baby-python | python |
import os
import time
from NMLearn.classifiers.tree.desicion_tree import classification_tree
from NMLearn.utilities.dataset_utils.mnist import load_mnist_data
from NMLearn.utilities.metrics import accuracy
##########
# config #
##########
# data parameters
DATA_PATH = "<Path to Dataset>"
# model parameters
MAX_FEATU... | nilq/baby-python | python |
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
from io import open
# Launch command
from os import path
import re
here = path.abspath(path.dirname(__file__))
project_homepage = "https://github.com/rbonghi/ros... | nilq/baby-python | python |
# misc.py --- Miscellaneous utility functions
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, 2016 Florent Rougon
#
# This file is distributed under the terms of the DO WHAT THE FUCK YOU WANT TO
# PUBLIC LICENSE version 2, dated December 2004, by Sam Hocevar. You should
# have received a copy of this license along wit... | nilq/baby-python | python |
import os
import operator
import unittest
from ..utils.py3compat import execfile
from .testing import assert_point_in_collection
def mapcall(name, iterative):
return list(map(operator.methodcaller(name), iterative))
class TestExamples(unittest.TestCase):
from os.path import abspath, dirname, join
root... | nilq/baby-python | python |
import re
import json
import urllib.error
import urllib.parse
import urllib.request
from lib.l2p_tools import handle_url_except, clean_exit
class DMAFinder():
location = {
"latitude": None,
"longitude": None,
"DMA": None,
"city": None,
... | nilq/baby-python | python |
from PyQt5 import QtCore as qtc
import cv2
import numpy as np
class DetectionsDrawer(qtc.QObject):
detections_drawn = qtc.pyqtSignal(np.ndarray)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dst_h = None
self.dst_w = None
@qtc.pyqtSlot(t... | nilq/baby-python | python |
from __future__ import print_function
import sys
import numpy as np
from yggdrasil.interface.YggInterface import YggRpcServer
from yggdrasil.tools import sleep
def fibServer(args):
sleeptime = float(args[0])
print('Hello from Python rpcFibSrv: sleeptime = %f' % sleeptime)
# Create server-side rpc connec... | nilq/baby-python | python |
from bs4 import BeautifulSoup, SoupStrainer
import requests
import time
def extrai_html(url_pronta):
# PASSAR TAG PRINCIPAL
custom = SoupStrainer('div', {'class': 'item'})
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/53... | nilq/baby-python | python |
import pprint
from uuid import uuid4
from twisted.internet.defer import Deferred, DeferredList, maybeDeferred
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web import server
from .base import BaseServer, LOGGER
from ..resources import InterfaceResource, ExposedResource
from... | nilq/baby-python | python |
# Generated by Django 3.0.6 on 2020-05-25 10:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sim', '0007_game_cost'),
]
operations = [
migrations.AddField(
model_name='game',
name='budget',
field=m... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-27 18:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('magic_cards', '0001_initial'),
]
operations = [
migrations.AddField(
... | nilq/baby-python | python |
from ursinanetworking import *
from easyursinanetworking import *
Server = UrsinaNetworkingServer("localhost", 25565)
Easy = EasyUrsinaNetworkingServer(Server)
Easy.create_replicated_variable("MyVariable", {"name" : "kevin"})
Easy.update_replicated_variable_by_name("MyVariablee", "name", "jean")
Easy.remove_replicate... | nilq/baby-python | python |
from PIL import Image, ImageDraw, ImageFont
from pkg_resources import resource_exists, resource_filename, cleanup_resources
def watermark_image(image, wtrmrk_path, corner=2):
'''Adds a watermark image to an instance of a PIL Image.
If the provided watermark image (wtrmrk_path) is
larger than the provided... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import json
import pprint
import requests
import sys
import urllib
import sqlalchemy
from sqlalchemy import *
import pymysql
from coffeeshop import CoffeeShop
from configparser import SafeConfigParser
pymysql.install_as_MySQLdb()
# This cli... | nilq/baby-python | python |
import deeplift
import numpy as np
def deeplift_zero_ref(X,score_func,batch_size=200,task_idx=0):
# use a 40% GC reference
input_references = [np.array([0.0, 0.0, 0.0, 0.0])[None, None, None, :]]
# get deeplift scores
deeplift_scores = score_func(
task_idx=task_idx,
input_d... | nilq/baby-python | python |
from utils import utils
from enums.enums import MediusEnum, RtIdEnum, MediusChatMessageType
from medius.mediuspackets.chatfwdmessage import ChatFwdMessageSerializer
import logging
logger = logging.getLogger('robo.chat')
class ChatCommands:
def __init__(self):
pass
def process_chat(self, player, text)... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Python import
import sys
# Local import
import settings
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#following from Python cookbook, #475186
def has_colors(stream):
if not hasattr(stream, "isatty") or not stream.isatty():
return False
try:
import curses
... | nilq/baby-python | python |
# Copyright 2021 Beijing DP Technology Co., Ltd.
#
# 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 ... | nilq/baby-python | python |
def disemvowel(string):
return "".join(i for i in string if not (i.lower() in "aeiou")) | nilq/baby-python | python |
"""Tests for Broadlink devices."""
from unittest.mock import patch
import broadlink.exceptions as blke
from openpeerpower.components.broadlink.const import DOMAIN
from openpeerpower.components.broadlink.device import get_domains
from openpeerpower.config_entries import ConfigEntryState
from openpeerpower.helpers.enti... | nilq/baby-python | python |
import time
import numpy as np
import sys
sys.path.append('..//Drivers')
sys.path.append('..//PlotModules')
import math
import csv
import matplotlib.pyplot as plt
from waferscreen.inst_control.Keysight_USB_VNA import USBVNA
#####
# Code which will take an S21 measurement with a Keysight USB VNA (P937XA) and plot it LM... | nilq/baby-python | python |
from .Algorithm import PoblationalAlgorithm
from ..Agents.RealAgent import RealAgent
class EvolutionStrategie(PoblationalAlgorithm):
def __init__(self, function, ind_size, p_size, generations, selection_op,
mutation_op, recombination_op, marriage_size=2, agent_args={}, **kwargs):
self.ind_siz... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# # MIT License
#
# Copyright (c) 2020 Mike Simms
#
# 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... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from gym.spaces import Discrete
from compiler_gym.spaces import Tuple
from tests.test_main import main
def test_equal():
assert Tuple([... | nilq/baby-python | python |
import os
import sys
from configobj import ConfigObj
import click
import requests
from kaos_cli.utils.helpers import run_cmd
from ..constants import KAOS_STATE_DIR, CONFIG_PATH, ENV_DICT
def pass_obj(obj_id):
def decorator(f):
def new_func(*args, **kwargs):
ctx = click.get_current_context()
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.