content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from Jumpscale import j
def test():
"""
to run:
kosmos 'j.data.rivine.test(name="sia_basic")'
"""
e = j.data.rivine.encoder_sia_get()
# you can add integers, booleans, iterateble objects, strings,
# bytes and byte arrays. Dictionaries and objects are not supported.
e.add(False)
e... | nilq/baby-python | python |
from nose.tools import *
from ..app import address_parts
@raises(TypeError)
def test_address_parts_no_address():
expected = []
actual = address_parts()
def test_address_parts_with_address():
expected = ['AddressNumber', 'StreetName']
actual = address_parts('123 main')
assert actual == expected
| nilq/baby-python | python |
from sys import *
def parse_weights(numberExpectedParams, filename):
f = open(filename, 'r')
contents = f.readlines()
params = []
linenumber=0
for i in contents:
linenumber = linenumber + 1
i = i.strip()
if i == "":
continue
try... | nilq/baby-python | python |
from flask import current_app as app
from flask import jsonify, request
from director.api import api_bp
from director.builder import WorkflowBuilder
from director.exceptions import WorkflowNotFound
from director.extensions import cel_workflows, schema
from director.models.workflows import Workflow
@api_bp.route("/wo... | nilq/baby-python | python |
nome = input('Digite seu nome:')
if nome == 'Cristiano':
print('Sou eu')
else:
print('Não sou seu')
| nilq/baby-python | python |
from django.db import models
from bitoptions import BitOptions, BitOptionsField
TOPPINGS = BitOptions(
('pepperoni', 'mushrooms', 'onions', 'sausage', 'bacon', 'black olives',
'green olives', 'green peppers', 'pineapple', 'spinach', 'tomatoes',
'broccoli', 'jalapeno peppers', 'anchovies', 'chicken', 'bee... | nilq/baby-python | python |
print(["ABC","ARC","AGC"][int(input())//50+8>>5]) | nilq/baby-python | python |
from __future__ import print_function
import sys
if sys.version_info < (3, 8):
print(file=sys.stderr)
print('This game needs Python 3.8 or later; preferably 3.9.', file=sys.stderr)
exit(1)
try:
import moderngl
import pyglet
import png
except ImportError:
print(file=sys.stderr)
print('Y... | nilq/baby-python | python |
#!/usr/bin/python2
#Dasporal
import swiftclient
import os, sys, mimetypes
import requests
import json
import pprint
data = file(os.path.join(sys.path[0], "../tokens.json"))
tokens = json.load(data)
if len(sys.argv) != 2 or len(sys.argv) != 3:
print ("Usage: podcast_upload.py [audio file name]")
exit(1)
# ... | nilq/baby-python | python |
DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
SPECIAL_CASES = {
'ee': 'et',
}
LANGUAGES = {
'af': 'afrikaans',
'sq': 'albanian',
'ar': 'arabic',
'be': 'belarusian',
'bg': 'bulgarian',
'ca': 'catalan',
'zh-CN': 'chinese_simplified',
'zh-TW': 'chinese_traditional',... | nilq/baby-python | python |
from keras.engine import InputSpec
from keras.layers import Dense
from keras.layers.wrappers import Wrapper, TimeDistributed
class Highway(Wrapper):
def __init__(self, layer, gate=None, **kwargs):
self.supports_masking = True
self.gate = gate
super(Highway, self).__init__(layer, **kwargs... | nilq/baby-python | python |
import tensorflow as tf
import tqdm
from one_shot_learning_network import MatchingNetwork
class ExperimentBuilder:
def __init__(self, data):
"""
Initializes an ExperimentBuilder object. The ExperimentBuilder object takes care of setting up our experiment
and provides helper functions such... | nilq/baby-python | python |
from __future__ import annotations
from typing import TYPE_CHECKING
from os import chdir, path
from asdfy import ASDFProcessor, ASDFAccessor
if TYPE_CHECKING:
from obspy import Trace, Stream
if not path.exists('traces.h5') and path.exists('tests/traces.h5'):
chdir('tests')
def func1(stream: Stream):
#... | nilq/baby-python | python |
import numpy as np
from starfish.core.expression_matrix.concatenate import concatenate
from starfish.core.expression_matrix.expression_matrix import ExpressionMatrix
from starfish.types import Features
def test_concatenate_two_expression_matrices():
a_data = np.array(
[[0, 1],
[1, 0]]
)
... | nilq/baby-python | python |
"""The plugin module implements various plugins to extend the behaviour
of community app.
The plugins provided by this module are:
SketchsTab - additional tab to show on the profile pages
LiveCodeExtension - injecting livecode css/js into lesson page
"""
import frappe
from community.plugins import PageExtensi... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
@description: 分类器
@author:XuMing
"""
import re
import jieba
from jieba import posseg
class DictClassifier:
def __init__(self):
self.__root_path = "data/dict/"
jieba.load_userdict("data/dict/user.dict") # 自定义分词词库
# 情感词典
self.__phrase_dict = self.__get... | nilq/baby-python | python |
import discord
import logging
import os
class ValorantBot(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.BOT_LOG = os.getenv('BOT_LOG')
if self.BOT_LOG == 'INFO' or self.BOT_LOG is None or self.BOT_LOG == '':
logging.getLogger().s... | nilq/baby-python | python |
import unittest
from typing import List, Text
INPUT_FILE = "input.txt"
TEST_INPUT_SHORT = "test_input_short.txt"
TEST_INPUT_LONG = "test_input_long.txt"
def getJolts(inputFile: Text):
jolts: List[int] = []
with open(inputFile, "r") as inputFile:
lines = inputFile.readlines()
for line in lines... | nilq/baby-python | python |
from resolwe.process import IntegerField, Process, StringField
class PythonProcessDataIdBySlug(Process):
"""The process is used for testing get_data_id_by_slug."""
slug = "test-python-process-data-id-by-slug"
name = "Test Python Process Data ID by Slug"
version = "1.0.0"
process_type = "data:pyth... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import pandas as pd
style.use('fivethirtyeight')
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
de... | nilq/baby-python | python |
import os
from src.MarkdownFile import MarkdownFile
class Parser:
def __init__(self, folderPath='.', ignoredDirectories=['.obsidian', '.git']):
self._folderPath = folderPath
self._ignoredDirectories = ignoredDirectories
self.mdFiles = list[MarkdownFile]
self._retrieveMarkdownFiles()... | nilq/baby-python | python |
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
import pero
class DrawTest(pero.Graphics):
"""Test case for text properties drawing."""
def draw(self, canvas, *args, **kwargs):
"""Draws the test."""
# clear canvas
canvas.fill(pero.color... | 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
# distributed under the Li... | nilq/baby-python | python |
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
AutoStartWaitHeartbeatSetting = Enum(
'no',
'systemDefault',
'yes',
)
| nilq/baby-python | python |
"""
Vulnerability service interfaces and implementations for `pip-audit`.
"""
from .interface import (
Dependency,
ResolvedDependency,
ServiceError,
SkippedDependency,
VulnerabilityResult,
VulnerabilityService,
)
from .osv import OsvService
from .pypi import PyPIService
__all__ = [
"Depend... | nilq/baby-python | python |
#!/usr/bin/env python
import sys
from shutil import rmtree
from os.path import abspath, dirname, join
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
media_root = join(abspath(dirname(__file__)), 'test_files')
rmtree(media_root, igno... | nilq/baby-python | python |
import lightgbm as lgbm
from sklearn.model_selection import StratifiedKFold
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
def load_data():
real_df = pd.read_csv(
"feat/real.txt",
delimiter=" ",
header=None,
names=["a", "b", "c", "d", "e", "f"],
... | nilq/baby-python | python |
class BudgetFiscalYear():
'''Class to describe the federal fiscal year'''
__base = None
__bfy = None
__efy = None
__today = None
__date = None
__startdate = None
__enddate = None
__expiration = None
__weekends = 0
__workdays = 0
__year = None
__month = None
__day ... | nilq/baby-python | python |
# import os
# import shutil
# from django.test import TestCase
# from django_dicom.data_import.local_import import LocalImport
# from django_dicom.models.image import Image
# from tests.fixtures import TEST_FILES_PATH, TEST_IMAGE_PATH, TEST_ZIP_PATH
# TESTS_DIR = os.path.normpath("./tests")
# TEMP_FILES = os.path.jo... | nilq/baby-python | python |
import os
import joblib
import pandas as pd
import numpy as np
from dataclasses import dataclass
from sklearn.preprocessing import RobustScaler
from sklearn.feature_selection import VarianceThreshold
from rdkit import Chem
from rdkit.Chem import MACCSkeys
from rdkit.Chem import MolFromSmarts
from mordred import Calc... | nilq/baby-python | python |
import torch.nn as nn
import functools
import torch
import functools
import torch.nn.functional as F
from torch.autograd import Variable
import math
import torchvision
class Bottleneck(nn.Module):
# expansion = 4
def __init__(self, inplanes, outplanes, stride=1, downsample=None):
super(... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Benjamin Kiessling
#
# 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 ... | nilq/baby-python | python |
hello = 'hello world'
print(hello) | nilq/baby-python | python |
# -*- coding: utf-8 -*-
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
print('A média foi de {:.2f}!'.format(media)) | nilq/baby-python | python |
import unittest
import sys
undertest = __import__(sys.argv[-1].split(".py")[0])
maioridade_penal = getattr(undertest, 'maioridade_penal', None)
class PublicTests(unittest.TestCase):
def test_basico_1(self):
assert maioridade_penal("Jansen Italo Ana","14 21 60") == "Italo Ana"
if __name__ == '__m... | nilq/baby-python | python |
#!/usr/bin/python3
import json
def stringToInt(origin_string):
result = 0
temp_string = origin_string.strip()
for c in temp_string:
if c >= '0' and c <= '9':
result = result * 10 + (ord(c) - ord('0'))
else:
return -1
return result
def getString(hint, default_value... | nilq/baby-python | python |
import sys
import zipfile
import shutil
import commands
import os
import hashlib
import re
import traceback
import json
from lib.dexparser import Dexparser
from lib.CreateReport import HTMLReport
from lib.Certification import CERTParser
import lib.dynamic as dynamic
dexList = [] #dexfile list
#program usage
def usag... | nilq/baby-python | python |
#!/usr/bin/env python
import setuptools
setuptools.setup(
author='Bryan Stitt',
author_email='bryan@stitthappens.com',
description='Mark shows unwatched on a schedule.',
long_description=__doc__,
entry_points={
'console_scripts': [
'plex-schedule = plex_schedule.cli:cli',
... | nilq/baby-python | python |
"""A class using all the slightly different ways a function could be defined
and called. Used for testing appmap instrumentation.
"""
# pylint: disable=missing-function-docstring
from functools import lru_cache, wraps
import time
import appmap
class ClassMethodMixin:
@classmethod
def class_method(cls):
... | nilq/baby-python | python |
# Copyright 2014 Google 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
#
# Unless required by applicable law or ag... | nilq/baby-python | python |
from unittest import TestCase
from gui_components import parser
from math import tan
class ParserTestCase(TestCase):
def test_ctan(self):
self.assertEqual(parser.ctan(0.5), 1 / tan(0.5))
def test__check_res(self):
self.assertEqual(parser._check_res('2*x+3', 1), (True, 5))
self.assertE... | nilq/baby-python | python |
import random
whi1 = True
while whi1 is True:
try:
print("Selamat Datang Di Game Batu, Gunting, Kertas!")
pilihanAwal = int(input("Apakah Kau Ingin Langsung Bermain?\n1. Mulai Permainan\n2. Tentang Game\n3. Keluar\nPilihan: "))
whi2 = True
while whi2 is True:
if pil... | nilq/baby-python | python |
# Generated by Django 2.0.13 on 2020-10-10 16:05
import ddcz.models.magic
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ddcz', '0024_skills_name'),
]
operations = [
migrations.AlterField(
model_name='commonarticle',
na... | nilq/baby-python | python |
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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/... | nilq/baby-python | python |
from .calibration import Calibration
from .capture import Capture
from .configuration import Configuration, default_configuration
from .device import Device
from .image import Image
from .imu_sample import ImuSample
from .transformation import Transformation | nilq/baby-python | python |
# some comment
""" doc string """
import math
import sys
class the_class():
# some comment
""" doc string """
import os
import sys
class second_class():
some_statement
import os
import sys
| nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Pizza Project - main.py - started on 8 November 2021
# Written by Garret Stand licensed under a MIT license for academic use.
# This file contains shell formatting and other output modification/redirections functions for the program. It is a non-executable library.
# Please ... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
# 把str编码由ascii改为utf8(或gb18030)
import random
import sys
import time
import requests
from bs4 import BeautifulSoup
file_name = 'book_list.txt'
file_content = '' # 最终要写到文件里的内容
file_content += '生成时间:' + time.asctime()
headers = [
{'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Li... | nilq/baby-python | python |
import numpy as np
from scipy.ndimage import map_coordinates
import open3d
from PIL import Image
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import functools
from multiprocessing import Pool
from utils_eval import np_coor2xy, np_coory2v
def xyz_2_coorxy(xs, ys, zs, H, W):
us... | nilq/baby-python | python |
import pytest
from openeye import oechem
from openff.recharge.aromaticity import AromaticityModel, AromaticityModels
from openff.recharge.utilities.openeye import smiles_to_molecule
@pytest.mark.parametrize(
"smiles",
[
"c1ccccc1", # benzene
"c1ccc2ccccc2c1", # napthelene
"c1ccc2c(c... | nilq/baby-python | python |
import pygame, math, os, time
from .Torpedo import Torpedo
from .Explosion import Explosion
FRICTION_COEFF = 1 - 0.015
class Spaceship(pygame.sprite.Sprite):
def __init__(self, colour, img_path, bearing, torpedo_group, explosion_group):
super().__init__()
self.torpedo_group = torpedo_group
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from datetime import datetime
class SyncModel:
""" Implements common methods used by the models for syncing data into database.
currently following models use this: Companies, Contacts, Departments, Events,
Invoices, Projects, Users."""
def ... | nilq/baby-python | python |
class InvalidBrowserException(Exception):
pass
class InvalidURLException(Exception):
pass
| nilq/baby-python | python |
import os
import time
import json
import string
import random
import itertools
from datetime import datetime
import numpy as np
import pandas as pd
from numba import jit
from sklearn.metrics import mean_squared_error
from contextlib import contextmanager, redirect_stdout
import matplotlib.pyplot as plt
N_TRAIN = 20216... | nilq/baby-python | python |
"""
Configurations for Reserved Virtual Machines simulations:
"""
###################################
### Don't touch this line - import
import numpy
###################################
################################################
### General configurations, for all simualtions
START_TIME = 0 # Seconds - NOT IMP... | nilq/baby-python | python |
#!/usr/bin/python
#
## @file
#
# Collection of classes that control the establish the basic operation of dave
# as it issues various types of commands to HAL and Kilroy
#
# Jeff 3/14
#
# Hazen 09/14
#
from xml.etree import ElementTree
from PyQt4 import QtCore
import sc_library.tcpMessage as tcpMessage... | nilq/baby-python | python |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
import asyncio
import loggi... | nilq/baby-python | python |
# Not used
# Author : Satish Palaniappan
__author__ = "Satish Palaniappan"
import os, sys, inspect
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
from twokenize import *
import re
Code = r"\\[... | nilq/baby-python | python |
import json
import cv2.aruco as aruco
import numpy as np
with open("config.json", "r") as json_file:
data = json.load(json_file)
arucoDictionary = aruco.Dictionary_get(data["arucoDictionary"])
timeStep = data["timeStep"]
isLogEnabled = bool(data["logEnabled"])
markerWidth = data["markerWidth"]
... | nilq/baby-python | python |
import unittest
import younit
# @unittest.skip("skipped")
class CommonTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
async def async_setUp(self):
pass
async def async_tearDown(self):
pass
def setUp(self):
pass
def tearDown(self):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
import pathlib
from .Decorators import Decorators
from ...Exceptions import AsyncyError
def safe_path(story, path):
"""
safe_path resolves a path completely (../../a/../b) completely
and returns an absolute path which can be used safely by prepending
the story's tmp ... | nilq/baby-python | python |
# Generated by Django 3.1.2 on 2020-10-30 18:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_auto_20201030_1417'),
]
operations = [
migrations.RemoveField(
model_name='book... | nilq/baby-python | python |
import logging
from application.utils import globals
from application.utils.helpers import Singleton
from pymongo import MongoClient, ASCENDING, DESCENDING
@Singleton
class Connection:
_client = None
db = None
def __init__(self):
try:
self._client = MongoClient(globals.configuration.m... | nilq/baby-python | python |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... | nilq/baby-python | python |
# Generated by Django 2.2.5 on 2019-11-21 01:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('id', mo... | nilq/baby-python | python |
import os
import sys
import tempfile
import mimetypes
import webbrowser
# Import the email modules we'll need
from email import policy
from email.parser import BytesParser
# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser
# In a real program you'd get the filename f... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
My first warp!
Using scikit-image piecewise affine transformation,
based on manual node assignment with stable corners.
A midpoint morph (halfway between the key frames) is generated.
http://scikit-image.org/docs/dev/auto_examples/plot_piecewise_affine.html
"""
####... | nilq/baby-python | python |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import os
import sys
import re
import traceback
# This is the global namespace.
# 2011.04.19: g.log is the only member of the global namespace. I think there
# were bigger plans for g.py, but i... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" contest forms: HTTP form processing for contest pages
:copyright: Copyright (c) 2014 Bivio Software, Inc. All Rights Reserved.
:license: Apache, see LICENSE for more details.
"""
import decimal
import re
import sys
import flask
import flask_mail
import flask_wtf
import paypalrest... | nilq/baby-python | python |
import sqlite3
import os
import urllib.request
from urllib.error import *
DATABASE_PATH = 'database/card_image_database.db'
def create_card_image_database(print_function):
print_function('Creating Database.')
if os.path.exists(DATABASE_PATH):
try:
os.remove(DATABASE_PATH)
except O... | nilq/baby-python | python |
/home/runner/.cache/pip/pool/37/a3/2b/4c0a8aea5f52564ead5b0791d74f0f33c3a5eea3657f257e9c770b86c6 | nilq/baby-python | python |
'''
Largest Palindrome of two N-digit numbers given
N = 1, 2, 3, 4
'''
def largePali4digit():
answer = 0
for i in range(9999, 1000, -1):
for j in range(i, 1000, -1):
k = i * j
s = str(k)
if s == s[::-1] and k > answer:
return i, j
def largePali3dig... | nilq/baby-python | python |
import os
import tempfile
from os import makedirs
from os.path import join, exists
from sys import platform
def get_home_folder():
from pathlib import Path
home_folder = f"{Path.home()}"
return home_folder
def get_temp_folder():
temp_folder = None
if platform == "linux" or platform == "linux2... | nilq/baby-python | python |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def addTwoNumbers(list1, list2, node, digit):
n = digit
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from chai import Chai
from arrow import arrow, locales
class ModuleTests(Chai):
def test_get_locale(self):
mock_locales = self.mock(locales, "_locales")
mock_locale_cls = self.mock()
mock_locale = self.mock()
self.... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (C) H.R. Oosterhuis 2021.
# Distributed under the MIT License (see the accompanying README.md and LICENSE files).
import numpy as np
import os.path
import gc
import json
FOLDDATA_WRITE_VERSION = 4
def _add_zero_to_vector(vector):
return np.concatenate([np.zeros(1, dtype=vector.d... | nilq/baby-python | python |
from django.test import TestCase
from django.urls import reverse
from .models import Post
# Create your tests here.
class PostModelTest(TestCase):
def setUp(self):
Post.objects.create(title='Mavzu', text='yangilik matni')
def test_text_content(self):
post = Post.objects.get(id=1)
expe... | nilq/baby-python | python |
from django.shortcuts import render, redirect, get_object_or_404
from .models import BlogPost as blog
from .models import Comment
from .forms import CreateCommentForm, UpdateCommentForm
# Create your views here.
def post_view(request):
qs=blog.objects.all()
context = {
'qs' : qs,
}
return render(request, 'blog/m... | nilq/baby-python | python |
from pyflink.common import ExecutionMode, RestartStrategies
from pyflink.common.serialization import JsonRowDeserializationSchema
from pyflink.common.typeinfo import Types
from pyflink.dataset import ExecutionEnvironment
from pyflink.datastream import StreamExecutionEnvironment, CheckpointingMode, ExternalizedCheckpoin... | nilq/baby-python | python |
import sys
import os
from bs4 import BeautifulSoup
import markdown
"""
将 Markdown 转换为 HTML
"""
class MarkdownToHtml:
headTag = '<head><meta charset="utf-8" /></head>'
def __init__(self,cssFilePath = None):
if cssFilePath != None:
self.genStyle(cssFilePath)
def genStyle(self,cssFile... | nilq/baby-python | python |
import math
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.transforms as mtransforms
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
def setup_axes(diff=False):
fig = plt.figure()
axes = []
if diff:
gs = gridspec.GridSpec(2, 1, height_rati... | nilq/baby-python | python |
from rest_framework import serializers
from polyclinics.models import Poly
class PolySerializer(serializers.ModelSerializer):
class Meta:
model = Poly
fields = '__all__'
| nilq/baby-python | python |
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''BuddyPress REST API Privilege Escalation to RCE''',
"description": '''The BuddyPress WordPress plugin was affected by an REST API Privilege Escalation to RCE''',
"severity": "high",
"re... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (C) 2017 Google 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 la... | nilq/baby-python | python |
import time
# only required to run python3 examples/cvt_arm.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import Dataset
import os
import math
import numpy as np
device = torch.device('cuda' if torch.cuda.is... | nilq/baby-python | python |
import os
import requests
from datetime import datetime, timedelta
import gitlab
class Gitlab():
def __init__(self, api_url, **kwargs):
self.gitlab = gitlab.Gitlab(api_url, **kwargs)
def is_gitlab(self):
if os.environ.get('CI', 'false') == 'true':
return True
else:
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---------------------------------------
# Project: PKUYouth Webserver v2
# File: __init__.py
# Created Date: 2020-07-28
# Author: Xinghong Zhong
# ---------------------------------------
# Copyright (c) 2020 PKUYouth
import time
import datetime
import calendar
from func... | nilq/baby-python | python |
import os
import re
import sys
import codecs
from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
setup_requires = ['pytest', 'tox']
install_requires = ['six', 'tox', 'atomos']
tests_require = ['six', 'pytest-c... | nilq/baby-python | python |
# Unsere Funktion nimmt eine Liste als Parameter
def find_nouns(list_of_words):
nouns = list()
# Das erste Wort ist wahrscheinlich großgeschrieben, fällt aber aus unserer Definition raus
for i in range(1, len(list_of_words)):
current_word = list_of_words[i]
if current_word[0].isupper():
#... | nilq/baby-python | python |
from app import app
from flask import Blueprint, render_template
@app.errorhandler(404)
def not_found_error():
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('errors/500.html'), 500
| nilq/baby-python | python |
import glob
import numpy as np
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description="Produce report from result files")
parser.add_argument('--path', type=str, default="",
help="Path to the result files (* will be appended)")
args = parser.parse_args()... | nilq/baby-python | python |
# This sample tests the case where a protocol class derives from
# another protocol class.
from typing import Generic, TypeVar, Protocol
Arg = TypeVar("Arg", contravariant=True)
Value = TypeVar("Value")
class Base1(Protocol[Value]):
def method1(self, default: Value) -> Value:
...
class Base2(Base1[Valu... | nilq/baby-python | python |
import collections
from supriya import CalculationRate
from supriya.synthdefs import WidthFirstUGen
class ClearBuf(WidthFirstUGen):
"""
::
>>> clear_buf = supriya.ugens.ClearBuf.ir(
... buffer_id=23,
... )
>>> clear_buf
ClearBuf.ir()
"""
### CLASS V... | nilq/baby-python | python |
from collections import OrderedDict
from itertools import takewhile
from dht.utils import last
class Cluster(object):
def __init__(self, members):
self.hash = hash
self.members = OrderedDict(((self.hash(node), node) for node in members))
def __len__(self):
return sum((len(node) for n... | nilq/baby-python | python |
from typing import Optional
from pydantic import BaseSettings, Json
from ._version import version as __version__ # NOQA
class Settings(BaseSettings):
auth_token_url: str = "https://solarperformanceinsight.us.auth0.com/oauth/token"
auth_jwk_url: str = (
"https://solarperformanceinsight.us.auth0.com/.w... | nilq/baby-python | python |
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from backend.api.models import MiembroSprint, Usuario, Rol
from backend.api.serializers import UsuarioSerializer
class UsuarioViewSet(viewsets.ViewSet):
"""
UsuarioViewSet View... | nilq/baby-python | python |
from thenewboston.accounts.manage import create_account
from thenewboston.verify_keys.verify_key import encode_verify_key
def random_encoded_account_number():
signing_key, account_number = create_account()
return encode_verify_key(verify_key=account_number)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import streamlit as st
import numpy as np
import pandas as pd
import altair as alt
from io import BytesIO
def to_excel(df):
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, index=True, sheet_name='杜子期血常规数据统计')
workbook = writer.book
... | nilq/baby-python | python |
import asyncio
import logging
import logging.handlers
import time
from contextlib import suppress
from typing import Optional, Union
from ..thread_pool import run_in_new_thread
def _thread_flusher(
handler: logging.handlers.MemoryHandler,
flush_interval: Union[float, int],
loop: asyncio.AbstractEventLoop... | nilq/baby-python | python |
#
# Copyright (c) 2006-2013, Prometheus Research, LLC
#
"""
:mod:`htsql.ctl.regress`
========================
This module implements the `regress` routine.
"""
from .error import ScriptError
from .routine import Argument, Routine
from .option import (InputOption, TrainOption, PurgeOption,
Forc... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.