content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import warnings
class AppPlatformError(Exception):
"""
Raised by :meth:`Client.request()` for requests that:
- Return a non-200 HTTP response, or
- Connection refused/timeout or
- Response timeout or
- Malformed request
- Have a malformed/missing header in the response.
"""
... | nilq/baby-python | python |
import setuptools
from glob import glob
setuptools.setup(
name="noteboard-extension",
version='0.1.0',
url="https://github.com/yuvipanda/noteboard",
author="Yuvi Panda",
description="Simple Jupyter extension to emit events about current notebooks to a noteboard server",
data_files=[
('s... | nilq/baby-python | python |
import os.path as osp
import numpy as np
class Dataset(object):
def __init__(self, ids, labels, is_train=True, name='default'):
self._ids = list(ids)
self._labels = labels
self.name = name
self.is_train = is_train
def get_data(self, id):
activity = np.load(id)
... | nilq/baby-python | python |
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#color spaces --> rgb spaces,grayscal
img = cv.imread('photos/dog.jpg')
cv.imshow('Dog',img)
# plt.imshow(img)
# plt.show()
# point to note --> there is conversion of colour spaces in matplotlib
# BGR to grayscale -->
gray = cv.cvtColor(img,cv.COLO... | nilq/baby-python | python |
from rest_framework import serializers
from users.models.organizations import Organization
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'domain')
| nilq/baby-python | python |
import sys
from data_wrapper.settings import MESSAGES
class DataWrapper:
def __init__(self, db=None, params=None, environment=None):
if db:
if db.lower() == 'mongodb':
from data_wrapper.mongodb_wrapper import MongodbDbWrapper
self.db = True
self... | nilq/baby-python | python |
# Copyright 2019 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 logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
from telemetry.internal.util import binary_manager
class Min... | nilq/baby-python | python |
# ------------------------------------------------------------------------------
# Portions of this code are from
# OpenPCDet (https://github.com/open-mmlab/OpenPCDet)
# Licensed under the Apache License.
# ------------------------------------------------------------------------------
import numpy as np
import torch
i... | nilq/baby-python | python |
import typing
def printBinary(n: int) -> None:
if n > 1:
printBinary(n // 2)
print(n % 2, end = "")
def main() -> None:
N = int(input("Input an integer:\n"))
printBinary(N)
return None
main() | nilq/baby-python | python |
# Authors: David Alexander, Lance Hepler
from __future__ import absolute_import, division, print_function
from GenomicConsensus.arrow.utils import allSingleBaseMutations
from GenomicConsensus.variants import Variant
from GenomicConsensus.quiver.diploid import variantsFromAlignment
import numpy as np
import ConsensusC... | nilq/baby-python | python |
"""Tests for the /sessions/.../commands routes."""
import pytest
from datetime import datetime
from decoy import Decoy, matchers
from fastapi import FastAPI
from fastapi.testclient import TestClient
from httpx import AsyncClient
from typing import Callable, Awaitable
from tests.helpers import verify_response
from op... | nilq/baby-python | python |
import discord
from discord.ext import commands
import steam
from steam import WebAPI, SteamID
import keys
##TODO: convert to psql or something
import pickle
import asyncio
import os
import re
## Used to track the worst players in MM
class PlayerTracker(commands.Cog):
## Init
def __init__(self, bot):
... | nilq/baby-python | python |
__all__ = ['ioc_api', 'ioc_common', 'ioc_et', 'xmlutils'] | nilq/baby-python | python |
import modin.pandas as pd
import swifter # Do not remove - this modified bindings for modin
import sys, os
import datetime
import csv
import random
import h5py
import numpy as np
import ipaddress
import datetime as datetime
def write_single_graph(f, graph_id, x, edge_index, y, attrs=None, **kwargs):
'''
store... | nilq/baby-python | python |
# Class to generate batches of image data to be fed to model
# inclusive of both original data and augmented data
# https://gist.github.com/devxpy/a73744bab1b77a79bcad553cbe589493
# example
# train_gen = PersonDataGenerator(
# train_df,
# batch_size=32,
# aug_list=[
... | nilq/baby-python | python |
from ._abstract import AbstractSearcher
from ._result import RecipeLink, SearchResult
import urllib.parse
from typing import List
class NyTimes(AbstractSearcher):
def __init__(self):
AbstractSearcher.__init__(self)
@classmethod
def host(cls):
return "https://cooking.nytimes.com"
d... | nilq/baby-python | python |
import json
import requests
import time
import hmac
import hashlib
from requests.exceptions import HTTPError
SDK_VERSION = '1.0.0'
CLOCK_DRIFT = 300
class HTTPClient(object):
def request(self, method, url, headers, data=None, auth=None):
raise NotImplementedError('subclass must implement request')
cl... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
if subprocess.Popen(['./problem']).wait() != 0:
print("Wow, you\'ve crushed this")
flagfile = open('flag')
if not flagfile:
print("Flag is missing, tell admin")
else:
print(flagfile.read())
| nilq/baby-python | python |
"""
Sudo2 is for Loomgild.py
"""
import time
from time import sleep
# Command Functions
def help():
print("Hello!")
print("Welcome to Loomgild, a script that imitates a command line.")
print("This is one of the few commands that you can use.")
print("We will now load the commands you can use..")
p... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script to hold temporary routines created during the beamtime.
Everything added here is star (*) imported into the IPython shell after the
``SplitAndDelay`` object has succesfully instantiated. Therefore, it is
recommended to run the specific unit-test to quickly ensur... | nilq/baby-python | python |
from random import randint
while True:
print("----------\n[j] para jogar o dado\n[e] para fechar")
res = str(input().replace(" ", "").lower())
if res == "j":
print(f"\nvalor do dado: {randint(1, 6)}")
if res == "e":
break
print("----------\n")
| nilq/baby-python | python |
import contextlib
import logging
import os
from pathlib import Path
import shutil
from subprocess import CalledProcessError, check_output
import sys
from tempfile import NamedTemporaryFile
from typing import cast
from spython.main import Client
from lm_zoo import errors
from lm_zoo.backends import ContainerBackend
fr... | nilq/baby-python | python |
#importamos la libreria forms:
from django import forms
#creamos una lista de las posibles opciones del select:
from .pqrsf import PQRSF_CHOICES
#creamos la estructura dl formulario
class ContactFrom(forms.Form):
"""creamos los campos"""
email = forms.EmailField(label="correo electrónico", widget=forms.EmailInput(a... | nilq/baby-python | python |
def test_load(session, inline):
inline("PASS")
| nilq/baby-python | python |
TAG_MAP = {
('landuse', 'forest'): {"TYPE": "forest", "DRAW_TYPE": "plane"},
('natural', 'wood'): {"TYPE": "forest", "SUBTYPE": "natural", "DRAW_TYPE": "plane"}
}
def find_type(tags):
keys = list(tags.items())
return [TAG_MAP[key] for key in keys if key in TAG_MAP]
| nilq/baby-python | python |
from twilio.twiml.voice_response import VoiceResponse, Dial
def generate_wait():
twiml_response = VoiceResponse()
wait_message = (
'Thank you for calling. Please wait in line for a few seconds.'
' An agent will be with you shortly.'
)
wait_music = 'http://com.twilio.music.classical.s3.... | nilq/baby-python | python |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from helper import find_csv
grid = plt.GridSpec(2, 2, wspace=0.4, hspace=0.3)
ax1 = plt.subplot(grid[0,0])
ax2= plt.subplot(grid[0,1])
ax3= plt.subplot(grid[1,:])
for i in find_csv():
df = pd.read_csv(i,header=None)
df_forward = df[:int(le... | nilq/baby-python | python |
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class SetMaterialRgbParamNode(Node, ArmLogicTreeNode):
'''Set material rgb param node'''
bl_idname = 'LNSetMaterialRgbParamNode'
bl_label = 'Set Material RGB Param'
bl_icon = 'GAME'
def ... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
from smisk.mvc import *
from smisk.serialization import data
import datetime, time
# Importing the serializers causes them to be registered
import my_xml_serializer
import my_text_serializer
# Some demo data
DEMO_STRUCT = dict(
string = "Doodah",
items = ["A", "B", 12, 32.1... | nilq/baby-python | python |
#!/usr/bin/env python
"""Stp - Stock Patterns
Usage: stp_mgr
stp_mgr insider
"""
from docopt import docopt
import stp
print(stp.__file__)
from stp import feed
from stp.feed.insidertrading import data
import sys
def insider():
records = data.get_records()
for record in records:
print(record)
... | nilq/baby-python | python |
# --------------------------------------------------------
# CRPN
# Written by Linjie Deng
# --------------------------------------------------------
import yaml
import caffe
import numpy as np
from fast_rcnn.config import cfg
from fast_rcnn.nms_wrapper import nms
from quad.quad_convert import whctrs, mkanchors, quad_2... | nilq/baby-python | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from yandex.cloud.access import access_pb2 as yandex_dot_cloud_dot_access_dot_access__pb2
from yandex.cloud.containerregistry.v1 import registry_pb2 as yandex_dot_cloud_dot_containerregistry_dot_v1_dot_registry__pb2
from yandex.cloud.con... | nilq/baby-python | python |
#-----------------------------------------------------------------------
#Copyright 2019 Centrum Wiskunde & Informatica, Amsterdam
#
#Author: Daniel M. Pelt
#Contact: D.M.Pelt@cwi.nl
#Website: http://dmpelt.github.io/msdnet/
#License: MIT
#
#This file is part of MSDNet, a Python implementation of the
#Mixed-Scale Dense... | nilq/baby-python | python |
import numpy as np
from utils.misc import arr2grid
from planner.astar import AStar
from planner.dijkstra import Dijkstra
from planner.bestfirst import BestFirst
from planner.breadthfirst import BreadthFirst
from planner.bi_astar import BiAStar
from planner.bi_dijkstra import BiDijkstra
from planner.bi_bestfirst import ... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding: utf8
# Author: Lenz Furrer, 2017
'''
Formatter base classes.
'''
import os
import io
from lxml import etree
class Formatter:
'''
Base class for all formatters.
'''
ext = None
binary = False # text or binary format?
def __init__(self, config, fmt_name):
... | nilq/baby-python | python |
# 첫 도착지
# 짝수: 1 -> 2
# 홀수: 1 -> 3
# 두번째 도착지
# 짝수: 1 -> 3
# 홀수: 1 -> 2
# 3번째 도착지
# 작은 아이가 두번째 아이에게 얹힌다. (마지막을 제외하고 다시 뭉친다.)
# 4번째
# 3번째로 큰 아이가 빈 곳으로 간다.
# 5번째
# 작은 아이가 두번째 + 3번째 아이에게 얹힌다. (마지막을 제외하고 다시 뭉친다.)
import sys
n = int(sys.stdin.readline())
count = 0
# 매개변수 : 총 개수, 시작, 목표, other,...?
def hanoi(total, sta... | nilq/baby-python | python |
from __future__ import unicode_literals
from .common import InfoExtractor
class YouJizzIE(InfoExtractor):
_VALID_URL = r'https?://(?:\w+\.)?youjizz\.com/videos/(?:[^/#?]+)?-(?P<id>[0-9]+)\.html(?:$|[?#])'
_TESTS = [{
'url': 'http://www.youjizz.com/videos/zeichentrick-1-2189178.html',
'md5': '... | nilq/baby-python | python |
# see https://docs.python.org/3/reference/expressions.html#operator-precedence
# '|' is the least binding numeric operator
# '^'
# OK: 1 | (2 ^ 3) = 1 | 1 = 1
# BAD: (1 | 2) ^ 3 = 3 ^ 3 = 0
print(1 | 2 ^ 3)
# '&'
# OK: 3 ^ (2 & 1) = 3 ^ 0 = 3
# BAD: (3 ^ 2) & 1 = 1 & 1 = 1
print(3 ^ 2 & 1)
# '<<', '>>'
# OK: 2 &... | nilq/baby-python | python |
import sys
import os
def jeff():
print('quick attack the enemy press a to attack b to block c for super ')
bob=10
alice=60
turn1=0
turn2=2
spr=5
mod1=0
mod2=0
speed=0
c1=print('bob health is ',bob)
c2=print('alice health is ',alice)
print(c1,c2)
... | nilq/baby-python | python |
wild = "https://image.ibb.co/dPStdz/wild.png"
wild_plus_four = "https://image.ibb.co/jKctdz/wild_4.png"
red = {
'0': 'https://image.ibb.co/gnmtB8/red_0.png',
'1': 'https://image.ibb.co/hvRFPT/red_1.png',
'2': 'https://image.ibb.co/f9xN4T/red_2.png',
'3': 'https://image.ibb.co/hDB4Jo/red_3.png',
'4'... | nilq/baby-python | python |
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# Copyright 2020 Tecnativa - Pedro M. Baeza
from odoo import api, fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
type_id = fields.Many2one(
comodel_name="sale.order.type",
string="Type",
compute="_... | nilq/baby-python | python |
import importlib
from functools import partial
from multiprocessing import Process, Queue
from flask import Flask, request
app = Flask("serverfull")
bees = ["a", "b"] # TODO: get this from somewhere
workers = {}
def bee_loop(handler, inq, outq):
request = inq.get()
print("Got request")
outq.put(handl... | nilq/baby-python | python |
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
facedetection = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
while True:
ret, frame = cap.read()
gry = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face = facedetection.detectMultiScale(gry,1.3,5)
fo... | nilq/baby-python | python |
# Copyright 2017 VMware Inc. All rights reserved.
# 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
#
# ... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
"""
Automatized configuration and execution of Inspect peptide identification for
a list of spectrum files and a list of reference proteomes. Specifications of
posttranslational modifications can either be directly passed by the user or
assigned to the dataset by its filename (if dataset group i... | nilq/baby-python | python |
from django.db import models
# Create your models here.
class TipoElectrodomestico(models.Model):
nombre = models.CharField(max_length=200)
foto = models.ImageField(null =True, blank=True)
def __str__(self):
#Identificar un objeto
return self.nombre
def numProductos(self):
... | nilq/baby-python | python |
# Copyright 2021 Lucas Fidon and Suprosanna Shit
"""
Data loader for a single case.
This is typically used for inference.
"""
import torch
from monai.data import Dataset, DataLoader
def single_case_dataloader(inference_transform, input_path_dict):
"""
:param inference_transform
:param input_path_dict: di... | nilq/baby-python | python |
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import threading
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
class WriteToCallback(beam.PTransform):
def __init__(self, callback, lock):
self._callback = callback
self._lock... | nilq/baby-python | python |
from sys import path
path.append('/home/joerojas/Desarrollo/Curso-Basico-Python/101_misModulos/modules')
import modulo2
zeroes = [0 for i in range(5)]
ones = [1 for i in range(5)]
print(modulo2.suma(zeroes))
print(modulo2.producto(ones)) | nilq/baby-python | python |
'''
Classes from the 'LinkPresentation' framework.
'''
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
LPMultipleMetadataPresentationTransformer = _Cla... | nilq/baby-python | python |
### Worker threads and payloads for sending web requests
from enum import Enum
from threading import Thread
import requests
from requests.adapters import HTTPAdapter
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
# The Worker class is reused for both stages of execution, so it needs to be able to... | nilq/baby-python | python |
import os
from datetime import datetime
from flask import Flask, request, flash, url_for, redirect, \
render_template, abort, send_from_directory
from doctor_api.app import doctor_api_bp
from patient_api.app import patient_api_bp
app = Flask(__name__)
app.config.from_pyfile('flaskapp.cfg')
app.register_blueprint... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# trump-net (c) Ian Dennis Miller
from flask_security import ConfirmRegisterForm
from flask_wtf.recaptcha import RecaptchaField
class ExtendedRegisterForm(ConfirmRegisterForm):
recaptcha = RecaptchaField()
def validate(self):
rv = ConfirmRegisterForm.validate(self)
if... | nilq/baby-python | python |
from crestdsl.model import * # bad practice, but used for the evaluation of commands
from .simulator import Simulator
import logging
logger = logging.getLogger(__name__)
import io
try:
import colored
from colored import stylize
color_enabled = True
except ImportError:
color_enabled = False
except io.... | nilq/baby-python | python |
#
# Constant Price Market Making Simulator
#
# simulate different liquidity provision and trading strategies
#
from typing import Tuple
import csv
import numpy as np
import pandas as pd
from numpy.random import binomial, default_rng
# TODO: switch to decimal type and control quantization. numeric errors will kill us... | nilq/baby-python | python |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def load_external_go_repositories():
########## Server request handling ###############
go_repository(
name = "com_github_andybalholm_brotli",
importpath = "github.com/andybalholm/brotli",
commit = "1d750214c25205863625bb3eb8190a51b2cef... | nilq/baby-python | python |
from datapackage_pipelines.wrapper import ingest, spew
from datapackage_pipelines.utilities.resources import PROP_STREAMING
from nli_z3950.load_marc_data import get_marc_records_schema, parse_record
from pymarc.marcxml import parse_xml_to_array
import datetime, json
def get_resource(parameters, stats):
stats['sea... | nilq/baby-python | python |
import os
import sqlite3
class DatabaseRepository:
def __init__(self, database_file, schema_file):
db_is_new = not os.path.exists(database_file)
self.connection = sqlite3.connect(database_file, check_same_thread=False)
if db_is_new:
with open(schema_file, 'rt') as f:
... | nilq/baby-python | python |
"""Utility methods for interacting with Kubernetes API server.
This module is merged into the `metalk8s_kubernetes` execution module,
by virtue of its `__virtualname__`.
"""
from __future__ import absolute_import
from salt.exceptions import CommandExecutionError
import salt.utils.files
import salt.utils.templates
imp... | nilq/baby-python | python |
import logging.config
import configparser
import metrics
from datetime import datetime
import urllib.request
from unittest import mock
from requests import request
from aiohttp.web import Response
from jiracollector import JiraCollector
import pytest
config = configparser.ConfigParser()
config.read('metrics.ini')
lo... | nilq/baby-python | python |
"""
MIT License
mift - Copyright (c) 2021 Control-F
Author: Mike Bangham (Control-F)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software, 'mift', and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limita... | nilq/baby-python | python |
from constant_sum import *
if __name__ == "__main__":
t = 56
n = 510
s = 510
for i in range(500):
l = (T_len(t,n-i,s))
if l>0:
print(log(l,2),t, n-i, s, t*n - s+i, t*n )
#for b in range(t, 1, -1):
# p = 0
# k = min(n*(t - b + 1), s)
# #k = s
#... | nilq/baby-python | python |
from .statement_base import Statement
import sasoptpy
class DropStatement(Statement):
@sasoptpy.class_containable
def __init__(self, *elements):
super().__init__()
for i in elements:
self.elements.append(i)
self.keyword = 'drop'
def append(self, element):
pas... | nilq/baby-python | python |
R = int(input())
print(2*3.141592653589793*R)
| nilq/baby-python | python |
import numpy as np
import pandas as pd
import sys
from typing import Literal
from arch import arch_model
import warnings
from sklearn.exceptions import ConvergenceWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=ConvergenceWarning)
def get_rolling_vol_forecasts(return_series,
... | nilq/baby-python | python |
from django.templatetags.static import static as get_static_url
from django.shortcuts import redirect
from .exceptions import UnknownMessageTypeError
from .models import Dispatch
from .signals import sig_unsubscribe_failed, sig_mark_read_failed
def _generic_view(message_method, fail_signal, request, message_id, disp... | nilq/baby-python | python |
"""
Modules for prediciting topological properties
"""
| nilq/baby-python | python |
"""
Class of water block
"""
import os
from .block import Block
import math
class CurrentWaterRight(Block):
"""
Represents the block of water
"""
def __init__(
self,
settings: any,
path: str = 'advancing_hero/images/blocks/water3.png',
):
super().__init__(os.path.ab... | nilq/baby-python | python |
# Importar las dependencias de flask
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for
# Importar clave/ayudantes de encriptacion
from werkzeug import check_password_hash, generate_password_hash
# Importar FireBase
from firebase import firebase
# Importar el objeto de base d... | nilq/baby-python | python |
def ErrorHandler(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e: # pragma: no cover
pass
return wrapper
| nilq/baby-python | python |
import pandas as pd
import numpy as np
import tensorflow as tf
from math import floor
from dataset.date_format import START_CODE, INPUT_FNS, OUTPUT_VOCAB, encodeInputDateStrings, encodeOutputDateStrings, dateTupleToYYYYDashMMDashDD
def generateOrderedDates(minYear: str, maxYear: str) -> list:
daterange = pd.date... | nilq/baby-python | python |
from __future__ import division, print_function, absolute_import
# LIBTBX_SET_DISPATCHER_NAME iota.single_image
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1
'''
Author : Lyubimov, A.Y.
Created : 05/31/2018
Last Change... | nilq/baby-python | python |
import requests
from bs4 import BeautifulSoup
import urllib.request
import pytesseract
from PIL import Image
from PIL import ImageEnhance
def shibie(filepath):
# 打开图片
img = Image.open(filepath)
img = img.convert('RGB')
enhancer = ImageEnhance.Color(img)
enhancer = enhancer.enhance(0)
enhancer =... | nilq/baby-python | python |
import random
import uuid
from datetime import timedelta
import re
from discord import AllowedMentions, ButtonStyle, Embed
from squid.bot import CommandContext, SquidPlugin, command
from squid.bot.errors import CommandFailed
from squid.utils import now, parse_time, s
from .views import GiveawayView
class Giveaways(S... | nilq/baby-python | python |
# Copyright 2016, FBPIC contributors
# Authors: Remi Lehe, Manuel Kirchen
# License: 3-Clause-BSD-LBNL
"""
This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC)
It defines the structure necessary to implement the moving window.
"""
from fbpic.utils.threading import njit_parallel, prange
# Check if CUDA... | nilq/baby-python | python |
from django.shortcuts import render
from swpp.models import Profile
from swpp.serializers import ProfileSerializer
from rest_framework import generics, mixins, permissions
from swpp.permissions import IsOwnerOrReadOnly
class ProfileList(generics.ListAPIView):
queryset = Profile.objects.all()
serializer_class =... | nilq/baby-python | python |
KIND = {
'JOB': 'job',
'DEPLOYMENT': 'deployment'
}
COMMAND = {
'DELETE': 'delete',
'CREATE': 'create'
} | nilq/baby-python | python |
# Copied from http://www.djangosnippets.org/snippets/369/
import re
import unicodedata
from htmlentitydefs import name2codepoint
from django.utils.encoding import smart_unicode, force_unicode
from slughifi import slughifi
def slugify(s, entities=True, decimal=True, hexadecimal=True, model=None, slug_field='slug', p... | nilq/baby-python | python |
from typing import Optional
from typing import Tuple
import attr
@attr.s(auto_attribs=True)
class SlotAttentionParams:
# model configs
resolution: Tuple[int, int] = (128, 128) # since we not using ViT
# Slot Attention module params
num_slots: int = 7 # at most 6 obj per image/video
# dim of sl... | nilq/baby-python | python |
from verifai.simulators.car_simulator.examples.control_utils.LQR_computation import *
from verifai.simulators.car_simulator.simulator import *
from verifai.simulators.car_simulator.lane import *
from verifai.simulators.car_simulator.car_object import *
from verifai.simulators.car_simulator.client_car_sim import *
impor... | nilq/baby-python | python |
import numpy as np
from mesostat.metric.impl.mar import unstack_factor, rel_err
def predict(x, alpha, u, beta):
# return np.einsum('ai,ijk', alpha, x) + np.einsum('ai,ijk', beta, u)
return x.dot(alpha.T) + u.dot(beta.T)
def fit_mle(x, y, u):
# # Construct linear system for transition matrices
# M11 ... | nilq/baby-python | python |
'''
The MIT License (MIT)
Copyright © 2021 Opentensor.ai
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,... | nilq/baby-python | python |
from srf.io.listmode import save_h5
import numpy as np
data = np.fromfile("normal_scan_true.txt", dtype=np.float32).reshape(-1,7)
result = {'fst': data[:, :3], 'snd': data[:, 3:6], 'weight': np.ones_like(data[:,0])}
save_h5('input.h5', result) | nilq/baby-python | python |
from flask import Flask
from . import api, web
app = Flask(
__name__,
static_url_path='/assets',
static_folder='static',
template_folder='templates')
app.config['SECRET_KEY'] = 'secret' # this is fine if running locally
app.register_blueprint(api.bp)
app.register_blueprint(web.bp)
| nilq/baby-python | python |
default_app_config = 'user_deletion.apps.UserDeletionConfig'
| nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Copyright 2012-2021 Smartling, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/l... | nilq/baby-python | python |
# ===============================================================================
# NAME: SerialHVisitor.py
#
# DESCRIPTION: A visitor responsible for the generation of header file
# for each serializable class.
#
# AUTHOR: reder
# EMAIL: reder@jpl.nasa.gov
# DATE CREATED : June 4, 2007
#
# Copyright 201... | nilq/baby-python | python |
import time
import os
import binascii
import re
from datetime import datetime
from bson.json_util import dumps, loads
from flask.helpers import get_template_attribute
from flask import render_template
from init import app, rdb
from utils.jsontools import *
from utils.dbtools import makeUserMeta
from db i... | nilq/baby-python | python |
import socket
import threading
class Server:
def __init__(self, ip, port):
self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sck.bind((ip, port))
self.sck.listen()
self.conCallback = None
self.clientThrCallback = None
self.disconCallback = None
self.clients = { }
self.nextClID = 0
def... | nilq/baby-python | python |
from math import pi, cos, log, floor
from torch.optim.lr_scheduler import _LRScheduler
class CosineWarmupLR(_LRScheduler):
'''
Cosine lr decay function with warmup.
Ref: https://github.com/PistonY/torch-toolbox/blob/master/torchtoolbox/optimizer/lr_scheduler.py
https://github.com/Randl/MobileNetV... | nilq/baby-python | python |
from construct import *
from construct.lib import *
switch_integers__opcode = Struct(
'code' / Int8ub,
'body' / Switch(this.code, {1: Int8ub, 2: Int16ul, 4: Int32ul, 8: Int64ul, }),
)
switch_integers = Struct(
'opcodes' / GreedyRange(LazyBound(lambda: switch_integers__opcode)),
)
_schema = switch_integers
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# bricks.py: utility collections.
#
# Copyright (C) 2009, 2010 Raymond Hettinger <python@rcn.com>
# Copyright (C) 2010 Lukáš Lalinský <lalinsky@gmail.com>
# Copyright (C) 2010 Yesudeep Mangalapilly <yesudeep@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a c... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
PyEVO reCAPTCHA API module
===============================================
.. module:: pyevo.api.recaptcha
:platform: Unix, Windows
:synopsis: PyEVO reCAPTCHA API module
.. moduleauthor:: (C) 2012 Oliver Gutiérrez
TODO: Check recaptcha API module for incomplete class method get_ch... | nilq/baby-python | python |
from ._container import AadModelContainer
from onnxconverter_common.topology import Topology
from onnxconverter_common.data_types import FloatTensorType
from ad_examples.aad.forest_aad_detector import AadForest
def _get_aad_operator_name(model):
# FIXME: not all possible AAD models are currently supported
if not is... | nilq/baby-python | python |
#import matplotlib.pyplot as plt
from flask import Flask, render_template, jsonify
import requests
import json
import numpy as np
import time
app = Flask(__name__)
@app.route('/')
def index():
r = requests.get("http://127.0.0.1:5000/chain").text
r = json.loads(r)
# Fetch the chain length
chain_leng... | nilq/baby-python | python |
import numpy as np
import lsst.afw.table as afwTable
import lsst.pex.config as pexConfig
import lsst.pipe.base as pipeBase
import lsst.geom as geom
import lsst.sphgeom as sphgeom
from lsst.meas.base.forcedPhotCcd import ForcedPhotCcdTask, ForcedPhotCcdConfig
from .forcedPhotDia import DiaSrcReferencesTask
__all__ = ... | nilq/baby-python | python |
# Generated by Django 2.1 on 2018-09-08 14:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0003_market'),
]
operations = [
migrations.AlterUniqueTogether(
name='market',
unique_together={('name', 'exchange')},
... | nilq/baby-python | python |
import serial
import struct
import time
def init_Serial():
print("Opening Serial Port COM 10")
ser = serial.Serial(
port='COM10',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
return ser
def wait_for_Pi(se... | nilq/baby-python | python |
from .Updater import Converters
class _DataManager:
def unpack(self, data):
return self.unpackItems(data.items())
def unpackItems(self, items):
return {key: self.itemsToDict(value) for key, value in items}
def itemsToDict(self, data):
if hasattr(data, "__dict__"):
ret... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function
import roslib
roslib.load_manifest('mct_watchdog')
import rospy
import threading
import functools
import numpy
import mct_introspection
import yaml
import cv
import Image as PILImage
import ImageDraw as PILImageDraw
import ImageFont as PILImageFont
from cv_b... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.