content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Blog (c) by yanjl
#
# Blog is licensed under a
# Creative Commons Attribution 3.0 Unported License.
#
# You should have received a copy of the license along with this
# work. If not, see <http://creativecommons.org/licenses/by/3.0/>.
from django.contrib.auth.models import User
from django.db import models
from djan... | nilq/baby-python | python |
import tablib
from collections import OrderedDict
from inspect import isclass
from sqlalchemy import create_engine,text
def _reduce_datetimes(row):
"""Receives a row, converts datetimes to strings."""
row = list(row)
for i in range(len(row)):
if hasattr(row[i], 'isoformat'):
row[i] =... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/26 0026 下午 5:54
# @Author : Exchris Tsai
# @Site :
# @File : imagedemo.py
# @Software: PyCharm
__author__ = 'Exchris Tsai'
import requests
import os
import urllib
import urllib.request
from bs4 import BeautifulSoup as BS
path = 'd:/images' #
t... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
"""
The `state` module holds (almost!) all the code for defining the global state of a pyiron instance.
Such "global" beh... | nilq/baby-python | python |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World with Flask"
@app.route('/user/<name>')
def user(name):
#example: access http://127.0.0.1:5000/user/dave
return '<h1> Hello, %s </h1>' % name
def main():
app.run(port=5000, debug=False, host='0.0.0.0')
i... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
import re
from subprocess import PIPE, Popen
from pip.download import PipSession
from pip.req import parse_requirements
setup_py_template = """
from setuptools import setup
setup(**{0})
"""
def get_git_repo_dir():
"""
Get the directory of the current git project
Retur... | nilq/baby-python | python |
# Decompiled by HTR-TECH | TAHMID RAYAT
# Github : https://github.com/htr-tech
#---------------------------------------
# Auto Dis Parser 2.2.0
# Source File : patched.pyc
# Bytecode Version : 2.7
# Time : Sun Jan 31 17:36:23 2021
#---------------------------------------
import os, sys, zlib, base64, marshal, binascii... | nilq/baby-python | python |
from django.core.management.base import BaseCommand
from tracking.harvest import harvest_tracking_email
class Command(BaseCommand):
help = "Runs harvest_tracking_email to harvest points from emails"
def add_arguments(self, parser):
parser.add_argument(
'--device-type', action='store', des... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... | nilq/baby-python | python |
import time
class Logging:
def logStateString(self, logStateString):
self._dt = time.strftime("%d %b %Y", time.localtime(time.time()))
self._logname = '/home/pi/PyIOT/logs/json/' + self._dt +'_log.txt'
self._stateLogFile = open(self._logname, 'a')
self._stateLogFile.write(logStateS... | nilq/baby-python | python |
from testtools import TestCase
import requests_mock
from padre import channel as c
from padre import handler
from padre.handlers import tell_joke
from padre.tests import common
class TellJokeHandlerTest(TestCase):
def test_expected_handled(self):
bot = common.make_bot()
m = common.make_message(... | nilq/baby-python | python |
import requests
import time
riot_token = ""
if(not riot_token):
riot_token = input("Please enter your Riot API token here, or replace variable riot_token with your token and rerun the program: \n")
summonerName = input ("Enter summoner's name: ")
url = "https://na1.api.riotgames.com/lol/summoner/v4/summ... | nilq/baby-python | python |
import subprocess
import threading
import logging
import queue
import sys
if sys.version_info < (3, 0):
sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
sys.exit(1)
def ps(hosts, grep_filter):
output = []
q = queue.Queue(len(hosts))
def work(host, grep_filter):
cmd = ['/bi... | nilq/baby-python | python |
from datetime import datetime, timedelta
from src.utils.generation import (
create_appointment,
create_appointment_patient_doctor_relation,
create_patient,
)
def populate(is_print=False):
patient = create_patient(is_print=is_print)
base_datetime = datetime.today()
datetimes_of_appointments = ... | nilq/baby-python | python |
"""
This file contains methods to attempt to parse horrible Specchio data into some coherent format.
This is only used in the case that reflectance and transmittance measurements have to be
loaded in separate files in separate folders one by one from specchio.ch web interface. The code is
a mess but one should not hav... | nilq/baby-python | python |
import json
from django.conf import settings
from django.contrib.auth.decorators import permission_required, login_required
from django.contrib import messages
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from django.shortcuts... | nilq/baby-python | python |
#!/usr/bin/env python3
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
from ev3dev2.button import Button
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.display import Display
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelna... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 12:25:51 2019
@author: Asier
"""
# Fourth: Production-style FizzBuzz. The horror.
# While I won't be adding __init__.py to this doodles folder, pretend it's there so this would be importable
# Finished in 30:24.49
"""
fizzbuzz takes a starting and stopping integer a... | nilq/baby-python | python |
from code.classes.aminoacid import AminoAcid
from code.classes.protein import Protein
import random
import copy
class Random():
'''
Algorithm that folds the amino acids in the protein at random.
'''
def __init__(self):
self.protein = None
self.best = [0, {}]
self.sol_dict = {}
... | nilq/baby-python | python |
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | nilq/baby-python | python |
###############################################################################
# Project: PLC Simulator
# Purpose: Class to encapsulate the IO manager functionality
# Author: Paul M. Breen
# Date: 2018-07-17
###############################################################################
import logging
import thre... | nilq/baby-python | python |
from django.urls import path
from api import view as local_view
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('top-movie/', local_view.top_movie),
path('detail-movie/<int:id>', local_view.detail_movie),
] +static(settings.STATIC_URL, document_root=settings.... | nilq/baby-python | python |
import os
import time
import random
import tkinter
import threading
import subprocess
import glob
from ascii_art import *
from widgets import *
import platform
platform = platform.system()
# thanks to everyone on https://www.asciiart.eu/
class FILE_HANDLER(object):
""" File opening and closing yes"""
def __init__... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
import os
import numpy as np
import pandas as pd
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import matplotlib.artist as martist
from matplotlib.offsetbox import AnchoredText
import pylab as plt
os.chdir('/Users/pauline/Documents/Python')
df = pd.read_csv("Tab... | nilq/baby-python | python |
import sys
import os
from subprocess import (Popen, PIPE, STDOUT)
APP = os.path.abspath(os.path.join(os.path.dirname(__file__), 'run.py'))
"""The Python script to run."""
def spawn():
"""
Start the Quantitaive Imaging Profile REST server.
:return: the completed process return code
"""
# The ... | nilq/baby-python | python |
#! /usr/bin/env python
import logging
import os
import sys
gitpath=os.path.expanduser("~/git/cafa4")
sys.path.append(gitpath)
from fastcafa.fastcafa import *
gitpath=os.path.expanduser("~/git/pyEGAD")
sys.path.append(gitpath)
from egad.egad import *
#SALMON_NET=os.path.expanduser('~/data/cococonet/atlanticsalmon_p... | nilq/baby-python | python |
'''
Created on Feb 7, 2011
@author: patnaik
'''
import sys
import time
from collections import defaultdict
from parallel_episode_mine import load_episodes
from itertools import izip
from numpy import diff
from math import sqrt
class S(object):
def __init__(self, alpha, event):
self.alpha = alpha
... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Copyright (C) 2018 Intel Corporation
?
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 ag... | nilq/baby-python | python |
import hashlib
from pyxbincodec import CodecUtils
from pyxbincodec import PixBlockDecoder
class PixBinDecoder:
"""docstring for """
def __init__(self):
self.MAGIC_NUMBER = "PIXPIPE_PIXBIN"
self._verifyChecksum = False
self._input = None
self._output = None
... | nilq/baby-python | python |
from xsbs.events import registerServerEventHandler
from xsbs.players import player
import logging
event_handlers = (
('player_connect', lambda x: logging.info(
'connect: %s (%i)' % (player(x).name(), x))
),
('player_disconnect', lambda x: logging.info(
'disconnect: %s (%i)' % (player(x).name(), x))
),
('pl... | nilq/baby-python | python |
import setuptools
with open('README.md') as readme_file:
long_description = readme_file.read()
setuptools.setup(
name='aioevproc',
version='0.1.0',
author='Anton Bryzgalov',
author_email='tony.bryzgaloff@gmail.com',
description='Minimal async/sync event processing framework on pure Python',
... | nilq/baby-python | python |
from flask import Flask, request
import os
import json
import socket
app = Flask(__name__)
@app.route('/dostep/<time>&<inputnames>&<inputvalues>&<outputnames>')
def step(time, inputnames, inputvalues, outputnames):
data = _parse_url(time, inputnames, inputvalues, outputnames)
outputs = [data['input1'] * data[... | nilq/baby-python | python |
import pygame
import sys
import random
from ..env_var.env_var import *
from pygame.locals import *
from ..geometry import vector
class Ball (object):
def __init__(self):
random.seed()
self.text = chr(random.randrange(ord('A'), ord('Z')))
pygame.init()
self.color = ball_color
... | nilq/baby-python | python |
import pandas as pd
import re
import os
def _export(data_dir):
file = "State Exports by NAICS Commodities.csv"
t = pd.read_csv(os.path.join(data_dir, file), skiprows=3, engine="c")
t.dropna(how="all", axis=1, inplace=True)
# rename in order to aid in joining with import data later
t.rename(colum... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# vispy: testskip (KNOWNFAIL)
# Copyright (c) 2015, Felix Schill.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Simple demonstration of mouse drawing and editing of a line plot.
This demo extends the Line visual from scene adding mouse events that allow
modificat... | nilq/baby-python | python |
#!/usr/bin/env python
f = open('new.txt')
lines = f.readlines()
for line in lines:
print(line.split()[8])
| nilq/baby-python | python |
import NsgaII
import random
# Non-dominated Ranking Genetic Algorithm (NRGA)
class Ngra(NsgaII.NsgaII):
# Initializes genetic algorithm
def __init__(self, configuration, numberOfCrossoverPoints=2, mutationSize=2, crossoverProbability=80,
mutationProbability=3):
NsgaII.NsgaII.__init__(... | nilq/baby-python | python |
import torch
from torch import nn
from allennlp.modules.span_extractors import SelfAttentiveSpanExtractor
class SpanClassifierModule(nn.Module):
def _make_span_extractor(self):
return SelfAttentiveSpanExtractor(self.proj_dim)
def _make_cnn_layer(self, d_inp):
"""
Make a CNN layer as a... | nilq/baby-python | python |
# run some simple select tests
import psycopg2 as psy
import simplejson as json
import argparse
import setup_db
def find_all_studies(cursor,config_obj):
STUDYTABLE = config_obj.get('database_tables','studytable')
sqlstring = "SELECT id FROM {t};".format(t=STUDYTABLE)
cursor.execute(sqlstring)
print "re... | nilq/baby-python | python |
#!/usr/bin/env python3
try:
from flask import Flask
except ImportError:
print ("\n[X] Please install Flask:")
print (" $ pip install flask\n")
exit()
from wordpot import app, pm, parse_options, check_options
from wordpot.logger import *
import os
check_options()
if __name__ == '__main__':
par... | nilq/baby-python | python |
import pyglet
from pyglet.gl import *
class Camera:
def __init__(self, width: float, height: float, position: list, zoom: float):
self.width = float(width)
self.height = float(height)
self.position = list(position)
self.zoom = float(zoom)
def left(self):
return self.pos... | nilq/baby-python | python |
from nnf import Var
from lib204 import Encoding
import geopy
import geopy.distance
from geopy.geocoders import Nominatim
import pyproj
#factors that might affect the trips
virus = Var('virus') # 🦠
documents = Var('documents') # document
international = Var('international') # crossing the border
toll_money = Var('mon... | nilq/baby-python | python |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
import pytest
from .. import PolarGrid, SphericalGrid
from ..boundaries.local import NeumannBC
@pytest.mark.parametrize("grid_class", [PolarGrid, SphericalGrid])
def test_spherical_base_bcs(grid_class):
""" test setting boundary ... | nilq/baby-python | python |
# Copyright (c) 2008-2012 by Enthought, Inc.
# All rights reserved.
import sys
from setuptools import setup
setup_data = {}
execfile('setup_data.py', setup_data)
INFO = setup_data['INFO']
if 'develop' in sys.argv:
INFO['install_requires'] = []
# The actual setup call.
setup(
name = 'ets',
version = INF... | nilq/baby-python | python |
def dobro(n):
d = n * 2
return d
def metade(n):
d = n / 2
return d
def aumento(n):
d = n + n * 10 / 100
return d
def reduzir(n):
d = n - (n * 13 / 100)
return d
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import turret
import turret.layers as L
from util import execute_inference
class BasicMathTest(unittest.TestCase):
def test_sum_ternary(self):
N, C, H, W = 3, 5, 7, 11
input0 = np.random.rand(N, C, H, W).astype(np.float32)
input... | nilq/baby-python | python |
from fastatomography.util import *
from scipy.io import loadmat, savemat
# %%
path = '/home/philipp/projects2/tomo/2019-03-18_Pd_loop/'
# path = '/home/philipp/projects2/tomo/2018-07-03-Pdcoating_few_proj/sample synthesis date 20180615-Pd coating/'
# path = '/home/philipp/projects2/tomo/2019-04-17-Pd_helix/philipp/'
fn... | nilq/baby-python | python |
# Copyright 2021 University of Manchester
#
# 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 t... | nilq/baby-python | python |
__all__ = ["Process", "ProcessError"]
import os
import sys
import shlex
import queue
import select
import logging
import subprocess
import collections
import threading
from itertools import chain
from dataclasses import dataclass
from typing import Sequence, Mapping
def poll(fd: int, stop_event: threading.Event,
... | nilq/baby-python | python |
# Copyright 2017 The TensorFlow Authors. 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 applica... | nilq/baby-python | python |
from pymongo import MongoClient
from pymongo.database import Database
import json
import os
from asset_manager.models.models import Asset, License
def connect_db(connection_string: str, database_name: str) -> Database:
client = MongoClient(connection_string)
return client.get_database(database_name)
def ini... | nilq/baby-python | python |
from __future__ import annotations
import csv
import gzip
import json
import os
import shutil
import time
from typing import Iterator
from decouple import config
from light_controller.const import MODE_BRIGHTNESS, MODE_COLOR_TEMP, MODE_HS
from light_controller.controller import LightController
from light_controller.h... | nilq/baby-python | python |
#!/usr/bin/python
"""
Euclid covariance matrices, taken from arXiv:1206.1225
"""
import numpy as np
def covmat_for_fom(sig_x, sig_y, fom, sgn=1.):
"""
Return covariance matrix, given sigma_x, sigma_y, and a FOM. Diagonal
elements are unique up to a sign (which must be input manually).
(N.B. In fi... | nilq/baby-python | python |
from spotcli.configuration.configuration import load
__all__ = ["load"]
| nilq/baby-python | python |
from mathutils import Vector, Matrix, Euler, Quaternion
from typing import List
def convert_source_rotation(rot: List[float]):
qrot = Quaternion([rot[0], rot[1], -rot[3], rot[2]])
# qrot.rotate(Euler([0, 0, 90]))
return qrot
def convert_source_position(pos: List[float]):
pos = Vector([pos[0], pos[2]... | nilq/baby-python | python |
# from vocab import Vocab
# from tr_embed import TREmbed | nilq/baby-python | python |
def hidden_layer_backpropagate(layer, prev_outputs, outputs, next_weights_totlin, rate):
tot_lin = []
weights = []
i = 0
for (n, o) in zip(layer, outputs):
op_lin = n.activation_d(o)
total_op = 0
for w, tl in zip(next_weights_totlin["w"], next_weights_totlin["tl"]):
... | nilq/baby-python | python |
#!/usr/bin/python
# code from https://www.raspberrypi.org/forums/viewtopic.php?t=220247#p1352169
# pip3 install pigpio
# git clone https://github.com/stripcode/pigpio-stepper-motor
'''
# connection to adafruit TB6612
# motor: SY28STH32-0674A
Vcmotor --> 12V 5A power supply
VM --> floating
Vcc --> 3V3 Pin 17
GND --> G... | nilq/baby-python | python |
import unittest
from linkml.generators.markdowngen import MarkdownGenerator
from linkml.utils.schemaloader import SchemaLoader
from linkml.utils.yamlutils import as_yaml
from tests.utils.test_environment import TestEnvironmentTestCase
from tests.test_issues.environment import env
class Issue63TestCase(TestEnvironmen... | nilq/baby-python | python |
# import gevent.monkey;gevent.monkey.patch_all()
import time
from funboost import boost, BrokerEnum,run_consumer_with_multi_process,ConcurrentModeEnum
import nb_log
logger = nb_log.get_logger('sdsda',is_add_stream_handler=False,log_filename='xxx.log')
@boost('20000', broker_kind=BrokerEnum.REDIS, concurrent_num=2, ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | nilq/baby-python | python |
__all__ = ['MASKED', 'NOMASK']
MASKED = object()
NOMASK = object()
| nilq/baby-python | python |
from torchreid import metrics
from torchreid.utils import re_ranking
import numpy as np
import torch
from torch.nn import functional as F
if __name__ == '__main__':
ff = torch.load('train_avg_feature.pt')
f_pids = np.load('train_pids.npy')
f_camids = np.load('train_camids.npy')
# eval_index = 5... | nilq/baby-python | python |
# General imports
import os, json, logging, yaml, sys
import click
from luna.common.custom_logger import init_logger
init_logger()
logger = logging.getLogger('generate_tiles')
from luna.common.utils import cli_runner
_params_ = [('input_slide_image', str), ('output_dir', str), ('tile_size', int), ('batch_size', i... | nilq/baby-python | python |
"""
sudoku.py -- scrape common web sources for Sudokus
"""
import json
from datetime import datetime
from dataclasses import dataclass
import requests
from bs4 import BeautifulSoup
sudokuexchange_head = "https://sudokuexchange.com/play/?s="
@dataclass
class Puzzle:
name: str
source_url: str
sudokuexcha... | nilq/baby-python | python |
from .BaseWriter import TensorboardWriter
from .visual import * | nilq/baby-python | python |
from .chat import Chat
from .livestream import Livestream
from .message import Message
from .tiny_models import *
from .user import User | nilq/baby-python | python |
import click
import maldnsbl
from collections import Counter
import json
import sys
# Utlity Functions
def iterate_report(report,sep=': '):
"""Converts an iterable into a string for output
Will take a list or dicitonary and convert it to a string where
each item in the iterable is joined by linebreaks (\... | nilq/baby-python | python |
from rest_framework.reverse import reverse_lazy
def get_detail_url(obj, url_name, request):
url_kwargs = {
'pk': obj.id,
}
return reverse_lazy(url_name, kwargs=url_kwargs, request=request)
# def get_base_fields():
# return [
# 'unique_id',
# 'integration_code'
# ]
# def... | nilq/baby-python | python |
from datetime import date
from email import message
from vigilancia.order_screenshot import Orders
from django.db.models.fields import DateField
from django.http import Http404
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import get_object_or_404, render
from .models imp... | nilq/baby-python | python |
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from .utils import *
from .addons import *
import qcdb
_ref_h2o_pk_rhf = -76.02696997325441
_ref_ch2_pk_uhf = -38.925088643363665
_ref_ch2_pk_rohf = -38.91973113928147
@using_psi4
def test_tu1_rhf_a():
"""tu1-h2o-energy/input.dat
glob... | nilq/baby-python | python |
from .naive_bayes import NaiveBayes
| nilq/baby-python | python |
import os
import codecs
import sqlite3
import re
from flask import Flask, render_template, abort, request, Response, g, jsonify, redirect, url_for
app = Flask(__name__)
if os.getenv('FLASK_ENV', 'production') == 'production':
debug = False
else:
debug = True
app.config.update(
DATADIR='pages',
IMGDIR=... | nilq/baby-python | python |
import matplotlib.pyplot as plt
plt.plot()
plt.show() | nilq/baby-python | python |
# Copyright 2015 The TensorFlow Authors. 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 applica... | nilq/baby-python | python |
#!flask/bin/python
from farm import app
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8001, debug=True)
| nilq/baby-python | python |
import datetime
def prev_month_range(when = None):
"""Return (previous month's start date, previous month's end date)."""
if not when:
# Default to today.
when = datetime.datetime.today()
# Find previous month: http://stackoverflow.com/a/9725093/564514
# Find today.
first = datetime... | nilq/baby-python | python |
'''
example code to join dataframes
merge_by_FIPS doesn't need to be it's own file; it's just calling .join on two data frames
'''
from deaths import death_sample
from vaccines import vaccine_sample
def merge_by_FIPS(desired_date):
# get dataframes with FIPS as indices
deaths_df = death_sample(desired_date)
... | nilq/baby-python | python |
# Generated by Django 3.1.2 on 2020-11-10 14:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('userauth', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='fccProfil... | nilq/baby-python | python |
import json
import time, os
import requests
from datetime import datetime
from PIL import Image
from PIL.ExifTags import TAGS
def download_img(url, basepath, filename):
with open(f'{basepath}/{filename}.jpg', "wb") as file:
res = requests.get(url)
file.write(res.content)
def download_movi... | nilq/baby-python | python |
#! /usr/bin/env python
from datetime import datetime
import hb_config
# import MySQLdb
import pymysql.cursors
import pymysql.converters as conv
# import pymysql.constants as const
from pymysql.constants import FIELD_TYPE
import hb_output_settings as output_settings
import hb_queries
import hb_templates as templates
im... | nilq/baby-python | python |
from accuracy2 import MyClassifier1
ob=MyClassifier1()
print(ob.predict()) | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source: https://github.com/simplegadget512/Truecolor
# MIT License
# Copyright (c) 2017 Albert Freeman
# 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 t... | nilq/baby-python | python |
import os
from charge.repository import Repository
if __name__ == '__main__':
test_data_dir = os.path.realpath(
os.path.join(__file__, '..', 'cross_validation_data'))
out_file = 'cross_validation_repository.zip'
repo = Repository.create_from(test_data_dir,
min_shell=0, max_shell... | nilq/baby-python | python |
import unittest
from typing import List
import utils
# https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
def round_up_to_power_of_2(v):
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
return v + 1
# O(n) space. Segment tree array.
class NumArray:
... | nilq/baby-python | python |
# Generated by Django 3.0.8 on 2020-08-12 16:14
from django.db import migrations, models
import utils.delete.managers
import utils.postgres.managers
class Migration(migrations.Migration):
dependencies = [
('definitions', '0008_auto_20200810_0520'),
]
operations = [
migrations.AlterModel... | nilq/baby-python | python |
from typing import Any, Optional
from baserow.core.models import Application, TrashEntry, Group
from baserow.core.registries import application_type_registry
from baserow.core.signals import application_created, group_restored
from baserow.core.trash.registries import TrashableItemType, trash_item_type_registry
clas... | nilq/baby-python | python |
"""
NetEvo for Python
=================
NetEvo is a computing framework designed to allow researchers to
investigate evolutionary aspects of dynamical complex networks. It
provides functionality to easily simulate dynamical networks with both
nodes and edges states, and includes optimization methods... | nilq/baby-python | python |
# Generated by Django 3.2.8 on 2021-11-02 22:22
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('tasks', '0009_alter_task_task_description'),
]
operations = [
]
| nilq/baby-python | python |
from processes.models import Workflow
import factory
from faker import Factory as FakerFactory
from .owned_model_factory import OwnedModelFactory
from .run_environment_factory import RunEnvironmentFactory
faker = FakerFactory.create()
class WorkflowFactory(OwnedModelFactory):
class Meta:
m... | nilq/baby-python | python |
"""
"""
from .utils import install_issubclass_patch
__version__ = "0.10.2"
install_issubclass_patch()
| nilq/baby-python | python |
import torch.nn as nn
from .fcn import FCNHead
def build_segmentor(opt):
n_class = opt.n_class
# channels = [18, 36, 72, 144]
channels = [128]
classifier = FCNHead(
sum(channels),
sum(channels),
n_class,
num_convs=1,
kernel_size=1
)
return classifier
def... | nilq/baby-python | python |
##############################################################################
# Copyright (c) 2016 HUAWEI TECHNOLOGIES CO.,LTD and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... | nilq/baby-python | python |
from collections import defaultdict
from typing import Optional
import ether.topology
from ether.core import Node, Connection
DockerRegistry = Node('registry')
class Topology(ether.topology.Topology):
def __init__(self, incoming_graph_data=None, **attr):
super().__init__(incoming_graph_data, **attr)
... | nilq/baby-python | python |
import os
from collections import Counter
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
def process_logfile(log_file) -> list:
with open(log_file, mode='r', encoding='utf-8') as file:
lines = file.readlines()
return [line.split(" : ")[0] for line in lines]
if __n... | nilq/baby-python | python |
from instagrapi import Client
import requests
import json
username = "USERNAME"
password = "PASSWORD"
def instagram_json():
response = requests.get(f"https://www.instagram.com/{username}/?__a=1")
data = response.json()
data1 = json.dumps(data)
data2 = json.loads(data1)
followers = data2[... | nilq/baby-python | python |
# Modules
from termenu import PlainMenu
# Initialize our menu
menu = PlainMenu()
# Main option list
@menu.option("Check out GitHub!")
def check_github():
print("You selected 'Check out GitHub!'.")
@menu.option("Read some documentation!")
def read_docs():
print("You selected 'Read some documentation!'.")
@me... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" Provides the Action class as part of the PokerNowLogConverter data model"""
from dataclasses import dataclass
from player import Player
@dataclass
class Action:
""" The Action class represents a single action made by a player in the active phase of the game.
Args:
player ... | nilq/baby-python | python |
from calc import calculate_reverse_polish_notation
print(
calculate_reverse_polish_notation(input().split(' '))
) | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Functions to load and write datasets."""
__all__ = [
"load_airline",
"load_arrow_head",
"load_gunpoint",
"load_basic_motions",
"load_osuleaf",
"load_italy_power_demand",
"load_japanese_vowels",
"load_longley",
"load_lynx",
"load_shampoo_sales",
"lo... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.