content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import pylab as pl fig = pl.figure() fig.subplots_adjust(bottom=0.025, left=0.025, top = 0.975, right=0.975) pl.subplot(2, 1, 1) pl.xticks(()), pl.yticks(()) pl.subplot(2, 3, 4) pl.xticks(()) pl.yticks(()) pl.subplot(2, 3, 5) pl.xticks(()) pl.yticks(()) pl.subplot(2, 3, 6) pl.xticks(()) pl.yticks(()) pl.show()
nilq/baby-python
python
from .FeatureDescriptionLabel import * from .FeatureExtractionLogic import * from .FeatureWidgets import *
nilq/baby-python
python
''' The np.npv() function estimates the present values for a given set of future cash flows. The first input value is the discount rate, and the second input is an array of future cash flows. This np.npv() function mimics Excel's NPV function. Like Excel, np.npv() is not a true NPV function. It is actually a PV fu...
nilq/baby-python
python
from tempfile import NamedTemporaryFile import boto3 from rivet import inform, s3_path_utils from rivet.s3_client_config import get_s3_client_kwargs from rivet.storage_formats import get_storage_fn def write(obj, path, bucket=None, show_progressbar=True, *args, **kwargs): """ Writes an object to a...
nilq/baby-python
python
import pandas as pd import numpy as np import tensorflow as tf from tensorflow import keras tf.random.set_seed(2021) from models import DNMC, NMC, NSurv, MLP, train_model, evaluate_model df = pd.read_csv('http://pssp.srv.ualberta.ca/system/predictors/datasets/000/000/032/original/All_Data_updated_may2011_CLEANED.cs...
nilq/baby-python
python
# test return statement def f(): return print(f()) def g(): return 1 print(g()) def f(x): return 1 if x else 2 print(f(0), f(1)) print("PASS")
nilq/baby-python
python
from contextlib import suppress import warnings import urllib.parse import calendar from cromulent import model, vocab from cromulent.model import factory from cromulent.extract import extract_physical_dimensions from pipeline.util.cleaners import ymd_to_datetime factory.auto_id_type = 'uuid' vocab.add_art_setter() ...
nilq/baby-python
python
import logging import os import random from collections import defaultdict, namedtuple from threading import Lock, Thread from time import sleep from consul import Consul instance = namedtuple('serviceinstance', ['address', 'port']) service = namedtuple('service', ['ts', 'instances']) class ServiceInstance(instance...
nilq/baby-python
python
from django.urls import path from material.admin.sites import site urlpatterns = [ path('', site.urls, name='base') ]
nilq/baby-python
python
## this version of get_freq collects %AT-richness, gene expression data and SumFreq statistic on top of the data collated by get_freq.py import pandas as pd import numpy as np ## NOTE: All filenames are placeholders raw = pd.read_csv("REDItools_processed_dedup-filt.genann.txt", header = 0, sep = "\t") exp = pd.read_cs...
nilq/baby-python
python
""" Pipeline code for training and evaluating the sentiment classifier. We use the Deepmoji architecture here, see https://github.com/bfelbo/DeepMoji for detail. """ import re import codecs import random import numpy as np import sys import json import argparse import pandas as pd import glob, os import matplotlib.pyla...
nilq/baby-python
python
# SPDX-License-Identifier: MIT # Copyright (C) 2021 Max Bachmann from rapidfuzz.cpp_process import extract, extractOne, extract_iter try: from rapidfuzz.cpp_process_cdist import cdist except ImportError: def cdist(*args, **kwargs): raise NotImplementedError("implementation requires numpy to be install...
nilq/baby-python
python
from django.shortcuts import render, redirect from hujan_ui import maas from hujan_ui.maas.utils import MAAS from .forms import VlanForm, VlanEditForm from django.utils.translation import ugettext_lazy as _ import sweetify from hujan_ui.maas.exceptions import MAASError def index(request): try: vlans = maa...
nilq/baby-python
python
# Generated by Django 2.1.7 on 2019-03-01 13:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('news', '0002_auto_20161125_0846'), ] operations = [ migrations.AlterModelOptions( name='news', options={'ordering': ('pub_da...
nilq/baby-python
python
import datetime import re import socket from jwt.exceptions import ExpiredSignatureError, InvalidSignatureError from mongoengine.errors import ( DoesNotExist, NotUniqueError, ValidationError as MongoValidationError, ) from pymongo.errors import DocumentTooLarge from thriftpy2.thrift import TException from ...
nilq/baby-python
python
from data_interface import Dataset, Data_Interface from utils import functions as ufunc import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import os import rasterio as rio import rasterio.mask as riom import shapely from IPython import embed import sys sys.path.append('/home/seba/Projects/swis...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Invoke the `tools/generate_package_config.dart` script. import os import os.path...
nilq/baby-python
python
# -*- coding: UTF-8 -*- """ cookie_parser.py Copyright 2015 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is di...
nilq/baby-python
python
""" The variables submodule. This module contains symbolic representations of all ARTS workspace variables. The variables are loaded dynamically when the module is imported, which ensures that they up to date with the current ARTS build. TODO: The group names list is redudant w.rt. group_ids.keys(). Should be remove...
nilq/baby-python
python
from collections import OrderedDict from time import time import unittest try: from django.test.runner import DiscoverRunner except ImportError: raise("Django 1.8 or 1.9 needs to be installed to use this test runner.") from .tabulate import tabulate class Bcolors: MAGENTA = '\033[95m' BLUE = '\033[1;...
nilq/baby-python
python
#!/usr/bin/env python # Copyright (C) 2013 Apple Inc. 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...
nilq/baby-python
python
import click import requests from bs4 import BeautifulSoup from ....utils.logging import logger url = "https://www.codechef.com" def login_web(self): global codechef_session codechef_session = self.session username = click.prompt('username') password = click.prompt('password', hide_input=True) lo...
nilq/baby-python
python
import socket, argparse, termcolor, threading open_ports = [] def get_open_ports(host, ports): global open_ports for port in ports: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) s.connect((host, port)) open_ports.appe...
nilq/baby-python
python
from urllib.parse import ParseResult, urlencode, urlparse class URLUtility(object): """Contains different helper methods simplifying URL construction.""" @staticmethod def build_url(base_url, query_parameters): """Construct a URL with specified query parameters. :param base_url: Base URL...
nilq/baby-python
python
import sys from queue import PriorityQueue from utils import Point import numpy as np class Astar(object): def __init__(self): self.N = 0 self.V = [] self.E = [] self.closed = set([]) def goalTest(self, u): return u == self.N - 1 def moveGen(self, u): r...
nilq/baby-python
python
import os import re import tempfile import subprocess import typing from typing import Any import logging from rever.tools import replace_in_file from conda_forge_tick.xonsh_utils import indir from conda_forge_tick.utils import eval_cmd from conda_forge_tick.recipe_parser import CondaMetaYAML from conda_forge_tick.mi...
nilq/baby-python
python
from argparse import ArgumentParser from functools import partial from traceback import StackSummary import asyncio import enum import logging import ssl import time import os from stem import CircStatus # type: ignore from stem.control import Controller, EventType # type: ignore from stem.response.events import Circ...
nilq/baby-python
python
from collections import Counter def read_sequence(datapath): protein_sequence = [] cleavage_site = [] # Loop condition conveniently discards the description lines with open(datapath, 'r') as f: while f.readline() is not '': # Slicing with :-1 to discard "\n" character ...
nilq/baby-python
python
리스트 = [100,200,300] for i in 리스트: print(i+10) menu = ["김밥","라면","튀김"] for i in menu: print("오늘의 메뉴:", i) 리스트 = ["하이닉스","삼성전자","LG전자"] for i in 리스트: print(len(i)) 리스트 = ['dog','cat', 'parrot'] for i in 리스트: print(i[0]) 리스트 = [1,2,3] for i in 리스트: print("3 x ", i) 리스트 = [1,2,3] for i in 리스트: ...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 17 09:17:38 2021 @author: maxmhuggins """ import matplotlib.pyplot as plt PV_i = 640 k = .25 time = range(0, 24) PV = [PV_i] for i in range(0, len(time)-1): PV.append(PV[i-1]*k+PV[i-1]) plt.plot(time, PV) print('Final value: %.2f' % PV[-1...
nilq/baby-python
python
#! python3 # imageSiteDownloader.py ''' Write a program that goes to a photo-sharing site like Flickr or Imgur, searches for a category of photos, and then downloads all the resulting images. You could write a program that works with any photo site that has a search feature. ''' import requests, bs4, os, ppri...
nilq/baby-python
python
# Python RegExp Syntax to Javascript RegExp Syntax Translator # This code was pulled from the repository at: # https://github.com/GULPF/rescrypt # Original license was MIT but was converted to Apache v2 for # ease of integrating with the Transcrypt project # # XXX: don't redefine those here T = (1<<0) TEMPLATE = T ...
nilq/baby-python
python
from deepmath.deephol import predictions def _proof_state_from_search(predictor, node): return predictor.ProofState(goal='goal')
nilq/baby-python
python
from matplotlib import pyplot as plt import numpy as np from math import ceil def comp_dist(sample: list): y = list() for i in range(len(sample)): y.append(i) y = np.array(y) sample_ = np.array(sample) plot = plt.plot(y, sample_, 'r.', markersize=1) plt.ylabel('Complexity') axis_x...
nilq/baby-python
python
# Copied from the uvloop project. If you add a new unittest here, # please consider contributing it to the uvloop project. # # Portions copyright (c) 2015-present MagicStack Inc. http://magic.io import asyncio import logging import os import threading import time import weakref from unittest import mock import pyte...
nilq/baby-python
python
"""Numpy to Javascript (JSON) conversion Assumes numpy matrices are nx8 where first 3 columns contain x, y, z respectively. Checks for `data/*.npy` by default, below. Uses the filename, stripped, for the data dictionary key. Remember that classes 1, 2, 3 are colored red, green, blue respectively. All other classes ar...
nilq/baby-python
python
from setuptools import setup setup( name = 'objectDetectionD3MWrapper', version = '0.1.0', description = 'Keras implementation of RetinaNet as a D3M primitive.', author = 'Sanjeev Namjoshi', author_email = 'sanjeev@yonder.co', packages = ['o...
nilq/baby-python
python
import sys import interpreter from interpreter.main import Interpreter # main def main(): # check passed parameter length if len(sys.argv) != 2: return code = '' with open(sys.argv[1], "r") as file: code = file.read() i = Interpreter(code) msg, code, _, _ = i.run() print('\nReturned with code ' +...
nilq/baby-python
python
from mmdet.apis import init_detector, inference_detector, show_result config_file = 'configs/faster_rcnn_r50_fpn_1x.py' checkpoint_file = 'checkpoints/faster_rcnn_r50_fpn_1x_20181010-3d1b3351.pth' # build the model from a config file and a checkpoint file # model = init_detector(config_file, checkpoint_file, device='...
nilq/baby-python
python
import setuptools setuptools.setup( name = 'django-livereload-notifier', keywords = 'django, development, server, runserver, livereload', description = 'LiveReload with the Django development server', long_description = open('README.md').read(), author ...
nilq/baby-python
python
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from data_refinery_api.test.test_api_general import API_VERSION from data_refinery_common.models import ( ComputationalResult, Organism, OrganismIndex, Processor, Sample, SampleResultAs...
nilq/baby-python
python
""" Zeroing out gradients in PyTorch ================================ It is beneficial to zero out gradients when building a neural network. This is because by default, gradients are accumulated in buffers (i.e, not overwritten) whenever ``.backward()`` is called. Introduction ------------ When training your neural ne...
nilq/baby-python
python
# # Copyright (c) 2016, deepsense.io # # 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 w...
nilq/baby-python
python
import sys sys.path.append('../pycaruna') import json import os from datetime import date, datetime, timedelta from pycaruna import Caruna, Resolution def make_min_hour_datetime(date): return datetime.combine(date, datetime.min.time()) def make_max_hour_datetime(date): return datetime.combine(date, dateti...
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms from RecoBTag.Skimming.btagDijet_SkimPaths_cff import * from RecoBTag.Skimming.btagElecInJet_SkimPaths_cff import * from RecoBTag.Skimming.btagMuonInJet_SkimPaths_cff import * from RecoBTag.Skimming.btagGenBb_SkimPaths_cff import *
nilq/baby-python
python
import math def get_divisors(n): divisors = 0 max = math.sqrt(n) i = 1 while i <= max: if n % i == 0: divisors += 2 i += 1 return divisors triangle = 1 counter = 2 testing = True while testing: if get_divisors(triangle) >= 500: print(triangle) test...
nilq/baby-python
python
# # ECE 5725 final project # RPi Robot Mover # Fall 2021 # Authors: Xu Hai (xh357), Yaqun Niu (yn232) # import cv2 import colorList import picamera import io import os import time import threading import numpy as np from piecamera import PieCamera import pygame.mixer # Capture the main color in fr...
nilq/baby-python
python
#!/usr/bin/env python # # PyUSBtmc # get_data.py # # Copyright (c) 2011 Mike Hadmack # This code is distributed under the MIT license import numpy import sys from matplotlib import pyplot from pyusbtmc import RigolScope """ Capture data from Rigol oscilloscope and write to a file usage: python save_channel.py <fil...
nilq/baby-python
python
"""Script to load model from file""" import pickle from sympy.utilities.lambdify import lambdify from mihifepe.simulation import model # pylint: disable = invalid-name config_filename = "GEN_MODEL_CONFIG_FILENAME_PLACEHOLDER" # This string gets replaced by name of config file during simulation with open(config_fi...
nilq/baby-python
python
from django.urls import path from . import views urlpatterns=[ path('', views.index,name='index'), path('login/',views.login, name='login'), path('register/', views.register, name='register'), path('profile/', views.profile, name='profile'), path('logout/', views.logout, name='logout'), path('n...
nilq/baby-python
python
import pandas as pd import matplotlib.pyplot as plt from datetime import date lower_limit = 25 date = str(date.today()) df = pd.read_excel(date + ".xlsx") lower_limit_list = [] for i in df['Sr No.']: lower_limit_list.append(lower_limit) plt.figure() plt.subplot(3, 1, (1, 2)) plt.plot(df['Sr No.'], df['Ready To B...
nilq/baby-python
python
import cv2 import urllib.request as req url = 'http://uta.pw/shodou/img/28/214.png' req.urlretrieve(url, '../datasets/opencv/downimage.png') img = cv2.imread('../datasets/opencv/downimage.png') print(img) import matplotlib.pyplot as plt img = cv2.imread('../datasets/opencv/test.jpg') plt.imshow(cv2.cvtColor(img, cv2...
nilq/baby-python
python
def menu(): print("") print("") print(" Welcome to Hotel Database Management Software") print("") print("") print("1-Add new customer details") print("2-Modify already existing customer details") print("3-Search customer details") print("4-View all customer...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 # pipenv install grpcio==1.42.0 flask gunicorn keras-image-helper # USE: # (base) ➜ ~ curl -X POST -d "{\"url\":\"http://bit.ly/mlbookcamp-pants\"}" -H 'Content-Type: application/json' localhost:9696/predict # { # "dress": -1.8682903051376343, # "hat": -4.761245250701904, ...
nilq/baby-python
python
#!/usr/bin/python3 """Manage the image disk.""" import os import argparse from azure.mgmt.compute import ComputeManagementClient from azure.common.credentials import ServicePrincipalCredentials def connect(): """Set up Azure Login Credentials from Environmental Variables.""" credentials = ServicePri...
nilq/baby-python
python
from django.urls import path from blog.views import * from blog.feeds import LatestEntriesFeed app_name = 'blog' urlpatterns = [ path('' , blog_view , name="index"), path('<int:pid>' , blog_single , name="single"), path('category/<str:cat_name>' , blog_view , name="category"), path('tag/<str:tag_name>' ...
nilq/baby-python
python
from django.conf.urls import patterns, url from django.contrib import admin from django.views.generic import TemplateView admin.autodiscover() urlpatterns = patterns('brainstorming.views', url(r'^$', 'index', name='home'), url(r'^(?P<brainstorming_id>\w{12})/notification$...
nilq/baby-python
python
import torch from torch import nn from .mobilenet_v2 import MobileNetV2 class Block(nn.Module): def __init__(self, num_residual_layers, in_channels, out_channels, kernel_size=3, stride=2, padding=1, remove_last_relu=False): super(Block, self).__init__() if remove_last_relu and num...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains tpDcc-tools-scripteditor client implementation """ from __future__ import print_function, division, absolute_import from tpDcc.core import client class ScriptEditorClient(client.DccClient, object): PORT = 43451 def get_dcc_completion_...
nilq/baby-python
python
import re, sys import base64 import json def start_item(line): regex = r"<item><type>(([A-Fa-f0-9]{2}){4})</type><code>(([A-Fa-f0-9]{2}){4})</code><length>(\d*)</length>" matches = re.findall(regex, line) typ = matches[0][0].decode('hex') code = matches[0][2].decode('hex') length = int(matches[0][4...
nilq/baby-python
python
# The Hirst Paining Project # Create a painting with 10 by 10 rows of spots # Each dot should be 20 in size and 50 spacing between them from turtle import Turtle, Screen import random def main(): # Color palette color_list = [ (203, 164, 109), (154, 75, 48), (223, 201, 135), (...
nilq/baby-python
python
import os import db from datetime import datetime import logging from config import Environment from fuzzywuzzy import process, fuzz import nltk import multiprocessing ev = Environment() logger = logging.getLogger(ev.app_name) # nltk punkt sentence trainer. nltk.download('punkt') detector = nltk.data.load('tokenizers...
nilq/baby-python
python
""" Manual script for merging csvs into one large CSV per state with plan info. FIXME: Incorporate this into a script with arguments. """ import gc import logging import pandas as pd logging.basicConfig(level=logging.INFO) HEALTHCARE_GOV_PATH = '/home/jovyan/work/data/healthcare_gov' state = 'FL' # Hard coded du...
nilq/baby-python
python
import cairo import vector import rectangle from .widget import Widget class CheckBox(Widget): _on_image = None _off_image = None _clicked_image = None _disabled_image = None _clicked = False _moused = False clickable = True mousable = True text = None toggled_responder ...
nilq/baby-python
python
from django.shortcuts import render from django.views.generic.base import View from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth import login, logout from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages from .forms import Login...
nilq/baby-python
python
#!/usr/bin/env python3 """ Lightmon Data Read Command This script reads the data from the light sensor. """ import lm import argparse import time import numpy if __name__ == "__main__": parser = argparse.ArgumentParser(description='Verify the calibration table') parser.add_argument('-p', ...
nilq/baby-python
python
from . import transformer from . import bert
nilq/baby-python
python
#! /usr/bin/jython # -*- coding: utf-8 -*- # # sqlite3_read.py # Jan/12/2011 # # ---------------------------------------------------------------- # import sys import string from java.lang import System # import java from java.sql import DriverManager # # -------------------------------------------------------------...
nilq/baby-python
python
import contextlib import logging import os from django import test from django.test import Client from djangae.environment import get_application_root from google.appengine.api import apiproxy_stub_map, appinfo from google.appengine.datastore import datastore_stub_util from google.appengine.tools.devappserver2.appli...
nilq/baby-python
python
import uuid from yggdrasil.tests import assert_raises, assert_equal import yggdrasil.drivers.tests.test_ConnectionDriver as parent from yggdrasil import runner, tools class TestServerParam(parent.TestConnectionParam): r"""Test parameters for ServerDriver class.""" def __init__(self, *args, **kwargs): ...
nilq/baby-python
python
from performance.ConfusionMatrix import ConfusionMatrix from performance.ConfusionMatrixToConfusionTable import ConfusionMatrixToConfusionTable import numpy as np class ModelPerformance: BETA = 1 def __init__(self, model, test_set): self.confusion_matrix = ConfusionMatrix(model, test_set) sel...
nilq/baby-python
python
"""Support for Nest devices.""" from datetime import datetime, timedelta import logging import threading from nest import Nest from nest.nest import APIError, AuthorizationError import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry from homeassistant.c...
nilq/baby-python
python
>>> print(*map(''.join, zip('abc', 'ABC', '123')), sep='\n') aA1 bB2 cC3 >>>
nilq/baby-python
python
from BS.utils import get_string_list_from_file, save_list_to_file def fix_adjusted_participles(): socket_group_28_01 = list(get_string_list_from_file( 'src_dict/БГ 28.01.21 изм.txt', encoding='cp1251')) socket_group_23_01 = list(get_string_list_from_file( 'src_dict/БГ 23.01.21.txt', encoding='...
nilq/baby-python
python
from google.cloud import bigquery from google.cloud.bigquery import LoadJobConfig from google.cloud.bigquery import SchemaField from queryless.parser import BasicParser class BigQuery(object): def __init__(self, project=None): self._client = bigquery.Client(project=project) @property def client...
nilq/baby-python
python
# See in the Dark (SID) dataset import torch import os import glob import rawpy import numpy as np import random from os.path import join import data.torchdata as torchdata import util.process as process from util.util import loadmat import h5py import exifread import pickle import PIL.Image as Image from scipy.io impo...
nilq/baby-python
python
from task import CustomTask from Agent import Agent if __name__ == '__main__': goal_task=CustomTask("自定义任务") aida=Agent() goal_task.set_agent(aida) goal_task.init_agent() # 采集5个队伍,每次采集等待5秒 goal_task.run_collection(collection_team=5,wait_sec=5)
nilq/baby-python
python
# * Copyright (c) 2020-2021. Authors: see NOTICE file. # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * http://www.apache.org/licenses/LICENSE-2.0 # * # * Unless ...
nilq/baby-python
python
import torch from utils.helpers import * import warnings from PIL import Image from torchvision import transforms #from torchsummary import summary def image_transform(imagepath): test_transforms = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), ...
nilq/baby-python
python
""" Compute or load tail cost of """ import scipy.io as sio import numpy as np class TailCost(object): def __init__(self, dyn_system, gamma): C = dyn_system.C self.P0 = C.T.dot(C) self.q0 = np.zeros(C.shape[1]) self.r0 = 0. self.gamma = gamma def load(self, name): ...
nilq/baby-python
python
from sqlalchemy import Column, Integer, String from models.base import Base class Tiered_Song(Base): __tablename__ = 'tiered_songs' id = Column(Integer, primary_key=True) name = Column(String(256), nullable=False) artist = Column(String(128), nullable=False) song_type = Column(String(256), nulla...
nilq/baby-python
python
import getopt args = [ '-a', '-b', 'foo', '--exclude', 'bar', 'x1','x2'] opts, pargs = getopt.getopt() print `opts` print `pargs`
nilq/baby-python
python
from decimal import Decimal from django.db.models import Sum from trojsten.results.generator import ( BonusColumnGeneratorMixin, PrimarySchoolGeneratorMixin, ResultsGenerator, ) from .default import CompetitionRules from .default import FinishedRoundsResultsRulesMixin as FinishedRounds class UFOResults...
nilq/baby-python
python
from .merchant_id import unique_order_id_generator from django.db.models.signals import pre_save from universal_billing_system.models import Merchant def pre_save_create_bill_id(sender, instance, *args, **kwargs): if not instance.bill_id: instance.bill_id= unique_order_id_generator(instance) pre_save...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Copy + Paste in OS X """ import subprocess from .base import * def copy(string): """Copy given string into system clipboard.""" try: subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate( string.encode("utf-8")) except OSError as why: ...
nilq/baby-python
python
#import discord from discord.ext import commands import configparser config = configparser.ConfigParser() config.read("config.ini") server_owner = config['role_name']['server_owner'] admin = config['role_name']['admin'] whis = config['id']['whis_id'] def possible(ctx, user, victim): msg = f"{ctx.message.author.m...
nilq/baby-python
python
# SPDX-License-Identifier: MIT # (c) 2019 The TJHSST Director 4.0 Development Team & Contributors import os import re import shutil from typing import Any, Dict import jinja2 from .. import settings from ..exceptions import OrchestratorActionError from ..files import get_site_directory_path TEMPLATE_DIRECTORY = os....
nilq/baby-python
python
import re import lorawanwrapper.LorawanWrapper as LorawanWrapper def formatData(data): result = "" if data is None: return result else: search = re.search('(.*)"data":"(.*?)"(.*)', data) if search is not None: #means that a PHYPayload was received result = "Pa...
nilq/baby-python
python
import sqlalchemy import sqlalchemy_utils from rentomatic.repository.postgres_objects import Base, Room # Just for development purposes. Should never store password in plain text and into GitHub setup = { "dbname": "rentomaticdb", "user": "postgres", "password": "rentomaticdb", "host": "localhost", } ...
nilq/baby-python
python
import http.server import logging from urllib.parse import urlparse logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class DefaultHTTPRequestHandler(http.server.BaseHTTPRequestHandler): """Default HTTP Request Handler Interface class.""" def do_OPTIONS(self): """Default OPTIONS fun...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ import meep as mp import numpy as np #import scipy as sp #from scipy import optimize as op from scipy import interpolate as itp from matplotlib import pyplot as plt from multiprocessing import Pool # from mpl_toolkits.mplot3d import Axes3D import meep_objects as ...
nilq/baby-python
python
from functools import partial from ..experiment_base import ExperimentBase from ...models.linear import Linear_S, Linear_M, Linear_L from ..training_args import LMMixupArgs from ...data_loaders.json_loader import JsonLoader from ...utils.label_convertors import convert2vec class ExperimentLinearGinFPNSNoPartial(Expe...
nilq/baby-python
python
import copy import rdtest import renderdoc as rd class VK_Vertex_Attr_Zoo(rdtest.TestCase): demos_test_name = 'VK_Vertex_Attr_Zoo' def check_capture(self): draw = self.find_draw("Draw") self.check(draw is not None) self.controller.SetFrameEvent(draw.eventId, False) # Make a...
nilq/baby-python
python
#!/usr/bin/python ####################################################### # Copyright (c) 2019 Intel Corporation. All rights reserved. # # GNU General Public License v3.0+ # (see LICENSE.GPL or https://www.gnu.org/licenses/gpl-3.0.txt) # # Authors: # - Marco Chiappero - <marco.chiappero@intel.com> ##################...
nilq/baby-python
python
r = float(input()) print("A=%.4f" % (3.14159 * (r ** 2)))
nilq/baby-python
python
# Copyright 2020 Unibg Seclab (https://seclab.unibg.it) # # 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 l...
nilq/baby-python
python
import play import tactics.line_up import behavior_sequence import tools.sleep import robocup import constants import time import enum class Brain(play.Play): # initialize constants, etc. def __init__(self): # not sure if we need this super().__init__(continuous=True) class State(enum.Enu...
nilq/baby-python
python
from .na_syndra_top import * from .na_syndra_jng import * from .na_syndra_mid import * from .na_syndra_bot import * from .na_syndra_sup import *
nilq/baby-python
python
import os __version__ = 'v0.0.8' # update also in setup.py root_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) info = { "name": "NiLabels", "version": __version__, "description": "", "repository": { "type": "git", "url":...
nilq/baby-python
python
from random import randint from time import sleep itens = ('pedra', 'papel', 'tesoura') computador = randint(0, 2) print('''Suas opções: [0] Pedra [1] Papel [2] Tesoura''') jogador = int(input('Qual é a sua jogada? ')) print('JO') sleep(1) print('KEN') sleep(1) print('PO =!!!') print('-=' * 12) print('O computador jogo...
nilq/baby-python
python