content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import os, sys, inspect # realpath() will make your script run, even if you symlink it :) 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) # use this if you want to include modules from a subfol...
nilq/baby-python
python
from Core.Anlyst import anlyse from Core.URLs import WayUrl from Core.URLs import WebUrl from Test.NetWorkTest import WebUrlPostTest from Core.NetWork import VisitorWays from Core.NetWork import visit xpaths = ['//*[@id="form3"]/a/@href'] selector = '#form3 > a' def TestOfAnlyseByRegex(): url = "regex://a/b0" ...
nilq/baby-python
python
import click from cortex.server import server from cortex.utils import logging # ----=========== CLI ===========---- @click.group() def cli(): pass @cli.command("run-server") @click.option("--host", "-h") @click.option("--port", "-p", type=int) @click.argument('publish_url') def run_server_cli(host, port, publis...
nilq/baby-python
python
""" Account base class for holding Account information """ class Account: def __init__(self): self.employee_id: int self.user_name: str self.password: str
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(verbose...
nilq/baby-python
python
import typing as T from dataclasses import dataclass from moonleap import Resource from titan.project_pkg.service import Tool @dataclass class SetupFile(Tool): pass @dataclass class SetupFileConfig(Resource): body: T.Union[dict, T.Callable] def get_body(self): return self.body() if callable(se...
nilq/baby-python
python
import numpy as np from utils.tt_dataset import AgentType, TrajectoryTypeDataset from test_problems.u_grid_encoding import xy2mrx_v1 as xy2mrx from test_problems.risk_distances import dist2rt_v1 as dist2rt from test_problems.grid_encoding import rt2enc_v1 as rt2enc from utils import general as ge import scipy.optimize ...
nilq/baby-python
python
""" **************************************************************************************************** :copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted ...
nilq/baby-python
python
""" Generate training source and target domain records """ import os import csv import random import argparse def write_csv(path, lines): with open(path, 'w') as f: csv_writer = csv.writer(f, delimiter='\t') for i, (p, l) in enumerate(lines): csv_writer.writerow([i, l, p]) def read_...
nilq/baby-python
python
# Copyright (c) 2021 Valerii Sukhorukov. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided 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
import cdat_info import cdms2 import numpy import unittest import sys PLOT = False if PLOT: from matplotlib import pylab as pl from mpl_toolkits.basemap import Basemap as bm class TestTasRegrid(unittest.TestCase): """ All test interpolate to the same grid """ def setUp(self): self.cl...
nilq/baby-python
python
#!/usr/bin/env python # EVAPOR Workflow written in Python 3.6 in April 2020 by mswartz2@gmu.edu # This code will import text string, extract the emojis as list # report out the unique emojis and unique emoji attributes for the text # then for text analyze the structure of the content # and then delve into the emojis a...
nilq/baby-python
python
# Generated by Django 2.2.13 on 2021-08-09 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0118_auto_20210809_1032'), ] operations = [ migrations.AlterField( model_name='reportcolumnpostfix', na...
nilq/baby-python
python
""" Serialiser tests """ from datetime import datetime import unittest from zorp.serialiser import Serialiser class TestSerialiser(unittest.TestCase): """ Test the serialiser """ def __test_encode_decode(self, expected): """ Test that encoding and decoding a value results in ...
nilq/baby-python
python
import torch import torch.utils.data as data_utils from torch.utils.data import DataLoader import torch.autograd as autograd import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from torch.nn.parameter import Parameter from allennlp.modules.attention im...
nilq/baby-python
python
from oscar.apps.offer import models class AlphabetRange(object): name = "Products that start with D" def contains_product(self, product): return product.title.startswith('D') def num_products(self): return None class BasketOwnerCalledBarry(models.Condition): name = "User must be ca...
nilq/baby-python
python
# Generated by Django 2.1.7 on 2019-04-09 14:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0044_auto_20190409_1448'), ] operations = [ migrations.RemoveField( model_name='badgesp...
nilq/baby-python
python
import requests from bs4 import BeautifulSoup blacklist = { "farms", "csa", "farmers-markets", "restaurants", "food-coops", "u-pick", "farm-stands", "others", "list"} city = '/locations/' wiki = f"https://www.localharvest.org/{city}" page = requests.get(wiki) soup = BeautifulSoup(page.text, "html.parser") for link in...
nilq/baby-python
python
"""Common functions.""" import re from socket import getaddrinfo, AF_INET, AF_INET6, IPPROTO_TCP from datetime import timedelta def explode_datetime(datetime_str): """Extract days minutes and seconds from datetime (days, minutes, seconds). Example: "1d 3h 2m" returns {"days": "1", "hours": "3", "minutes": "...
nilq/baby-python
python
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, current_app, json from flask.ext.login import login_user, login_required, logout_user from app.users.models import Users from app.users.forms import LoginForm, RegisterForm, UserForm, PasswordForm, ResetPassForm, NewPassForm fr...
nilq/baby-python
python
import argparse import os import zipfile def make_rel_archive(a_args): archive = zipfile.ZipFile("(Part 1) Engine Fixes.zip".format(a_args.name), "w", zipfile.ZIP_DEFLATED) def do_write(a_path): archive.write(a_path, "SKSE/Plugins/{}".format(os.path.basename(a_path))) def write_rootfile(a_extension): do_write("...
nilq/baby-python
python
#!/usr/bin/env python ## Create Microsoft Test Server DRM keys, parse LAURL array ## python.exe RegisterDRM_MicrosoftTest.py > keys_microsofttest.json ## Aki Nieminen/Sofia Digital ## 2017-11-30/Aki: changed hexdecode to python3 ## 2017-08-21/Aki: initial release import sys, os, time, datetime, json, base64 f...
nilq/baby-python
python
from .face_utils import align_crop_face_landmarks, compute_increased_bbox, get_valid_bboxes, paste_face_back from .misc import img2tensor, load_file_from_url, scandir __all__ = [ 'align_crop_face_landmarks', 'compute_increased_bbox', 'get_valid_bboxes', 'load_file_from_url', 'paste_face_back', 'img2tensor', 's...
nilq/baby-python
python
import numpy as np def AdjHE_estimator(A,data, npc=0, std=False): # remove identifiers form y for linear algebra y = data.Residual # select PC columns PC_cols = [ col.startswith("PC") for col in data ] PCs = data.iloc[:, PC_cols] # If standardized AdjHE is chosen if (std == True) : ...
nilq/baby-python
python
import os, sys, hashlib, argparse BLOCK_SIZE = 65536 def calculateFileHash(path): hasher = hashlib.md5() with open(path, 'rb') as targetFile: buffer = targetFile.read(BLOCK_SIZE) while len(buffer) > 0: hasher.update(buffer) buffer = targetFile.read(BLOCK_SIZE) retur...
nilq/baby-python
python
import os import torch import numpy as np from sentence_transformers import SentenceTransformer from experiment.qa.evaluation import BasicQAEvaluation class QAEvaluationSBert(BasicQAEvaluation): def __init__(self, config, config_global, logger): super(QAEvaluationSBert, self).__init__(config, config_glo...
nilq/baby-python
python
"""Test Home Assistant ulid util methods.""" import uuid import homeassistant.util.ulid as ulid_util async def test_ulid_util_uuid_hex(): """Verify we can generate a ulid.""" assert len(ulid_util.ulid_hex()) == 32 assert uuid.UUID(ulid_util.ulid_hex())
nilq/baby-python
python
from flask import Flask, render_template, request, Response from Models import db, SensorData, CustomSensor from flask.json import jsonify from Arduino import serial_port from threading import Thread from Helpers import search_sensor from Constants import DataTypes import os.path db_path = os.path.join('sqlite://', o...
nilq/baby-python
python
#basic program of finding the SECOND LARGEST VALUE among the given list of value #finding the RUNNER UP in other words #used map(),split(),sorted() #the sorted()function here creates a new set returns a sorted list of the specified iterable object. if __name__ == '__main__': #getting the number of scores you are g...
nilq/baby-python
python
from collections import namedtuple ButtonOptions = namedtuple('ButtonOptions', ['activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'disabledforeground', 'font', 'foreground', 'highlightbackground', 'highlightcolor', ...
nilq/baby-python
python
"""Constants for the Thruk Livestatus sensor integration.""" # This is the internal name of the integration, it should also match the directory # name for the integration. DOMAIN = "thruk_livestatus" HOST_COUNT = "Host count" NUM_SERVICES_CRIT = "Services CRITICAL" NUM_SERVICES_WARN = "Services WARNING" NUM_SERVICES_...
nilq/baby-python
python
import decoder inp_fn = raw_input("Enter the file name to decode:") sp_fn_a = inp_fn.split('.') sp_fn_b = sp_fn_a[0].split('_') inp_fs = open(inp_fn,"r") out_fs = open("decoded_"+sp_fn_b[1]+'.'+sp_fn_b[2],"wb+") enc_ln = int(inp_fs.readline()) st_to_dec = inp_fs.readline() while st_to_dec!='': out_fs.write(decoder....
nilq/baby-python
python
"""Plants tests"""
nilq/baby-python
python
import time, sys, random from pygame import mixer from PyQt5.QtWidgets import QDialog, QApplication from PyQt5 import QtWidgets, QtCore from src.ui.controlPenalUI import Ui_controlPenal from src.songScreen import picWindow class controlPenal(QDialog): def __init__(self): super().__init__() ...
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 t...
nilq/baby-python
python
import sys import argparse import json import logging import os from TrainFace import TrainFace from InferFace import InferFace if __name__ == "__main__": # Read the input information by the user on the command line parser = argparse.ArgumentParser() parser.add_argument("--config_file", help="co...
nilq/baby-python
python
class Solution(object): def defangIPaddr(self, address): """ :type address: str :rtype: str """ return address.replace(".", "[.]") if __name__ == '__main__': address = "0.0.0.0" obj = Solution() obj.defangIPaddr(address)
nilq/baby-python
python
#!/usr/bin/env python # coding:utf-8 import os import sys current_path = os.path.dirname(os.path.abspath(__file__)) helper_path = os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'data', 'launcher', 'helper') if __name__ == "__main__": python_path = os.path.abspath( os.path.join(current_path, os.pardi...
nilq/baby-python
python
#!/usr/bin/python3 import argparse import getpass import glob import os import socket import subprocess import time import sys script_description = ( "Prepare current system for migrate attack, output XSS payload\n" "Requires to be run with sudo/root privs for writing files to system dirs" ) def is_port_op...
nilq/baby-python
python
import typing from core import scriptercore class LinuxDisplayPwnedMsgBox(scriptercore.Scripter): AUTHOR: str = "Danakane" def __init__(self): super(LinuxDisplayPwnedMsgBox, self).__init__() self.__title__: str = "" self.__text__: str = "" self.customize({"title": "The title...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Пример распаковки/упаковки контейнеров (cf/epf/ert) при помощи onec_dtools Функционал аналогичен C++ версии v8unpack Copyright (c) 2016 infactum """ import argparse import sys from onec_dtools import extract, build def main(): parser = argparse.ArgumentParser() group = parser.ad...
nilq/baby-python
python
__author__ = "MetaCarta" __copyright__ = "Copyright (c) 2006-2008 MetaCarta" __license__ = "Clear BSD" __version__ = "$Id: VersionedPostGIS.py 496 2008-05-18 13:01:13Z crschmidt $" from FeatureServer.DataSource import DataSource from vectorformats.Feature import Feature from FeatureServer.DataSource.PostGIS import P...
nilq/baby-python
python
import requests as reqs import base64 import logging import re import json # 调用淘宝识图请求接口,获取商品源和标签 def taobao_pic_recognize(pic_dir,pic_name,cookie): # with open(pic_dir+'/'+pic_name, "rb") as f: # # b64encode:编码,b64decode: 解码 # base64_data = base64.b64encode(f.read()) imagefile={ "file": (pic_n...
nilq/baby-python
python
from flask import Flask, request, redirect from twilio.twiml.messaging_response import MessagingResponse import pandas as pd import datetime import pytz # the below import is only needed for forwarding the sms, in case the client sends KONTAKT from twilio.rest import Client account_sid = '###################...
nilq/baby-python
python
from src.bert_classifier.model import Model from src.bert_classifier.fit import fit
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from telegram.ext import Updater, MessageHandler, Filters import traceback as tb import json import random import threading START_MESSAGE = (''' Loop message in chat / group / channel. add - /add message: add message to loop. list - /list: list message inside the loop....
nilq/baby-python
python
# Copyright 2019 Google LLC. 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 a...
nilq/baby-python
python
from setuptools import setup setup( name="backbones", version="0.1", description="Common neural network architectures implemented in PyTorch.", url="https://github.com/bentaculum/backbones", author="Benjamin Gallusser", author_email="benjamin.gallusser@epfl.ch", license="MIT", install_r...
nilq/baby-python
python
from typing import List, Tuple, Callable, Optional import numpy as np import tweedie from gluonts.model.forecast import SampleForecast, QuantileForecast from scipy.optimize import fmin_l_bfgs_b from scipy.special import gammaln, factorial, psi from scipy.stats import norm, beta, gamma, nbinom, poisson from sklearn.pre...
nilq/baby-python
python
import argparse import os import time from keystoneauth1 import loading from keystoneauth1 import session from heatclient import client _TERMINAL = [ 'CREATE_FAILED', 'CREATE_COMPLETE', 'UPDATE_FAILED', 'UPDATE_COMPLETE' ] _INTERVAL = 20 def get_session(): """Get a keystone session :returns...
nilq/baby-python
python
from pydantic import BaseModel #fastapi接口的数据模型 class User(BaseModel): first_name: str last_name: str age: int class Config: orm_mode = True
nilq/baby-python
python
import sys import getpass from mlflow.tracking.context.abstract_context import RunContextProvider from mlflow.entities import SourceType from mlflow.utils.mlflow_tags import ( MLFLOW_USER, MLFLOW_SOURCE_TYPE, MLFLOW_SOURCE_NAME, ) _DEFAULT_USER = "unknown" def _get_user(): """Get the current comput...
nilq/baby-python
python
import numpy as np import torch from torch.utils.data import Dataset from torch.utils.data.dataloader import default_collate from fairseq.data.fairseq_dataset import FairseqDataset def sine(phase, amplitude, x): return np.sin(x + phase) * amplitude class SineDataset(Dataset): def __init__(self, split, phas...
nilq/baby-python
python
import socket server = "localhost" #settings channel = "#domino" botnick = "firestorck_bot" print("Server : ", server) print("Channel : ", channel) print("Name : ", botnick) irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print ("connecting to: "+server) irc.connect((server, 6667)) ...
nilq/baby-python
python
import numpy as np import copy as cp DIRECTIONS = [np.array((0, 1)), np.array((1, 0)), np.array((1, 1)), np.array((0, -1)), np.array((-1, 0)), np.array((-1, -1)), np.array((1, -1)), np.array((-1, 1))] class State: def __init__(self, grid=None, previous_skip=False, side=2, master_side=2): if...
nilq/baby-python
python
import os import glob import shutil import tempfile import numpy as np import common import features import folds from audio_toolbox import ffmpeg, sox from constants import * def normalize(input_file): temp_dir = tempfile.mkdtemp() transcoded_file = os.path.join(temp_dir, 'transcoded.flac') ffmpeg.tra...
nilq/baby-python
python
import django_describer.actions import django_describer.datatypes import django_describer.permissions import django_describer.describers import django_describer.utils import django_describer.adapters name = "django_describer"
nilq/baby-python
python
from ctypes import * from .jenv import * from . import Object from . import ClassUtils from . import Executable from . import String from . import Modifier class Method(Executable.Executable, Modifier.Modifier): _isInit = None _Class = None _getName = None _getReturnType = None _count = 0 def ...
nilq/baby-python
python
"""Tests for the ResourceTracker class""" import errno import gc import os import pytest import re import signal import subprocess import sys import time import warnings import weakref from loky import ProcessPoolExecutor import loky.backend.resource_tracker as resource_tracker from loky.backend.context import get_con...
nilq/baby-python
python
from abc import ABC, abstractmethod from datetime import datetime from typing import List, Optional, Tuple, Any, Dict, Iterable, Generator import yaml from smart_open import smart_open from blurr.core import logging from blurr.core.aggregate_block import BlockAggregate, TimeAggregate from blurr.core.errors import Pr...
nilq/baby-python
python
from .base_requests import AnymailRequestsBackend, RequestsPayload from ..exceptions import AnymailRequestsAPIError from ..message import AnymailRecipientStatus from ..utils import get_anymail_setting class EmailBackend(AnymailRequestsBackend): """ Postal v1 API Email Backend """ esp_name = "Postal" ...
nilq/baby-python
python
# encoding: utf-8 # module NationalInstruments.RFmx calls itself RFmx # from NationalInstruments.RFmx.InstrMX.Fx40, Version=19.1.0.49152, Culture=neutral, PublicKeyToken=dc6ad606294fc298 # by generator 1.145 # no doc # no imports # no functions # no classes # variables with complex values
nilq/baby-python
python
from ..mime import GlueMimeListWidget, LAYERS_MIME_TYPE class TestGlueMimeListWidget(object): def setup_method(self, method): self.w = GlueMimeListWidget() def test_mime_type(self): assert self.w.mimeTypes() == [LAYERS_MIME_TYPE] def test_mime_data(self): self.w.set_data(3, 'tes...
nilq/baby-python
python
# Generated by Django 2.0.5 on 2018-05-07 13:56 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ticket', fields=[ ...
nilq/baby-python
python
import torch import torch.nn.functional as F import random class NGDSAC: ''' Neural-Guided DSAC to robustly fit lines. ''' def __init__(self, hyps, inlier_thresh, inlier_beta, inlier_alpha, loss_function, invalid_loss): ''' Constructor. hyps -- number of line hypotheses sampled for each image inlier_thr...
nilq/baby-python
python
import Signatures class Tx: inputs = None #input addreses outputs = None #output addreses sigs = None # signatures reqd = None #required signatures that are not inputs def __init__(self): self.inputs = [] self.outputs = [] self.sigs = [] self.reqd = [] def add_inp...
nilq/baby-python
python
from rest_framework import serializers from rest_framework.fields import SerializerMethodField from .models import content_choice, visibility_choice from .models import Post as Post from backend.settings import SITE_ADDRESS from author.serializers import AuthorSerializer from comment.serializers import ChoiceField, Co...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import time import requests from bs4 import BeautifulSoup session = requests.session() session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0' words = [] for page in range(1, 94+1): if pa...
nilq/baby-python
python
import torch import torch.nn as nn from einops.layers.torch import Rearrange # This model is modified from https://github.com/lucidrains/vit-pytorch class ViT(nn.Module): def __init__(self, image_size, patch_size, dim, transformer, num_classes, channels=3, joint=True): super().__init__() num_patch...
nilq/baby-python
python
import os import signal import asyncio import datetime import json import logging import edgefarm_application as ef from schema_loader import schema_read # # Using the ads_producer/encoder, you can publish a message towards ADS # ads_producer = None ads_encoder = None async def temperature_handler(msg): """This ...
nilq/baby-python
python
import datetime import unittest import isce from isceobj.Orbit.Orbit import StateVector class StateVectorTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testEqualCompare(self): """ Test that __cmp__ returns true when the times are the s...
nilq/baby-python
python
"""Batching Lambda function - puts all S3 objects into SQS to be re-analyzed.""" # Expects the following environment variables: # BATCH_LAMBDA_NAME: The name of this Lambda function. # BATCH_LAMBDA_QUALIFIER: The qualifier (alias) which is used to invoke this function. # OBJECTS_PER_MESSAGE: The number of S3 obje...
nilq/baby-python
python
from cmanager import CreditManager
nilq/baby-python
python
# -*- coding: utf-8 -*- import ldap #import ldap.modlist as modlist from brie.config import ldap_config from brie.lib.log_helper import BrieLogging from brie.model.ldap import Groupes class Groups(object): __groups = list() def __init__(self, groups): self.__groups = groups #end def def __g...
nilq/baby-python
python
import sys import json import twint import threading import lzma import glob import instaloader import os import shutil from datetime import datetime from googleapiclient.discovery import build from facebook_scraper import get_posts from PySide2.QtQml import QQmlApplicationEngine from PySide2.QtCore import QObject, Slo...
nilq/baby-python
python
from _Framework.ButtonSliderElement import ButtonSliderElement SLIDER_MODE_OFF = 0 SLIDER_MODE_TOGGLE = 1 SLIDER_MODE_SLIDER = 2 SLIDER_MODE_PRECISION_SLIDER = 3 SLIDER_MODE_SMALL_ENUM = 4 SLIDER_MODE_BIG_ENUM = 5 #TODO: repeat buttons. # not exact / rounding values in slider and precision slider class DeviceContr...
nilq/baby-python
python
from selenium.webdriver.common.by import By class MainPageLocators(): SEARCH_STRING = (By.ID, 'text') SUGGEST = (By.CSS_SELECTOR, '[role=listbox]') IMAGES = (By.CSS_SELECTOR, '[data-statlog="services_new.item.images.2"]') class ResultPageLocators(): FIRST_RESULT = (By.CSS_SELECTOR, '[data-cid="0"] .organic__path...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function def env_or_default(name, d): from os import environ try: a = environ[name] if a: return type(d)(a) else: return d except Exception: return d def print_stats(steps, t_diff, dl): from time import strf...
nilq/baby-python
python
import glob, os, numpy from music21 import converter, instrument, note, chord from itertools import chain import json import pickle PATH = '../Bach-Two_Part_Inventions_MIDI_Transposed/txt' OUTPUT_PATH = '../Bach-Two_Part_Inventions_MIDI_Transposed/txt_tokenized' CHUNK_SIZE = 4 # MEASURES def write_pickle(filename,...
nilq/baby-python
python
import webbrowser import os import re # Styles and scripting for the page main_page_head = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Learn To Code Pakistan ...
nilq/baby-python
python
# demo - opencv import cv2 # Black and White (gray scale) img = cv2.imread ('lotus.jpg', 1 ) cv2.imshow('lotus', img) cv2.waitKey(0) # cv2.waitKey(2000) cv2.destroyAllWindows()
nilq/baby-python
python
''' import data here and have utility functions that could help ''' import pandas as pd import pickle from thefuzz import fuzz, process ratings = pd.read_csv('./data/ml-latest-small/ratings.csv') movies = pd.read_csv('./data/ml-latest-small/movies.csv') # import nmf model with open('./nmf_recommender.pkl', 'rb') ...
nilq/baby-python
python
from bs4 import BeautifulSoup import requests import pprint headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'} base_url = 'https://news.ycombinator.com/news' response = requests.get(base_url, headers=headers) soup = Beautiful...
nilq/baby-python
python
#!/usr/bin/env python3 # # __main__.py """ CLI entry point. """ # # Copyright (c) 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # 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...
nilq/baby-python
python
from typing import Any, Union from bot.event import Event, EventType from pydantic.utils import deep_update def event( event_data: Union[str, dict[str, Any]], event_type: EventType = EventType.NEW_MESSAGE, ) -> Event: default = { "chat": {"chatId": "test"}, "from": "someone@mail.ru", ...
nilq/baby-python
python
import cv2 from matplotlib import pyplot as plt img = cv2.imread('open')
nilq/baby-python
python
from pathlib import Path from flask import current_app from flask_marshmallow import Marshmallow from PIL import Image from flask_app.commons.util import pil_to_base64 from flask_app.database.database import Version, Card ma = Marshmallow() class VersionSchema(ma.SQLAlchemyAutoSchema): class Meta: mode...
nilq/baby-python
python
# coding=utf-8 #!/bin/python3 # 这个插件用来去掉Equation的xor系列混淆 # 仅仅支持python 3,只在ida pro 7.7下测试过 # 将本文件放到IDA安装目录的plugins目录下,然后启动ida,在ida View中把光标放在解码函数开始,就可以在 Edit->Plugings->Xor Batch Deobfuscation # 也可以使用快捷键Ctrl+Shift+D进行反混淆 import sys try: import idaapi import idc import idautils import flare_emu # imp...
nilq/baby-python
python
__all__ = ['App'] import control_characters import mdfind import os import plistlib import stat import subprocess import sys from writable_property import writable_property """ path/to/<name>.py class Name(mac_app.App) output: ~/Applications/.mac-app-generator/<name>.app ...
nilq/baby-python
python
from pymongo import MongoClient client = MongoClient() def get_db(): return client['parallel_chat']
nilq/baby-python
python
import numpy as np import os # Readme_2_data_abstracts showed how the data abstracts work. # Technically, they embody all functionality to work with data # This part introduces the dataset class, which is based on a dictseqabstract # This means that you can use it in a similar way. # However it has additional function...
nilq/baby-python
python
from .model import EfficientUnetPlusPlus
nilq/baby-python
python
import machine import time import json # GPIO connections on test fixture gpio_conn = [ { 'out': 2, 'io': (23, 32) }, { 'out': 1, 'io': (33, 34) }, { 'out': 2, 'io': (5, 12, 35) }, { 'out': 2, 'io': (4, 18) }, { 'out': 2, 'io': (13, 15) }, { 'out': 2, 'io': (2, 14) } ] def testGPIO(): # List of problem ...
nilq/baby-python
python
import os import re import sqlite3 import configparser from helpers.logger import Logger from helpers.match import MatchDatabase, MatchSource from helpers.searchwords import Searchwords class File: config = configparser.ConfigParser() config.read("config.ini") non_regex_indicator = config.get("ProgramCo...
nilq/baby-python
python
#!/usr/bin/env python3 """ Interpret all transforms, thereby flattening cairo operations to just a few primitives, such as move_to line_to and curve_to. """ import sys from math import sin, cos, pi from bruhat.argv import argv from bruhat.render import back from bruhat.render.base import Context class Flatten(Cont...
nilq/baby-python
python
"""REPL server for inspecting and hot-patching a running Python process. This module makes your Python app serve up a REPL (read-eval-print-loop) over TCP, somewhat like the Swank server in Common Lisp. In a REPL session, you can inspect and mutate the global state of your running program. You can e.g. replace top-le...
nilq/baby-python
python
# standard from collections import defaultdict, OrderedDict import csv import sys import tempfile import unittest class File: ''' An abstract class simplifying file access through the use of only two functions: - read (file) - write (data, file): ''' @classmethod def read(cls, filename): ...
nilq/baby-python
python
from setuptools import setup, find_packages setup( name="users", version="0.1.0", description="Stoic authentication service", license="Apache", packages=find_packages(), )
nilq/baby-python
python
from __future__ import print_function # for Python 2/3 compatibility try: import queue except ImportError: import Queue as queue import logging import serial import time import threading from binascii import hexlify, unhexlify from uuid import UUID from enum import Enum from collections import defaultdict f...
nilq/baby-python
python
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-31-optimal-strategy-for-a-game/ def optimal_strategy(coins): if len(coins) == 1: return coins[0] elif len(coins) == 2: return max(coins[0], coins[1]) else: return max(coins[0] + min(optimal_strategy(coins[2:...
nilq/baby-python
python