content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from flask import Flask
app = Flask(__name__)
@app.route('/hello/<name>')
def hello(name: str) -> str:
return f"Hello {name}!"
| nilq/baby-python | python |
#!/usr/bin/env python
import roslib; roslib.load_manifest('teleop_twist_keyboard')
import rospy
from geometry_msgs.msg import Twist
import sys, select, termios, tty, rospy
import curses
msg = """
Reading from the keyboard and Publishing to Twist!
---------------------------
Moving options:
-------------------------... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from Box2D.b2 import contactListener
from parameters import *
from creatures import Animatronic
class nnContactListener(contactListener):
def __init__(self):
contactListener.__init__(self)
self.sensors = dict()
def BeginC... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
import click
from services.waas.src.oci_cli_waas.generated import waas_cli
from oci_cli import cli_util
from oci_cli import custom_types # noqa: F401
from oci_cli import json_skeleton_utils
# oci waas purge-cache purge-cac... | nilq/baby-python | python |
""""""
from SSNRoom import SSNRoom
import json
class WallRoom(SSNRoom):
def __init__(self, room):
super().__init__(room)
# self._load()
self.wall_store = None
def _load(self):
self.wall_store = json.loads(self.room.topic)
print("hi")
# room_events = self.room.g... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# escpostools/commands/cmd_test.py
#
# Copyright 2018 Base4 Sistemas Ltda ME
#
# 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/L... | nilq/baby-python | python |
# This is a preliminary version of the code
from typing import Any
import time
import torch
import numpy
from torch import Tensor
from torch import autograd
from torch.autograd import Variable
from torch.autograd import grad
def hessian_vec(grad_vec, var, retain_graph=False):
v = torch.ones_like(var)
vec, = a... | nilq/baby-python | python |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: DeepSeaScene
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class SubpassDependency(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls):
return 28
# SubpassDependency... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_selection import mutual_info_classif
def draw_cat_plot(df: pd.DataFrame, id_var: str, cat_feats: list, *, output_filename: str =None):
"""
Draw plot showing value counts of categorical features.
... | nilq/baby-python | python |
import numpy as np
from lmfit import Parameters, minimize, report_fit
from lmfit.models import LinearModel, GaussianModel
from lmfit.lineshapes import gaussian
def per_iteration(pars, iter, resid, *args, **kws):
"""iteration callback, will abort at iteration 23
"""
# print( iter, ', '.join(["%s=%.4f" % (p.... | nilq/baby-python | python |
from typing import List
class Solution:
def maximum69Number (self, num: int) -> int:
ls = list('%d'%num)
ans = 0
try:
index = ls.index(6)
ls[index] = 9
for it in ls:
ans = ans * 10 + it
return ans
except ValueError a... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
from scitbx.array_family import flex # import dependency
from simtbx.nanoBragg import shapetype
from simtbx.nanoBragg import convention
from simtbx.nanoBragg import nanoBragg
import libtbx.load_env # possibly implicit
from cctbx import crystal
import os
... | nilq/baby-python | python |
import brainscore
from brainscore.benchmarks._neural_common import NeuralBenchmark, average_repetition
from brainscore.metrics.ceiling import InternalConsistency, RDMConsistency
from brainscore.metrics.rdm import RDMCrossValidated
from brainscore.metrics.regression import CrossRegressedCorrelation, pls_regression, pear... | nilq/baby-python | python |
import json, time, argparse, getpass, re, requests
try:
input = raw_input
except NameError:
pass
parser = argparse.ArgumentParser(description='Bytom UTXO Tool')
parser.add_argument('-o', '--url', default='http://127.0.0.1:9888', dest='endpoint', help='API endpoint')
parser.add_argument('--http-user', default=No... | nilq/baby-python | python |
S = set()
S.add(5)
S.add(3)
S.add(1)
# Prints out the numbers 5, 3, 1 in no particular order
for element in S:
print "{} is in the set".format(element)
S.remove(3)
S.remove(5)
s.remove(1) | nilq/baby-python | python |
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
import sqlite3
import os.path
from os import listdir, getcwd
import sys
from os import listdir
from os.path import isfile, join
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
db_dir = os.path.join(BASE_DIR,"sql/")
img_dir = os.path.join(BASE_DIR,"images/")
full_dir = lambda x,y: x+y
known_fac... | nilq/baby-python | python |
data = open('data/input6.txt', 'r')
orbs = data.readlines()
d = {}
for orb in orbs:
c1 = orb[:3]
c2 = orb[4:7]
d[c2] = c1
s = 0
for p in d:
curr_p = p
while curr_p in d:
curr_p = d[curr_p]
s += 1
print(s)
trajet_you = []
curr = 'YOU'
while True:
if curr not in d: break
c... | nilq/baby-python | python |
#! /usr/bin/env python
#
# Check the option usage.
# Make sure the union member matches the option type.
#
import sys, os, fnmatch
# just use the first letter of the member name - should be unique
opt_suffix = {
'b' : 'AT_BOOL',
'a' : 'AT_IARF',
'n' : 'AT_NUM',
'l' : 'AT_LINE',
't' : 'AT_POS'
}... | nilq/baby-python | python |
from pathlib import Path
import pytest
from md_translate.exceptions import ObjectNotFoundException, FileIsNotMarkdown
from md_translate.files_worker import FilesWorker
TEST_FIRST_FILE = 'tests/test_data/md_files_folder/first_file.md'
TEST_SECOND_FILE = 'tests/test_data/md_files_folder/second_file.md'
class Setting... | nilq/baby-python | python |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class Top20Page(page_module.Page):
def __init__(se... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
##
# @file backend.py
# @brief
# @author wondereamer
# @version 0.5
# @date 2016-07-10
from quantity.digger.event.rpc import EventRPCServer
from quantity.digger.event.eventengine import ZMQEventEngine
from quantity.digger.interaction.interface import BackendInterface
from quantity.digger.util... | nilq/baby-python | python |
#%% Test Module
from pyCMC import CMC
def test_results(returnVal, tname):
if 'status' in returnVal.keys():
if returnVal['status']['error_code'] == 0:
print('{} works!'.format(tname))
else:
print('Error message: {}'.format(returnVal['status']['error_message']))
else:
print(returnVal)
with open('./cmc_key... | nilq/baby-python | python |
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.conf import settings
from django.contrib.auth.models import User, Group
from reports.models impo... | nilq/baby-python | python |
#!/Users/juan/venv-3.8.6/bin/python3.8
# Copyright 2020 Telleztec.com, Juan Tellez, All Rights Reserved
#
import boto3
import datetime
import argparse
# convert bytes to kb, mb, and gb
def to_units(b, unit):
if unit=='b':
return b
elif unit=='k':
return round(b/1000, 2)
elif unit=='m':
... | nilq/baby-python | python |
from django.db.models import Count
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
from tastypie import http, fields
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.bundle import Bundle
import json
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.... | nilq/baby-python | python |
"""
Copyright 2017 Balwinder Sodhi
Licenced under MIT Licence as available here:
https://opensource.org/licenses/MIT
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.... | nilq/baby-python | python |
#
# Sample: Gamut clamping
#
from lcms import *
Lab = cmsCIELab(80, -200, 50)
print "Original", Lab
#
# Desaturates color to bring it into gamut.
# The gamut boundaries are specified as:
# -120 <= a <= 120
# -130 <= b <= 130
cmsClampLab(Lab, 120, -120, 130, -130)
print "Constrained", Lab
| nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path("numbers", views.NumberListView.as_view(), name="number_list_view"),
path("numbers/<int:pk>/", views.NumberView.as_view(), name="number_view"),
path("numbers/add_number/", views.NumberEditView.as_view(), name="add_number"),
path('nu... | nilq/baby-python | python |
import re
import pytest
from ratus import Evaluator, __version__
from ratus.execer import Executor, ExecutorError
from ratus.parse import (
BinaryOp,
BinaryOpType,
Float,
Function,
Integer,
Parser,
ParserError,
String,
UnaryOp,
UnaryOpType,
)
from ratus.token import Token, Toke... | nilq/baby-python | python |
from hilbert import main
main()
| nilq/baby-python | python |
from rest_framework import serializers
from attendance.models import Attendance, AttendanceBlock, Session
class SessionSerializer(serializers.ModelSerializer):
subject = serializers.SerializerMethodField()
class Meta:
model = Session
fields = [
"subject",
"start",
... | nilq/baby-python | python |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
import scipy.stats as st
from math import exp, copysign, log, sqrt, pi
import sys
sys.path.append('..')
from rto_l1 import *
# ground truth parameter
thetatruth = np.array([0.5, 1.0, 0, 0.1, 0.0, 0.0, 0.0,... | nilq/baby-python | python |
import requests
import json
def send(text, path):
requests.post('https://meeting.ssafy.com/hooks/k13xxxszfp8z8ewir4qndiw63c',
data=json.dumps({"attachments": [{
"color": "#FF8000",
"text": str(text),
"author_name": "django",
"author_icon": "http://www.matter... | nilq/baby-python | python |
#-*- coding: utf-8 -*-
import datetime
from PyQt4 import QtGui
from campos import CampoNum, CampoCad
from controllers.orden_controller import initData, translateView, updateData, checkValidacion, Save
class OrdenView(QtGui.QGroupBox):
def __init__(self, parent=None):
super(OrdenView, self).__init__(parent)
... | nilq/baby-python | python |
#!/usr/bin/env python3
from distutils.core import setup
import os
os.system("make ")
setup(name='pi',
version='1.0',
description='pi digits compute',
author='mathm',
author_email='mingtinglai@58.com',
url="https://igit.58corp.com/mingtinglai/pi",
)
| nilq/baby-python | python |
import os
import sys
import threading
import boto3
import logging
import shutil
from botocore.client import Config
from matplotlib import pyplot as plt
from botocore.exceptions import ClientError
from boto3.s3.transfer import TransferConfig
END_POINT_URL = 'http://uvo1baooraa1xb575uc.vm.cld.sr/'
A_KEY = 'AKIAtEpiGWUc... | nilq/baby-python | python |
#coding:utf-8
import hashlib
from scrapy.dupefilters import RFPDupeFilter
from scrapy.utils.url import canonicalize_url
class URLSha1Filter(RFPDupeFilter):
"""根据urlsha1过滤"""
def __init__(self, path=None, debug=False):
self.urls_seen = set()
RFPDupeFilter.__init__(self, path)
def re... | nilq/baby-python | python |
from sys import *
sid = 11 if len(argv) <= 1 else int(argv[1])
from random import *
seed(sid)
for cas in range(int(input())):
input()
m = {}
for i, v in enumerate(map(int, input().split())): m.setdefault(v, []).append(i)
b = [v for i, v in sorted((choice(l), v) for v, l in m.items())]
print(len(b)... | nilq/baby-python | python |
#
# Project FrameVis - Video Frame Visualizer Script
# @author David Madison
# @link github.com/dmadison/FrameVis
# @version v1.0.1
# @license MIT - Copyright (c) 2019 David Madison
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associate... | nilq/baby-python | python |
import os
import pickle
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from task_dyva.utils import save_figure
from task_dyva.visualization import PlotModelLatents
class FigureS6():
"""Analysis methods and plotting routines to reproduce
Figure S6 from the manusc... | nilq/baby-python | python |
import random
from flask import render_template, redirect, flash, url_for, request, jsonify
from flask_login import login_user, logout_user, current_user, login_required
from sqlalchemy import desc
from app import app, db, login_manager, forms
from app.models import User, Game, GameMove
from app.decorators import not_i... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 15:49:57 2018
@author: pranavjain
This model predicts the quality of the red wine. Also, an optimal model is built using Backward Elimination.
Required Data to predict
Fixed acidity
Volatile acidity
Citric acid
Residual sugar
Chlorides
Free sul... | nilq/baby-python | python |
from mqtt_panel.web.component import Component
class Modal(Component):
def __init__(self):
super().__init__(4)
def _body(self, fh):
self._write_render(fh, '''\
<div id="modal" class="d-none"></div>
''', indent=self._indent)
| nilq/baby-python | python |
from gym_gazebo2.envs.MARA.mara import MARAEnv
from gym_gazebo2.envs.MARA.mara_random import MARARandEnv
from gym_gazebo2.envs.MARA.mara_real import MARARealEnv
from gym_gazebo2.envs.MARA.mara_camera import MARACameraEnv
from gym_gazebo2.envs.MARA.mara_orient import MARAOrientEnv
from gym_gazebo2.envs.MARA.mara_collisi... | nilq/baby-python | python |
# Dependencies
import requests as req
from config import api_key
url = f"http://www.omdbapi.com/?apikey={api_key}&t="
# Who was the director of the movie Aliens?
movie = req.get(url + "Aliens").json()
print("The director of Aliens was " + movie["Director"] + ".")
# What was the movie Gladiator rated?
movie = req.get... | nilq/baby-python | python |
"""Clean Code in Python - Chapter 9: Common Design Patterns
> Monostate Pattern
"""
from log import logger
class SharedAttribute:
def __init__(self, initial_value=None):
self.value = initial_value
self._name = None
def __get__(self, instance, owner):
if instance is None:... | nilq/baby-python | python |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in th... | nilq/baby-python | python |
# Eyetracker type
# EYETRACKER_TYPE = "IS4_Large_Peripheral" # 4C eyetracker
#EYETRACKER_TYPE = "Tobii T120" # Old eyetracker
EYETRACKER_TYPE = "simulation" # test
# EYETRACKER_TYPE = "Tobii Pro X3-120 EPU" # Tobii X3
SCREEN_SIZE_X = 1920
SCREEN_SIZE_Y = 1080
#Pilot condition
PILOT_CONDITION_TEXT_INTERVENTION = True... | nilq/baby-python | python |
#-
# Copyright (c) 2013 Robert M. Norton
# All rights reserved.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. BERI licenses t... | nilq/baby-python | python |
import os
import telebot
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
def medit(message_text,chat_id, message_id,reply_markup=None,parse_mode=None):
return bot.edit_message_text(chat_id=chat_id,message_id=message_id,text=message_text,reply_markup=reply_markup,
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making QT4C available.
# Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
# QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below.
# A copy of the BSD ... | nilq/baby-python | python |
from spire.mesh import ModelController
from spire.schema import SchemaDependency
from platoon import resources
from platoon.models import *
class QueueController(ModelController):
resource = resources.Queue
version = (1, 0)
mapping = 'id subject name status'
model = Queue
schema = SchemaDependenc... | nilq/baby-python | python |
import argparse
import shutil
import errno
import time
import glob
import os
import cv2
import numpy as np
from merge_tools import do_merge_box
DEBUG = True
class MergeBox(object):
def __init__(self):
args = self.parse_arguments()
self.output_dir = args.output_dir
self.input_dir = args.... | nilq/baby-python | python |
"""Tests"""
import unittest
from html_classes_obfuscator import html_classes_obfuscator
class TestsGenerateCSS(unittest.TestCase):
"""Tests
Args:
unittest (unittest.TestCase): Unittest library
"""
def test_generate_css_simple_case(self) -> None:
"""Test"""
new_css = html_cl... | nilq/baby-python | python |
import urllib.request
def obtain_webpage(url: str):
return urllib.request.urlopen(url)
| nilq/baby-python | python |
filepath = 'Prometheus_Unbound.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
cnt += 1
| nilq/baby-python | python |
# Time: O(nlogn)
# Space: O(n)
import collections
# hash, sort
class Solution(object):
def findWinners(self, matches):
"""
:type matches: List[List[int]]
:rtype: List[List[int]]
"""
lose = collections.defaultdict(int)
players_set = set()
for x, y in matche... | nilq/baby-python | python |
# flake8: noqa
elections_resp = {
'kind': 'civicinfo#electionsQueryResponse',
'elections': [{
'id': '2000',
'name': 'VIP Test Election',
'electionDay': '2021-06-06',
'ocdDivisionId': 'ocd-division/country:us'
}, {
'id': '4803',
'name': 'Los Angeles County Elec... | nilq/baby-python | python |
def readFile(path):
try:
with open(path, "r") as file:
return file.read()
except:
print(
"{Error: Failed to load file. File doesn't exist or invalid file path, "
+ "Message: Please check arguments or import strings.}"
)
return ""
class Stack:... | nilq/baby-python | python |
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import time
import logging
import random
import googletrans
prefix = "$"
BOT_TOKEN = "token-goes-here"
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=pr... | nilq/baby-python | python |
"""Helper file to check if user has valid permissions."""
from application.common.common_exception import (UnauthorizedException,
ResourceNotAvailableException)
from application.model.models import User, UserProjectRole, RolePermission, \
Permission, UserOrgRole, Org... | nilq/baby-python | python |
#!/bin/python3
# this script should be run with a "script" command to save the output into a file
import requests
import io
import json
# put the instance needed here
inst='https://octodon.social/api/v1/timelines/public?local=1'
with io.open("toots.txt","a",encoding="utf8") as f:
while True:
res = reque... | nilq/baby-python | python |
/home/runner/.cache/pip/pool/40/4e/54/4dc30f225358504ac2a93685d7323e0851fea2c2a9937f25f1d53d20f9 | nilq/baby-python | python |
# Licensed under MIT license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""Utility functions."""
import numpy as np
__all__ = ['mag_to_flux', 'flux_to_mag', 'e1_e2_to_shape']
def mag_to_flux(mag, zeropoint=27.0):
"""Convert magnitude into flux unit.
"""
return 10.0 ** ((zeropoint - mag) / 2.5)
def flux_... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import sys
import json
import random
from pathlib import Path
from PySide6 import QtCore, QtWidgets
from pikepdf import Pdf, Encryption
class ProtectPdfWindow(QtWidgets.QWidget):
def __init__(self, lang_file='en.json'):
super().__init__()
if os.path.isfile(lang_fi... | nilq/baby-python | python |
def remap( x, oMin, oMax, nMin, nMax ):
#range check
if oMin == oMax:
print("Warning: Zero input range")
return None
if nMin == nMax:
print("Warning: Zero output range")
return None
#check reversed input range
reverseInput = False
oldMin = min( oMi... | nilq/baby-python | python |
import pandas as pd
import mysql.connector
import json
from pandas.io.json import json_normalize
from sqlalchemy import create_engine
import pymysql.cursors
import datetime
def connect():
""" Connect to MySQL database """
source = None
try:
source = pymysql.connect(host='35.220.139.166',
... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import helper_functions.DataFrames as dfimport
def FillNaNWithCurrentDistribution(column, df):
'''
Input : The name of the column to witch the fillig strategy should be applied to,
plus the DataFrame object contanig the relevant data.
Output : The ... | nilq/baby-python | python |
################################################################################
# Copyright (C) 2013 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################
"""
Unit tests for bayespy.utils.linalg module.
"""
import numpy as n... | nilq/baby-python | python |
# Taken from https://github.com/ojroques/garbled-circuit
import json
# HELPER FUNCTIONS
def parse_json(json_path):
with open(json_path) as json_file:
return json.load(json_file)
| nilq/baby-python | python |
"""Support the binary sensors of a BloomSky weather station."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA,
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.const import CONF_MONITORED_CONDITIONS
from ho... | nilq/baby-python | python |
import pygame
from buttons.image_button import ImageButton
class CardComponent:
def __init__(self, screen, x, y, suit, value):
self.flipped = False
self.value = value
self.suit = suit
card_image = f"assets/{value}_{suit}.png"
self.card = ImageButton(screen, x, y, card_imag... | nilq/baby-python | python |
import os
import time
import torch
import argparse
import torchvision
import torch.nn as nn
import torch.utils.data
import torch.optim as optim
import torchvision.transforms as transforms
from utils.function import *
from model.SE import SEresnet, loss_fn_kd
from torch.optim import lr_scheduler
from torch.utils.data ... | nilq/baby-python | python |
# Parent Class
class Shape:
sname = "Shape"
def getName(self):
return self.sname
# child class
class XShape(Shape):
# initializer
def __init__(self, name):
self.xsname = name
def getName(self): # overriden method
return (super().getName() + ", " + self.xsname)
circle =... | nilq/baby-python | python |
# encoding: utf8
from __future__ import print_function, unicode_literals
from io import BytesIO
import re
from unicodedata import combining, normalize
from aspen.resources.pagination import parse_specline, split_and_escape
from aspen.utils import utcnow
from babel.core import LOCALE_ALIASES
from babel.dates import fo... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
from vissl.utils.hydra_config import compose_hydra_configuration, convert_to_attrdict
from vissl.utils.test_utils import (
... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding:utf-8
def fib(n):
yield 0
x, y = 0, 1
yield x
for i in range(n-1):
x, y = y, x + y
yield x
'''
fib() 可以简化
简化 1
def fib(n):
x, y = 0, 1
for i in range(n):
yield x
x, y = y, x + y
简化 2
def fib(n):
x, y = 0, 1
for i in range(... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import tensorflow as tf
import keras as keras
def print_elapsed_time(total_time):
''' Prints elapsed time in hh:mm:ss format
'''
hh = int(total_time / 3600)
mm = int((total_time % 3600) / 60)
ss = int((total_time % 3600) % 60)
print(
"\n** Total Elapsed ... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
import re
import sys
import gzip
import pysam
#import itertools
import mimetypes
from collections import OrderedDict #,defaultdict
class VCF(object):
"""docstring for VCF"""
def __init__(self,
input,
output=None,
popu... | nilq/baby-python | python |
"""
Создать класс Car. Атрибуты: марка, модель, год выпуска, скорость (по умолчанию 0).
Методы: увеличить скорости (скорость +5), уменьшение скорости (скорость -5),
стоп (сброс скорости на 0), отображение скорости, задния ход (изменение знака скорости).
"""
class Car:
def __init__(self, brand, model, year, speed)... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import importlib
import itertools
from string import Formatter
from adapt.intent import IntentBuilder
from adapt.engine import DomainIntentDeterminationEngine
from padatious import IntentContainer
from padatious.util import expand_parentheses
clas... | nilq/baby-python | python |
"""
This is companion code to Project 4 for CSEP576au21
(https://courses.cs.washington.edu/courses/csep576/21au/)
Instructor: Vitaly Ablavsky
"""
# ======================================================================
# Copyright 2021 Vitaly Ablavsky https://corvidim.net/ablavsky/
#
# Permission is hereby granted, f... | nilq/baby-python | python |
# Mikaela Uy (mikacuy@cs.stanford.edu)
import argparse
import os
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import datetime
import time
import sys
import importlib
import shutil
import numpy as np
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR) # model... | nilq/baby-python | python |
# Generated by Django 3.0.4 on 2020-04-22 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tutors', '0007_auto_20200416_1433'),
]
operations = [
migrations.AddField(
model_name='postanad',
name='views',
... | nilq/baby-python | python |
import configparser
import os
config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), '../config.ini'))
STEAM_ACCOUNT = config['steam']['account_name']
STEAM_PASSWORD = config['steam']['password']
driver_path = config['selenium']['driver_path'] if config['selenium']['driver_path'].st... | nilq/baby-python | python |
# Author: Guilherme Aldeia
# Contact: guilherme.aldeia@ufabc.edu.br
# Version: 1.0.0
# Last modified: 05-29-2021 by Guilherme Aldeia
r"""Interaction Transformation Evolutionary Algorithm for **regression**
This sub-module implements a specialization of the base classes ``BaseITEA``
and ``BaseITExpr`` to be... | nilq/baby-python | python |
from Tkinter import *
from tkMessageBox import *
def komunikaty():
if askyesno('Podaj odpowiedz!', u'Czy wiesz co robisz?'):
showwarning('Tak', u'Jak widze wiesz co robisz.')
else:
showinfo('Nie', 'Nie przejmuj sie, nie ty jeden.')
Button(text=u'Koniec', command=komunikaty).pack(fill=X)
Button(text=u'Blad',
co... | nilq/baby-python | python |
import json
from typing import TYPE_CHECKING
from django.urls import reverse
from telegram import Bot as TelegramBot, Update
from telegram.ext import Updater
from ..dispatcher.setup import setup_dispatcher
if TYPE_CHECKING:
from django.http import HttpRequest
from telegram.ext import Dispatcher
from ..mo... | nilq/baby-python | python |
import os
import xml.etree.ElementTree as ET
from shutil import copyfile
import paths
def get_all_laws():
counter=0
wrd = "".join(os.getcwd())
laws_dir=wrd+"\\akn"
for root,subFolder,files in os.walk(wrd):
for item in files:
if(item.endswith("main.xml")):
dst = wrd +... | nilq/baby-python | 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 ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | nilq/baby-python | python |
from typing import Union, List, Tuple, Callable, Dict, Optional
import numpy as np
from medsearch.models.base import TorchModelBase
from medsearch.models.utils import cosine_similarity
from medsearch.datasets.dataset import SemanticCorpusDataset
from sentence_transformers import SentenceTransformer
class SentenceTran... | nilq/baby-python | python |
from itertools import product
import numpy as np
from astropy import units as u
from astropy.io import fits
from astropy.table import Table
from astropy.visualization import quantity_support
from scipy.ndimage.measurements import label as ndi_label
from gammapy.extern.skimage import block_reduce
from gammapy.utils.inte... | nilq/baby-python | python |
from .shi import Shi
from .ni import Ni
from .mi import Mi
from .i import I
from ._diacritic import Ji
__all__ = [
"Shi",
"Ni",
"Mi",
"I",
"Ji",
]
| nilq/baby-python | python |
from fido2.ctap1 import ApduError
from yubikit.core import TRANSPORT
from yubikit.management import CAPABILITY
from yubikit.core.smartcard import SW
from ykman.fido import fips_change_pin, fips_verify_pin, fips_reset, is_in_fips_mode
from . import condition
import pytest
@pytest.fixture(autouse=True)
@condition.fips... | nilq/baby-python | python |
import random
from utils import cosine_distance
import numpy as np
class IterativeCondensedNN:
def __init__(self):
self.y_index = {}
def fit(self, X_train,y):
for idx, observation in enumerate(X_train):
self.y_index[observation.tostring()] = idx
samples = []
_r... | nilq/baby-python | python |
import autograd.numpy as np
from autograd.scipy.special import gammaln
def sigmoid(a):
return 1. / (1. + np.exp(-a))
def logit(a):
return np.log(a) - np.log(1-a)
def mvn_diag_logpdf(x, mean, log_std):
D = len(mean)
qterm = -.5 * np.sum((x - mean)**2 / np.exp(2.*log_std), axis=1)
coef = -.5*D *... | nilq/baby-python | python |
from bs4 import BeautifulSoup
import urllib.request
import csv
web_page = urllib.request.urlopen('https://en.wikipedia.org/wiki/List_of_Super_Bowl_champions')
soup = BeautifulSoup(web_page, "html.parser")
super_bowl_table = soup.find_all('table', {'class': 'wikitable'})[1]
in_file = open("result.csv", 'w')
csv_writer... | nilq/baby-python | python |
import factory
from app.utils import db
from app.models.category import Category
from factories.department_factory import DepartmentFactory
class CategoryFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = Category
sqlalchemy_session = db.session
category_id = factory.Sequenc... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.