content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import itertools as it LOW = 172851 HIGH = 675869 doubles = set() for i in range(10): doubles.add(str(i)*2) triples = set() for i in range(10): triples.add(str(i)*3) def main(): score = 0 for i in range(LOW, HIGH +1): flag = True s = str(i) s_list = list(s) s_list_s...
nilq/baby-python
python
def apply_async(func, args, *, callback): result = func(*args) callback(result) def print_result(result): print('Got:', result) def add(x, y): return x + y apply_async(add, (2, 3), callback=print_result) # Got: 5 apply_async(add, ("hello", "world"), callback=print_result) # Got: helloworld cla...
nilq/baby-python
python
# Copyright 2020 Makani Technologies LLC # # 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...
nilq/baby-python
python
import pytest from bmipy import Bmi class EmptyBmi(Bmi): def __init__(self): pass def initialize(self, config_file): pass def update(self): pass def update_until(self, then): pass def finalize(self): pass def get_var_type(self, var_name): p...
nilq/baby-python
python
# Natural Language Toolkit: Word Sense Disambiguation Algorithms # # Authors: Liling Tan <alvations@gmail.com>, # Dmitrijs Milajevs <dimazest@gmail.com> # # Copyright (C) 2001-2015 NLTK Project # URL: <http://nltk.org/> # For license information, see LICENSE.TXT from nltk.corpus import wordnet def lesk(cont...
nilq/baby-python
python
from ...gpstime import GPSTime from ..utils import Enums, TestCaseFailure from .standby import DualSatStandbyCase from .utils import log_fc_data, log_psim_data class DualSatFarFieldCase(DualSatStandbyCase): def post_boot(self): """To put us in fair field, we need to be able to initialize each sat...
nilq/baby-python
python
#!/usr/bin/env python from methods import ( PlanToConfigurationTest, PlanToConfigurationStraightLineTest, PlanToConfigurationCompleteTest, PlanToEndEffectorPoseTest, PlanToEndEffectorOffsetTest, ) from planning_helpers import BasePlannerTest from prpy.planning.cbirrt import CBiRRTPlanner from unitte...
nilq/baby-python
python
import MySQLdb db_connection = MySQLdb.connect( host="localhost", user="tycho_dev", passwd="dev123", db="tycho" ) def fatality_data(): cursor = db_connection.cursor() cursor.execute("SELECT AVG(CountValue) FROM noncumulative_all_conditions WHERE Fatalities = 1;") average_fatalities = curs...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Tests for Predicates, mostly took from repoze.what test suite""" ############################################################################## # # Copyright (c) 2007, Agendaless Consulting and Contributors. # Copyright (c) 2008, Florent Aide <florent.aide@gmail.com>. # Copyright (c) 2008-20...
nilq/baby-python
python
from pathlib import Path import shutil import re import nbformat as nbf from wrap_notebook_lines import find_links from link_fix import markdown_cells input_nb_pattern = r'0[0123].*.ipynb' p = Path('.') (p / 'converted').mkdir(exist_ok=True) input_notebooks = p.glob(input_nb_pattern) def nuke_dir_tree(top): s...
nilq/baby-python
python
from openvino.inference_engine import IENetwork, IEPlugin from argparse import ArgumentParser from PIL import Image, ImageDraw import logging as log import numpy as np import time import cv2 import sys import os def build_argparser(): parser = ArgumentParser() parser.add_argument("-m", "--model", help="Path to an .x...
nilq/baby-python
python
# -*- coding: utf-8 -*- __version__ = '0.0.0' __author__ = 'Mike Bland' __license__ = "CC0-1.0"
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 31 13:10:48 2018 @author: kazuki.onodera """ import gc, os from tqdm import tqdm import pandas as pd import numpy as np import sys sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary') import lgbextension as ex import lightgbm as lgb from...
nilq/baby-python
python
from io import StringIO from django.apps import apps from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import connection from ....account.utils import create_superuser, create_user from ...utils.random_data import ( add_address_to_admin ) class Co...
nilq/baby-python
python
from numpy import genfromtxt import numpy as np from time import sleep from sklearn.datasets import make_regression as mr import matplotlib.pyplot as plt from sklearn.metrics import r2_score class WML(object): ''' Class to solve a linear regression problem using calculating the maximum likelihood and solv...
nilq/baby-python
python
#---------------------------------------------------------------------------------------------------------- # # AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX # # NAME: Link CornerPin # COLOR: #5a892b # TEXTCOLOR: #ffffff # #------------------------------------------------------------------------------------------...
nilq/baby-python
python
import numpy as np import cv2 import staple from sklearn.metrics import jaccard_score import SimpleITK as sitk from LabelFusion.wrapper import fuse_images from skimage.filters import threshold_otsu def to3(src, axis=2): return np.stack((np.zeros_like(src), src.max() - src, src), axis=axis) def get_majority_vote...
nilq/baby-python
python
import paramiko import tarfile import sys import socket import nmap import os import sys import struct import fcntl import netifaces import urllib import shutil from subprocess import call # Make a list of credentials login_list= [('this', 'one?'), ("hell0", "Adel3"), ('admin', 'admin'), ('root', '94849390') ] #This ...
nilq/baby-python
python
"""The top level of the package contains functions to load and save data, display rendered scores, and functions to estimate pitch spelling, voice assignment, and key signature. """ import pkg_resources from .io.musescore import load_via_musescore from .io.importmusicxml import load_musicxml, musicxml_to_notearray f...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 # # Get key to relevant CARD products in CREODIAS catalog # Version 1.3 - 2020-05-14 # - Make end date inclusive # # Version 1.2 - 2020-04-14 # - Changed to JSON format parsing # - added s1 selection # # Version 1.1 - 2020-03-24 # - Include intersection calculation # import reque...
nilq/baby-python
python
# # テンプレート構成 # from typing import List, Optional from .argument import Argument from .content import Content class Config: """パッケージテンプレートの構成. """ def __init__(self, name: str, args: List[Argument], contents: List[Content], args_handler...
nilq/baby-python
python
import jwt from flask import current_app from datetime import datetime, date, timedelta from marshmallow import Schema, fields, validate, validates, ValidationError from werkzeug.security import generate_password_hash, check_password_hash from book_library_app import db class Author(db.Model): __tablename__ = '...
nilq/baby-python
python
import json import inspect from datetime import datetime import itertools import requests ########################################## # Utility functions # def _str_or_none(value: any) -> any: """will convert any value to string, except None stays None""" return None if value is None else str(value) #######...
nilq/baby-python
python
import compute_merw as merw import scipy.sparse as sparse import metrics import dataset def print_similarity_matrix(S): if not sparse.issparse(S): S = sparse.csr_matrix(S) n, m = S.get_shape() for row in range(n): print('[', end='') for col in range(m): print('{:6.3f} '...
nilq/baby-python
python
# Generated by Django 3.1 on 2021-01-02 12:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0006_message'), ] operations = [ migrations.RemoveField( model_name='room', name='staff_only', ), ]
nilq/baby-python
python
""" rbac changes for jupyterhub 2.0 Revision ID: 833da8570507 Revises: 4dc2d5a8c53c Create Date: 2021-02-17 15:03:04.360368 """ # revision identifiers, used by Alembic. revision = '833da8570507' down_revision = '4dc2d5a8c53c' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from...
nilq/baby-python
python
""" Parse a Canadian Census XML document (in SDMX format) and yield a CSV with the same data. The data will be Tidy (http://vita.had.co.nz/papers/tidy-data.pdf). However, all the column names and concept values will remain as they appear in the SDMX file -- which is to say, not very human-readable. See the other scrip...
nilq/baby-python
python
"""Class that represents the network to be evolved.""" import random import logging from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix class Network(): """Represent a netwo...
nilq/baby-python
python
''' Created on 2015年12月10日 @warning: 请务必在命令行添加选项参数,以支持不同方法的处理流程 @summary: 初始化工作,将文件的内容写入数据库 @author: suemi ''' import sys,os sys.path.append(".") from optparse import OptionParser from utils.DBUtil import DBUtil option_0 = { 'name' : ('-s', '--start'), 'help' : '选择处理的起始位置', 'nargs' : 1 } option_1 = { 'name' : ('-e','...
nilq/baby-python
python
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class AnswerForm(forms.Form): content = forms.CharField(label='Answer content', max_length=2048) class _EmailForm(forms.ModelForm): ...
nilq/baby-python
python
from pget import Downloader def sha1sum(file_name): import hashlib BUF_SIZE = 65536 sha1 = hashlib.sha1() with open(file_name, 'rb') as f: while True: data = f.read(BUF_SIZE) if not data: break sha1.update(data) return sha1.hexdigest()...
nilq/baby-python
python
import setuptools # Open the requirements file and dump them with open("requirements.txt") as file: requirements = file.read().splitlines() # Do the same with the dev requirements with open("requirements-dev.txt") as file: extras = {"dev": file.read().splitlines()} setuptools.setup( name="tokki", ver...
nilq/baby-python
python
import threading import websocket, json, time class CoinbaseWebsocket(threading.Thread): def __init__(self): # websocket.enableTrace(True) self.ws = websocket.WebSocketApp("wss://ws-feed.exchange.coinbase.com", on_message = self.on_message, ...
nilq/baby-python
python
from ipywidgets import register, Widget, DOMWidget, widget_serialization from traitlets import ( default, TraitError, Bool, Int, Unicode, Enum, Tuple, Instance ) import uuid from ._version import __version__ def id_gen(): return uuid.uuid4().urn[9:] @register class Node(Widget): """ The node widget ...
nilq/baby-python
python
# test resources manager - parser (PM) # test resources loader # test Music / SOund / Font classes. import os import pytest from laylib import resources as rc @pytest.fixture def class_resources(scope='module'): res_class = rc.Resources('examples/data') yield res_class @pytest.fixture def folder_data(scope...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from sympy import cos,sin,diff,integrate,simplify,limit,solve,Symbol x = Symbol('x') y = Symbol('y') # Algebraic computation print(2*x + 3*x - y) # Differentiates x**2 wrt. x print(diff(x**2, x)) # differentiates cos(x) and sin(x) wrt. x print(...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'AzureSkuName', 'AzureSkuTier', ] class AzureSkuName(str, Enum): """ SKU name """ S1 = "S1...
nilq/baby-python
python
from chemreps.coulomb_matrix import coulomb_matrix import numpy as np import pytest as pt def test_cm(): cm_true = np.array([36.84, 23.33, 36.84, 23.38, 14.15, 36.84, 14.15, 23.38, 9.195, 36.84, 5.492, 2.762, 2.775, 2.162, 0.5, 5.492, 2.762, 2.775, 2.162, ...
nilq/baby-python
python
from __future__ import unicode_literals import re import time from ncclient import manager import paramiko import xmltodict CONNECT_TIMEOUT = 5 # seconds class RPCClient(object): def __init__(self, device, username='', password=''): self.username = username self.password = password tr...
nilq/baby-python
python
from django.urls import path from django.conf.urls import url from django.urls import include from rest_framework import routers from . import views from .viewsets import MaskDetectorViewSet # app_name = 'api' # router = routers.DefaultRouter() # router.register('', MaskDetectorViewSet, basename='predict') urlpatt...
nilq/baby-python
python
from abc import abstractmethod from typing import Any, Optional, Union from PySide6.QtWidgets import QCheckBox, QDoubleSpinBox, QHBoxLayout, QLabel, QSpinBox from cilissa_gui.widgets.inputs.base import ( MAX_NEG_INTEGER, MAX_POS_INTEGER, CQInputWidget, ) class CQNumberInputWidget(CQInputWidget): sb:...
nilq/baby-python
python
#!/usr/bin/env python -O """ This is the test class for testing Display module algorithms and models. """ # -*- coding: utf-8 -*- # # tests.unit.TestDisplay.py is part of The RTK Project # # All rights reserved. import sys from os.path import dirname sys.path.insert(0, dirname(dirname(dirname(__file__))) + "/r...
nilq/baby-python
python
import tropomi_tools as tt import letkf_utils as lu from datetime import datetime timeperiod = [datetime.strptime('2019-01-01 00:00', '%Y-%m-%d %H:%M'), datetime.strptime('2019-01-02 23:59', '%Y-%m-%d %H:%M')] histens = lu.HIST_Ens('20190102_0000',True) histens.getLocObsMeanPertDiff(0,0) trans = tt.TROPOMI_Translato...
nilq/baby-python
python
from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from ohjelma.models import Song from ohjelma.models import Track import json impo...
nilq/baby-python
python
import glob import os import shutil import base64 from subprocess import Popen, PIPE import io import matplotlib import imageio from ..config import Configuration class FrameWriter(object): '''A writer of frames from Matplotlib figures. This class writes out individual frames to the specified directory. No anima...
nilq/baby-python
python
from wtforms import PasswordField, StringField, SelectField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.forms.users import attach_custom_user_fields, build_custom_user_fields def Registrat...
nilq/baby-python
python
# Command line tool for dealing with file attachments import os #import sys #sys.path.append(os.path.abspath("..")) from common_utils import * from items_in_collection import * # Main to accept command line and do the operation on images. if __name__ == '__main__': # get the command line arguments if len(sys.a...
nilq/baby-python
python
def calcular_precio_producto(coste_producto): """ num -> num se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste :param coste_producto: valor numerico del coste :return: precio del producto >>> calcular_precio_producto(1000) 1500.0 >>> calcular_precio_...
nilq/baby-python
python
from django.contrib import admin from .models import News class NewsAdmin(admin.ModelAdmin): date_hierarchy = 'date' list_display = ('title', 'author', 'club', 'date') list_filter = ('date',) class Meta: model = News admin.site.register(News, NewsAdmin)
nilq/baby-python
python
import chainer import chainer.functions as F import chainer.links as L import numpy from tgan2.utils import make_batch_normalization class GeneratorConv3D(chainer.Chain): def __init__(self, n_frames=16, z_slow_dim=256, out_channels=3): self.n_frames = n_frames self.z_slow_dim = z_slow_dim ...
nilq/baby-python
python
from werkzeug.serving import run_simple import tuber import sys from .backgroundjobs import AsyncMiddleware tuber.database.migrate() app = tuber.app
nilq/baby-python
python
from django.apps import AppConfig class SeliaMapsConfig(AppConfig): name = 'selia_maps'
nilq/baby-python
python
import os import random import numpy as np from tqdm import tqdm def self_play_history(env, agent, turn, gamma=1.0, all_purple=False): env = env() if all_purple: obsv = env.update('14U24U34U44U15U25U35U45U41u31u21u11u40u30u20u10u') else: obsv = env.reset(agent.init_red(), agent.init_red()...
nilq/baby-python
python
import RPi.GPIO as GPIO import dht11 import time import datetime import sys import os import serial #import serialget sys.path.append('/home/pi/proj/Adafruit_CharLCD') from Adafruit_CharLCD import Adafruit_CharLCD # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() lcd = Adafruit_CharLCD(rs...
nilq/baby-python
python
""" Packages required terminaltables colorclass """ from schema_validation import CheckGrants as CG from schema_validation import CheckJSON as CJ from schema_validation import CheckTable as CT from schema_validation import OrderFiles as OF import os import re from terminaltables import SingleTable, AsciiTa...
nilq/baby-python
python
# Ivan Carvalho # Solution to https://www.urionlinejudge.com.br/judge/problems/view/1222 #!/usr/bin/env python2.7 # -*- coding : utf-8 -*- while True: try: a,b,c = [int(i) for i in raw_input().split()] except EOFError: break entrada = raw_input().split() paginas = 1 linha_da_vez = [] linhas = 1 for palavra i...
nilq/baby-python
python
import os import shutil from typing import Optional import pytest from pandas._testing import assert_frame_equal import pandas as pd from numpy import nan import datacode as dc import datacode.hooks as dc_hooks from datacode import Variable from tests.pipeline.base import PipelineTest, EXPECT_GENERATED_DF from tests...
nilq/baby-python
python
#-*- coding: utf-8 -*- from privtext.env import _PY_V from random import randint def cross_input(): if _PY_V == 2: return raw_input() return input() def cross_encode(s): if _PY_V == 2: return s return s.encode('utf-8') def cross_decode(s): if _PY_V == 2: return s return s.decode('utf-8') # ...
nilq/baby-python
python
#!/usr/bin/env python import os import re import shlex import sys from distutils.dep_util import newer from shutil import which from cx_Freeze import setup, Executable import jinja2 #import setuptools from setuptools import Command, find_packages PO_FILES = 'po/*/messages.po' class CleanCommand(Command): """ ...
nilq/baby-python
python
"""Collection of nodes used in unittests. PYTHONPATH will be automatically set so Python can find this package. """ import sys import argparse def main(argv): parser = argparse.ArgumentParser("hello") parser.add_argument("name", type=str, help="your name") args = parser.parse_args(argv[1:]) print(f"...
nilq/baby-python
python
from nose.tools import raises import numpy as np from numpy.testing import assert_equal, assert_allclose from menpo.math import dot_inplace_left, dot_inplace_right n_big = 9182 k = 100 n_small = 99 a_l = np.random.rand(n_big, k) b_l = np.random.rand(k, n_small) a_r = np.ascontiguousarray(b_l.T) b_r = np.ascontiguousa...
nilq/baby-python
python
from laptimize.solver import Solver ''' Source : A global optimization method for non convex separable programming problems, European Journal of Operational Research 117 (1999) 275±292 Authors : Han-Lin Li, Chian-Son Yu Minimize : F0(x1) = 40*x1 + 5*(|x1-10| + x1-10) - 5*(|x1-12| + x1-12) F0(x2) =...
nilq/baby-python
python
#!/usr/bin/python3.9 # Copyright (c) 2021 MobileCoin Inc. # Copyright (c) 2021 The Forest Team from forest.core import Bot, Message, run_bot class TemplateBot(Bot): async def do_template(self, _: Message) -> str: """ A template you can fill in to make your own bot. Anything after do_ is a / comma...
nilq/baby-python
python
#!/usr/bin/env python import rospy import sys sys.path.append("../../") import configparser import numpy as np import time import tf import actionlib import signal import std_msgs.msg import geometry_msgs.msg import sensor_msgs.msg from geometry_msgs.msg import Pose from std_msgs.msg import Float32MultiArray from co...
nilq/baby-python
python
import numpy as np import math c = 2.9979 * pow(10,8) #Practice test question 2 Type def MagneticField(): ElecMax = float(input("Input the Emax (V/m): ")) angularVelocity = float(input("Input (x10^6 Rad/s): ")) * pow(10,6) magneticField = (ElecMax/c) * pow(10,9) print("Magnetic Field:" ...
nilq/baby-python
python
import pygame, sys, random def draw_floor(): screen.blit(floor_surface, (floor_x_pos, 900)) screen.blit(floor_surface, (floor_x_pos+576, 900)) def create_pipe(): random_pipe_pos = random.choice(pipe_height) bottom_pipe = pipe_surface.get_rect(midtop=(700, random_pipe_pos)) top_pipe = pipe_surface....
nilq/baby-python
python
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ This implementation is based on the blog post at https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html """...
nilq/baby-python
python
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility 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; either version 2 of the License, or # (at your o...
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms ct2ct = cms.EDProducer("CaloTowersReCreator", # Weighting factor for EB EBWeight = cms.double(1.0), HBGrid = cms.vdouble(0.0, 2.0, 4.0, 5.0, 9.0, 20.0, 30.0, 50.0, 100.0, 1000.0), # energy scale for each subdetector (only Eb-Ee-Hb-He interpolations a...
nilq/baby-python
python
import simulator BCM = 0 IN = 0 OUT = 1 PUD_DOWN = 0 RISING = 0 def setmode(mode): pass def setup(pin, direction, pull_up_down=PUD_DOWN): if direction == IN: print("New button @pin{}".format(pin)) def add_event_detect(pin, on, callback): print("Callback @pin{}".format(pin)) simulator.buttons...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 21 15:21:32 2020 @author: daniel """ import numpy as np from cmath import sqrt from scipy.special import sph_harm from numpy.linalg import pinv from matplotlib import pyplot as plt #import shtns class spherical: def __init__(self, lmax): ...
nilq/baby-python
python
import numpy as np import xpart as xp import xobjects as xo def test_basics(): for context in xo.context.get_test_contexts(): print(f"Test {context.__class__}") particles = xp.Particles(_context=context, mass0=xp.PROTON_MASS_EV, q0=1, p0c=7e12, # 7 TeV x=[1e-3, 0], ...
nilq/baby-python
python
from __future__ import print_function # OneWire part try: import ow onewire = True owsensorlist = [] except: print("Onewire package not available") onewire = False import sys, time, os, socket import struct, binascii, re, csv from datetime import datetime, timedelta # Twisted from twisted.protocol...
nilq/baby-python
python
from concurrent import futures from datetime import datetime from typing import Tuple, Dict, List from zipfile import ZipFile from io import BytesIO from collections import defaultdict from utils.github import get_github_metadata, get_artifact from utils.pypi import query_pypi, get_plugin_pypi_metadata from api.s3 imp...
nilq/baby-python
python
#!/usr/bin/env python3 ''' Shapeless bot for MsgRoom @ Windows96.net Shapeless bot © Diicorp95. MIT License Windows 96 © Mikesoft. All rights reserved, except for some parts Open-Source Part: Functional Wrap for File System (excerpt) ''' import os.path # not implemented def askterm(s,mgrp): s+=' (y/n): ' i...
nilq/baby-python
python
"""Graph database for storing harvested data.""" from neo4j import GraphDatabase from neo4j.exceptions import ServiceUnavailable, ConstraintError from typing import Tuple, Dict, Set import logging import json from pathlib import Path from os import environ import boto3 import base64 from botocore.exceptions import Clie...
nilq/baby-python
python
import os from glue.core import data_factories as df from glue.tests.helpers import requires_astropy DATA = os.path.join(os.path.dirname(__file__), 'data') @requires_astropy def test_load_vot(): # This checks that we can load a VO table which incidentally is a subset of # the one included in the tutorial. ...
nilq/baby-python
python
#Faça um programa que leia um ano e mostre se ele é BISSEXTO a = int(input('Digite um ano: ')) if a % 4 == 0: print(f'O ano {a} é BISSEXTO') else: print(f'O ano {a} NÃO É BISSEXTO')
nilq/baby-python
python
with open("myside.txt","r+") as f: new_f = f.readlines() f.seek(0) for line in new_f: if "<Media omitted>" not in line: f.write(line) f.truncate() with open("otherside.txt","r+") as f: new_f = f.readlines() f.seek(0) for line in new_f: if "<Media omitted>" not in...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
nilq/baby-python
python
import unittest from rx.core import Observable from rx.testing import TestScheduler, ReactiveTest, is_prime on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed ...
nilq/baby-python
python
""" The transport decorator (~transport). This decorator allows changes to agent response behaviour and queue status updates. """ from marshmallow import fields, validate from ..models.base import BaseModel, BaseModelSchema from ..valid import UUIDFour, WHOLE_NUM class TransportDecorator(BaseModel): """Class r...
nilq/baby-python
python
for svc in SERVICES: db.define_table( 'report_card_%s' % svc[0], Field('choose_file', 'upload', uploadfield='file_data'), Field('file_data', 'blob'), Field('file_description', requires=IS_NOT_EMPTY()), ) db.define_table( 'award', YES_NO_FIELD, ) db.de...
nilq/baby-python
python
# # PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:02:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
nilq/baby-python
python
# Generated by Django 3.2.8 on 2022-02-02 20:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ProjectSite', '0001_initial'), ] operations = [ migrations.CreateModel( name='Category', ...
nilq/baby-python
python
#------------------------------------------------------------------------------------------- ''' #barchar and histogram of sensors df = pd.read_csv('../data/trafico/raw_data/07-2020.csv', sep=';') df_month = df.groupby(['id']).mean() fig = px.bar(x = df_month.index, y=df_month['intensidad']) fig.show() fig = px.hist...
nilq/baby-python
python
#assignment one k=float(input("\t\tENTER THE VALUE OF K = \t")) p=(k-1)/(k+1) print(p) #the value of p is #assignment two x=int(input("\t\tENTER THE VALUE OF X = \t")) y=int(input("\t\tENTER THE VALUE OF Y = \t")) z=int(input("\t\tENTER THE VALUE OF Z = \t")) result=max(min(x,y),z) #the value stored in...
nilq/baby-python
python
import numpy as np class MaskGenerator(object): def __init__(self, h, w, rng=None): self.h = h self.w = w if rng is None: rng = np.random.RandomState(None) self.rng = rng def gen(self, n): return np.ones((n, h, w)) class AllOnesMaskGenerator(MaskGenerator)...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-09-13 05:13 import core.csv_export from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracon2018', '0001_initial'), ] operations = [ migrations.CreateModel( name='Pois...
nilq/baby-python
python
import cProfile def test_fib(func): lst = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] for i, item in enumerate(lst): assert item == func(i) print(f'Test {i} OK') def fib_list(n): fib_l = [None] * 1000 fib_l[:2] = [0, 1] def _fib_list(n): if fib_l[n] is None: fib_l[n] =...
nilq/baby-python
python
import logging from boto3 import client from botocore.exceptions import ClientError logger = logging.getLogger(__name__) class SSM: """An SSM class that provides a generic boto3 SSM client with specific SSM functionality necessary for dspace submission service""" def __init__(self): self.client...
nilq/baby-python
python
# https://github.com/georgezlei/algorithm-training-py # Author: George Lei import random def union_find(vertices, edges): unions = [i for i in range(vertices)] for a, b in edges: while a != unions[a]: a = unions[a] while b != unions[b]: b = unions[b] unions[b] = a return len([i for i i...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import JsonResponse from django.http import HttpResponse from django.shortcuts import render_to_response from django.shortcuts import render from models import * # Create your views here. def home(request): texto = "banana" template =...
nilq/baby-python
python
import json import plotly import pandas as pd import joblib import nltk from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from sklearn.base import BaseEstimator, TransformerMixin from flask import Flask from flask import render_template, request, jsonify from plotly.graph_objs import Bar...
nilq/baby-python
python
import gzip import os from parser import Parser path = os.getcwd() + "/corpus" articles = ["a", "the", "an"] pronouns = ["i", "you", "we", "it", "they", "he", "she", "my", "mine", "their", "theirs", "his", "her", "that", "this", "us", "me", "him"] connectives = ["in", "s", "d", "t", "by", "of",...
nilq/baby-python
python
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.10 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (3,0,0): new_instancemethod = lambda func, inst, cls: _HLRBRep...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ continuity.tests.github ~~~~~~~~~~~~~~~~~~~~~~~ Continuity GitHub tests. :copyright: 2015 by Jonathan Zempel. :license: BSD, see LICENSE for more details. """ from . import ContinuityTestCase class GitHubCommandTestCase(ContinuityTestCase): """Base GitHub command...
nilq/baby-python
python
class A: def f2(self, *args, a = 1): pass class B(A): def f2(self, *args, a=1): <selection>super().f2(*args, a=a)</selection>
nilq/baby-python
python
# Generated from 'Movies.h' def FOUR_CHAR_CODE(x): return x xmlIdentifierUnrecognized = -1 kControllerMinimum = -0xf777 notImplementedMusicOSErr = -2071 cantSendToSynthesizerOSErr = -2072 cantReceiveFromSynthesizerOSErr = -2073 illegalVoiceAllocationOSErr = -2074 illegalPartOSErr = -2075 illegal...
nilq/baby-python
python
from part2 import test_num def test_test_num(): assert test_num(112233) == True, "Expected 112233 to pass" assert test_num(123444) == False, "Expected 123444 to fail" assert test_num(111133) == True, "Expected 111133 to pass" print("Passed!") if __name__ == "__main__": test_test_num()
nilq/baby-python
python