content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python
#
# Copyright (C) 2007 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General ... | nilq/baby-python | python |
#!/usr/bin/env python
from qiskit import QuantumProgram
Circuit = 'oneBitFullAdderCircuit'
# Create the quantum program
qp = QuantumProgram()
# Creating registers
n_qubits = 5
qr = qp.create_quantum_register("qr", n_qubits)
cr = qp.create_classical_register("cr", n_qubits)
# One-bit full adder circuit, where:
# qr... | nilq/baby-python | python |
"""add degree denormalizations
Revision ID: 38c7982f4160
Revises: 59d7b4f94cdf
Create Date: 2014-09-11 20:32:37.987989
"""
# revision identifiers, used by Alembic.
revision = '38c7982f4160'
down_revision = '59d7b4f94cdf'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(u'grano_entit... | nilq/baby-python | python |
from protodata.serialization_ops import SerializeSettings
from protodata.reading_ops import DataSettings
from protodata.utils import create_dir
from protodata.data_ops import NumericColumn, split_data, feature_normalize, \
map_feature_type, float64_feature, int64_feature
import tensorflow as tf
import pandas as pd... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""argparse and main entry point script"""
import argparse
import logging
import os
import sys
from logging.handlers import TimedRotatingFileHandler
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import kootkounter.bot
LOG_LEVEL_STRINGS = ... | nilq/baby-python | python |
import sys
from pathlib import Path
# Path modifications
paths = ["../build/src", "../src/preproc", "../src/util"]
for item in paths:
addPath = Path(__file__).parent / item
sys.path.append(str(addPath.resolve()))
#-----------------------------------------------------------------------------#
import util_yam... | nilq/baby-python | python |
import os
import yaml
def root():
mydir = os.path.dirname(os.path.realpath(__file__))
return os.path.dirname(mydir)
def tla_result_fixture(zone_number, score=0):
return {
'score': score,
'present': True,
'disqualified': False,
'zone': zone_number,
}
def get_data(da... | nilq/baby-python | python |
from django.urls import include, path, re_path
from . import handlers
article_urlpatterns = [
path("2020/", handlers.handler_2020, name="articles-2020"),
path(
"categories/",
include(
[
path("<str:category>", handlers.category, name="categories"),
pa... | nilq/baby-python | python |
import base64
import os
from io import BytesIO
from PIL import Image
from rest_framework import serializers
from photologue.models import Photo, Gallery
from oms_cms.config import settings
from django.conf import settings
BASE_DIR = settings.BASE_DIR
class ImageSerializerField(serializers.Field):
def to_repr... | nilq/baby-python | python |
# vim: set expandtab shiftwidth=4 :
# pylint: disable=missing-docstring
import json
import requests
from . import base
from . import settings
class KeysSymmTest(base.BaseTest):
user = settings.EXISTING_USERS[1]
wrong_user = settings.EXISTING_USERS[2]
def make_put_body(self):
return {
... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate ERT vs param. figures.
The figures will show the performance in terms of ERT on a log scale
w.r.t. parameter. On the y-axis, data is represented as
a number of function evaluations. Crosses (+) give the median number of
function evaluations for the smallest r... | nilq/baby-python | python |
# Generated by Django 2.1.5 on 2019-02-18 12:48
from django.db import migrations, models
def change_negative_fields(apps, schema_editor):
Resource = apps.get_model('resources', 'Resource')
for resource in Resource.objects.all():
resource_has_changed = False
if resource.area and resource.area ... | nilq/baby-python | python |
""" Samples of how to use tw2.jit
Each class exposed in the widgets submodule has an accompanying Demo<class>
widget here with some parameters filled out.
The demos implemented here are what is displayed in the tw2.devtools
WidgetBrowser.
"""
from tw2.core.resources import JSSymbol
from tw2.jit.widgets import SQLAR... | nilq/baby-python | python |
import numpy as np
from matplotlib import pyplot as plt
from neural_network import NeuralNet
def generate_data():
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N * K, D))
y = np.zeros(N * K, dtype='uint8') # class labels
for j in range... | nilq/baby-python | python |
def rev(string):
reverse_string = ''
for c in range(len(string)-1, -1, -1):
reverse_string += string[c]
return reverse_string
| nilq/baby-python | python |
from typing import Any, Iterable, Iterator, Mapping, Optional, Tuple, TypedDict, Union
from eth_enr import ENRAPI
from eth_enr.abc import ENRManagerAPI
from eth_enr.typing import ENR_KV
from eth_typing import HexStr
from eth_utils import (
encode_hex,
is_hex,
is_integer,
is_text,
to_bytes,
to_d... | nilq/baby-python | python |
# vim:fileencoding=utf-8
# License: BSD Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
# globals: ρσ_str
def strings():
string_funcs = set((
'capitalize strip lstrip rstrip islower isupper isspace lower upper swapcase'
' center count endswith startswith find rfind index rindex format join ... | nilq/baby-python | python |
from collections import OrderedDict
import pytest
from .. import *
from .subroutines import (
findRecursionPoints,
spillLocalSlotsDuringRecursion,
resolveSubroutines,
)
def test_findRecursionPoints_empty():
subroutines = dict()
expected = dict()
actual = findRecursionPoints(subroutines)
... | nilq/baby-python | python |
#!/bin/python
def opDeterminer(ops):
vals = []
for op in ops:
if op[0] == 'r':
(vals, success) = removeOp(vals, long(op[1]))
if not success:
print ('Wrong!')
continue
elif op[0] == 'a':
(vals, success) = addOp(vals, long(op[1])... | nilq/baby-python | python |
import signal, time
STATE = 0
def state2(signum, frame):
print('state2')
signal.signal(signal.SIGHUP, signal.SIG_DFL)
def state1(signum, frame):
print('state1')
signal.signal(signal.SIGHUP, state2)
signal.signal(signal.SIGHUP, state1)
while STATE < 10:
time.sleep(0.01)
| nilq/baby-python | python |
''' testing models '''
from io import BytesIO
from collections import namedtuple
import json
import pathlib
import re
from unittest.mock import patch
from PIL import Image
import responses
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.db import models
fr... | nilq/baby-python | python |
class _Position:
def __init__(self, shares, share_price):
if share_price <= 0:
raise ValueError("Please enter a positive number for share_price")
self.shares = shares
self.position_size = float(shares * share_price)
def buy(self, shares, share_price):
if shares < 0 o... | nilq/baby-python | python |
import io
import re
from pathlib import Path
from zipfile import ZipFile
import typer
from typer import Option, Argument
from patterns.cli.services.lookup import IdLookup
from patterns.cli.services.output import sprint, abort_on_error, abort
from patterns.cli.services.pull import (
download_graph_zip,
downloa... | nilq/baby-python | python |
# Copyright (C) 2014, Red Hat, 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... | nilq/baby-python | python |
import os
from flask import render_template, url_for, flash, redirect,request,abort
from blog import app,db,bcrypt
from blog.models import User,Post
from blog.forms import RegistrationForm, LoginForm,UpdateAccountForm,PostForm
from flask_login import login_user,current_user,logout_user,login_required
import secrets
@... | nilq/baby-python | python |
import pandas as pd
import logging
def ris_detect(raw):
""" Detect RIS format style. """
if raw.startswith('TY -'):
logging.debug('RIS file format detected.')
return 'ris'
elif raw.startswith('%0'):
logging.debug('Endnote file format detected.')
return 'endnote'
else:
... | nilq/baby-python | python |
import unittest
import tethys_gizmos.views.gizmo_showcase as gizmo_showcase
from requests.exceptions import ConnectionError
from unittest import mock
from django.test import RequestFactory
from ... import UserFactory
class TestGizmoShowcase(unittest.TestCase):
def setUp(self):
self.user = UserFactory()
... | nilq/baby-python | python |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask... | nilq/baby-python | python |
import json
class ObjectLogService:
"""
Служба журналирования логов по объектам
"""
def __init__(self, app):
"""
:type app: metasdk.MetaApp
"""
self.__app = app
self.__options = {}
def log(self, record):
"""
Делает запись по объекту в журна... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import scrapy
import re
from bgm.items import Record, Index, Friend, User, SubjectInfo, Subject
from bgm.util import *
from scrapy.http import Request
import datetime
import json
mpa = dict([(i, None) for i in range(32)])
class UserSpider(scrapy.Spider):
name = 'user'
def __init__(sel... | nilq/baby-python | python |
if __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from functools import partial
from Stream import Stream, StreamArray
from Stream import _no_value
from Operators import stream_func
from stream_test import *
def square(v):
... | nilq/baby-python | python |
'''
xbrlDB is an interface to XBRL databases.
Two implementations are provided:
(1) the XBRL Public Database schema for Postgres, published by XBRL US.
(2) an graph database, based on the XBRL Abstract Model PWD 2.
(c) Copyright 2013 Mark V Systems Limited, California US, All rights reserved.
Mark V copyright app... | nilq/baby-python | python |
"""Heat pump module
Modelling a heat pump with modelling approaches of
simple, lorentz, generic regression, and standard test regression
"""
import os
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from sklearn.line... | nilq/baby-python | python |
#
# PySNMP MIB module APTIS-HDLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APTIS-HDLC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:24:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | nilq/baby-python | python |
from datetime import datetime
from validator.kube.resource import KubernetesResourceProvider
from validator.base import ClusterResult
from validator.namespace import validate_namespaces
def run_validate(host, token):
provider = KubernetesResourceProvider(host, token)
ns = validate_namespaces(provider)
no... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
# # Coding Exercises (Part 1)
# ## Full Data Workflow A-Z: Merging, Joining, Concatenating
# ### Exercise 12: Merging, joining, aligning and concatenating Data
# Now, you will have the opportunity to analyze your own dataset. <br>
# __Follow the instructions__ and insert your ... | nilq/baby-python | python |
# Incorrect order
a = 5
b = 5
print(c)
c = 6 | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from scapy.layers.l2 import Dot3, LLC, STP
from scapy.all import sendp, RandMAC
# --------------------------------------------------------------------------
# STP TCN ATTACK
# --------------------------------------------------------------------------
def run(int... | nilq/baby-python | python |
# define self-attention
# simply modify the code for this paper A Structured Self-Attentive Sentence Embedding
class StructuredSelfAttention(torch.nn.Module):
def __init__(self, batch_size, lstm_hid_dim, d_a, r, max_len, emb_dim=128, vocab_size=None,
use_pretrained_embeddings = False, embeddin... | nilq/baby-python | python |
from django.test import override_settings
from django.utils import timezone
from hotels.models import HotelRoomReservation
from pretix.exceptions import PretixError
from pytest import mark
def test_cannot_create_order_unlogged(graphql_client, user, conference, mocker):
response = graphql_client.query(
"""... | nilq/baby-python | python |
import io
import cv2
import fs
import fs.memoryfs
import numpy as np
import matplotlib.pyplot as plt
class ramp4():
"""
INTRODUCTION
------------
A simple library to make mp4 movies with matplotlib.pyplot. It use RAM instead of disk storage for the temporary images.
HOW TO USE
-----------
... | nilq/baby-python | python |
table_config = [
{
'field': None,
'title': '选择',
'display': True,
'text':
{
'tpl': '<input type="checkbox" value="{n1}" />',
'kwargs':
{
'n1': '@id',
}
},
'... | nilq/baby-python | python |
#!/usr/bin/python2
import sys
import time
fh = open(sys.argv[1], 'rb')
stage_2 = fh.read()
fh.close()
sploit = [
'\x00', '\x00', # r7
'\x30', '\x30', # r6
'\x31', '\x31', # r5
'\x32', '\x32', # r3
'\x34', '\x33', # r2
'\x34', '\x34', # r1
'\x00', '\x0A', # canary
'\x35', '\x35', # rbp
'\x02', '\x2E', # ret
... | nilq/baby-python | python |
#!/usr/bin/python3
import cmath
import numpy as np
import pytest
from pytest import approx
from emtoolbox.tline.tline import TLine
from emtoolbox.tline.mtl_network import MtlNetwork
def pol2rect(mag, deg):
return cmath.rect(mag, np.deg2rad(deg))
@pytest.mark.parametrize(
"f",
[
5e6,
np.... | nilq/baby-python | python |
# Section 10.8.1 snippets
# 10.8.1 Base Class CommissionEmployee
# Testing Class CommissionEmployee
from commissionemployee import CommissionEmployee
from decimal import Decimal
c = CommissionEmployee('Sue', 'Jones', '333-33-3333',
Decimal('10000.00'), Decimal('0.06'))
c
print(f'{c.earnings():,.2f}')
c.gros... | nilq/baby-python | python |
"""
solution AdventOfCode 2019 day 20 part 2.
https://adventofcode.com/2019/day/20.
author: pca
"""
from general.general import read_file, get_location_input_files, measure
import matplotlib.pyplot as plt
from collections import Counter
import networkx as nx
import heapq
def to_grid(grid_txt):
grid = dict()
... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
from maze import Maze
from RL_brain import SarsaLambdaTable, QLambdaTable
import numpy as np
METHOD = "QLambda"
def get_action(q_table, state):
state_action = q_table.ix[state, :]
state_action_max = state_action.max()
idxs = []
for max_item in range(len(state... | nilq/baby-python | python |
from abc import ABC, abstractmethod
from datetime import datetime
from typing import List
from dateutil.tz import tz
from pytz import timezone
from dataclasses import dataclass
from importlib import import_module
from .constant import Interval, Exchange
from .object import BarData, TickData
from .setting import SETTI... | nilq/baby-python | python |
import os
import requests
import subprocess
import wget
import zipfile
def download_latest_version(version_number, driver_directory):
"""Download latest version of chromedriver to a specified directory.
:param driver_directory: Directory to save and download chromedriver.exe into.
:type driver... | nilq/baby-python | python |
"""
Given an array, return the max difference between
2 numbers in array whereby:
- larger number is after smaller number in array order
eg: [0, 1, 12] -> 12
eg: [12, 0, 1] -> 1
"""
def maxDiff(arr, n):
# Initialize Result
maxDiff = -1
# Initialize max element from
# right side
maxRight = arr[n... | nilq/baby-python | python |
from datetime import datetime
import dill as pickle
from pathlib import Path
from copy import deepcopy
import numpy as np
from skimage.io import imread
import GPnd
from GPnd import *
from plotting import MAP_Estimator
if __name__=='__main__':
f_path = Path('chains/2019-09-22T16-01-08_n100000.pkl')
with op... | nilq/baby-python | python |
# encoding=utf8
# pylint: disable=line-too-long
"""Implementation of modified nature-inspired algorithms."""
from NiaPy.algorithms.modified.hba import HybridBatAlgorithm
from NiaPy.algorithms.modified.hde import DifferentialEvolutionMTS, DifferentialEvolutionMTSv1, DynNpDifferentialEvolutionMTS, DynNpDifferentialEvolu... | nilq/baby-python | python |
from __future__ import annotations
from typing import Any, TypeVar, cast
from discord.ext import typed_commands
C = TypeVar('C', bound='Cog[Any]')
CT = TypeVar('CT', bound=typed_commands.Context)
class Cog(typed_commands.Cog[CT]):
def _inject(self: C, bot: typed_commands.Bot[CT], /) -> C:
self.__pre_in... | nilq/baby-python | python |
import xlrd
import csv
def Excel2CSV(ExcelFile='SicCodesAllLevels.xls',
SheetName='SIC4', CSVFile='ref_list.csv'):
workbook = xlrd.open_workbook(ExcelFile)
worksheet = workbook.sheet_by_name(SheetName)
csvfile = open(CSVFile, 'wb')
wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
for... | nilq/baby-python | python |
import numpy as np
import os
class Lay(object):
def __init__(self):
self.__m = self.m_world = None
self.__r = self.m_world = None
self.__s = self.m_world = None
self.m_world = None
self.m_world_inv = None
self.is_ready = False
def set(self, move=np.eye(4), rota... | nilq/baby-python | python |
"""Class instance for Transformer
"""
import argparse
# pylint: disable=unused-argument
class Transformer():
"""Generic class for supporting transformers
"""
def __init__(self, **kwargs):
"""Performs initialization of class instance
Arguments:
kwargs: additional parameters pass... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtCore, QtGui, QtWidgets
class GraphicView(QtWidgets.QGraphicsView):
def __init__(self):
QtWidgets.QGraphicsView.__init__(self)
self.setWindowTitle("QGraphicsView")
scene = QtWidgets.QGraphicsScene(self)
sce... | nilq/baby-python | python |
# Generated by Django 3.2.7 on 2021-09-27 15:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rgd_fmv', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='fmv',
name='status',
fiel... | nilq/baby-python | python |
from bs4 import BeautifulSoup
import requests
import re
from graph import Graph
from player import Player
class Crawler:
def __init__(self,link_root=""):
self.link_root = "https://www.hltv.org/stats/teams"
self.headers = {}
self.headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) Appl... | nilq/baby-python | python |
from flask_wtf import FlaskForm
class NameForm(FlaskForm):
pass
| nilq/baby-python | python |
# coding: utf-8
"""
MailSlurp API
MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://ww... | nilq/baby-python | python |
""""""
import pytest
import random
import tempfile
from textwrap import dedent
from unittest import mock
from pybryt.utils import *
from .test_reference import generate_reference_notebook
def test_filter_picklable_list():
"""
"""
l = [1, 2, 3]
filter_picklable_list(l)
assert len(l) == 3
w... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 :audit_utils.py
@说明 :
@时间 :2020/07/21 16:38:22
@作者 :Riven
@版本 :1.0.0
'''
import base64, logging, socket, sys
sys.path.append('.')
from app_server.src.utils.collection_utils import get_first_existing
from app_server.src.utils.to... | nilq/baby-python | python |
#!/home/jeffmur/archiconda3/envs/face_recon/bin/python3
import face_recognition
import cv2
import numpy as np
import pickle
from pathlib import Path
from datetime import datetime
import signal,sys,time
from google.cloud import pubsub_v1
# TODO (developer config)
project_id = "{GOOGLE_CLOUD_PROJECT_ID}"
topic_id = ... | nilq/baby-python | python |
from eeval.evaluator import evaluate
from math import pi
import timeit
exprs = (
"2+2*2",
"(2+2)+(2+2)",
"-(2+2)+(-(2+2))",
"(2+2)*(-(2+2))",
"-(-(-(-(3*88888))))",
"pi*2",
"(pi+1)*(pi+2)",
"-pi",
"pi^2"
)
constants = {
"pi": pi
}
itercount = 1000
print("Evaluator test:")
f... | nilq/baby-python | python |
from typing import Dict
from smartz.api.constructor_engine import ConstructorInstance
def is_true(arr, key):
return key in arr and bool(arr[key])
class Constructor(ConstructorInstance):
_SWAP_TYPE_ETHER = 'Ether'
_SWAP_TYPE_TOKENS = 'ERC20 tokens'
def __init__(self):
self._TEMPLATES:... | nilq/baby-python | python |
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import permissions
class ReadSelf(permissions.BasePermission):
"""Permits access to the (user)model instance if the user corresponds to the instance"""
message = _("You may only view your... | nilq/baby-python | python |
from __future__ import annotations
def search_in_a_sorted_matrix(
mat: list[list], m: int, n: int, key: int | float
) -> None:
"""
>>> search_in_a_sorted_matrix(
... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 5)
Key 5 found at row- 1 column- 2
>>> search_in_a_sorte... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'PinOnDiskMain.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... | nilq/baby-python | python |
from tests.utils import W3CTestCase
class TestGridPositionedItemsContentAlignment(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'grid-positioned-items-content-alignment-'))
| nilq/baby-python | python |
def search(nums: list[int], target: int) -> int:
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = (start + end) // 2
if nums[mid] == target:
return mid
# Situaion 1: mid is in the left ascending part
if nums[mid] > nums[start]:
if ... | nilq/baby-python | python |
from .csv_parser import Parser as BaseParser
class Parser(BaseParser):
"""Extract text from tab separated values files (.tsv).
"""
delimiter = '\t'
| nilq/baby-python | python |
from mbctl import cli
def test_cli_ok():
cli.run(['list'])
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 5 00:25:04 2021
@author: Perry
"""
# import csv and matplotlib
import csv
import matplotlib.pyplot as plt
# read data.csv into a dictionary called data
data = csv.DictReader(open("data.csv"))
# split the data into three lists for x, y, and z
dataArrays = {"time": [], "x... | nilq/baby-python | python |
"""
Run MWEP
Usage:
main.py --config_path=<config_path>\
--project=<project>\
--path_event_types=<path_event_types>\
--path_mapping_wd_to_sem=<path_mapping_wd_to_sem>\
--languages=<languages>\
--wikipedia_sources=<wikipedia_sources>\
--verbose=<verbose>
Options:
--config_path=<config_path>
... | nilq/baby-python | python |
# -*- mode: python -*-
# -*- coding: utf-8 -*-
##
# 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 Li... | nilq/baby-python | python |
import logging
from heisen.config import settings
class ExtraFields(logging.Filter):
def filter(self, record):
for key, value in getattr(settings, 'EXTERNAL_FIELDS', {}).items():
setattr(record, key, value)
return True
class AbsoluteModuleName(logging.Filter):
def filter(self, ... | nilq/baby-python | python |
from core.commands import *
def execute_from_command_line(argv=None):
"""
A simple method that runs something from command line.
argv[1] is the command
argv[2] is the remaining command or project name
"""
if argv[1] == 'createproject':
createproject(argv[2])
| nilq/baby-python | python |
"""
generate-bus-data.py
Module for automatically generating a simulated bus data set.
"""
import os
import json
import xlrd
from tqdm import tqdm
from grid import Grid # Module local to this project.
def str_ascii_only(s):
'''
Convert a string to ASCII and strip it of whitespace pre-/suffix.
'''
re... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import cv2
import xml.etree.ElementTree as ET
import numpy as np
def get_data(input_path, mode):
all_imgs = []
classes_count = {}
class_mapping = {}
visualise = False
# data_paths = [os.path.join(input_path,s) for s in ['VOC2007', 'VOC2012']]
... | nilq/baby-python | python |
from django.db import models
# Create your models here.
class UserInfo(models.Model):
""" 用户表 """
username = models.CharField(max_length=32, verbose_name="用户名", unique=True)
phone = models.CharField(max_length=11, verbose_name="手机号", unique=True)
email = models.EmailField(max_length=32, verbose_name="... | nilq/baby-python | python |
"""discard columns in web chapter 1 objectives
Revision ID: f1be4ab05a41
Revises: a4ac4ebb0084
Create Date: 2022-01-01 17:33:05.304824
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f1be4ab05a41'
down_revision = 'a4ac4ebb0084'
branch_labels = None
depends_on ... | nilq/baby-python | python |
#!/usr/bin/python
# coding=utf-8
#
# This script reformats a list of leaked names
import anomdns
from anomdns import anonymizer
key = "blahh"
anom = anonymizer()
anom.set_key(key)
test = [
"WWW.GOOGLEAPIS.COM.DAVOLINK", "IB.TIKTOKV.COM.DAVOLINK", "YOUTUBE.COM.DAVOLINK",
"MTALK.GOOGLE.COM.DAVOLINK", "US.PERF... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-04 09:09
from __future__ import unicode_literals
import aether.odk.api.models
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timez... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function
from os import path, getcwd
from runana.run import execute, print_time, generate_list
def main():
input_file = 'config.nml'
chain_iters = setup_replacers()
scratch_base = path.expanduser('~/test_run/runana/integrate_test')
pro... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Author: Thamme Gowda [tg (at) isi (dot) edu]
# Created: 2019-11-11
import argparse
import sys
import logging as log
import io
import collections as coll
from nlcodec.utils import make_n_grams, make_n_grams_all
from nlcodec import load_scheme, EncoderScheme
from pathlib import Path
import json... | nilq/baby-python | python |
version https://git-lfs.github.com/spec/v1
oid sha256:db80e7c15180793b640419d93a414f5ab56bd0fa3c44275e9d251fc513face49
size 14291
| nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import absolute_import
import argparse
import yaml
from pymongo import MongoClient
from pymongo.errors import OperationFailure
##
## Reads users and collections from a yaml file.
##
## User passwords will be set to [username]_pw.
##
def create_users(client, databases):
for ... | nilq/baby-python | python |
from django.conf.urls import url
from django.urls import include
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import routers, permissions, authentication
from environments.views import SDKIdentities, SDKTraits
from features.views import SDKFeatureStates
from organisations... | nilq/baby-python | python |
dia= float(input("Digite o dia do seu nascimento "))
mes= input("Digite o mês do seu nascimento")
ano= float(input("Digite o ano do seu nascimento"))
print("{}/{}/{} dia do nascimento".format(dia,mes,ano)) | nilq/baby-python | python |
#!/usr/bin/env python3
from constr import *
import sys
f = open(sys.argv[1])
s = f.read()
c = parse(s)
# print(f"BEFORE: {c}")
d = dnf(c)
# print(f"DNF: {d}")
app = approx(c)
act = actual(d)
# print(f"APPROX: {app}")
# print(f"ACTUAL: {act}")
if app != act:
sys.stderr.write(f"* FAILED: {sys.argv[1]} (got {app... | nilq/baby-python | python |
from requests import get, put
import json
def kelvin_to_mired(kelvin):
return int(1000000 / kelvin)
def secs_to_lsecs(secs):
return secs * 10
class RestObject(object):
def __init__(self, object_id='', bridge=None):
self.object_id = object_id
self.rest_group = 'unknown'
self.bri... | nilq/baby-python | python |
import cv2
class PlateDisplay():
# create an annotated image with plate boxes, char boxes, and labels
def labelImage(self, image, plateBoxes, charBoxes, charTexts):
(H, W) = image.shape[:2]
# loop over the plate text predictions
for (plateBox, chBoxes, charText) in zip(plateBoxes, charBoxes, charText... | nilq/baby-python | python |
import os
randomkey = "f0f18c4e0b04edaef0126c9720fd"
if randomkey not in os.environ:
print("Intentionally missing random unknown env-var")
os.environ[randomkey] = "999"
print(os.environ[randomkey])
print(os.environ["PATH"])
| nilq/baby-python | python |
from schematics.types import BooleanType
from openprocurement.tender.core.procedure.models.bid import (
PostBid as BasePostBid,
PatchBid as BasePatchBid,
Bid as BaseBid,
)
from openprocurement.tender.core.models import (
ConfidentialDocumentModelType,
validate_parameters_uniq,
)
from openprocurement... | nilq/baby-python | python |
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1>Hola, mundo.</h1>")
def vista(request):
return HttpResponse('<ul><li>URL: {}</li><li>Método: {}</li><li>Codificación: {}</li><li>Argumentos: {}</li></li></ul>'.format(request.path, request.method, request.encoding, request.GET.d... | nilq/baby-python | python |
from .base import KaffeError
from .core import GraphBuilder, DataReshaper, NodeMapper
from . import tensorflow
| nilq/baby-python | python |
import pygame
import time
class Config:
def __init__(self):
self.quit = False
self.pause = False
self.dir_l = False
self.dir_r = False
self.dir_u = False
self.dir_d = False
self.mouse_pos = None
self.mouse_pos_x = None
self.mouse_pos_y = None
self.bullets = []
self.mbd = { # Mouse Bu... | nilq/baby-python | python |
import json
import requests
from insightconnect_plugin_runtime.exceptions import PluginException
import time
from requests import Response
class ZscalerAPI:
def __init__(self, url: str, api_key: str, username: str, password: object, logger: object):
self.url = url.rstrip("/")
self.url = f"{self.ur... | nilq/baby-python | python |
from test_utils import run_query
def test_quadbin_fromgeogpoint_no_srid():
"""Computes quadbin for point with no SRID"""
result = run_query(
'SELECT QUADBIN_FROMGEOGPOINT(ST_MAKEPOINT(40.4168, -3.7038), 4)'
)
assert result[0][0] == 5209574053332910079
def test_quadbin_fromgeogpoint_4326_srid... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.