content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import factory from faker import Faker import random from .models import Rating from item.models import Item from actor.models import Actor fake = Faker() class RatingFactory(factory.django.DjangoModelFactory): class Meta: model = Rating
nilq/baby-python
python
import pandas as pd def _exchanges(): # 通过 `股票.exchange = exchanges.exchange`来关联 # 深证信 股票信息 上市地点 return pd.DataFrame({ 'exchange': ['深交所主板', '上交所', '深交所中小板', '深交所创业板', '上交所科创板', '深证B股', '上海B股', '指数'], 'canonical_name': ['XSHE', 'XSHG', 'XSHE', 'XSHE', 'XSHG', 'XSHE', 'XSHG', 'XSHG'], ...
nilq/baby-python
python
from django.db import models from datetime import datetime from django.db.models.functions import Lower from guardian.models import UserObjectPermissionBase, GroupObjectPermissionBase from main.models import User from main.validators import validate_item_name class AccountHolder(models.Model): name = models.Cha...
nilq/baby-python
python
# -*- coding: utf-8 -*- # @Time : 2020/12/1 09:29 # @Author : ooooo from typing import * from bisect import bisect_left, bisect_right class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if len(nums) == 0 or target > nums[-1] or target < nums[0]: return [-1, ...
nilq/baby-python
python
""" from marshmallow import Schema, EXCLUDE from marshmallow.fields import Str from marshmallow.validate import Length class ProfileSchema(Schema): username = Str(required=True, validate=[Length(min=1, max=16)]) full_name = Str(required=True) personal_address = Str(required=True) profession = Str(requ...
nilq/baby-python
python
# Copyright (C) 2016 Li Cheng at Beijing University of Posts # and Telecommunications. www.muzixing.com # # 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/licens...
nilq/baby-python
python
import os import sys from flake8.api import legacy as flake8 from collectd_haproxy import compat DIRS_TO_TEST = ("collectd_haproxy", "tests") MAX_COMPLEXITY = 11 # flake8 does not work on python 2.6 or lower __test__ = sys.version_info >= (2, 7) def test_style(): for path in DIRS_TO_TEST: python_fil...
nilq/baby-python
python
from causalml.propensity import ElasticNetPropensityModel from causalml.metrics import roc_auc_score from .const import RANDOM_SEED def test_elasticnet_propensity_model(generate_regression_data): y, X, treatment, tau, b, e = generate_regression_data() pm = ElasticNetPropensityModel(random_state=RANDOM_SEED...
nilq/baby-python
python
# -------------- import numpy as np new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] data = np.genfromtxt(path, delimiter=",", skip_header=1) print(data.shape) census=np.concatenate((data, new_record),axis = 0) print(census.shape) # -------------- #Code starts here import numpy as np age=census[:,0] print(a...
nilq/baby-python
python
# -*- coding: utf-8 -*- import logging from typing import List import eduid_msg from eduid_common.api.exceptions import MsgTaskFailed from eduid_common.config.base import MsgConfigMixin __author__ = 'lundberg' logger = logging.getLogger(__name__) TEMPLATES_RELATION = { 'mobile-validator': 'mobile-confirm', ...
nilq/baby-python
python
from __future__ import division import numpy as np import numpy.ma as ma cimport numpy as np from libc.stdint cimport int32_t cimport cython from libc.stdio cimport printf @cython.embedsignature(True) @cython.cdivision(True) @cython.wraparound(False) @cython.boundscheck(False) def get_fit(object theta, object height)...
nilq/baby-python
python
from market import application from flask import render_template, redirect, url_for, flash, request from market.models import Item, User from market.forms import RegisterForm, LoginForm, PurchaseItemForm, SellItemForm from market import db #we can directly import from market becasue db is located in the dunder init...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' File: zenodo_api_access.py Created Date: September 22nd 2019 Author: ZL Deng <dawnmsg(at)gmail.com> --------------------------------------- Last Modified: 22nd September 2019 7:45:14 pm ''' import requests import json import click from os import path @click.command...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Plot results from simulations optimizing 2D randomly-generated synthetic objective functions. """ import numpy as np import scipy.io as io import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib import rcParams rcParams.update({'f...
nilq/baby-python
python
from setuptools import setup, find_packages classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2", ...
nilq/baby-python
python
import numpy as np import cv2 as cv def dist(p1x, p1y, p2x, p2y): return np.sqrt((p1x-p2x)**2 + (p1y-p2y)**2) class Map: def __init__(self, length, height, thickness): self.length = length self.height = height self.wallThickness = thickness self.map = np.zeros((self.height, self.length, 3), dtype=np.uint8...
nilq/baby-python
python
#!/usr/bin/env python import re f = open('/Users/kosta/dev/advent-of-code-17/day12/input.txt') links = f.readlines() graph = {} def traverse_graph(node): if node == 0: return True node = graph[node] node['is_visited'] = True for edge in node['edges']: if not graph[edge]['is_visited']:...
nilq/baby-python
python
""" Useful neuroimaging coordinate map makers and utilities """ from __future__ import print_function from __future__ import absolute_import import numpy as np from nibabel.affines import from_matvec from ...fixes.nibabel import io_orientation from .coordinate_system import CoordSysMaker, is_coordsys, is_coordsys_m...
nilq/baby-python
python
from unittest import TestCase import copy from chibi.atlas import Chibi_atlas from chibi_command import Command from chibi_command import Command_result from chibi_command.nix.systemd_run import System_run from chibi_command.nix.systemd import Journal_status, Journal_show class Test_systemd_run( TestCase ): def ...
nilq/baby-python
python
tuple = (1, 2, 4, 5, 6, 6) print(f'{tuple =}) print(f'{tuple.count(6) =}')
nilq/baby-python
python
import unittest import time from app import create_app, db from app.models import Permission, Role, User class UserModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() ...
nilq/baby-python
python
# coding: utf-8 import typing from rolling.model.measure import Unit class GlobalTranslation: def __init__(self) -> None: self._translation: typing.Dict[typing.Any, str] = { Unit.LITTER: "litres", Unit.CUBIC: "mètre cubes", Unit.GRAM: "grammes", Unit.KILOGR...
nilq/baby-python
python
"""The tests for the Xiaogui ble_parser.""" from ble_monitor.ble_parser import BleParser class TestXiaogui: """Tests for the Xiaogui parser""" def test_xiaogui_tzc4_stab(self): """Test Xiaogui parser for Xiaogui TZC4 (stabilized weight).""" data_string = "043e1d0201030094e0e5295a5f1110ffc0a302...
nilq/baby-python
python
from apiv1 import blueprint as apiv1 from flask import Flask app = Flask(__name__) app.debug = True app.secret_key = 'cc_development' app.register_blueprint(apiv1) if __name__ == "__main__": app.run()
nilq/baby-python
python
from flask import render_template, url_for, flash, redirect, request, abort, Blueprint from flask_login import login_user, logout_user, current_user, login_required from thewarden import db from thewarden.users.forms import (RegistrationForm, LoginForm, UpdateAccountForm, RequestReset...
nilq/baby-python
python
from python import radar import matplotlib.pyplot as plt import glob import os import imageio import cv2 import numpy as np import scipy.io as sio from skimage import io Rad_img=True if Rad_img: i=0 ncols=4 else: i=-1 ncols=3 #scene = 3 scene = 'city_3_7' data_dir_image_info = '/home/ms75986/Deskto...
nilq/baby-python
python
from django.db import models class User(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) password = models.CharField(max_length=12, blank=True) email = models.CharField(max_length=50, blank=True) telephone = models.CharField(max_length=15) ...
nilq/baby-python
python
from dku_error_analysis_decision_tree.node import Node, NumericalNode, CategoricalNode from dku_error_analysis_utils import safe_str from mealy import ErrorAnalyzerConstants import pandas as pd from collections import deque class InteractiveTree(object): """ A decision tree ATTRIBUTES df: pd.DataFram...
nilq/baby-python
python
from io import StringIO from differently.cli import entry def test__text_vs_text() -> None: writer = StringIO() assert entry(["examples/1.md", "examples/2.md"], writer) == 0 assert ( writer.getvalue() == """# "differently" example file = # "differently" example ...
nilq/baby-python
python
# .--. .-'. .--. .--. .--. .--. .`-. .% #:::::.\::::::::.\::::::::.\::::::::.\::::::::.\::::::::.\::::::::.\::::::% #' `--' `.-' `--' `--' `--' `-.' `--' % # Information % #' .--. ...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 3 11:51:03 2018 @author: robertcarson """ import numpy as np a = 3.0 * np.ones((5, 2)) a[:, 0] = 1.0 print(a) a[a < 3.0] = 4.0 print(a) ''' Let's do a rotation example next using Bunge angles and then a simple passive rotation of our coordinate...
nilq/baby-python
python
from platon_env.base.host import Host # host = Host('10.10.8.209', 'juzhen', 'Juzhen123!') from platon_env.utils.md5 import md5 # host = Host('192.168.16.121', 'juzix', password='123456') host = Host('192.168.21.42', 'shing', password='aa123456') base_dir = '/home/shing' def test_pid(): pid = host.pid('cpu') ...
nilq/baby-python
python
import numpy as np import gym from gym import spaces import math import cv2 import random import time import pybullet import pybullet_data from src.mini_cheetah_class import Mini_Cheetah from src.dynamics_randomization import DynamicsRandomizer class Terrain(): def __init__(self,render = True,on_rack = Fals...
nilq/baby-python
python
#!/usr/bin/env python2 import sys import re import os if len(sys.argv) < 2 or not re.match(r"\d{4}-\d\d-\d\d", sys.argv[1]): print "Usage: git daylog 2013-01-01 ..." sys.exit(1) day = sys.argv[1] after = "--after=%s 00:00" % day before = "--before=%s 23:59" % day os.execlp("git", "git", "log", after, before, ...
nilq/baby-python
python
"""Extractor for hpfanficarchive.com.""" from fanfic_scraper.base_fanfic import BaseFanfic, BaseChapter from urllib.parse import urlparse, urljoin, parse_qs from bs4 import BeautifulSoup, Comment from collections import defaultdict import re import os from datetime import datetime def chapter_nav(tag): test = (t...
nilq/baby-python
python
# Filename: ZerkGameState.py # Author: Greg M. Krsak # License: MIT # Contact: greg.krsak@gmail.com # # Zerk is an Interactive Fiction (IF) style interpreter, inspired by Infocom's # Zork series. Zerk allows the use of custom maps, which are JSON-formatted. # # This file contains game state constants, which are impleme...
nilq/baby-python
python
from ws import ws import unittest import json class FlaskrTestCase(unittest.TestCase): def setUp(self): ws.app.config['TESTING'] = True self.app = ws.app.test_client() def test_hello(self): response = self.app.get('/') self.assertEquals(200, response.status_code) def test...
nilq/baby-python
python
from .base import * from birdway import Type, ArgumentModifier, Composite from .string_literal import StringLiteral class Parameter(SyntaxNodeABC, PrettyAutoRepr, Identified): def __init__(self): self.type = Type.UNKNOWN self.modifier = ArgumentModifier.NONE self.name = str() self...
nilq/baby-python
python
"""Subjects interface Access to the subjects endpoint. The user is not expected to use this class directly. It is an attribute of the :class:`Archivist` class. For example instantiate an Archivist instance and execute the methods of the class: .. code-block:: python with open(".auth_token", mo...
nilq/baby-python
python
import os import requests import json import hikari import lightbulb from dotenv import load_dotenv, find_dotenv from datetime import datetime from geopy.geocoders import Nominatim weather_plugin = lightbulb.Plugin("Weather") class Weather: """Weather class that interacts with OpenWeatherMap API for weather infor...
nilq/baby-python
python
from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url('^$', views.home, name='welcome'), url(r'^category/$', views.search_image, name='search_image'), url(r'^location/(\d+)$', views.filter_by_location, name='loca...
nilq/baby-python
python
from django.shortcuts import render from music.models import Music # Create your views here. def index(request): musiclist=Music.objects.all() context={'music':musiclist} return render(request,'music/index.htm',context)
nilq/baby-python
python
#! /usr/bin/env python # -*- coding: utf-8 -*- import datetime import logging import os import sys from collections import defaultdict import configargparse sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__fil...
nilq/baby-python
python
from requests.adapters import HTTPAdapter from nivacloud_logging.log_utils import LogContext, generate_trace_id class TracingAdapter(HTTPAdapter): """ Subclass of HTTPAdapter that: 1. Adds Trace-Id if it exists in LogContext. 2. Adds Span-Id if it exists in LogContext or auto-generates it otherwise...
nilq/baby-python
python
""" Util functions for dictionary """ __copyright__ = '2013, Room77, Inc.' __author__ = 'Yu-chi Kuo, Kyle Konrad <kyle@room77.com>' from collections import MutableMapping, OrderedDict def dict_key_filter(function, dictionary): """ Filter dictionary by its key. Args: function: takes key as argument and retu...
nilq/baby-python
python
#!/usr/bin/env python3.6 # coding=utf-8 ''' This reader reads all psd vallex file, and add possible cannonical vallex lemma to the corresponding copying dictionary of a word and aliases of the word @author: Jie Cao(jiessie.cao@gmail.com) @since: 2019-06-28 ''' import xml.etree.ElementTree as ET from utility.psd_util...
nilq/baby-python
python
load("@bazel_gazelle//:deps.bzl", "go_repository") def nogo_deps(): go_repository( name = "com_github_gostaticanalysis_analysisutil", importpath = "github.com/gostaticanalysis/analysisutil", sum = "h1:ZMCjoue3DtDWQ5WyU16YbjbQEQ3VuzwxALrpYd+HeKk=", version = "v0.7.1", ) go_re...
nilq/baby-python
python
from ._download import download def airline_tweets(directory: str): """ Downloads a modified version of the 'Twitter US Airlines Sentiment' dataset, in the given directory """ download(directory, "airline_tweets.csv", "https://drive.google.com/file/d" "/1Lu4iQucxVBncxeyCj...
nilq/baby-python
python
from typing import Iterable from stock_indicators._cslib import CsIndicator from stock_indicators._cstypes import List as CsList from stock_indicators.indicators.common.candles import CandleResult, CandleResults from stock_indicators.indicators.common.quote import Quote def get_doji(quotes: Iterable[Quote], max_pric...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Tue Jun 4 12:07:46 2019 @author: jamiesom """ from electricitylci.model_config import replace_egrid, use_primaryfuel_for_coal from electricitylci.elementaryflows import map_emissions_to_fedelemflows import pandas as pd import numpy as np from electricitylci.glo...
nilq/baby-python
python
#!/usr/bin/env python3 # encoding: utf-8 """ DatabaseManager.py This class handles saving the list of tweets and pruning it according to age. """ from ManagerBase import * import sqlite3 import os from typing import List from GlobalSettings import * from RSSItemTuple import * import string class DatabaseManager(Mana...
nilq/baby-python
python
import kiui kiui.try_import('os', 'os', True) print(os) kiui.env(verbose=True) print(globals()) kiui.env('torch', verbose=True) print(globals()) kiui.env('notapack', verbose=True)
nilq/baby-python
python
import argparse import os import sys import torch from IPython import get_ipython from utils.data import ManualSeedReproducible from utils.dep_free import in_notebook from utils.filesystems.gdrive.colab import ColabFilesystem, ColabFolder, ColabCapsule from utils.filesystems.gdrive.remote import GDriveCapsule, GDrive...
nilq/baby-python
python
from django.contrib import admin from cats.models import Cat,Breed # Register your models here. admin.site.register(Cat) admin.site.registe...
nilq/baby-python
python
if __name__ == '__main__': n = int(input()) vars = input().split() integer_list = map(int, vars) print(hash(tuple(integer_list)))
nilq/baby-python
python
# # Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. # # Example: # # Given array nums = [-1, 2, 1, -4], and target = 1. # # The sum that is c...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # Copyright (C) 2022 Chris Caron <lead2gold@gmail.com> # All rights reserved. # # This code is licensed under the MIT License. # # 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 th...
nilq/baby-python
python
def post_order(node): if node.left: post_order(node.left) if node.right: post_order(node.right) print(node.data)
nilq/baby-python
python
#!/usr/bin/env python3 """Integration test for traveling to the mast""" import os import sys parent_dir = os.path.dirname(os.path.abspath(__file__)) gparent_dir = os.path.dirname(parent_dir) ggparent_dir = os.path.dirname(gparent_dir) gggparent_dir = os.path.dirname(ggparent_dir) sys.path += [parent_dir, gparent_dir,...
nilq/baby-python
python
""" Question: Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. """ """ Solution 1: We can easily find recursive nature in above problem. The person can reach n’th stair from either (n-1)’th stair or from (n-2)’th stair. Let the total number of ways to reach n’t stair be ‘w...
nilq/baby-python
python
#!/bin/env python import os import logging import pandas as pd class DatasetMerger: def __init__(self, workDir=None): self.logger = logging.getLogger("DatasetMerger") self.cwd = os.path.abspath(os.getcwd()) if not workDir else os.path.abspath(workDir) # self.dataframes = { ...
nilq/baby-python
python
""" WSGI config for my_hubu project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from os.path import join,dirname,abspath PROJECT_DIR=dirname(dirname(a...
nilq/baby-python
python
from .util import get_groups def students_processor(request): absolute_url = "{}://{}:{}".format(request.scheme, request.META['SERVER_NAME'], request.META['SERVER_PORT']) return {'ABSOLUTE_URL': absolute_url} def groups_processors(request): return {'GROUPS': get_groups(request)}
nilq/baby-python
python
from .PercentChangeTransformer import PercentChangeTransformer from .ColumnDropperTransformer import ColumnDropperTransformer from .DFFeatureUnion import DFFeatureUnion from .SMATransformer import SMATransformer from .EMATransformer import EMATransformer from .MACDTransformer import MACDTransformer from .GreaterThanTra...
nilq/baby-python
python
# project/server/models.py import jwt import datetime from flask import current_app from service.database import db, bcrypt from uuid import uuid4 class Organisation(db.Model): """Organisation data""" __tablename__ = "organisation" id = db.Column(db.Integer, primary_key=True, autoincrement=True) nam...
nilq/baby-python
python
""" Microsoft Archive parser Author: Victor Stinner Creation date: 2007-03-04 """ MAX_NB_FILE = 100000 from hachoir_parser import Parser from hachoir_core.field import FieldSet, String, UInt32, SubFile from hachoir_core.endian import LITTLE_ENDIAN from hachoir_core.text_handler import textHandler, filesizeHandler, h...
nilq/baby-python
python
import sys import click from moulinette import hwserializer, itemserializer, testserializer from moulinette.homework.models import * from moulinette.stats_and_logs.models import RequestLog def startup(): value = click.prompt( 'Please select an action:\n' '1. Create a homework assignment.\n' ...
nilq/baby-python
python
# Higher order functions are functions that take other functions as parameter # This function prints its parameter two times def print2times(x): print(x) print(x) def print3times(x): print(x) print(x) print(x) # This function calls the function it takes as parameter on each digit def for_digits(...
nilq/baby-python
python
import codecs import jaconv import etldr.jis0201 from etldr.etl_data_names import ETLDataNames from etldr.etl_data_set_info import ETLDataSetInfo class ETLCodes(): """ A convenience class for using all codecs which are used in the ETL data set. Warning: The 'euc_co59.dat'-file from the ETL data...
nilq/baby-python
python
"""make_one_annotation.py Usage: make_one_annotation.py <game_id> <anno_id> <dir-prefix> <pnr-prefix> <time-frame-radius> <raw_file> Arguments: <dir-prefix> the prefix prepended the directory that will be created to hold the videos <pnr-prefix> the prefix for annotation filenames (e.g. 'raw') <time-fr...
nilq/baby-python
python
""" Copyright 2021 InfAI (CC SES) 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...
nilq/baby-python
python
import Layers import Wavelets
nilq/baby-python
python
from django.contrib import admin from comments.models import Comment class CommentAdmin(admin.ModelAdmin): list_display = ('author', 'text', 'private', 'created_on', 'modified_on',) search_fields = ('author', 'text',) # class ToDoAdmin(admin.ModelAdmin): # list_display = ('author', 'text', 'private', '...
nilq/baby-python
python
import os import pytest import merlin.io from merlin.datasets.advertising import get_criteo from merlin.datasets.synthetic import generate_data MAYBE_DATA_DIR = os.environ.get("INPUT_DATA_DIR", None) def test_synthetic_criteo_data(): dataset = generate_data("criteo", 100) assert isinstance(dataset, merlin...
nilq/baby-python
python
__author__ = 'Sergei' from model.contact import Contact class ContactHelper: def __init__(self, app): self.app = app def fill_contact_first_last(self, Contact): wd = self.app.wd wd.find_element_by_name("firstname").click() wd.find_element_by_name("firstname").clear() w...
nilq/baby-python
python
""" twtxt.models ~~~~~~~~~~~~ This module implements the main models used in twtxt. :copyright: (c) 2016 by buckket. :license: MIT, see LICENSE for more details. """ from datetime import datetime, timezone import humanize from dateutil.tz import tzlocal class Tweet: """A :class:`Tweet` rep...
nilq/baby-python
python
# %% [markdown] ## Acessando todos os parâmetros (genérico) # %% def todos_params(*posicionais, **nomeados): print(f'Posicionais: {posicionais}') print(f'Nomeados: {nomeados}\n') todos_params(1,2,3) #3 Parâmetros posicionais e nenhum parâmetro nomeado todos_params(1,2,3, nome='Victor', solteiro=True) #3 parâ...
nilq/baby-python
python
import numpy as np from ivory.callbacks.results import concatenate def test_libraries(runs): for run in runs.values(): run.start("both") for mode in ["val", "test"]: outputs = [] for run in runs.values(): outputs.append(run.results[mode].output) for output in out...
nilq/baby-python
python
from sqlalchemy.orm import Session from apps.crud.pusher import get_pushers_by_token, get_pushers_by_token_and_type from apps.serializer.record import RecordSerializer from apps.pusher import test_wechat, official_wechat, e_mail, android, wechat, qq type_func_dict = { 1: test_wechat.send_msg, 2: official_wec...
nilq/baby-python
python
from __future__ import print_function import logging import pandas as pd import numpy as np import scipy.stats as stats from matplotlib.backends.backend_pdf import PdfPages import os.path from .storemanager import StoreManager from .condition import Condition from .constants import WILD_TYPE_VARIANT from .sfmap import ...
nilq/baby-python
python
import sys import os import glob import shutil import xml.etree.ElementTree as ET if not os.path.exists("../results/"): os.makedirs("../results/") if os.path.exists("../results/detection/"): shutil.rmtree("../results/detection/") os.makedirs("../results/detection/") # create VOC format files xml_list = [f for f i...
nilq/baby-python
python
""" Calculate the number of proteins per kingdom / phylum / genus / species per genera for the phages """ import os import sys import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description="Calculate the kingdom / phylum / genus / species per genera for the phages") parser.add_argume...
nilq/baby-python
python
from flask_restful import Resource, reqparse, request from lib.objects.namespace import Namespace from lib.objects.lock import Lock class LockController(Resource): # TODO Check access as separate method or decorator # https://flask-restful.readthedocs.io/en/latest/extending.html#resource-method-decorators ...
nilq/baby-python
python
__author__ = "Polymathian" __version__ = "0.3.0"
nilq/baby-python
python
# coding=utf-8 """ The MIT License Copyright (c) 2013 Mustafa İlhan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
nilq/baby-python
python
# This is automatically-generated code. # Uses the jinja2 library for templating. import cvxpy as cp import numpy as np import scipy as sp # setup problemID = "quantile_0" prob = None opt_val = None # Variable declarations # Generate data np.random.seed(0) m = 400 n = 10 k = 100 p = 1 sigma = 0.1 x = np.rand...
nilq/baby-python
python
from starlette.config import Config # Configuration from environment variables or '.env' file. config = Config(".env") DB_NAME = config("DB_NAME") TEST_DB_NAME = config("TEST_DB_NAME") DB_USER = config("DB_USER") DB_PASSWORD = config("DB_PASSWORD") DB_HOST = config("DB_HOST") DB_PORT = config("DB_PORT") SECRET_KEY = c...
nilq/baby-python
python
"""Migration for the Submitty system.""" import os def up(config): """ Run up migration. :param config: Object holding configuration details about Submitty :type config: migrator.config.Config """ os.system("apt install -qy python3-numpy") os.system("apt install -qy python3-opencv") os...
nilq/baby-python
python
# -*- coding: utf-8 -*- from sqlalchemy import Column, String, Integer, Float from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from src.model.base import Base from src.model.EstacaoZona import EstacaoZona class Zona(Base): __tablename__ = 'Zona' Zona_id = Column...
nilq/baby-python
python
import matplotlib.pyplot as plt from playLA.Matrix import Matrix from playLA.Vector import Vector import math if __name__ == "__main__": points = [[0, 0], [0, 5], [3, 5], [3, 4], [1, 4], [1, 3], [2, 3], [2, 2], [1, 2], [1, 0]] x = [point[0] for point in points] y = [point[1] for point in poin...
nilq/baby-python
python
import ast import json import os from base_automation import report # ---------------------------- terminal ------------------------------------# @report.utils.step('send terminal command: {command}') def terminal_command(command): try: step_data(f"send command to terminal:\n{command}") return os...
nilq/baby-python
python
# PLUGIN MADE BY DANGEROUSJATT # KEEP CREDIT # MADE FOR HELLBOT # BY TEAM HELLBOT # NOW IN darkbot import math from darkbot.utils import admin_cmd, sudo_cmd, edit_or_reply from userbot import CmdHelp from userbot import bot as darkbot @darkbot.on(admin_cmd(pattern="sin ?(.*)")) @darkbot.on(sudo_cmd(pattern="sin ?(....
nilq/baby-python
python
# Copyright 2021 cstsunfu. 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 agr...
nilq/baby-python
python
import os import os.path from os.path import exists import hashlib import json import uuid import pprint import unittest from pathlib import Path from collections import defaultdict import settings import pathlib from cromulent import model, vocab, reader from cromulent.model import factory from pipeline.util import C...
nilq/baby-python
python
import logging from datalad_lgpdextension.utils.dataframe import Dataframe from datalad_lgpdextension.writers.dataframe import Dataframe as dfutils from datalad_lgpdextension.utils.folder import Folder from datalad_lgpdextension.runner.actions import Actions from datalad_lgpdextension.utils.generate_config import Gener...
nilq/baby-python
python
class LinkedListNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.num_elements = 0 self.head = None def push(self, data): new_node = LinkedListNode(data) if self.head is None: self.head = ne...
nilq/baby-python
python
import numpy as np def project(W, X, mu=None): if mu is None: return np.dot(X,W) return np.dot(X - mu, W) def reconstruct(W, Y, mu=None): if mu is None: return np.dot(Y,W.T) return np.dot(Y, W.T) + mu def pca(X, y, num_components=0): [n,d] = X.shape if (num_components <= 0) or (num_components>n): num_com...
nilq/baby-python
python
import pytest from copy import deepcopy import mosdef_cassandra as mc import unyt as u from mosdef_cassandra.tests.base_test import BaseTest from mosdef_cassandra.writers.inp_functions import generate_input from mosdef_cassandra.writers.writers import write_mcfs from mosdef_cassandra.utils.tempdir import * class Tes...
nilq/baby-python
python
class Solution: def largestPerimeter(self, A: List[int]) -> int: A.sort() for i in range(len(A)-1, 1, -1): if A[i-2] + A[i-1] > A[i]: return A[i-2] + A[i-1] + A[i] else: return 0
nilq/baby-python
python
class Permissions(object): # ccpo permissions VIEW_AUDIT_LOG = "view_audit_log" VIEW_CCPO_USER = "view_ccpo_user" CREATE_CCPO_USER = "create_ccpo_user" EDIT_CCPO_USER = "edit_ccpo_user" DELETE_CCPO_USER = "delete_ccpo_user" # base portfolio perms VIEW_PORTFOLIO = "view_portfolio" #...
nilq/baby-python
python