content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import os import sys import json from src.api_reader import get_members from src.intellisense import IntellisenseSchema from src.version import schema_version, sdk_go_version if __name__ == '__main__': ...
nilq/baby-python
python
from setuptools import setup import platform if platform.system() == 'Windows': setup( name='imagesimilarity', version='0.1.2', packages=[''], url='https://github.com/marvinferber/imagesimilarity', license='Apache License 2.0', author='Marvin Ferber', author_...
nilq/baby-python
python
from bytecodemanipulation import ( CodeOptimiser, Emulator, InstructionMatchers, MutableCodeObject, OptimiserAnnotations, ) from bytecodemanipulation.TransformationHelper import BytecodePatchHelper from bytecodemanipulation.Transformers import TransformationHandler from bytecodemanipulation.util imp...
nilq/baby-python
python
#o objetivo desse programa é escrever na tela a taboada do número que o usuário digitar. n = int(input('Digite um número para ver sua taboada: ')) print('-=' * 10) print("{} x {:2} = {} ".format(n,1, n*1)) print("{} x {:2} = {} ".format(n,2, n*2)) print("{} x {:2} = {} ".format(n,3, n*3)) print("{} x {:2} = {} ".format...
nilq/baby-python
python
# project/server/models.py from flask import current_app from project.server import db, bcrypt class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(255), unique=True, nullable=False) password = db.Column(db.Stri...
nilq/baby-python
python
# Copyright (C) 2021 Satoru SATOH <satoru.satoh@gmail.com> # SPDX-License-Identifier: MIT # """Entry point of tests.common.*. """ from .base import ( MaybeModT, Base ) from .constants import ( TESTS_DIR, TESTS_RES_DIR, RULES_DIR, ) from .testcases import ( RuleTestCase, CliTestCase ) __all__ = [ 'TESTS...
nilq/baby-python
python
import pytest import logging from multiprocessing.process import current_process from threading import current_thread import time logging.basicConfig(filename="log.txt", filemode="w") log = logging.getLogger() log.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) formatter = lo...
nilq/baby-python
python
from os import listdir import core.log as log async def main(message, client, serverdata): #Part 1 commandfiles = listdir("./core/commands") commandList = [] #Check if Command is a file for commands in commandfiles: if commands.endswith('.py'): commandList.append(commands.replac...
nilq/baby-python
python
""" ===================== Fitting a light curve ===================== This example shows how to fit the parameters of a SALT2 model to photometric light curve data. First, we'll load an example of some photometric data. """ import sncosmo data = sncosmo.load_example_data() print(data) ############################...
nilq/baby-python
python
#!/bin/python3 # Copyright (C) 2017 Quentin "Naccyde" Deslandes. # Redistribution and use of this file is allowed according to the terms of the MIT license. # For details see the LICENSE file distributed with yall. import sys import os import requests import json import argparse import subprocess import fnmatch owne...
nilq/baby-python
python
# reverse words in a string # " " output is wrong lol class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ reverse = [] temp = "" for i in s: if i == " ": if temp != "": reverse.app...
nilq/baby-python
python
import sys from os.path import join, isfile import threading import importlib.util as iutil from uuid import uuid4 from multiprocessing.dummy import Pool as ThreadPool from datetime import datetime from aequilibrae.project.data import Matrices from aequilibrae.paths.multi_threaded_skimming import MultiThreadedNetworkSk...
nilq/baby-python
python
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
nilq/baby-python
python
# License: BSD 3 clause import tick.base import tick.base_model.build.base_model from .model_hawkes_expkern_leastsq import ModelHawkesExpKernLeastSq from .model_hawkes_expkern_loglik import ModelHawkesExpKernLogLik from .model_hawkes_sumexpkern_leastsq import ModelHawkesSumExpKernLeastSq from .model_hawkes_sumexpkern...
nilq/baby-python
python
from radar import db __all__ = ['Commit'] class Commit(db.Model): id = db.Column(db.Integer, primary_key=True) commit_hash = db.Column(db.String(40)) summary = db.Column(db.String(100)) branch = db.Column(db.String(50)) author = db.Column(db.String(100)) commit_time = db.Column(db.DateTime) ...
nilq/baby-python
python
from django.contrib.gis.db import models class Mansion(models.Model): class Meta: db_table = 'mansion' gid = models.BigAutoField(primary_key=True) housing_area_code = models.BigIntegerField(null=False) facility_key = models.CharField(max_length=4000, null=True) shape_wkt = models.MultiLin...
nilq/baby-python
python
"""Create svg images from a keyboard definition.""" import xml.etree.ElementTree as ET import io from math import sin, cos, atan2, degrees, radians from kbtb.plate import generate_plate def shape_to_svg_element(shape, props={}, x_scale=1, y_scale=-1): return ET.Element( "path", { "d": ...
nilq/baby-python
python
# 工具类,字符串处理 import re class BFStringDeal(object): def __init__(self,arg): self.arg = arg @classmethod # 删除垃圾字符 -- 比如:\n def specialTXT(cls, text): return text.replace("\n", "") @classmethod # 正则表达式处理,字符串 def getAssignContent(cls, text, assignContent): # 获取正则表达式实例,其...
nilq/baby-python
python
__author__ = 'Alexander Horkun' __email__ = 'mindkilleralexs@gmail.com' from django.conf.urls import patterns, url from xanderhorkunspider.web.websites.views import websites, auth urlpatterns = patterns('', url(r'^$', websites.index_view, name='index'), url(r'^add-websi...
nilq/baby-python
python
""" opbeat.contrib.django.celery ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011-2012 Opbeat Large portions are :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from opbeat.contrib.celery import CeleryMixin from opbeat.contrib.django import Dja...
nilq/baby-python
python
# from glob import glob from setuptools import setup setup( name='pybrightsign', version='0.9.4', description='BrightSign APIs for humans. Python module to simplify using the BrightSign BSN/BSNEE API.', long_description=open('../README.md').read(), long_description_content_type='text/markdown', ...
nilq/baby-python
python
# coding: utf-8 # 2019/10/17 @ tongshiwei
nilq/baby-python
python
from curses import meta import shutil from unittest import TestCase import sys import os import metadata_mp3 import shutil import unittest from mutagen.easyid3 import EasyID3 class TestRenameSongName(TestCase): def test_1(self): songNameBefore = "Counting Crows - Colorblind (Official Video)" songN...
nilq/baby-python
python
#!/usr/bin/env python # coding=utf-8 """Writes uninstallation SQL script to stdout.""" from os.path import abspath, join, dirname import sys def uninstall(): with open(join(dirname(abspath(__file__)), 'uninstall.sql')) as f: sys.stdout.write(f.read()) if __name__ == '__main__': uninstall()
nilq/baby-python
python
import os from PIL import Image, ImageDraw from pylab import * import csv class ImageScatterPlot: def __init__(self): self.h, self.w = 20000,20000 self.resize_h = 275 self.resize_w = 275 def create_save_fig(self, image_paths, projected_features, out_file): img_scatter = self.create_fig(image_paths...
nilq/baby-python
python
# Lagoon (2400004) | Zero's Temple (320000000) from net.swordie.ms.loaders import StringData options = [] al = chr.getAvatarData().getAvatarLook() selection = sm.sendNext("Hello. How can I help you? #b\r\n" "#L0#Change hair colour#l\r\n" "#L1#Change eye colour#l\r\n" "#L2#Change ...
nilq/baby-python
python
def a_method(): pass class AClass: pass var = "A Variable" print("Support library name: {}".format(__name__)) if __name__ == '__main__': age = 0 while age <= 0: age = int(input("How old are you? "))
nilq/baby-python
python
''' Manage file shares that use the SMB 3.0 protocol. ''' from ... pyaz_utils import _call_az from . import copy, metadata def list(share_name, account_key=None, account_name=None, connection_string=None, exclude_dir=None, marker=None, num_results=None, path=None, sas_token=None, snapshot=None, timeout=None): '''...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import uuid from django.core.urlresolvers import reverse from rest_framework.test import APITestCase from kolibri.core.auth.models import FacilityUser from kolibri.core.auth.test.helpers import setup_...
nilq/baby-python
python
"""Tests for the config.config-module """ # System library imports from collections import namedtuple from datetime import date, datetime import pathlib import re import sys # Third party imports import pytest # Midgard imports from midgard.config import config from midgard.collections import enums from midgard.dev ...
nilq/baby-python
python
#!/usr/bin/python3 # Created by Jared Dunbar, April 4th, 2020 # Use this as an example for a basic game. import pyxel, random, math import os.path from os import path # Width and height of game screen, in tiles WIDTH = 16 HEIGHT = 12 # Width and height of the game level GL_WIDTH = 170 GL_HEIGHT = 150 # Window offs...
nilq/baby-python
python
import os from urllib.parse import urljoin, urlparse import urllib import ntpath is_win32 = os.name == "nt" def createDirectory(base, new_dir): if is_win32: new_dir = cleanName(new_dir, ".") if not base.startswith("\\\\?\\"): base = "\\\\?\\" + base path_new_dir = os.path.join(base, new_dir) ...
nilq/baby-python
python
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
nilq/baby-python
python
import json import logging from platform import system from ctypes import (c_char_p, c_int, c_uint, c_long, Structure, cdll, POINTER) from typing import Any, TYPE_CHECKING, Tuple, List, AnyStr from rita.engine.translate_standalone import rules_to_patterns, RuleExecutor from rita.types import Rules logger = logging....
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from codecs import open import json import opengraph from repos import final_theses as thesis_slugs template = open('_template.html', 'r', 'utf-8').read() theses = [] for thesis_slug in thesis_slugs: url = 'http://kabk.github....
nilq/baby-python
python
import matplotlib matplotlib.use('TkAgg') from collections import namedtuple import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode def f(x, y): """ Правая часть ДУ y'=f(x, y) """ return x/4-1/(1+y**2) def on_move(event): """ Обработчик событий мыши """ ...
nilq/baby-python
python
# Generated by Django 2.2.8 on 2019-12-11 16:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('django_eveonline_connector', '0010_auto_20191211_1514'), ] operations = [ migrations.AlterField( ...
nilq/baby-python
python
import time import numpy as np from yaaf.evaluation import Metric class SecondsPerTimestepMetric(Metric): def __init__(self): super(SecondsPerTimestepMetric, self).__init__(f"Seconds Per Timestep") self._deltas = [] self._last = None def reset(self): self._deltas = [] ...
nilq/baby-python
python
from pytest import raises from async_cog.tags import Tag def test_tag_format() -> None: tag = Tag(code=254, type=4, length=13) assert tag.format_str == "13I" assert tag.data_pointer is None def test_tag_size() -> None: tag = Tag(code=254, type=4, length=13) assert tag.data_size == 52 def test...
nilq/baby-python
python
""" RenameWidget: This widget permit the rename of the output files in the MKVCommand Also if files are drop from directories in the OS it will rename them. """ # LOG FW0013 import logging import re from pathlib import Path from PySide2.QtCore import Signal, Qt, Slot from PySide2.QtWidgets import ( QGridLayou...
nilq/baby-python
python
# Copyright (c) 2013 Stian Lode # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distrib...
nilq/baby-python
python
""" @author: Hasan Albinsaid @site: https://github.com/hasanabs """ import matplotlib.pyplot as plt import numpy as np import itertools import os def nck(n,k): return np.math.factorial(n)/np.math.factorial(k)/np.math.factorial(n-k) def nchoosek(arr, k): return np.array(list(itertools.combinations(arr, k))) d...
nilq/baby-python
python
#! /usr/bin/env python #----------------------------------------------------------------------- # COPYRIGHT_BEGIN # Copyright (C) 2016, FixFlyer, LLC. # All rights reserved. # COPYRIGHT_END #----------------------------------------------------------------------- class SessionStore(object): """ """ class Liste...
nilq/baby-python
python
"""Process the markdown files. The purpose of the script is to create a duplicate src directory within which all of the markdown files are processed to match the specifications of building a pdf from multiple markdown files using the pandoc library (***add link to pandoc library documentation***) with pdf specific text...
nilq/baby-python
python
# django from hashlib import sha256 from uuid import uuid4 from django.utils.text import slugify from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags # python from bs4 import BeautifulSoup from ...
nilq/baby-python
python
import attr from jstruct import JStruct, JList, REQUIRED from typing import Optional, List @attr.s(auto_attribs=True) class Appointment: type: str date: Optional[str] = None time: Optional[str] = None phone: Optional[str] = None @attr.s(auto_attribs=True) class Address: postalCode: str provi...
nilq/baby-python
python
# Project Euler Problem 19 Solution # # Problem statement: # You are given the following information, but you may prefer to # do some research for yourself. # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-ei...
nilq/baby-python
python
#!/usr/bin/python """Executes Android Monkey stress test over adb to attached Android device.""" __author__ = 'jeff.carollo@gmail.com (Jeff Carollo)' import datetime import json import logging import os import subprocess import sys import time from tasklib import apklib ADB_COMMAND = apklib.ADB_COMMAND MONKEY_COMM...
nilq/baby-python
python
from vol import Vol from net import Net from trainers import Trainer from util import * import os from random import shuffle, sample, random from sys import exit embeddings = None training_data = None testing_data = None network = None t = None N = None tokens_l = None def load_data(): global embeddings, N, tok...
nilq/baby-python
python
# # Copyright(c) 2019 Intel Corporation # SPDX-License-Identifier: BSD-3-Clause-Clear # from enum import Enum class OutputFormat(Enum): table = 0 csv = 1 class StatsFilter(Enum): all = 0 conf = 1 usage = 2 req = 3 blk = 4 err = 5
nilq/baby-python
python
import networkx as nx import numpy as np import math def create_network (correct_answers, data, p_factor, realmodelQ, n_edges_score): #correct_answers is a string which assumes the following values: True, False, "All" #p_factor is a bool that assumes the value True if the factor (1-p) is to be considered for...
nilq/baby-python
python
from django.contrib import admin from .models import ( EconomicAssessment, EconomicImpactAssessment, ResolvabilityAssessment, StrategicAssessment, ) @admin.register(EconomicImpactAssessment) class EconomicImpactAssessmentAdmin(admin.ModelAdmin): pass @admin.register(EconomicAssessment) class Ec...
nilq/baby-python
python
import textwrap from pathlib import Path import pyexasol import pytest from exasol_udf_mock_python.column import Column from exasol_udf_mock_python.connection import Connection from exasol_udf_mock_python.group import Group from exasol_udf_mock_python.mock_exa_environment import MockExaEnvironment from exasol_udf_mock...
nilq/baby-python
python
# -*- coding: utf-8 -*- import ast # This has to be a global due to `exec` shenanigans :-( current_spec = {} # SQL types SQL_TYPES = [ 'TEXT', 'DATE', 'DATETIME', 'INTEGER', 'BIGINT', 'UNSIGNED_BIGINT', 'DOUBLE', 'BLOB', ] # Functions that we don't need DUMMY_FUNCTIONS = [ 'Forei...
nilq/baby-python
python
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright © 2021, Spyder Bot # # Licensed under the terms of the MIT license # ---------------------------------------------------------------------------- """ Status bar widgets. """ # Third-party imports from qt...
nilq/baby-python
python
from .. import Provider as CreditCardProvider class Provider(CreditCardProvider): pass
nilq/baby-python
python
import collections import time import warnings from collections import namedtuple import numpy as np import torch from tianshou.data import Batch, ReplayBuffer from tianshou.env import BaseVectorEnv, VectorEnv Experience = namedtuple('Exp', ['hidden', 'obs', 'act', 'reward', 'obs_next', 'done']) HIDDEN_SIZE = 256 ...
nilq/baby-python
python
# 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 writing, software # d...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Jul 23 13:56:25 2020 Authors: Pavan Kota, Daniel LeJeune Reference: P. K. Kota, D. LeJeune, R. A. Drezek, and R. G. Baraniuk, "Extreme Compressed Sensing of Poisson Rates from Multiple Measurements," Mar. 2021. arXiv ID: """ # Multiple Measurement Vector Compressed Sensi...
nilq/baby-python
python
import torch import torch.nn as nn from lazytorch import ( LazyConv2dInChannelModule, create_lazy_signature, NamedSequential, ) from .depth_sep_conv import DepthwiseConv2d, PointwiseConv2d from .squeeze_excitation import SqueezeExcitation from typing import Optional class InvertedBottleneck(nn.Module): ...
nilq/baby-python
python
from rest_framework import generics, status from rest_framework import viewsets from rest_framework.exceptions import ( ValidationError ) from rest_framework.response import Response from rest_framework.permissions import AllowAny from .models import ( Category, Recipe ) from .serializers import ( Categor...
nilq/baby-python
python
import shutil from tokenizers.normalizers import NFKC from autonmt.preprocessing import tokenizers from autonmt.bundle import utils from autonmt.bundle.utils import * def normalize_file(input_file, output_file, normalizer, force_overwrite, limit=None): if force_overwrite or not os.path.exists(output_file): ...
nilq/baby-python
python
"""PythonHere app.""" # pylint: disable=wrong-import-order,wrong-import-position from launcher_here import try_startup_script try: try_startup_script() # run script entrypoint, if it was passed except Exception as exc: startup_script_exception = exc # pylint: disable=invalid-name else: startup_script_ex...
nilq/baby-python
python
#!/usr/bin/env python3 import random #random.seed(1) # comment-out this line to change sequence each time # Write a program that stores random DNA sequence in a string # The sequence should be 30 nt long # On average, the sequence should be 60% AT # Calculate the actual AT fraction while generating the sequence # Rep...
nilq/baby-python
python
import numpy as np import typing as tp import matplotlib.pyplot as plt import pickle import scipy.signal as signal import shapely.geometry import scipy.interpolate as interp from taylor import PointAccumulator from dataclasses import dataclass def find_datapoints(image, start=0): # _image = 255 - image ...
nilq/baby-python
python
""" Tests for the GeniusZone class """ import unittest from unittest.mock import Mock from geniushubclient.const import IMODE_TO_MODE, ZONE_MODE, ZONE_TYPE from geniushubclient.zone import GeniusZone class GeniusZoneDataStateTests(unittest.TestCase): """ Test for the GeniusZone Class, state data...
nilq/baby-python
python
from django.conf.urls import url, include from . import views from django.urls import path urlpatterns = [ path('', views.index, name = 'index'), path('allcomment/',views.allcomment, name = 'allcomment'), path('allexpert/',views.allexpert, name = 'allexpert'), path('apply/',views.apply, name = 'apply')...
nilq/baby-python
python
# -*- coding: utf-8 -*- import wx import wx.xrc import time import pyperclip import os import sys import platform import data ########################################################################### ## Class MyFrame1 ########################################################################### class MyFrame1 ( wx....
nilq/baby-python
python
''' ''' import os import numpy as np from provabgs import models as Models def test_DESIspeculator(): ''' script to test the trained speculator model for DESI ''' # initiate desi model Mdesi = Models.DESIspeculator() # load test parameter and spectrum test_theta = np.load('/Users/cha...
nilq/baby-python
python
import datetime import difflib # import datefinder from dateparser.search import search_dates from dateutil.parser import parse from SMELT.validators.twitter.tweets import get_tweets from SMELT.Validation import Validator # from twitterscraper import import twint def fetch_closest_matching_tweet(username, message, t...
nilq/baby-python
python
# # This file is part of Brazil Data Cube Collection Builder. # Copyright (C) 2019-2020 INPE. # # Brazil Data Cube Collection Builder is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Define the Collection Builder utilities for Land...
nilq/baby-python
python
"""Custom CSV-related functionality.""" import csv import os def create_csv(): """Create new csv to store git-geo result Delete any existing csv and the create new csv. Args: None Returns: None """ # delete csv if it already exists filename = "git-geo-results.csv" i...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function, with_statement from __future__ import unicode_literals from tornado import ioloop, web, websocket, httpserver, concurrent from collections import defaultdict import mock class DeepstreamHandler(websocket.WebSocketHandler): connections = defaultd...
nilq/baby-python
python
# -*- coding: utf-8 -*- import json import logging from pathlib import Path from questionary import prompt from ... import constants as C from ...core import display from ...core.app import App from ...core.arguments import get_args from ...core.crawler import Crawler from .open_folder_prompt import display_open_fold...
nilq/baby-python
python
from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.pagination import PageNumberPagination from django_filters.rest_framework import DjangoFilterBackend from rest_framework.response import Response from rest_framework import status from perm.models import PerMisson from ...
nilq/baby-python
python
import gc import json import warnings import flask_restful from eventlet import greenthread from injector import CallableProvider, inject from flask import Blueprint, Flask from flask.templating import render_template_string from flask.views import View from nose.tools import eq_ from flask_injector import request, F...
nilq/baby-python
python
# -*- coding: utf-8 -*- from validator import Validator class VimLParserLint(Validator): __filetype__ = 'vim' checker = 'vimlparser' args = '' regex = r""" .+?: (?P<lnum>\d+): (?P<col>\d+): \svimlparser:\s (?P<text> ( ...
nilq/baby-python
python
a = 4.9 b = 9.8 sum1 = a + b print('resultado:', sum1)
nilq/baby-python
python
from functools import reduce from itertools import combinations from operator import mul from aocd import data as expense_report entries = list(map(int, expense_report.splitlines())) for part in (1, 2): for combo in combinations(entries, part+1): if sum(combo) == 2020: print(f'Part {part}:',...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 8 18:50:45 2021 @author: patrick """ from .Facebook_Chat_Analysis import *
nilq/baby-python
python
"""Module for the base objects of the abstract argumentation frameworks.""" from .relation import RelationType from .relation import Relation from .premise import FallacyType from .premise import Premise from .graph import Graph from .extension import Extension
nilq/baby-python
python
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped, Quaternion from mavros_msgs.srv import CommandBool, CommandTOL, SetMode, SetModeRequest from mavros_msgs.msg import State import time from tf.transformations import quaternion_from_euler flight_alt = 1.0 # (m) class TakeOffLand(): def _...
nilq/baby-python
python
from flask import ( g, redirect, url_for ) from tmc.db import get_db, make_dicts # Get list of all industries available in the database. def get_industries(): db = get_db() try: db.row_factory = make_dicts query = db.execute( 'SELECT id as db_id, industry_name as Industry FROM indu...
nilq/baby-python
python
''' Miscellaneous math functions. ''' from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np def matrix_sqrt(X=None, symmetric=False, inverse=False, eigs=None): '''Returns the matrix square root of X. Arguments: `X` (square class::`numpy.ndarrray`) ...
nilq/baby-python
python
import tkinter as tk def get_line_numbers(): output = '' row, col = text_editor.index("end").split('.') #row give the no of row in text #print(int(row)-1) for i in range(1, int(row)): output += str(i) + '\n' #making a string with row no. with \n(next line) #print(output) ret...
nilq/baby-python
python
# -*- encoding=utf8 -*- __author__ = "srz_zumix" sys.path.append(r"../pmbase") from airtest.core.api import * from pmbase import PmBase auto_setup(__file__) # adb = ADB() # def update(): # print adb.shell('dumpsys battery') sleep_mul = 1 pm = PmBase(sleep_mul) pm.setup() def pm_sleep(s): pm.pm_sleep(s) d...
nilq/baby-python
python
# coding=utf8 from __future__ import unicode_literals, absolute_import, division, print_function """ This is the SpiceBot AI system. Based On Chatty cathy """ from sopel.tools import Identifier from sopel.config.types import StaticSection, ListAttribute, ValidatedAttribute import os import tempfile import aiml from ...
nilq/baby-python
python
""" TODO TESTS: - Syntax errors, - general tests """ from helper import ( ValueChecker, FlaskValueCheckerSyntaxError, FlaskValueCheckerValueError, ) import random import string import pytest import io test_restriction_code = """ # some simple data for tests here firstName : str/lenlim(5, 15) #...
nilq/baby-python
python
import hashlib string1 = 'Teste inicial'.encode('utf-8') string2 = 'Teste inicial'.encode('utf-8') hash1 = hashlib.new('ripemd160') hash1.update(string1) hash2 = hashlib.new('ripemd160') hash2.update(string2) print("-" * 60) print(hash1.hexdigest()) print(hash2.hexdigest()) if hash1.digest() == hash2.digest(...
nilq/baby-python
python
from django.conf.urls import url import lessons.views urlpatterns = ( url(r'^create/(?P<course_id>\d+)$', lessons.views.schedule_create_page, name="lessons.views.schedule_create_page"), url(r'^edit/(?P<lesson_id>\d+)$', lessons.views.schedule_edit_page, name="lessons.views.schedule_edit_page"),...
nilq/baby-python
python
import warnings import numpy as np from skimage.restoration import denoise_wavelet def apply_rolling_window(mainchunk: np.array, meterchunk: np.array, window_size: int): if not window_size: raise Warning('Window size is not defined.') indexer = np.arange(window_size)[None, :] + np.arange(len(mainchun...
nilq/baby-python
python
#pylint: disable=line-too-long,broad-except """Calculates total time from calendar events, grouped by an event attribute. Usage: calcatime -c <calendar_uri> [-d <domain>] -u <username> -p <password> <timespan>... [--by <event_attr>] [--include-zero] [--json] [--debug] Options: -h, --help ...
nilq/baby-python
python
""" db_fun.py This module contains helper functions for database entry creation. """ from models import Resource, Category from datetime import datetime def get_or_create(session, model, **kwargs): """ Determines if a given record already exists in the database. Args: session: The database se...
nilq/baby-python
python
# # 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 License, Version 2.0 # (the "License"); you may not us...
nilq/baby-python
python
#!/usr/bin/env python3 import sys from setuptools import setup, find_packages from urllib.parse import urlparse with open('requirements.txt', 'r') as f: install_requires = [] dependency_links = [] append_version = '-' + str(sys.maxsize) requirements = [ line.strip() for line in f ] for requireme...
nilq/baby-python
python
from flask import session, request from flask_restful import Resource, reqparse, inputs, abort from api.common.database import database from api.common.utils import checkTag, checkTime, checkTel import json import requests ''' ### sendOfflineCapsule Use this method to send offline capsule. HTTP Request Method: **POST...
nilq/baby-python
python
""" Read a set of input files for the child oids and generate a SQL file that queries for the master records changed by those OID. This one uses an IN clause instead of the simple query to test relative performance of the two I am using the therory that runing the commands directly from psql should yield the h...
nilq/baby-python
python
"""""" import os import sys import uuid import bz2 import pickle import traceback import zlib import json from abc import ABC from copy import copy from typing import Any, Callable from logging import INFO, ERROR from datetime import datetime from vnpy.trader.constant import Interval, Direction, Offset, Status, OrderTy...
nilq/baby-python
python
# Copyright 2017, Wenjia Bai. 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 applicable law or ...
nilq/baby-python
python
# coding:utf-8 from lxml import etree import requests import config def checkProxyType(selfip, proxies): ''' 用来检测代理的类型,突然发现,免费网站写的信息不靠谱,还是要自己检测代理的类型 :param proxies: 代理(0 高匿,1 匿名,2 透明 3 无效代理 :return: ''' try: r = requests.get(url='https://incloak.com/ip/', headers=config.get_header(), ...
nilq/baby-python
python