content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from __future__ import absolute_import, unicode_literals from appearance.classes import Icon icon_acl_list = Icon(driver_name='fontawesome', symbol='lock')
nilq/baby-python
python
#!/usr/bin/env/python3 import os import sys import typing THIS_SCRIPT_DIR = sys.path[0] INCLUDE_DIR = THIS_SCRIPT_DIR + "/../src/include/cleantype/" ALL_IN_ONE_FILE = THIS_SCRIPT_DIR + "/include/cleantype/cleantype.hpp" MAIN_TITLE = """ // CleanType : amalgamated version // // This file is part of CleanType: Clean T...
nilq/baby-python
python
import datetime from bs4 import BeautifulSoup from kik_unofficial.utilities.cryptographic_utilities import CryptographicUtils from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement, XMPPResponse class GetMyProfileRequest(XMPPElement): def __init__(self): super().__init__() def seriali...
nilq/baby-python
python
import sys sys.path.append('../../../') import unittest import numpy as np from spiketag.base import ProbeFactory class TestProbe(unittest.TestCase): def test_linear_probe(self): linear_probe = ProbeFactory.genLinearProbe(25e3, 32) expected_type = 'linear' expected_n_group = ...
nilq/baby-python
python
"""{{cookiecutter.project_description}}""" import logging from {{cookiecutter.package_name}}.wsgi import ApplicationLoader from {{cookiecutter.package_name}}.version import __version__ # noqa: F401 # initialize logging log = logging.getLogger(__name__) log.addHandler(logging.NullHandler())
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : Mar-27-21 01:06 # @Author : Kan HUANG (kan.huang@connect.ust.hk) # @RefLink : https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html from __future__ import unicode_literals, print_function, division import os import random import s...
nilq/baby-python
python
from . import db from flask.ext.login import UserMixin, AnonymousUserMixin from datetime import datetime class ScrapeCount(db.Model): __tablename__ = 'scrapecounts' id = db.Column(db.Integer, primary_key=True) websitename = db.Column(db.String(200)) count = db.Column(db.Integer) date = db.Column(d...
nilq/baby-python
python
import json import torchvision import data as data_module from examples.NIPS.generate_data_utils import gather_examples import pandas as pd preprocessable = pd.read_pickle('/home/roigvilamalam/projects/Urban-Sound-Classification/preprocessable.pkl') preprocessable = preprocessable[preprocessable['preprocessable']] ...
nilq/baby-python
python
from flask import Flask, render_template, url_for, request, redirect, g, jsonify, flash, session, Markup from bs4 import BeautifulSoup from pymongo import * from functools import wraps from datetime import datetime import requests import csv import boto3 import ckapi import validation from settings import * # FLASK CO...
nilq/baby-python
python
# @Author: Leeroy P. Williams # @Date: 29/09/19 # @Problem: If we list all the natural numbers below 10 that are # multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000 # @Solution: Correct def multi(a, b, array): ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ =============================================================================== Trajectory class for MD simulations (:mod:`sknano.core.atoms._trajectory`) =============================================================================== Classes for analyzing the atom trajectories of molecular...
nilq/baby-python
python
from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.shortcuts import redirect, render, get_object_or_404 from django.urls import reverse from django.contrib.auth.decorators import login_required from ranbo.forms import * from django.core.exc...
nilq/baby-python
python
import nltk, re, pprint from urllib.request import urlopen url = "http://nrs-projects.humboldt.edu/~st10/s20cs328/328lect15-1/328lect15-1-projected_txt.html" raw = urlopen(url).read() print(type(raw)) print(len(raw)) #natural language string nls = nltk.clean_html(raw) tokens = nltk.word_tokenize(raw) print(tokens)
nilq/baby-python
python
import os from setuptools import ( setup, find_packages ) curr_dir = os.path.dirname(os.path.abspath(__file__)) install_requirements = [ "pydantic>=1.8", "cryptography>=3.4" ] setup( name="restless", version="0.0.1-dev", description="Just an easy-to-use cryptographic Python module", long_description=...
nilq/baby-python
python
from django.apps import apps from rest_framework import serializers from common.constants import models Profile = apps.get_model(models.PROFILE_MODEL) User = apps.get_model(models.USER_MODEL) class ProfileSerializer(serializers.ModelSerializer): """ API serializer for :class:`Profile`. """ class Me...
nilq/baby-python
python
# -*- coding: UTF-8 -*- # @Author : Chenyang Wang # @Email : THUwangcy@gmail.com """ Caser Reference: "Personalized Top-N Sequential Recommendation via Convolutional Sequence Embedding" Jiaxi Tang et al., WSDM'2018. Reference code: https://github.com/graytowne/caser_pytorch Note: We use a maximum of...
nilq/baby-python
python
from pseudo_python.builtin_typed_api import builtin_type_check from pseudo_python.errors import PseudoPythonTypeCheckError class Standard: ''' Standard classes should respond to expand and to return valid nodes on expand ''' pass class StandardCall(Standard): ''' converts to a standard cal...
nilq/baby-python
python
import tensorflow as tf def MaxAvgPooling2D(m,n, model): max = tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=1, padding='SAME')(model) avg = tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=1, padding='SAME')(model) model = (max*m + avg*n)/(m+n) return model
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Preprocessing ZTF database to be saved as a samplesx21x21x3 numpy array in a pickle TODO: clean_NaN once cropped TODO: unit tests ToDo: instead of cascade implement as pipeline, in order to have single call and definition ToDo: smart way to shut down nans @author: as...
nilq/baby-python
python
import base64 import random from django.conf import settings from django.core.cache import caches from django.core.mail import send_mail from apps.user.models import User from libs.yuntongxun.sms import CCP from meiduoshop.celery import app @app.task def async_send_sms(to, datas, template_id): """异步发送短信验证码 注意结果...
nilq/baby-python
python
import os from typing import Dict, List, Optional, Union, Callable from tinydb.storages import MemoryStorage, JSONStorage from ..custom_typings import DataDict, PathType class BaseDB(JSONStorage, MemoryStorage): """Base storage class that reads which extensions are available to feed the path handling functio...
nilq/baby-python
python
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...
nilq/baby-python
python
""" utility functions """ import collections def flatten(d, parent_key="", sep="_"): """ flatten nested dictionary, preserving lists Arguments: parent_key (str): sep (str): """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k ...
nilq/baby-python
python
import tensorflow as tf import datetime as dt import pandas as pd import os def load_data(): col_names = [ 'id', 'event_timestamp', 'course_over_ground', 'machine_id', 'vehicle_weight_type', 'speed_gps_kph', 'latitude', 'longitude'] data = pd.DataFrame(columns=col_names) files = os.listd...
nilq/baby-python
python
from jenkinsapi.jenkins import Jenkins import xml.etree.ElementTree as ET J = Jenkins('http://localhost:8080') EMPTY_JOB_CONFIG = ''' <?xml version='1.0' encoding='UTF-8'?> <project> <actions>jkkjjk</actions> <description></description> <keepDependencies>false</keepDependencies> <properties/> <scm class="hud...
nilq/baby-python
python
import os from typing import List, Optional from uuid import uuid4 import PIL import pytest import arcade import arcade.gui from arcade.gui import UIClickable, UIManager from arcade.gui.ui_style import UIStyle class TestUIManager(UIManager): def __init__(self, *args, **kwargs): super().__init__(*args, *...
nilq/baby-python
python
class Solution(object): def deleteDuplicates(self, head): ht = {} it = head while head: if head.val in ht: ht[head.val] += 1 else: ht[head.val] = 1 head = head.next headRef = None last = None whi...
nilq/baby-python
python
#!/usr/bin/env python import sys from os.path import exists as path_exists from pyscaffold.api import create_project from pyscaffold.cli import run from pyscaffold.extensions.github_actions import GithubActions def test_create_project_with_github_actions(tmpfolder): # Given options with the GithubActions extensi...
nilq/baby-python
python
import glob from os.path import join import numpy as n import astropy.io.fits as fits import lib_functions_1pt as lib import os import sys #Quantity studied version = 'v4' qty = "mvir" # one point function lists fileC = n.array(glob.glob( join(os.environ['MD_DIR'], "MD_*Gpc*", version, qty,"out_*_Central_JKresampli...
nilq/baby-python
python
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
nilq/baby-python
python
from django.test import TestCase from rest_framework.test import APIClient from teams.models import Team class TeamTestCase(TestCase): """ Test set for Team CRD (there is no update here) """ client = APIClient() trainer_id = 0 team_id = 0 def setUp(self): """ Set up case. ...
nilq/baby-python
python
import os import sqlite3 from datetime import datetime from flask import g DATABASE = 'test.db' def get_db(): if not os.path.isfile(DATABASE): create_database() db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db def save_msg(msg...
nilq/baby-python
python
__author__ = "Hangi,Kim" __copyright__ = "Copyright 2012-2013, The SAGA Project" __license__ = "MIT" """ IBM LoadLeveler job adaptor implementation reference for pbs job adaptor & sge job adaptor implementation Hangi, Kim hgkim@kisti.re.kr """ import os import re import time from urllib.parse impor...
nilq/baby-python
python
# Privacy Policy Browser # Credit: Josiah Baldwin, Eric Dale, Ethan Fleming, Jacob Hilt, # Darian Hutchinson, Joshua Lund, Bennett Wright # # The alexa skill is implemented as a collection of handlers for certain types of user input. # This is paired with a S3 bucket that is holding data about location & acce...
nilq/baby-python
python
from sklearn.preprocessing import StandardScaler from scipy import ndimage import nilearn from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import PowerTransformer from scipy.stats import variation import numpy as np from densratio import densratio ...
nilq/baby-python
python
class Player(object): def __init__(self, name, connection): self.connection = connection self.name = name self.score = 0
nilq/baby-python
python
import json from typing import List, Tuple import boto3 from botocore.client import BaseClient from logger.decorator import lambda_auto_logging from logger.my_logger import MyLogger from utils.lambda_tool import get_environ_values from utils.s3_tool import ( create_key_of_eorzea_database_merged_item, create_k...
nilq/baby-python
python
#!/usr/bin/python """ `yap_ipython.external.mathjax` is deprecated with yap_ipython 4.0+ mathjax is now install by default with the notebook package """ import sys if __name__ == '__main__' : sys.exit("yap_ipython.external.mathjax is deprecated, Mathjax is now installed by default with the notebook package")
nilq/baby-python
python
from random import random from player import Player from pokerUtils import PokerUtils from board import Board def decide(playerdecision, player, callamount, raiseamount=0): # fold if playerdecision == 2: print(player.getname() + " loses") players.remove(player) # raise if...
nilq/baby-python
python
# # # This script compiles and runs all examples in /examples # by mpifort and mpirun on four processors. # # # Glob: https://docs.python.org/2/library/glob.html import glob # OS: https://docs.python.org/2/library/os.html import os for ftest in glob.glob('examples/*.f90'): print("compile "+ftest) os.system('mpifor...
nilq/baby-python
python
from django_unicorn.components import UnicornView import requests from bs4 import BeautifulSoup class ContcompView(UnicornView): url = "https://example.com" headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Ac...
nilq/baby-python
python
from flask import Blueprint, render_template, jsonify, app from edinet import edinet_methods from eve_docs.config import get_cfg def edinet_docs(): blueprints = [edinet_methods.edinet_methods] eve_docs = Blueprint('eve_docs', __name__, template_folder='templates') @eve_docs.route...
nilq/baby-python
python
from app.dao.permissions_dao import permission_dao from tests.app.db import create_service def test_get_permissions_by_user_id_returns_all_permissions(sample_service): permissions = permission_dao.get_permissions_by_user_id(user_id=sample_service.users[0].id) assert len(permissions) == 8 assert sorted(["m...
nilq/baby-python
python
from django.urls import path from .views import * from .import views app_name = 'offers' urlpatterns = [ # Renda Fixa # ------------------------------------------------------------------------------------------------------------------ # Listar path('rf/listar/', OfferRfListView.as_view(), name="lista...
nilq/baby-python
python
from ..legend import Legend def size_continuous_legend(title=None, description=None, footer=None, prop='size', variable='size_value', dynamic=True, ascending=False, format=None): """Helper function for quickly creating a size continuous legend. Args: prop (str, optional): A...
nilq/baby-python
python
import unittest from app.models import Role class RoleModelTest(unittest.TestCase): def setUp(self): self.new_role = Role('1','admin') if __name__ =='__main__': unittest.main()
nilq/baby-python
python
""" dotfiles ~~~~~~~~ Dotfiles is a tool to make managing your dotfile symlinks in $HOME easy, allowing you to keep all your dotfiles in a single directory. :copyright: (c) 2011-2016 by Jon Bernard. :license: ISC, see LICENSE.rst for more details. """ __version__ = '0.9.dev0'
nilq/baby-python
python
""" """ import sys sys.path.append("..") # import one subdirectory up in files import numpy as np from networks.networks import IsoMPS #%% XXZ Tenpy MPO from tenpy.models.model import CouplingMPOModel, NearestNeighborModel from tenpy.tools.params import asConfig from tenpy.networks.site import SpinHalfSite #__all__...
nilq/baby-python
python
#!/usr/bin/env python """booleanRules.py: Infers network from pseudotime and binary expression. To run type python booleanRules.py gene expressionFile step orderFile maxAct maxRep networkFile threshold thresholdStep gene: name of gene e.g. Gata1. This should match gene names in expression and network files. expressionF...
nilq/baby-python
python
"""Ekea for EAM model""" import os, subprocess, json, shutil from ekea.e3smapp import E3SMApp, here from ekea.utils import xmlquery # EAM app class EAMKernel(E3SMApp): _name_ = "eam" _version_ = "0.1.0" # main entry def perform(self, args): self.generate(args, "exclude_e3sm_eam.ini")
nilq/baby-python
python
import os import sys from pathlib import Path from data_pipeline.config import settings from data_pipeline.utils import ( download_file_from_url, get_module_logger, ) logger = get_module_logger(__name__) def check_score_data_source( score_csv_data_path: Path, score_data_source: str, ) -> None: "...
nilq/baby-python
python
""" This file contains the implementation of the class GameObject. Author: Alejandro Mujica (aledrums@gmail.com) Date: 07/22/20 """ from src.mixins import DrawableMixin, CollisionMixin class GameObject(DrawableMixin, CollisionMixin): # Object sides TOP = 'top' RIGHT = 'right' BOTTOM = 'bottom' LE...
nilq/baby-python
python
#!/usr/bin/env python2 # Fill in checksum/size of an option rom, and pad it to proper length. # # Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net> # # This file may be distributed under the terms of the GNU GPLv3 license. import sys def alignpos(pos, alignbytes): mask = alignbytes - 1 return (pos + mas...
nilq/baby-python
python
# We start by importing all the modules we will need, as well as the helper document with all our functions import argparse import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F import os from torchvision import datasets, transforms, models from collections import ...
nilq/baby-python
python
from django.contrib import admin from django.urls import path, include from django.contrib.sitemaps.views import sitemap from website.sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap } urlpatterns = [ path('mkubwa/', admin.site.urls), path('accounts/', include('accounts.urls', namespace='acco...
nilq/baby-python
python
import multiprocessing import time from multiprocessing.connection import Listener, Client from typing import Dict, Any, List import tqdm from autopandas_v2.ml.inference.interfaces import RelGraphInterface class ModelStore: def __init__(self, path_map: Dict[Any, str]): self.path_map = path_map s...
nilq/baby-python
python
# -*- coding: utf-8 -*- """This module populates the tables of bio2bel_reactome.""" import logging from collections import defaultdict from typing import Dict, List, Mapping, Optional, Set import pandas as pd from tqdm import tqdm from bio2bel.compath import CompathManager from pyobo import get_name_id_mapping from...
nilq/baby-python
python
from collections import namedtuple from sqlalchemy.orm.exc import NoResultFound from parks.models import DBSession from parks.models import Park from parks.models import StampCollection from parks.models import User from parks.models import UserEmail def get_user_by_id(user_id): return DBSession.query( U...
nilq/baby-python
python
from tkinter import * from tkinter.ttk import * from cep_price_console.cntr_upload.CntrUploadTab import CntrUploadTab from cep_price_console.utils.log_utils import CustomAdapter, debug from cep_price_console.cntr_upload.Treeview import TreeviewConstructor, TreeColumn, TreeRow import logging class Step5ReviewUpload(Cn...
nilq/baby-python
python
# start_chrome -> input_date -> scroll_down-> find_cards_info -> save -> find_next (goto) from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import csv import os def start_chrome(): driver = webdriver.Chrome(executable_path='./chromedriver.exe') driver.start_client() ...
nilq/baby-python
python
import client import get_plant import time import RPi.GPIO as GPIO import picamera import math import numpy as np import argparse import cv2 import json import MPU9250 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.setup(25, GPIO.OUT) servo=GPIO.PWM(17, 100) # Connect to the server and take possess...
nilq/baby-python
python
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from variance.models.muscle import MuscleModel, MuscleGroupModel class MuscleSchema(SQLAlchemyAutoSchema): class Meta: model = MuscleModel load_instance = False class MuscleGroupSchema(SQLAlchemyAutoSchema): class Meta: model = ...
nilq/baby-python
python
from django.contrib import admin from .models import PageCheckResult @admin.register(PageCheckResult) class PageCheckResultAdmin(admin.ModelAdmin): list_display = ('buschenschank', 'created', 'tag_name', 'website', 'return_code') list_filter = ('created', 'return_code', 'tag_name') se...
nilq/baby-python
python
from player import Player class Human(Player): def __init__(self, symbol: str, name: str = "You"): super().__init__(name, symbol) def move(self, state: list[str]): print(f"{self.name} is to move!") while True: inp = input("Enter an integer between 1 and 9 representing an e...
nilq/baby-python
python
import mnist_loader import network2 from task_gen import TaskGen import numpy as np training_data2, validation_data2, test_data2 = mnist_loader.load_data_wrapper() task_gen = TaskGen() training_data = task_gen.generate(1000) validation_data = task_gen.generate(1000, False) ''' print training_data2[0][1] print training...
nilq/baby-python
python
# -*- coding: utf-8 -*- import hashlib import unicodedata from collections import Counter, defaultdict from six import text_type from hayes.analysis import builtin_simple_analyzer from hayes.ext.stopwords import ( english_stopwords, finnish_stopwords, russian_stopwords, swedish_stopwords, unicode_punctuation_...
nilq/baby-python
python
from app import db from datetime import datetime from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin from app import login class User(UserMixin,db.Model): id=db.Column(db.Integer,primary_key=True) username = db.Column(db.String(64),index=True,unique=True...
nilq/baby-python
python
from dataclasses import dataclass from typing import Sequence from .phrase import Phrase from .translation_sources import TranslationSources from .word_alignment_matrix import WordAlignmentMatrix @dataclass(frozen=True) class TranslationResult: source_segment: Sequence[str] target_segment: Sequence[str] ...
nilq/baby-python
python
#!/usr/bin/env python from collections import defaultdict # 000000000111111111122222222222333333333344444444 # 123456789012345678901234567890123456789012345678 # Step G must be finished before step X can begin. def parse_line(input_line): return input_line[5], input_line[36] def parse_input(content): retur...
nilq/baby-python
python
from lxml.builder import E from sciencebeam_lab.lxml_to_svg import ( iter_svg_pages_for_lxml, SVG_TEXT, SVG_G, SVG_DOC ) SOME_TEXT = "some text" SOME_X = "10" SOME_Y = "20" SOME_BASE = "25" SOME_HEIGHT = "30" SOME_FONT_SIZE = "40" SOME_FONT_FAMILY = "Fontastic" SOME_FONT_COLOR = '#123' class LXML(object): ...
nilq/baby-python
python
# coding: utf8 from __future__ import print_function import os, sys, re from xml.dom import minidom class HamshahriReader(): """ interfaces [Hamshahri Corpus](http://ece.ut.ac.ir/dbrg/hamshahri/files/HAM2/Corpus.zip) that you must download and extract it. >>> hamshahri = HamshahriReader(root='corpora/hamshahri')...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2019 all rights reserved # # class declaration class Mapping: """ Mix-in class that forms the basis of the representation of mappings Mappings are dictionaries with arbitrary keys whose values are nodes """ # types fro...
nilq/baby-python
python
import streamlit as st st.title('titulo') st.button('cl') st.sidebar.radio('radio',[1,2,3]) for i in range(10): st.write('holla')
nilq/baby-python
python
#!python from __future__ import print_function import time from arduino_device import findArduinoDevicePorts from arduino_olfactometer import ArduinoOlfactometers from arduino_olfactometer import isOlfactometerPortInfo from faa_actuation import PwmController from faa_actuation import CurrentController from faa_actuati...
nilq/baby-python
python
import bs4 print("BlockDMask") print(3 + 4)
nilq/baby-python
python
from collections import Counter,defaultdict import numpy as np import os import pandas as pd import time start_time=time.time() def time_passed(): return time.time() - start_time scores={} num_row_ids=8607230 def update_tally(preds,preds_per_row_id,weight): for i in range(len(preds)): if preds[i] i...
nilq/baby-python
python
from django.conf.urls import patterns, url urlpatterns = patterns( '', url(r'^(?P<slug>[-\w]+)/$', 'blog.views.show_post', name='post'), )
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # time: 2020-8-9 23:11:00 # version: 1.0 # __author__: zhilong import pymysql def main(): conn = pymysql.connect(host='localhost', user='root', password='rootpwd', db='novelsite') cursor = conn.cursor() sql = 'create table novel(novelid int primary key auto_incr...
nilq/baby-python
python
import simuvex from simuvex.s_type import SimTypeFd, SimTypeInt from claripy import BVV ###################################### # getc ###################################### class _IO_getc(simuvex.SimProcedure): # pylint:disable=arguments-differ def run(self, f_p): #additional code trace_dat...
nilq/baby-python
python
import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') def get_data(filename): with open(filename) as f: lines = f.readlines() data=[[],[]] for line in lines: curr_line=line[0:-2] x,y=curr_line.split(" "); x=float(x) y=float(y) data[0].append(x) data[1].append(y) ...
nilq/baby-python
python
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) http://pypi.python.org/pypi/PyDispatcher/2.0.1 See license.txt for original license. Heavily modified for Django's purposes. """ from .dispatcher import Signal, receiver # NOQA from .tasks import register_tasks, set_task_name...
nilq/baby-python
python
import requests import pathlib import shutil from typing import Dict, Tuple, List, Optional import xml.etree.ElementTree as ET HERE = pathlib.Path(__file__).absolute().parent GL_XML_URL = 'https://raw.githubusercontent.com/KhronosGroup/OpenGL-Registry/master/xml/gl.xml' # noqa: E501 class Command: def ...
nilq/baby-python
python
"""Refactor candidates table Revision ID: fbf89710dead Revises: d67d42b06b11 Create Date: 2020-11-12 16:34:25.642126 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'fbf89710dead' down_revision = '73ca57416d1c' branch_labels = None depends_on = None def upgra...
nilq/baby-python
python
from django.template import RequestContext, loader from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import HttpResponseForbidden class Http403(Exception): pass def render_to_403(*args, **kwargs): """ Returns a HttpResponseForbidden whose content i...
nilq/baby-python
python
# Copyright (C) 2019 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mixins for entities.""" # pylint: disable=too-few-public-methods class Reviewable(object): """A mixin for reviewable objects.""" def update_review(self, new_review): """Update obj review dict an...
nilq/baby-python
python
from time import sleep x = 10 while x >= 0: print(x) sleep(0.5) x -= 1 print('Fogo!!')
nilq/baby-python
python
from django.conf.urls import url from . import views urlpatterns = [ url(r"^login/(?P<service>\w+)/$", views.oauth_login, name="oauth_access_login"), url(r"^callback/(?P<service>\w+)/$", views.oauth_callback, name="oauth_access_callback"), url(r"^finish_signup/(?P<service>\w+)/$", views.finish_signup, na...
nilq/baby-python
python
import typing import bs4 __author__ = "Jérémie Lumbroso <lumbroso@cs.princeton.edu>" __all__ = [ "split_name", "extract_text", ] CS_SCRAPING_LABEL_CLASS = "person-label" def split_name(name: str) -> typing.Tuple[str, str]: """ Returns a likely `(first, last)` split given a full name. This uses ...
nilq/baby-python
python
from django.contrib import admin from reviews import models class CompanyAdmin(admin.ModelAdmin): form = models.CompanyForm list_display = ('name',) exclude = () class CityAdmin(admin.ModelAdmin): form = models.CityForm list_display = ('name',) exclude = () class PersonAdmin(admin.ModelAdm...
nilq/baby-python
python
# coding: utf-8 """ qTest Manager API Version 8.6 - 9.1 qTest Manager API Version 8.6 - 9.1 OpenAPI spec version: 8.6 - 9.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class CommentQuery...
nilq/baby-python
python
#!/usr/bin/env python import rospy import sys import time import math import tf import tf2_ros import serial import csv from rugby_lib.imu_gy85 import GY85 from geometry_msgs.msg import Twist, TransformStamped from rugby.msg import * from nav_msgs.msg import Odometry from std_msgs.msg import String from std_msgs.msg ...
nilq/baby-python
python
######################################################################### # Walks through a file system tree and execute a command on files # # Jean-Louis Dessalles 2012 # ######################################################################### """ Walks through ...
nilq/baby-python
python
#!/usr/bin/env python3 import sys import re txt = sys.stdin.read() def logger(msg): sys.stderr.write("{}\n".format(msg)) txt = txt.replace("’", "'") lines = txt.split("\n") lines = [line.strip() for line in lines] lines = [line for line in lines if len(line)] row = None num = 0 tmpl = "MarketVendor.where(mark...
nilq/baby-python
python
#!/usr/bin/env python ############################################################################ # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The A...
nilq/baby-python
python
import json import requests import secrets sld = "pleasenoban2011" tlds = [] with open('tlds.txt') as _tlds: _tlds = _tlds.readlines() for _tld in _tlds: _tld = _tld.strip("\n") tlds.append(f"{sld}.{_tld}") # split list in half _len_half = len(tlds) // 2 tlds_first_set = tlds[:len(tlds) // ...
nilq/baby-python
python
# coding=utf-8 import re from sqlalchemy.orm.exc import NoResultFound from ultros_site.base_sink import BaseSink from ultros_site.database.schema.news_post import NewsPost from ultros_site.decorators import render_api __author__ = "Gareth Coles" class APINewsRoute(BaseSink): route = re.compile(r"/api/v1/news/(...
nilq/baby-python
python
class api_response: def __init__(self, status, info, data): self.status = status self.info = info self.data = data def get_api_response(self): return { "status": self.status, "info": self.info, "data": s...
nilq/baby-python
python
# -*- coding: utf-8 -*- def get_file_content(filename): """ 读取文件, 返回一个生成器对象 :param filename: :return: """ with open(filename, encoding='utf-8') as f: while True: line = f.read(512) if line: yield line else: # 如果line为None, 那么说明已经读取到文...
nilq/baby-python
python
from django.urls import path from .views import ProfileUpdateView, ProfileDetailView urlpatterns = [ path('<slug:slug>/', ProfileDetailView.as_view(), name='profile-detail'), path('<slug:slug>/edit/', ProfileUpdateView.as_view(), name='profile-settings'), ]
nilq/baby-python
python
#!/usr/bin/env python #-*- coding: utf-8 -*- # Python 3.7 # # @Author: Jxtopher # @License: CC-BY-NC-SA # @Date: 2019-04 # @Version: 1 # @Purpose: # see https://packages.debian.org/jessie/wordlist # see /usr/share/dict/ # import numpy as np from itertools import cycle import matplotlib matplotlib...
nilq/baby-python
python