content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from math import sqrt
from django.test import TestCase
from ..models import InstructionSet
class InstructionSetModelTest(TestCase):
def setUp(self):
self.test_set = InstructionSet.objects.create(up=1, down=3, left=5, right=7)
def test_model_fields(self):
self.assertEqual(self.test_set.up, ... | nilq/baby-python | python |
from .site import SiteCommand
from .platform import PlatformCommand
from .system import SystemCommand
AVAILABLE_COMMANDS = [SiteCommand(), PlatformCommand(), SystemCommand()]
| nilq/baby-python | python |
# Generated by Django 2.0.8 on 2018-08-25 09:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('information_pages', '0004_auto_20180825_1114'),
]
operations = [
migrations.AlterModelOptions(
name='informationdocument',
o... | nilq/baby-python | python |
"""
This script is used to construct, test and analyze the various variants
for digit addition and subtraction.
"""
import re
import sys
import subprocess
import colorama
# snippet construction
def define_all():
global ADD_09_09, ADD_09_90, ADD_90_09, ADD_90_90
global SUB_09_09, SUB_90_09, SUB_09_90, SUB_90... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Spyder Editor
AutoGIS lesson 2 geopandas
This is a temporary script file.
"""
import geopandas as gpd
# set filepath
fp = r'F:\GS\harrisab2\S18\GeoViz\autoGIS_2\Data\DAMSELFISH_distributions.shp'
# read file using gpd.read_file()
data = gpd.read_file(fp)
# write first 50 r... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import division
from pyevolve import G1DList, GSimpleGA, Selectors, Statistics
from pyevolve import Initializators, Mutators, Consts, DBAdapters
import os
from math import log, log1p, exp
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
... | nilq/baby-python | python |
import datetime
import random
import matplotlib.pyplot as plt
from graphpkg.live.graph import LiveTrend,LiveScatter
# plt.style.use('')
count1 = 0
cluster = 0.30
def func1():
global count1
count1 += 1
return datetime.datetime.now(), [random.randrange(1, 10) + count1,random.randrange(1,10)+ count1]
def... | nilq/baby-python | python |
'''
Created on 2016/9/20
:author: hubo
'''
from __future__ import print_function
from vlcp.server import main
from vlcp.event import Client
from vlcp.server.module import Module
from vlcp.config import defaultconfig
from vlcp.protocol.zookeeper import ZooKeeper, ZooKeeperConnectionStateEvent,\
ZooKeeperWatcherEven... | nilq/baby-python | python |
from mbdata import models
from sqlalchemy import inspect
from sqlalchemy.orm.session import object_session
ENTITY_TYPES = {
'artist': models.Artist,
'label': models.Label,
'place': models.Place,
'release_group': models.ReleaseGroup,
'release': models.Release,
'url': models.URL,
'work': mod... | nilq/baby-python | python |
import enum
class Encrypting:
def __init__(self):
encrypting_type = "" #szyfr wybrany w gui
class Cipher(enum.Enum):
NO_CIPHER = 1
CAESAR = 2
FERNET = 3
POLYBIUS = 4
RAGBABY = 5
| nilq/baby-python | python |
from flask import Flask
from flask import render_template
from flask import request, jsonify
import argparse
import itertools
import dateutil.parser
import os
from flask_sqlalchemy import SQLAlchemy
from libs import gcal_client
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
app = Flask(__name__)
app.conf... | nilq/baby-python | python |
#!/usr/bin/env python
#
import webapp2
import re
from google.appengine.ext import ndb
from google.appengine.ext import blobstore
from google.appengine.api import users
from google.appengine.ext.webapp import blobstore_handlers
import logging
import parsers
import headers
# This is the triple store api.
# We have a n... | nilq/baby-python | python |
'''
Created By ILMARE
@Date 2019-3-1
'''
from bs4 import BeautifulSoup
from urllib.request import urlretrieve
import requests
from PIL import Image
import os
import re
totalCount = 0
pre_path = r"/home/ilmare/Desktop/FaceReplace/data/image/"
class PhotoScrawler:
def __init__(self, savePath, destUrl, maxPage):
... | nilq/baby-python | python |
from diary.models import Note
from django.forms import Textarea, ModelForm
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.html import format_html
from django.views.generic import ListView, CreateView
class NoteListView(ListView):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
from lib.ipc import ActorProcess
from lib.systray import SysTrayIcon
from lib.utils import init_logging
class UI(ActorProcess):
def __init__(self, coordinator):
super(UI, self).__init__()
self.coordinator = coordinator
def systray_quit(self, systray_... | nilq/baby-python | python |
# Copyright 2017 Open Source Robotics Foundation, 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... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# Copyright 2019 Kakao Brain
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f... | nilq/baby-python | python |
import numpy as np
import string
wrd_fname = 'p042_words.txt'
def gen_triang_list(elems = 1000):
out_list = []
for x in xrange(1, elems):
out_list.append((x*(x+1))/2)
return out_list
def word_to_sum(word):
total_sum = 0
word = string.lower(string.strip(word))
base_sub = ord('a')-1
... | nilq/baby-python | python |
from flask import Flask, jsonify
from flask_marshmallow import Marshmallow
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_restful import Api
from flask_jwt_extended import JWTManager
ma = Marshmallow()
cors = CORS()
bcrypt = Bcrypt()
jwt = JWTManager()
def create_app(config_object=None):
... | nilq/baby-python | python |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# bot_bcad_3.6.py
import utilities, os, fnmatch, re
async def membersDump(ctx):
serverName = (f"*{ctx.message.guild.name.replace(' ', '-')}*")
membersList = []
for file in os.listdir('./logs'):
if fnmatch.fnmatch(file, 'members-server*'):
... | nilq/baby-python | python |
# Greedy
class Solution:
def maxProfit(self, prices):
profit = 0
for i in range(len(prices) - 1):
profit += max(0, prices[i + 1] - prices[i])
return profit
if __name__ == "__main__":
i = [7, 1, 5, 3, 6, 4]
s = Solution()
print(s.maxProfit(i)) | nilq/baby-python | python |
# source code: binary_decoder.py
# author: Lukas Eder
# date: 13.02.2018
#
# Descr.:
# Userinput wird von ASCII in binaere Byte-Strings gewandelt oder umgekehrt.
# Funktion Binaer zu Ascii
def bin_read(binCode):
for line in file:
line_split = line.strip('\n').split(",")
... | nilq/baby-python | python |
#!/usr/bin/env python3
"""main.py: The main file used to execute MindFull."""
__author__ = "Rhys Read"
__copyright__ = "Copyright 2019, Rhys Read"
import logging
from display import Display
logging.basicConfig(level=logging.DEBUG)
class Main(object):
def __init__(self):
self.__display = Display()
... | nilq/baby-python | python |
from Utils.alerter import send
from Utils.urlShortener import short
import discord
from discord.ext import commands
import config
class AntiCaps(commands.Cog):
def __init__(self, client):
self.client = client
self.title = "Anti-Caps System"
self.type = config.CAPS_TYPE
if self.t... | nilq/baby-python | python |
import numpy as np
def get_quantization_matrix(quality: int = 100) -> np.ndarray:
"""
Get quantization matrix denpends on quality.
Args:
quality: quality of quantization
Returns:
quantiazation matrix
"""
# quantization matrix
q = [[16, 11, 10, 16, 24, 40, 51, 61],
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Hash/CMAC.py - Implements the CMAC algorithm
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perp... | nilq/baby-python | python |
# Copyright (c) 2013 Hortonworks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | nilq/baby-python | python |
from abc import ABCMeta, abstractclassmethod
class iDocGenerator(metaclass=ABCMeta):
"""
Generate documents
"""
def __init__(self):
pass
@abstractclassmethod
def createDocumentTuple(self):
"""
Yield list of documents
"""
pass
@abstractclassmethod
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Setup script for the pyexodus module.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2016
:license:
MIT License
"""
import inspect
import os
import sys
from setuptools import setup, find_packages
# Import the version string.
path = os.path.j... | nilq/baby-python | python |
import numpy as np
import os
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
import pandas as pd
if __name__ == '__main__':
data_path = './augmentation_vtk_data/'
output_path = './'
num_augmentations = 20
train_size = 0.8
with_flip = True
num_sam... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
# Copyright (c) 2017 Servionica
#
# 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 l... | nilq/baby-python | python |
"""Utility code for facilitating collection of code coverage when running tests."""
from __future__ import annotations
import atexit
import os
import tempfile
import typing as t
from .config import (
IntegrationConfig,
SanityConfig,
TestConfig,
)
from .io import (
write_text_file,
make_dirs,
)
f... | nilq/baby-python | python |
import argparse
p = argparse.ArgumentParser()
p.add_argument("--foo", action="store_true")
args = p.parse_args()
print(args.foo)
| nilq/baby-python | python |
#!/usr/bin/env python3
""" Tests for processing microsegment data """
# Import code to be tested
import mseg as rm
# Import needed packages
import unittest
import re
import numpy as np
import os
import itertools
# Skip this test if running on Travis-CI and print the given skip statement
@unittest.skipIf("TRAVIS" i... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import openingbook
book = openingbook.build_table(10)
assert len(book) > 0, "Your opening book is empty"
assert all(isinstance(k, tuple) for k in book), \
"All the keys should be `hashable`"
assert all(isinstance(v, tuple) and len(v) == 2 for v in book.values()), \
"All the values sho... | nilq/baby-python | python |
"""
Insertion resources for SGAS.
Used for inserting usage records into database.
Author: Henrik Thostrup Jensen <htj@ndgf.org>
Magnus Jonsson <magnus@hpc2n.umu.se>
Copyright: NorduNET / Nordic Data Grid Facility (2009, 2010, 2011)
"""
from twisted.internet import defer
from twisted.python import log
from tw... | nilq/baby-python | python |
# Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. 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
#
# Un... | nilq/baby-python | python |
# Generated by Django 3.2.8 on 2021-11-01 19:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('neighbor', '0002_rename_neighbourhood_neighborhood'),
]
operations = [
migrations.RemoveField(
model_name='business',
name='... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""The Windows EventLog (EVT) file event formatter."""
from plaso.formatters import interface
from plaso.formatters import manager
from plaso.lib import errors
class WinEVTFormatter(interface.ConditionalEventFormatter):
"""Formatter for a Windows EventLog (EVT) record event."""
DATA_TYPE... | nilq/baby-python | python |
"""
Some basic admin tests.
Rather than testing the frontend UI -- that's be a job for something like
Selenium -- this does a bunch of mocking and just tests the various admin
callbacks.
"""
import mock
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.test import TestCase
fro... | nilq/baby-python | python |
import os
import json
import functools
from tornado import web
from notebook.base.handlers import IPythonHandler
from nbgrader.api import Gradebook
from nbgrader.apps.api import NbGraderAPI
class BaseHandler(IPythonHandler):
@property
def base_url(self):
return super(BaseHandler, self).base_url.rstr... | nilq/baby-python | python |
"""Test creating new settings """
import pytest
from bot.core.database.settings_collection import SettingsCollection
from test_framework.asserts.database_asserts.check_settings_collection import check_create_new_settings
from test_framework.scripts.common.data_factory import get_test_data
@pytest.mark.asyncio
@pytes... | nilq/baby-python | python |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
# pylin... | nilq/baby-python | python |
import unittest
import mock
from able.queue import ble_task
class TestBLETask(unittest.TestCase):
def setUp(self):
self.queue = mock.Mock()
self.task_called = None
@ble_task
def increment(self, a=1, b=0):
self.task_called = a + b
def test_method_not_executed(self):
s... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""@package Operators
This module offers various methods to process eye movement data
Created by Tomas Knapen on .
Copyright (c) 2010 TKLAB. All rights reserved.
More details.
"""
from __future__ import division
import os, pickle, inspect
import numpy as np
import scipy as s... | nilq/baby-python | python |
class LOG:
""" This class specifies the different logging levels that we support.
Levels can be trivially added here and in src/core/utility.py#Msg along
with their pretty output information.
"""
INFO = 1 # green
SUCCESS = 2 # bold green
ERROR = 3 # red
DEBUG = 4 ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Marker Property
===============
"""
# %% IMPORTS
# Package imports
from matplotlib import rcParams
# GuiPy imports
from guipy import widgets as GW
from guipy.plugins.figure.widgets.types.props import BasePlotProp
from guipy.widgets import set_box_value
# All declaration
__all__ = ['Lin... | nilq/baby-python | python |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.metrics import r2_score
import pandas as ... | nilq/baby-python | python |
import flask
from pypi_vm.infrastructure.view_modifiers import response
from pypi_vm.viewmodels.packages.package_details_viewmodel import PackageDetailsViewModel
from pypi_vm.viewmodels.packages.popular_viewmodel import PopularPackageViewModel
blueprint = flask.Blueprint('packages', __name__, template_folder='templat... | nilq/baby-python | python |
#!/usr/bin/python3
import requests as rq
from hbtn_api.urls import URL_AUTH
def auth(apikey, email, psswd, *args):
data = {
'api_key': apikey,
'email': email,
'password': psswd,
'scope': 'checker'
}
r = rq.get(URL_AUTH, data=data)
return r.json()
| nilq/baby-python | python |
import configparser
import datetime
import wx
import os
# local imports
from . import core
class Config:
"""
Used as a common config manager thorought the application,
it uses configparser functionality to load configuration files
and theme files.
"""
def __init__(self):
self.load_c... | nilq/baby-python | python |
valores: list = list()
maior = menor = 0
for cv in range(0, 5):
valores.append(int(input(f'Digite um valor na posição {cv}: ')))
maior = max(valores)
menor = min(valores)
# if cv == 0:
# maior = menor = valores[cv]
# else:
# if valores[cv] > maior:
# maior = valores[cv]
... | nilq/baby-python | python |
import random
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUMBERS = "0123456789"
class Robot(object):
ROBOT_NAME_CHARS_NUMBER = 2
ROBOT_NAME_NUM_NUMBERS = 3
def __init__(self):
self.reset()
@staticmethod
def _generate_name_section(collection, number_of_iteration):
"""_generate_name... | nilq/baby-python | python |
import sublime,sublime_plugin,threading,json,os,threading,subprocess,socket,shutil
from base64 import b64encode, b64decode
# python 2.6 differences
try:
from hashlib import md5, sha1
except: from md5 import md5; from sha import sha as sha1
from SimpleHTTPServer import SimpleHTTPRequestHandler
from struct import pac... | nilq/baby-python | python |
"""Providers services related to the cache."""
from typing import Optional
from limberframework.cache.cache import Cache
from limberframework.cache.lockers import Locker, make_locker
from limberframework.cache.stores import Store, make_store
from limberframework.foundation.application import Application
from limberfra... | nilq/baby-python | python |
#!/usr/bin/env python2.7
# Distributed under the terms of MIT License (MIT)
# Based on fa.wikipedia's AbarAbzar tool
##https://fa.wikipedia.org/wiki/Mediawiki:Gadget-Extra-Editbuttons-persianwikitools.js
##https://fa.wikipedia.org/wiki/Mediawiki:Gadget-Extra-Editbuttons-persiantools.js
##https://fa.wikipedia.org/wiki... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import logging
import sys
LOG_FORMAT = "[%(process)d] %(asctime)s.%(msecs)03d [%(levelname).1s] %(message)s"
LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
def setup_logging() -> None:
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE_FORMAT)
handler = logging.StreamHandler(sys... | nilq/baby-python | python |
#!/usr/bin/env python
# ClusterShell.Node* test suite
"""Unit test for NodeSet with Group support"""
import copy
import shutil
import sys
import unittest
sys.path.insert(0, '../lib')
from TLib import *
# Wildcard import for testing purpose
from ClusterShell.NodeSet import *
from ClusterShell.NodeUtils import *
... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import io
import math
import numpy as np
import random
import torch
from PIL import Image
def temporal_sampling(hdf5_video, hdf5_video_key, start_idx, end_idx, num_samples, video_length):
"""
Given the start and en... | nilq/baby-python | python |
from setuptools import setup, Extension
import setuptools
stream_json_parser_utils = Extension('stream_json_parser_utils', extra_compile_args = [ '--std=c++11' ], sources = [ 'utils/src/utils.cpp' ])
if __name__ == '__main__':
setup(
name='streamjsonparser',
version='1.1',
description='Stream ... | nilq/baby-python | python |
from collections import OrderedDict
from datetime import datetime, timezone
from pytest import raises
from qsck import serialize
def test_serialize_is_a_function():
assert hasattr(serialize, '__call__')
def test_it_formats_identifier_and_timestamp_as_unix_epoch():
identifier = 'LOG'
some_key_value_pa... | nilq/baby-python | python |
"""
This build static figures with dataset from
the google drive : "study_mearec_SqMEA1015um".
"""
import sys
sys.path.append('../../examples/modules/comparison/')
from generate_erroneous_sorting import generate_erroneous_sorting
import spikeinterface.extractors as se
import spikeinterface.comparison as sc
impor... | nilq/baby-python | python |
from optparse import OptionParser
from random import randint
import random
import sys
import io
import queue
#import statprof
from contextlib import contextmanager
#@contextmanager
#def stat_profiler():
#statprof.start()
#yield statprof
#statprof.stop()
#statprof.display()
class Edge:
def __in... | nilq/baby-python | python |
from moneywave.account import Account
from moneywave.resources import Resource
from moneywave.transaction import Transaction
from moneywave.utils import Util, Settings
from moneywave.wallet import Wallet
class MoneyWave:
def __init__(self, api_key, secret_key, mode="test"):
self.settings = Settings(api_ke... | nilq/baby-python | python |
class PropsdDictionary(dict):
"""A dictionary backed by propsd
This dictionary enables the use of a standard python dictionary
that is backed by the propsd service. The dictionary must be
refreshed by calling the refresh method.
"""
def __init__(self, propsd_client):
self.__propsd_client = propsd_cli... | nilq/baby-python | python |
import argparse
import seaborn as sns # noqa
from matplotlib import pyplot as plt
from pathlib import Path
from dask import dataframe as dd
import const
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True)
args = parser.parse_args()
data_dir = Path(args.... | nilq/baby-python | python |
default_chunk_size = 32 * 1024 * 1024
gs_max_parts_per_compose = 32
upload_chunk_identifier = "gs-chunked-io-part"
reader_retries = 5
writer_retries = 5
| nilq/baby-python | python |
import cmath
def usual(tab):
N = len(tab)
tab2 = [0] * N
for n in range(0, N):
for k in range(0, N):
tab2[n] = tab2[n] + tab[k] * cmath.exp(-2 * 1j * cmath.pi * n * (k / N))
return tab2
def inverse(tab):
N = len(tab)
tab2 = [0] * N
for n in range(0, N):
for ... | nilq/baby-python | python |
from sklearn import preprocessing
from desafio_iafront.jobs.common import transform
from desafio_iafront.data.saving import save_partitioned
class Preprocessing:
def __init__(self, result, saida):
self.result = result
self.saida = saida
def normalizer(self):
# Faz a escala dos valor... | nilq/baby-python | python |
from typing import TYPE_CHECKING
from contextlib import closing
from nonebot.rule import Rule
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import MessageEvent
from .. import crud
from ..db import get_db
if TYPE_CHECKING:
from nonebot.typing import Bot, Event
def validate_user() -> Rule:
... | nilq/baby-python | python |
from django.utils.encoding import force_text
import pytest
from apps.core.tests.base_test_utils import (
generate_uid_and_token,
mock_email_backend_send_messages,
)
from apps.users.constants.messages import EXPIRED_LINK_MESSAGE
from .constants import NEW_TEST_PASSWORD, PASS_RESET_CONFIRM_URL, PASS_RESET_URL
... | nilq/baby-python | python |
from pftools.module_conv_utils import PFConversion
class pncConversion(PFConversion):
"""Class for probe data conversion
inherits from PFConversion
Parameters
----------
pfFile : string
probe file (surface or volume)
verbose : bool
Activate or desactivate informative prints (d... | nilq/baby-python | python |
# Generated by Django 3.0.8 on 2020-08-20 19:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0019_auto_20200820_1508'),
]
operations = [
migrations.AlterField(
model_name='course',
name='hours',
... | nilq/baby-python | python |
""" This module contains the code that allows the LWR to stage file's during
preprocessing (currently this means downloading or copying files) and then unstage
or send results back to client during postprocessing.
:mod:`lwr.managers.staging.preprocess` Module
-------------------------------
.. automodule:: lwr.manage... | nilq/baby-python | python |
import re
import json
VIEW_KEY_RE = r"a.+?href=\".+?viewkey=(.+?)\""
INFO_RE = r"var flashvars_.+? = ({.+})"
class Extractor(object):
def __init__(self):
self._viewkey_re = re.compile(VIEW_KEY_RE, re.MULTILINE)
self._videoinfo_re = re.compile(INFO_RE, re.MULTILINE)
def get_viewkeys(self, dat... | nilq/baby-python | python |
import logging
import random
import re
from datetime import datetime
from plugins import Processor, handler, match
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("neikea.plugins")
class Strip(Processor):
"""
Turn the 'message' string into a dict that will contain different
versions o... | nilq/baby-python | python |
import os
import numpy as np
import sys
import json
def read_text_lines(filepath):
with open(filepath, 'r') as f:
lines = f.readlines()
lines = [l.rstrip() for l in lines]
return lines
def check_path(path):
if not os.path.exists(path):
os.makedirs(path, exist_ok=True) ... | nilq/baby-python | python |
from twilio.rest import Client
from twilio.twiml.voice_response import Gather, VoiceResponse
import os
class TwilioNotification:
def __init__(self, sid, auth_token):
self.client = Client(sid, auth_token)
def send_call(self, action_url, contacts):
response = VoiceResponse()
gather = ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Time : 2021/5/10 11:13
# @Author : Jiangzhesheng
# @File : test0.py
# @Software: PyCharm
import sys
import os
from flye.repeat_graph.repeat_graph import RepeatGraph
import flye.utils.fasta_parser as fp
from my_change.ond_algo import *
from bioclass import Sequence
def get_e... | nilq/baby-python | python |
# @Author: Yang Li
# @Date: 2020-05-20 21:17:13
# @Last Modified by: Yang Li
# @Last Modified time: 2021-04-19 22:14:04
from __future__ import division
from __future__ import print_function
import argparse
import time
import numpy as np
import scipy.sparse as sp
import networkx as nx
import torch
fr... | nilq/baby-python | python |
'''This is sandbox code
'''
| nilq/baby-python | python |
i=0
while False:
i+=1
print("Hello:",i)
| nilq/baby-python | python |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from settings import EMAIL_SMTP_SETTINGS
def send_mail(subject, message, message_type='html'):
message = MIMEText(message, message_type, 'utf-8')
message['From'] = Header(EMAIL_SMTP_... | nilq/baby-python | python |
from zeus import factories
from zeus.constants import Result, Status
from zeus.models import Job
def test_new_job(client, default_source, default_repo, default_hook):
build = factories.BuildFactory(
source=default_source, provider=default_hook.provider, external_id="3"
)
job_xid = "2"
path =... | nilq/baby-python | python |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_descriptio... | nilq/baby-python | python |
from flask import Flask, make_response, render_template, request
app = Flask(__name__, template_folder='template')
@app.route('/')
def index():
return render_template('index02.html')
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request... | nilq/baby-python | python |
'''unit test class for churn library'''
import time
import logging
import unittest
from pandas.api.types import is_string_dtype
from functools import wraps
from churn_library import ChurnLibrarySolution
keep_cols = [
'Customer_Age',
'Dependent_count',
'Months_on_book',
'Total_Relationship_Count',
... | nilq/baby-python | python |
from django.db import models
from s3upload.fields import S3UploadField
class Cat(models.Model):
custom_filename = S3UploadField(dest="custom_filename", blank=True)
class Kitten(models.Model):
mother = models.ForeignKey("Cat", on_delete=models.CASCADE)
video = S3UploadField(dest="vids", blank=True)
... | nilq/baby-python | python |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from .util import number_color
from functools import partial
import glob
import math
from ui.util import number_object
from ui.mouse_event import ReferenceDialog, SnapshotDialog
import copy
Lb_width = 100
Lb_height = 40
Lb... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Warning: Auto-generated file, don't edit.
pinyin_dict = {
0x3416: 'xié',
0x3469: 'luo',
0x36BB: 'jī',
0x378E: 'bǎ,ba',
0x393D: 'chóu',
0x39D1: 'huī',
0x3D89: 'xī',
0x3E62: 'jiā',
0x3E74: 'gěng',
0x3EA2: 'huò',
... | nilq/baby-python | python |
class DefaultableEntityEndpointsMixin(object):
"""
Defaultable entity endpoints.
"""
def set_default(self, id_):
"""
Sets a entity with given ID as default.
Args:
id_ (str): entity ID.
Returns:
dict: new entity.
"""
self.request... | nilq/baby-python | python |
sexo = str(input('Informe seu sexo [M / F]: ')).strip().upper()[0] # pega somente a primeira letra
while sexo != 'M' and sexo != 'F':
sexo = str(input('DADOS INVALIDOS. Informe seu sexo [M / F]: ')).strip().upper()
| nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, DateField
from wtforms.validators import DataRequired
class EntryForm(FlaskForm):
entry = StringField('Entry',validators=[DataRequired()])
project = StringField('Project')
notes = StringField('Notes')... | nilq/baby-python | python |
'''
# DC Racer Testing and Reporting System (DC RTRS)
This script runs a standard test across all the different
student code bases. The tests will be based on 100 frame
scenarios.
'''
import cv2
import numpy as np
import platform
#import matplotlib.pyplot as plt
import time
import sys
from os import listdir
from ... | nilq/baby-python | python |
from io import * | nilq/baby-python | python |
with open('/usr/local/airflow//dags/1','a+') as f:
f.write("1")
| nilq/baby-python | python |
x = input("x : ")
print(type(x))
y = int(x) + 1
print(y)
print(f"x : {x}, y : {y}")
#there are some falsy values in python3 whenever we use them in boolean sense it will output false
# "" --> this a empty string which is falsy according to python3
# 0 --> no. zero is also falsy
# None --> which represent absense... | nilq/baby-python | python |
#
# PySNMP MIB module XEDIA-L2DIAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-L2DIAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:36:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | nilq/baby-python | python |
'''
Stacking the cubes with sizes in descending order from bottom to top.
**NOTE**
Every time only the left-most or the right-most cube can be stacked from the array/list.
'''
#Input Format:
'''
The first line contains a single integer T, the number of test cases.
For each test case, there are 2 lines.
The f... | nilq/baby-python | python |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from taysistunto.feeds import SpeakerFeed, DocumentFeed, ActionFeed, ActionsByWordFeed
urlpatterns = patterns('',
# Examples:
url(r'^$', 'taysistunto.vi... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.