content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
'''
Python program to add two positive integers without using the '+' operator
'''
'''
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the ... | nilq/baby-python | python |
import timer.helper.thread as thread
class TestThreadIsNone():
def test_real_none(self) -> None:
assert thread.is_none(None) is True
def test_text_none_uppercase(self) -> None:
assert thread.is_none("NONE") is True
def test_text_none_lowercase(self) -> None:
assert thread.... | nilq/baby-python | python |
# Copyright (c) 2019, Stefan Grönke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | nilq/baby-python | python |
# todo
| nilq/baby-python | python |
import pickle
from pathlib import Path
import torch
import os
from sklearn.model_selection import GroupKFold
from torch.utils.data import DataLoader
from classifier.config import get_conf
from classifier.fracture_detector.data import get_meta, WristFractureDataset
from classifier.fracture_detector.data._transform im... | nilq/baby-python | python |
# pylint: disable=all
__version__ = "2.12.0"
__author__ = "Criteo"
| nilq/baby-python | python |
from ray.util.collective.collective import nccl_available, gloo_available, \
is_group_initialized, init_collective_group, destroy_collective_group, \
create_collective_group, get_rank, get_collective_group_size, \
allreduce, allreduce_multigpu, barrier, reduce, reduce_multigpu, \
broadcast, broadcast_mu... | nilq/baby-python | python |
from sys import argv, exit
import sys
sys.path.append('src')
import os
import pandas as pd
import numpy as np
import random
from matplotlib import pyplot as plt
from ag import Ag
from graph import Graph
from pprint import pprint
from utils import readFiles
if __name__=='__main__':
vertexes, edges, cities_df, cit... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64
import time
import gzip
from hashlib import md5
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8', line_buffering=True)
def Decrypt(key:str, text:str) -> str:
if len(key) < 32: key += ' '... | nilq/baby-python | python |
import pytest
from time import time
from bitmex_async_rest import BitMEXRestApi
@pytest.fixture
def testnet():
return BitMEXRestApi('testnet')
async def test_throttle(testnet: BitMEXRestApi):
# for i in range(120):
# funding = await testnet.funding(count=1)
# assert i == 119
assert True
asyn... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unsupervised Kernel Regression (UKR) for Python.
Implemented as a scikit-learn module.
Author: Christoph Hermes
Created on Januar 16, 2015 18:48:22
The MIT License (MIT)
Copyright (c) 2015 Christoph Hermes
Permission is hereby granted, free of charge, to any pers... | nilq/baby-python | python |
from typing import *
@overload
def check_array_indexer(array: geopandas.array.GeometryArray, indexer: numpy.ndarray):
"""
usage.geopandas: 4
"""
...
@overload
def check_array_indexer(
array: geopandas.array.GeometryArray, indexer: slice[None, int, None]
):
"""
usage.geopandas: 2
"""
... | nilq/baby-python | python |
import pandas as pd
from scipy import stats
def my_oneway_anova(x):
my_data = pd.read_csv(x)
normal = my_data[my_data['condition']=='condition_a']['response_time']
degraded = my_data[my_data['condition']=='condition_b']['response_time']
return stats.f_oneway(normal, degraded)
| nilq/baby-python | python |
#!/usr/bin/env python
import argparse
from argparse import RawTextHelpFormatter
import bammend as bm
def parse_args():
"""Parse command-line arguments"""
summary = ('Remove pulses from reads in Pacbio Bam. Annotation indices \n'
'are indexed from the beginning of the ZMW read (i.e. query \n'
... | nilq/baby-python | python |
"""
The API, responsible for receiving the files, submitting jobs, and getting their results.
"""
import asyncio
from contextlib import suppress
import os
from typing import Optional
from uuid import UUID, uuid4
from fastapi import (
Depends,
FastAPI,
File,
HTTPException,
Path,
Query,
Resp... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Safe
a commandline password manager using AES encryption, written in python.
:: author Erick Daniszewski
:: date 05 December 2015
"""
import json
import getpass
import argparse
import struct
from os import mkdir, remove
from os.path import join as join_path
fr... | nilq/baby-python | python |
# coding: utf-8
from __future__ import absolute_import
from unittest.mock import patch
from xcube_hub import api
from xcube_hub.controllers.callbacks import put_callback_by_cubegen_id
from xcube_hub.models.callback import Callback
from test import BaseTestCase
class TestCallbacksController(BaseTestCase):
"""Ca... | nilq/baby-python | python |
"""AI Engines
Here is a set of AI- and ML-patterns for adavanced research of business data.
"""
| nilq/baby-python | python |
from unittest.mock import MagicMock
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super().__call__(self, *args, **kwargs)
| nilq/baby-python | python |
from django.db import models
from django.test import TestCase
from django_fsm import FSMField, transition, can_proceed
class TestExceptTargetTransitionShortcut(models.Model):
state = FSMField(default="new")
@transition(field=state, source="new", target="published")
def publish(self):
pass
@t... | nilq/baby-python | python |
# Problem: https://www.hackerrank.com/challenges/py-check-strict-superset/problem
set_A = set(input().split())
n = int(input())
ind = 0
for _ in range(n):
set_n = set(input().split())
union_set = set_A.union(set_n)
if (union_set == set_A) and (len(set_A) > len(set_n)):
ind += 1
if ind == n:
pri... | nilq/baby-python | python |
import sys
import os
import os.path
import glob
def compareOutputs( expected, actual, message ):
expected = expected.strip().replace('\r','').split('\n')
actual = actual.strip().replace('\r','').split('\n')
diff_line = 0
max_line_to_compare = min( len(expected), len(actual) )
for index in xrange(0... | nilq/baby-python | python |
from unittest import mock
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
from django_countries.fields import Country
from django_prices_vatlayer.models import VAT
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from saleor.core.taxes.vatlayer im... | nilq/baby-python | python |
#These variables are needed to make local variables in functions global
custom_end=''
homework_end=''
assignment_end=''
test_end=''
quiz_end=''
final_end=''
custom_advance_details=''
def quizzes():
while True:
quiz_weight=input('How much does your quizzes weigh? or if not applicable type n/a ')
... | nilq/baby-python | python |
from msal.authority import *
from msal.exceptions import MsalServiceError
from tests import unittest
class TestAuthority(unittest.TestCase):
COMMON_AUTH_ENDPOINT = \
'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
COMMON_TOKEN_ENDPOINT = \
'https://login.microsoftonline.com/co... | nilq/baby-python | python |
#!/usr/bin/env python3
class BarItem(object):
valid_options = set(['full_text', 'short_text', 'color', 'min_width',
'align', 'name', 'instance', 'urgent', 'separator',
'separator_block_width'])
COLOR_DEFAULT = '#FFFFFF'
def __init__(self, name):
a... | nilq/baby-python | python |
# a1.py advice for manhattan distance taken from
# https://stackoverflow.com/questions/39759721/calculating-the-manhattan-distance-in-the-eight-puzzle
# https://www.geeksforgeeks.org/sum-manhattan-distances-pairs-points/
from search import *
import time
import random
# ...
SOLVED_STATE = (1, 2, 3, 4, 5, 6, 7, 8, 0)
... | nilq/baby-python | python |
from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for
from flask.json import jsonify
import os
from requests_oauthlib.compliance_fixes import facebook_compliance_fix
app = Flask(__name__)
# This information is obtained upon registration of a new GitHub OAuth
# applic... | nilq/baby-python | python |
############################################################################
# This Python file is part of PyFEM, the code that accompanies the book: #
# #
# 'Non-Linear Finite Element Analysis of Solids and Structures' #
# R. ... | nilq/baby-python | python |
#!/usr/bin/env python
'''
@todo: turn this into a real test runner for everything in the test subdir.
'''
import sys
from aisutils.BitVector import BitVector
from aisutils import binary
import ais_msg_1
import ais_msg_8
import sls.waterlevel
if __name__=='__main__':
# Try to parse some binary message
if Fal... | nilq/baby-python | python |
import streamlit as st
import pandas as pd
from itertools import groupby
from datetime import datetime
import re
from pretty_html_table import build_table
st.set_page_config(layout='wide')
JIRA_REGEX= "[A-Z]{2,}-\d+"
def parse_blame(chunk):
branch = chunk[0].split()[0]
line_start = chunk[0].split()[1]
... | nilq/baby-python | python |
import ast
import csv
import korbinian
import korbinian.utils as utils
import numpy as np
import os
import pandas as pd
import sys
import time
# import debugging tools
from korbinian.utils import pr, pc, pn, aaa
def get_TM_indices_from_TMSEG_topo_str(topo_str, TM_symbol="H"):
"""Get TM indices from TMSEG topology ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Swets NDVI filtering
author: Laust Færch @ DHI GRAS
Created on 2020/08/29
Based on the article:
Swets, D.L, Reed, B.C., Rowland, J.D., Marko, S.E., 1999. A weighted least-squares approach to temporal
NDVI smoothing. In: Proceedings of the 1999 ASPRS Annual Conference, Portland, Oregon, pp. ... | nilq/baby-python | python |
import json
from django import forms
from commons.file import file_utils
from commons import file_name_tools
from wikis.attachments import attachment_tool
from django.core.exceptions import ValidationError
from datetime import datetime
from uzuwiki.settings_static_file_engine import MAX_FILE_SIZE, MAX_FILE_SIZE_MESSAGE... | nilq/baby-python | python |
# Jared Dyreson
# CPSC 386-01
# 2021-11-29
# jareddyreson@csu.fullerton.edu
# @JaredDyreson
#
# Lab 00-04
#
# Some filler text
#
"""
This module contains a basic "factory" pattern for generating new Display instances
"""
import abc
import dataclasses
import functools
import json
import pathlib
import pygame
import sy... | nilq/baby-python | python |
from intent_parser.server.intent_parser_server import app, IntentParserServer
import os
import logging.config
import os
logger = logging.getLogger(__name__)
def _setup_logging():
logging.basicConfig(level=logging.INFO,
format="[%(levelname)-8s] %(asctime)-24s %(filename)-23s line:%(lineno)... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 10 21:32:34 2019
@author: teddy
"""
from docx import Document
from docx.shared import RGBColor
#from docx.dml.color import ColorFormat
def getText(filename):
doc = Document(filename)
fullText = []
for para in doc.paragraphs:
... | nilq/baby-python | python |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
extends("BaseKPI.py")
"""
Consumption (Wh)
------------------
Indexed by
* scope
* deli... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
##########################################################################
ZipMe : GAE Content Downloader
##########################################################################
Just add this lines in your app.yaml :
- url: /zipme
script: zipme.py
####... | nilq/baby-python | python |
""" Models for mongo database """
# from pymongo.write_concern import WriteConcern
from pymodm import MongoModel, fields
class Testing(MongoModel):
onefield = fields.CharField()
# NOTE: do not touch connection here, see experiments/mongo.py
# class Meta:
# connection_alias = 'test'
# # w... | nilq/baby-python | python |
# Generated by Django 2.2.1 on 2019-05-10 22:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wells', '0082_auto_20190510_0000'),
('wells', '0082_merge_20190510_1926'),
]
operations = [
]
| nilq/baby-python | python |
from unittest import TestCase
from semanticpy.vector_space import VectorSpace
from nose.tools import *
class TestSemanticPy(TestCase):
def setUp(self):
self.documents = ["The cat in the hat disabled", "A cat is a fine pet ponies.", "Dogs and cats make good pets.","I haven't got a hat."]
def it_sh... | nilq/baby-python | python |
#! /usr/bin/env python
from yices import *
cfg = Config()
cfg.default_config_for_logic('QF_BV')
ctx = Context(cfg)
bv32_t = Types.bv_type(32)
x = Terms.new_uninterpreted_term(bv32_t, 'x')
y = Terms.new_uninterpreted_term(bv32_t, 'y')
zero = Terms.bvconst_integer(32, 0)
fmla0 = Terms.bvsgt_atom(x, zero)
fmla1 = Te... | nilq/baby-python | python |
"""A virtual pumpkin which flash neopixels and play sound"""
import random
import math
import time
import board
import digitalio
import audioio
import busio
import adafruit_vl53l0x
import adafruit_thermistor
import neopixel
#########################
# -- slide switch to enable/disable running loop
slide_switch = digit... | nilq/baby-python | python |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import json
import ctypes as ct
from .._constants import VSCODE_CREDENTIALS_SECTION
def _c_str(string):
return ct.c_char_p(string.encode("utf-8"))
clas... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Northwestern University.
#
# invenio-subjects-mesh is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""MeSH subjects_mesh.yaml writer."""
from pathlib import Path
import yaml
def writ... | nilq/baby-python | python |
# Copyright (c) 2013 eBay Inc.
# Copyright (c) 2013 OpenStack Foundation
#
# 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
#
# ... | nilq/baby-python | python |
# Задача 3. Вариант 30.
#Напишите программу, которая выводит имя "Илья Арнольдович Файзильберг", и запрашивает его псевдоним.
# Shemenev A.V
# 14.03.16
print("Герой нашей программы Илья Арнольдович Файзильберг")
print("Под каким именем мы знаем этого человека? Ваш ответ:")
x=input()
print ("Все верно, псевдоним - " +x)... | nilq/baby-python | python |
from models.generators.fcn32s import FCN32s
from models.generators.fcn16s import FCN16s
from models.generators.fcn8s import FCN8s
| nilq/baby-python | python |
from django.conf.urls import url
from messenger import views
urlpatterns = [
url(r'^messenger/send', views.send, name='send'),
url(r'^messenger/read', views.read, name='read')
]
| nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import progressbar
import requests
import os
import sys
sourceapp = "AS50559-DIVD_NL"
def rest_get(call,resource,retries=3):
url = "https://stat.ripe.net/data/{}/data.json?resource={}&sourceapp={}".format(call,resource,sourceapp)
try:
response = requests.get(url, timeout = ... | nilq/baby-python | python |
# Every line of these files consists of an image, i.e. 785 numbers between 0 and 255. size 28 x 28
# first no is label
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.l... | nilq/baby-python | python |
#!/usr/bin/env python
"""
@package mi.dataset.parser.test
@file marine-integrations/mi/dataset/parser/test/
@author Jeff Roy
@brief Test code for a wc_sbe_cspp data parser
wc_sbe_cspp is based on cspp_base.py
test_wc_sbe_cspp.py fully tests all of the capabilities of the
base parser. That level of testing is omitted... | nilq/baby-python | python |
from datetime import datetime
from os.path import dirname, join
import pytest # noqa
from city_scrapers_core.constants import ADVISORY_COMMITTEE, PASSED
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.cuya_audit import CuyaAuditSpider
test_response = f... | nilq/baby-python | python |
from django.db import models
from djchoices import DjangoChoices, ChoiceItem
class UserStatuses(DjangoChoices):
enter_address = ChoiceItem()
enter_name = ChoiceItem()
start = ChoiceItem()
allowed = ChoiceItem()
enter_org_name = ChoiceItem()
enter_role = ChoiceItem()
allowed_group = ChoiceI... | nilq/baby-python | python |
my_list= [3, 4, 6, 2]
my_list1 = list(("Hello World"))
| nilq/baby-python | python |
from itertools import product as product
from math import sqrt as sqrt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Function
# from utils.box_utils import decode, nms
# from utils.config import Config
class L2Norm(nn.Module):
def __init__(self, n_c... | nilq/baby-python | python |
from django.shortcuts import render
from django.template import RequestContext, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.http import JsonResponse
import simplejson as json
import requests
from django import template
import urllib
from collections i... | nilq/baby-python | python |
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
# This file should only be present in a source checkout, and never in a release
# package, to allow us to determine whether we're running in a development or
# production mode.
| nilq/baby-python | python |
import math
if __name__ != "common":
from objects import glob
import time
import json
from common.ripple import userUtils
def load_achievement_data(ACHIEVEMENT_BASE, ACHIEVEMENT_KEYS, ACHIEVEMENT_STRUCT):
LENGTH = 0
ACHIEVEMENTS = []
for struct in ACHIEVEMENT_STRUCT:
LENGTH = max(LENGTH, len(ACHIEVEMENT_KEYS... | nilq/baby-python | python |
from hashlib import pbkdf2_hmac, md5
import binascii
from Crypto.Cipher import AES
import os
import sys
def generate_key(title_id, pwd):
# remove 00 padding from title id
title_idGen = title_id[2:]
# get secret string, append title id, and convert to binary string
secret = binascii.unhexlify('fd040105... | nilq/baby-python | python |
# https://github.com/python-poetry/poetry/issues/11
import glob
import os
from distutils.command.build_ext import build_ext
from distutils.core import Extension
from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError
def filter_extension_module(name, lib_objs, lib_headers):
return... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Created by: Michael Lan
import os
import sys
import re
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2 import QtGui, QtWidgets, QtCore
from ui_main import Ui_Dialog
from pyside_material import apply_stylesheet
from dbconnection import connect, insert_data, close, valida... | nilq/baby-python | python |
""" $lic$
Copyright (C) 2016-2017 by The Board of Trustees of Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiative.
If you use this program in your research, we request that you reference th... | nilq/baby-python | python |
# Basic Frame Differencing Example
#
# Note: You will need an SD card to run this example.
#
# This example demonstrates using frame differencing with your OpenMV Cam. It's
# called basic frame differencing because there's no background image update.
# So, as time passes the background image may change resulting in iss... | nilq/baby-python | python |
import tetris.input.gamepad as gp
import pygame
pygame.init()
if __name__ == "__main__":
sticks = []
qs = gp.PygameEventReader.q
for stick in gp.get_available():
print(gp.display_gamepad_info(stick) + '\n')
sticks.append(gp.GamepadWrapper(stick.get_id()))
print('Listening...')
... | nilq/baby-python | python |
import datetime # enables the start time elements in date and time format
# Interaction for patient with learning disabilities
# "psychol_assessment",
# "iapt",
# "cmh_for_smi"
# Mental health interaction 1: Psychological assessment
def psychol_assessment(patient, environment, patient_time):
encounter = {
... | nilq/baby-python | python |
def temp(input, output):
img = cv2.imread(input)
xmap, ymap = utils.buildmap_1(Ws=800, Hs=800, Wd=800, Hd=800, fov=193.0)
cv2.imwrite(output, cv2.remap(img, xmap,ymap,cv2.INTER_LINEAR))
| nilq/baby-python | python |
from datetime import date
# random person
class Person:
# def __new__(cls, name, age):
# print("New object called")
# # super.__new__(cls[name, age])
def __init__(self, name, age):
print('__init__ called')
self.name = name
self.age = age
@classmethod
def from... | nilq/baby-python | python |
import logging
from discord.ext import tasks, commands
from naotomori.cogs.source.anime import _9anime, gogoanime
from naotomori.cogs.sourcecog import SourceCog
logger = logging.getLogger('NaoTomori')
class AnimeCog(SourceCog):
"""
AnimeCog: extends the SourceCog.
"""
def __init__(self, bot):
... | nilq/baby-python | python |
def params_to_string(task: dict) -> dict:
for k in task['parameters'].keys():
if (isinstance(task['parameters'][k], int) or isinstance(task['parameters'][k], float)):
task['parameters'][k] = str(task['parameters'][k])
return task
| nilq/baby-python | python |
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('./source/cython_functions.pyx',compiler_directives={'language_level' : "3"}))
| nilq/baby-python | python |
from .chem import BOND_TYPES, BOND_NAMES, set_conformer_positions, draw_mol_image, update_data_rdmol_positions, \
update_data_pos_from_rdmol, set_rdmol_positions, set_rdmol_positions_, get_atom_symbol, mol_to_smiles, \
remove_duplicate_mols, get_atoms_in_ring, get_2D_mol, draw_mol_svg, GetBestRMSD
from ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu June 17 11:53:42 2021
@author: Pavan Tummala
"""
import os, numpy as np
import cv2
import random
import torch
import torch.utils.data as data
import xml.etree.ElementTree as ET
from abc import ABCMeta, abstractmethod
import scipy.cluster.vq as vq
import pickle
import pandas a... | nilq/baby-python | python |
# Copyright (c) 2011-2013 Kunal Mehta. All rights reserved.
# Use of this source code is governed by a BSD License found in README.md.
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResp... | nilq/baby-python | python |
import unittest
import torchtext.vocab as v
import han.encode.sentence as s
class SentenceEncoderTestCase(unittest.TestCase):
def test(self):
vocab = v.build_vocab_from_iterator([["apple", "is", "tasty"]])
sut = s.SentenceEncoder(vocab)
res = sut.forward(["apple is tasty", "tasty is appl... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional
import torch
from torch import Tensor
from fairseq impo... | nilq/baby-python | python |
from .abstract_choices_factory import AbstractChoicesFactory
from .choice import Choice
from src.round import Output
from random import randrange
class PlayerVsComChoicesFactory(AbstractChoicesFactory):
def make_player1_choice():
player_choice = Choice('placeholder')
while not player_choice.is_val... | nilq/baby-python | python |
from apple_health.util import parse_date, parse_float
DATE_COMPONENTS = "@dateComponents"
ACTIVE_ENERGY_BURNED = "@activeEnergyBurned"
ACTIVE_ENERGY_BURNED_GOAL = "@activeEnergyBurnedGoal"
ACTIVE_ENERGY_BURNED_UNIT = "@activeEnergyBurnedUnit"
APPLE_EXERCISE_TIME = "@appleExerciseTime"
APPLE_EXERCISE_TIME_GOAL = "@appl... | nilq/baby-python | python |
# Warning: Don't edit file (autogenerated from python -m dev codegen).
ROBOCODE_GET_LANGUAGE_SERVER_PYTHON = "robocode.getLanguageServerPython" # Get a python executable suitable to start the language server.
ROBOCODE_GET_PLUGINS_DIR = "robocode.getPluginsDir" # Get the directory for plugins.
ROBOCODE_CREATE_ACTIVIT... | nilq/baby-python | python |
import urllib2
import threading
from bs4 import BeautifulSoup
import re
import json
import sys
import os
import django
from stock_list import getlist, getLSEList
from extract_stock_info import get_info, getLSEInfo
from extract_stock_history import get_historical_info
from extract_sector_history import get_sector_histo... | nilq/baby-python | python |
import Tkinter as tk
class NatnetView:
def __init__(self, parent, reader):
self.parent = parent
self.reader = reader
self.setup()
def __del__(self):
self.destroy()
def destroy(self):
self.frame.grid_forget()
def setup(self):
# container
self.fr... | nilq/baby-python | python |
import gmpy2
from gmpy2 import (
mpz,
powmod,
mul,
invert,
)
B = 2 ** 20
p = mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171')
g = mpz('117178298803662070095161175963353670885580849999989522... | nilq/baby-python | python |
#单一状态
class Borg:
__shared_state = {"1":"2"}
def __init__(self):
self.x = 1
self.__dict__ = self.__shared_state
b = Borg()
b1 = Borg()
b.x = 4
print("Borg Object b:",b)
print("Borg Object b1:",b1)
print("Object state b:",b.__dict__)
print("Object state b1:",b1.__dict__)
| nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 06:10:44 2018
@author: Kazuki
"""
import numpy as np
import pandas as pd
from tqdm import tqdm
import gc, os
from collections import defaultdict
import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
#import lgbextension as... | nilq/baby-python | python |
# flake8: noqa
'''
All step-related classes and factories
'''
from .base_steps import (
BaseStep,
BaseStepFactory,
BaseValidation,
)
from .steps import TestStep
from .outputs import OutputValueStep
from .steps_aggregator import StepsAggregator
from .validations import (
Validation,
XPathValidatio... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import math
# Respect seigot
class Waypoint:
way_point = 0
def __init__(self, path):
self.points = []
# self.way_point = 0
with open(path) as f:
lines = csv.reader(f)
for l in lines:
p... | nilq/baby-python | python |
import typing
from ariadne import SchemaDirectiveVisitor
from ariadne.types import GraphQLResolveInfo
from graphql import default_field_resolver
from pytimeparse import parse as parse_duration
from .utils.rate_limit import RateLimit, TooManyRequests
class DateDirective(SchemaDirectiveVisitor):
def visit_field_d... | nilq/baby-python | python |
import random
import math
import operator
from collections import Counter, defaultdict
import twokenize
import peewee
from models import database, SMS, Contact
class NaiveBayes(object):
def __init__(self):
self.doccounts = Counter()
self.classcounts = Counter()
self.wordcounts = defaultdic... | nilq/baby-python | python |
from LucidDynamodb import DynamoDb
from LucidDynamodb.exceptions import (
TableNotFound
)
import logging
logging.basicConfig(level=logging.INFO)
if __name__ == "__main__":
try:
db = DynamoDb()
db.delete_table(table_name='dev_jobs')
logging.info("Table deleted successfully")
tabl... | nilq/baby-python | python |
from .queries import *
| nilq/baby-python | python |
import Transformation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def calc_cov_ellipse(a, b, d):
s = np.array([[a, b], [b, d]])
(w, v) = np.linalg.eig(s)
angle = np.degrees(np.arctan2(v[1, 0], v[0, 0]))
return 2*np.sqrt(w[0]), 2*np.sqrt(w[1]), angle
class SubPlot:
... | nilq/baby-python | python |
from django.db import models
from django.utils.text import gettext_lazy as _
from common.models import CommonData, ErrorMessages
from jobs.models import JobOffer, Profile
class Comment(CommonData):
model_name = 'Comment'
profile: Profile = models.ForeignKey(
to=Profile,
on_delete=models.PROT... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-#
# MIT License
#
# Copyright (c) 2019 Pim Witlox
#
# 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 limita... | nilq/baby-python | python |
from hello.hello import print_hello
from world.world import print_world
def main():
print_hello()
print_world()
return
if __name__ == '__main__':
main()
| nilq/baby-python | python |
from django.contrib.sites.models import Site
from .settings import CMS_TEMPLATES
from django.contrib.auth.models import User
# Default page settings Not used for installation
# Content for adding a page
# Still under development
title = 'Django CMS setup'
description = 'Open Source programming at its best'
template =... | nilq/baby-python | python |
from .shared import replace_gender
#TODO At some point, I want to be able to pass only part of the subject tree
# to child snippets.
class Snippet(object):
''' The base snippet class that all snippets will extend.
Responsible for listing required and optional subject data, validating a
passed subject, genera... | nilq/baby-python | python |
#!/usr/bin/python2.7
###############################################################
#### Assembled by: Ian M. Pendleton ######################
#### www.pendletonian.com ######################
###############################################################
# Updated December 17, 2019
### T... | nilq/baby-python | python |
#!/usr/bin/env python
from setuptools import setup
from setuptools.command.install import install as _install
class install(_install):
def pre_install_script(self):
pass
def post_install_script(self):
pass
def run(self):
self.pre_install_script()
_install.run(self)
... | nilq/baby-python | python |
bg_black = "\u001b[48;5;0m"
bg_gray = "\u001b[48;5;8m"
bg_red = "\u001b[48;5;9m"
bg_green = "\u001b[48;5;10m"
bg_yellow = "\u001b[48;5;11m"
bg_blue = "\u001b[48;5;12m"
bg_purple = "\u001b[48;5;13m"
bg_cyan = "\u001b[48;5;14m"
bg_white = "\u001b[48;5;15m"
def customColor(number):
print(f"\u001b[48;5;{number}m") | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.