content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/python
import heat as h
dir='trace-azure-globe-6dc-24h-202005170045-202005180045'
src_dc_l = ['eastus2']
dst_dc_l = ['westus2', 'francecentral', 'australiaeast']
for src in src_dc_l:
for dst in dst_dc_l:
if dst is src:
continue
df=dir+'/' + src+'-'+dst+'.log.txt'
print df
##h.lat_he... | nilq/baby-python | python |
# Time: O(s*t) # for every node in s, you traverse every node in t.
# Space: O(s) # number of nodes in s
# Mar 30th '20
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubtree(s... | nilq/baby-python | python |
#!/usr/bin/python
# coding=utf-8
import logging
import itertools
import rdflib
# Import NameSpace RDF
from rdflib.namespace import RDF
from rdflib import Literal
# Import Namespace class for create new RDF Graph
from rdflib import Namespace
logging.basicConfig()
rdf = rdflib.Graph()
rdf.load("data.owl")
FOAF = Na... | nilq/baby-python | python |
import django
from ..base import *
from ..i18n import *
from .services import *
from ..static import *
django.setup() | nilq/baby-python | python |
import os
import json
import StringIO
import shapely
from shapely.geometry import shape, mapping
from flask import Flask, request, send_file, jsonify, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['js', 'json', 'geojson'])
app = Flask(__name__)
def allowed_file(filename):
ret... | nilq/baby-python | python |
'''
Author: Hanqing Zhu(hqzhu@utexas.edu)
Date: 2022-04-07 10:38:34
LastEditTime: 2022-04-08 23:57:19
LastEditors: Hanqing Zhu(hqzhu@utexas.edu)
Description:
FilePath: /projects/ELight/core/models/__init__.py
'''
from .vgg import * | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from datetime import datetime
#from suit.widgets import SuitDateWidget, SuitTimeWidget, SuitSplitDateTimeWidget
#from .models import PrintTask
class TaskForm(forms.ModelForm):
... | nilq/baby-python | python |
from __future__ import absolute_import
import warnings
from django.template import loader
from django.utils import six
from .. import compat
from . import filterset, filters
class DjangoFilterBackend(object):
default_filter_set = filterset.FilterSet
@property
def template(self):
if compat.is_c... | nilq/baby-python | python |
from .rawheader import HeaderFactory, LAS_FILE_SIGNATURE
| nilq/baby-python | python |
testinfra_hosts = ["ansible://mariadb-centos7"]
def test_mariadb_el7_config(host):
innodb7 = host.file('/etc/my.cnf.d/innodb.cnf')
assert not innodb7.contains('innodb_large_prefix=1')
testinfra_hosts = ["ansible://mariadb-centos8"]
def test_mariadb_el8_config(host):
innodb8 = host.file('/etc/my.cnf.d/... | nilq/baby-python | python |
import requests
from .okra_base import OkraBase
from .utils import validate_id, validate_dates, validate_date_id
class Balance(OkraBase):
""" This handles all balance requests to the okra API. This contains the following functions.\n
Key functions:
get_balances -- This returns the realtime balance for e... | nilq/baby-python | python |
# Import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from warmUpExercise import warmUpExercise
from computeCost import computeCost
from gradientDescent import gradientDescent
from plotData import plotData
# Machine Learning Online Class - Exercise 1:... | nilq/baby-python | python |
# Generate the randomized beta map for further testing changes of prediction accuracy and discrimination
from os.path import join as pjoin
import cifti
import numpy as np
from ATT.iofunc import iofiles
def randomize_ROI(rawdata, mask=None):
"""
Randomize the averaged data in ROI that defined by the mask
i... | nilq/baby-python | python |
from discord.ext import commands
from .formats import plural
class StringMaxLengthConverter(commands.Converter):
"""A converter that only accepts strings under a certain length."""
def __init__(self, length):
super().__init__()
self.length = length
async def convert(self, ctx, arg):
... | nilq/baby-python | python |
# Generated by Django 3.1.8 on 2021-06-08 17:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sections', '0003_delete_techstack'),
]
operations = [
migrations.CreateModel(
name='TechStack',... | nilq/baby-python | python |
import cv2 as cv
import numpy as np
import numpy.ma as ma
import scipy.interpolate
from scipy.interpolate import Akima1DInterpolator
def findTransform(fn):
pattern_size = (15,8)
trg_img_size = (1920, 1080)
scale_fact = 10 # to speed up calculations
print('processing %s... ' % fn)
orig = cv.... | nilq/baby-python | python |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
import random
import time
try:
import thread
except ImportError:
import _thread as thread
import board
import neopixel
from gpiozero import Button
import json
import requests
import websocket
pixels = neopixel.NeoPixel(board.D18, 60+13, auto_write=False)
#0-60:tape, 6... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 o... | nilq/baby-python | python |
"""Elabore um programa que calcule o valor a ser pago por um produto,
considerando o seu preço normal e condição de pagamento:
- a vista dinheiro/cheque: 10% de desconto
- em até 2x no cartão: preco normal
- 3x ou mais no cartão: 20% de juros
"""
import time
print('========== Calculando Valores de Um Produto ==========... | nilq/baby-python | python |
from django.contrib.gis import admin
from vida.vida.models import Person, Shelter, Track, Form, Report, Note, Profile
import uuid
import helpers
from django.conf import settings
class VidaAdmin(admin.OSMGeoAdmin):
openlayers_url = settings.STATIC_URL + 'openlayers/OpenLayers.js'
class NoteInline(admin.StackedIn... | nilq/baby-python | python |
# 혁진이의 프로그램 검증
# DFS를 이용한 풀이
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV4yLUiKDUoDFAUx&categoryId=AV4yLUiKDUoDFAUx&categoryType=CODE
import sys
sys.setrecursionlimit(10**9)
def dfs(x, y, dir, cur):
global r, c
stat=False
rot=False
if cmd[x][y]=='>':
dir=... | nilq/baby-python | python |
def add():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x+y
print("Your final result is: ", z)
def multiply():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x*y
print("Your final result is: ", z)
def factorial():
a=int(input())
f=1
if(a>1):
fo... | nilq/baby-python | python |
from typing import NewType
from pydantic import SecretStr
from mirumon.api.api_model import APIModel
SharedKey = NewType("SharedKey", SecretStr)
class CreateDeviceBySharedKeyRequest(APIModel):
name: str
shared_key: SharedKey
| nilq/baby-python | python |
# Flask imports
from flask import Blueprint, render_template
errors_blueprint = Blueprint('errors_blueprint', __name__)
@errors_blueprint.app_errorhandler(404)
def page_not_found(error):
return render_template('error_pages/404.html'), 404
@errors_blueprint.app_errorhandler(500)
def internal_server_error(error):... | nilq/baby-python | python |
"""empty message
Revision ID: e47fb2d3a756
Revises:
Create Date: 2017-06-30 17:30:56.066364
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e47fb2d3a756'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | nilq/baby-python | python |
from __future__ import division
from operator import attrgetter
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.lib import... | nilq/baby-python | python |
import torch
from torch.utils.data import DataLoader, Dataset
import numpy as np
from librosa.util import find_files
from torchaudio import load
from torch import nn
import os
import re
import random
import pickle
import torchaudio
import sys
import time
import glob
import tqdm
from pathlib import Path
CACHE_PATH = ... | nilq/baby-python | python |
"""
A component which allows you to send data to an Influx database.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/influxdb/
"""
import logging
import voluptuous as vol
from homeassistant.const import (
EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STA... | nilq/baby-python | python |
# Generated by Django 3.1.7 on 2021-03-07 16:44
from django.db import migrations
import django_enumfield.db.fields
import events.models
class Migration(migrations.Migration):
dependencies = [
('events', '0047_participant_date_of_birth'),
]
operations = [
migrations.AlterField(
... | nilq/baby-python | python |
import warnings
import numpy as np
import torch
import torch.nn.functional as F
from sklearn import metrics
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from tqdm import tqdm
from datasets.bert_processors.abstract_processor import convert_examples_to_features
from utils.preprocessing impo... | nilq/baby-python | python |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
path('', views.events_home, name='events_home'),
# Events urls.
path('eventos/', views.events_list, name='event_list'),
path('eventos/<pk>/configuracion/', views.... | nilq/baby-python | python |
from ipykernel.comm import Comm
from varname import nameof
import inspect
# import threading
from multiprocessing import Process
from .mwserver import run_server, run_server_from_id
import uuid
import subprocess
import threading
# jupyter notebook --ip='*' --NotebookApp.token='' --NotebookApp.iopub_data_rate_l... | nilq/baby-python | python |
import sys, os, collections, copy
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
data_fn = 'data/WikiQA-train.tsv'
X = pd.read_csv(data_fn, sep='\t', header=0, dtype=str, skiprows=None, na_values='?', keep_default_na=False)
| nilq/baby-python | python |
# -*- coding:utf-8 -*-
'''!
@file interrupt.py
@brief Interrupt detection of free fall, an interrupt signal will be generated in int1 once a free fall event occurs.
@n When a free-fall motion is detected, it will be printed on the serial port.
@n When using SPI, chip select pin can be modified by changing ... | nilq/baby-python | python |
from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token
from . import views
from .views import RegisterUsernameCountAPIView, UserCenterInfoAPIView, UserEmailInfoAPIView,UserEmailVerificationAPIView, \
AddressViewSet
urlpatterns = [
url(r'^usernames/(?P<username>\w{5,20})/count/$... | nilq/baby-python | python |
## Plotting functions
# Imports
import math
import matplotlib.pyplot as plot
import pandas
import seaborn
from evolve_soft_2d import file_paths
################################################################################
def histogram(
template,
tm: str,
data: list,
t: str,
y: str,
x:... | nilq/baby-python | python |
from .box_colombia import BoxColombia
from .box_daily_square import BoxDailySquare
from .box_don_juan import BoxDonJuan
from .box_don_juan_usd import BoxDonJuanUSD
from .box_office import BoxOffice
from .box_partner import BoxPartner
from .box_provisioning import BoxProvisioning
| nilq/baby-python | python |
from mintools import ormin
class Chaininfo(ormin.Model):
bestblockhash = ormin.StringField()
blocks = ormin.IntField()
mediantime = ormin.IntField()
class Block(ormin.Model):
height = ormin.IntField(index=True)
blob = ormin.TextField()
class Tx(ormin.Model):
blockhash = ormin.StringField(ind... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Simple OSC client."""
import socket
try:
from ustruct import pack
except ImportError:
from struct import pack
from uosc.common import Bundle, to_frac
if isinstance("", bytes):
have_bytes = False
unicodetype = unicode # noqa
else:
have_bytes = True
... | nilq/baby-python | python |
# Copyright (c) 2018 Robin Jarry
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distrib... | nilq/baby-python | python |
import sys
import re
from setuptools.command.test import test as TestCommand
from setuptools import setup
from setuptools import find_packages
metadata = dict(
re.findall("__([a-z]+)__ = '([^']+)'", open('consul/__init__.py').read()))
requirements = [
x.strip() for x
in open('requirements.txt').readlin... | nilq/baby-python | python |
import uuid
from app.api.models.namespaces import NamespacePrimaryKey, NamespaceSchema, NamespaceResources, NamespacePrimaryKeyProjectID
from app.db import namespaces, database
async def post(payload: NamespaceSchema):
query = namespaces.insert().values(payload.dict())
return await database.execute(query=que... | 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 |
import logging
from webapp2_extras.auth import InvalidAuthIdError, InvalidPasswordError
from authentication import BaseHandler
from authentication import app
@app.route('/login', 'login')
class LoginHandler(BaseHandler):
def get(self):
self._serve_page()
def post(self):
username = self.requ... | nilq/baby-python | python |
import random
class Dealer:
'''
Represents the dealer in the game.
Responsible for drawing a card and showing it.
Responsible for showing the current card.
Attributes: last_card, current_card
'''
def __init__(self):
#Initializes the last card and sets current card equal to it
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from twitter import updater
from selenium import webdriver
from selenium.webdriver.common.k... | nilq/baby-python | python |
import cv2
import numpy as np
from sklearn.metrics import mutual_info_score
import time
from tkinter import Tk
from tkinter.filedialog import askopenfilename
start_time = time.time()
detector = cv2.ORB_create()
Tk().withdraw()
path1 = askopenfilename(initialdir = "E:\Research\Datasets\MVS",
fi... | nilq/baby-python | python |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Geant4(CMakePackage):
"""Geant4 is a toolkit for the simulation of the passage of particl... | nilq/baby-python | python |
# import_export_ballotpedia/views_admin.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .controllers import attach_ballotpedia_election_by_district_from_api, \
retrieve_ballot_items_for_one_voter_api_v4, \
retrieve_ballot_items_from_polling_location, retrieve_ballot_items_from_polling_loc... | nilq/baby-python | python |
from django.contrib import admin
from . import models
admin.site.site_header = 'FAIR Data Management'
class BaseAdmin(admin.ModelAdmin):
"""
Base model for admin views.
"""
readonly_fields = ('updated_by', 'last_updated')
list_display = ('last_updated',)
def save_model(self, request, obj, f... | nilq/baby-python | python |
#!/usr/bin/env python
from I3Tray import *
from os.path import expandvars
from icecube import icetray,dataclasses,dataio,phys_services
amageofile = expandvars("$I3_SRC/phys-services/resources/amanda.geo")
icecubegeofile = expandvars("$I3_SRC/phys-services/resources/icecube.geo")
tray = I3Tray()
tray.AddModule("I3Inf... | nilq/baby-python | python |
import pytest
import numpy as np
from mcalf.utils.smooth import moving_average, gaussian_kern_3d, smooth_cube, mask_classifications
from ..helpers import class_map
def test_moving_average():
x = np.array([0.4, 1.2, 5.4, 8, 1.47532, 23.42, 63, 21, 14.75, 6, 2.64, 0.142])
res = moving_average(x, 2)
asser... | nilq/baby-python | python |
def Validate(num, tar):
v = 0
while num>0:
v += num
num //= 10
return v == tar
if __name__ == '__main__':
s = input()
digits = len(s)
s = int(s)
chushu = 1
chenshu = 1
for i in range(digits-1):
chenshu*=10
chushu = chushu*10+1
success = False
... | nilq/baby-python | python |
import urllib,json
def btc_alarm():
VOL_BUY=20
VOL_DIFF=100
url = "https://api.bitfinex.com/v1/trades/btcusd?limit_trades=500"
trades=json.loads(urllib.urlopen(url).read())
past_time=trades[0]['timestamp']-5*60
buy_volume=[float(trade['amount']) for trade in trades if trade['type']=='buy' and... | nilq/baby-python | python |
from manim_imports_ext import *
class KmpPrefixScene(AlgoScene):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.data = "cbccbcbccb"
def compute_prefix_function(self):
t = self.data
n = len(t)
prefix = np.zeros(n, dtype=int)
prefix[0] = ... | 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... | nilq/baby-python | python |
from itertools import permutations
class Solution:
def getProbability(self, balls: List[int]) -> float:
setOfBalls = []
currentBall = 1
for b in balls:
setOfBalls.extend([currentBall] * b)
currentBall += 1
equal = 0
total = 0
for choice in... | nilq/baby-python | python |
from .item import get_basket_item_model
from .basket import get_basket_model, BaseBasket
from ..settings import basket_settings
if basket_settings.is_dynamic:
from .item import DynamicBasketItem
| nilq/baby-python | python |
import pandas as pd
import plotly.express as px
prices = pd.read_csv("prices_history.csv", index_col=0)
prices.index = pd.to_datetime(prices.index, unit="s")
prices_change = prices / prices.mean()
print(prices_change)
prices_total_change = (prices_change.iloc[-1][:] - prices_change.iloc[0][:]) * 100
print(prices_total... | nilq/baby-python | python |
from bitresource import resource_registry
from http_resource import HttpResource
@resource_registry.register()
class KrakenHttpResource(HttpResource):
name = 'kraken'
endpoint_url = 'https://api.kraken.com/0/public/'
CurrencyResource = KrakenHttpResource('Assets')
MarketResource = KrakenHttpResource('Asset... | nilq/baby-python | python |
from spidriver import SPIDriver
s = SPIDriver("/dev/ttyUSB0") # change for your port
s.sel() # start command
s.write([0x9f]) # command 9F is READ JEDEC ID
print(list(s.read(3))) # read next 3 bytes
s.unsel() # end command
| nilq/baby-python | python |
'''
Which stocks move together?
In the previous exercise, you clustered companies by their daily stock price movements. So which company have stock prices that tend to change in the same way? You'll now inspect the cluster labels from your clustering to find out.
Your solution to the previous exercise has already bee... | nilq/baby-python | python |
'''
Made By Sai Harsha Kottapalli
Tested on python3
About : SSH Command
Use : make a connection to SSH server and run a command
'''
import sys
import paramiko
import subprocess
import argparse
def command(ip_addr,username,pwd,cmd):
client = paramiko.SSHClient()
#can use keys for authentication
#client.load_h... | nilq/baby-python | python |
from PySide2.QtCore import QAbstractItemModel, QModelIndex, Qt
from hexrd.ui.tree_views.tree_item import TreeItem
KEY_COL = 0
class BaseTreeItemModel(QAbstractItemModel):
KEY_COL = KEY_COL
def columnCount(self, parent):
return self.root_item.column_count()
def headerData(self, section, orient... | nilq/baby-python | python |
#!/usr/bin/env python3
"""Tests that all evidence codes seen in NCBI's gene2go have description."""
from __future__ import print_function
__copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import os
from goatools.associations import dnld_ncbi_gene... | nilq/baby-python | python |
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2018 Datadog, Inc.
import copy
import traceback
import re
import logging
import unicodedata
from aggreg... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from parglare import GLRParser, Grammar, Parser, ParseError
from parglare.exceptions import SRConflicts
def test_lr2_grammar():
grammar = """
Model: Prods EOF;
Prods: Prod | Prods Prod;
Prod: ID "=" ProdRefs;
ProdRefs: ... | nilq/baby-python | python |
from hatano.errors import HatanoError
import boto3
import zipfile
import shutil
import subprocess as sp
import os
import random
import string
import sys
import json
global_conf_file = './hatano_settings.json'
region = boto3.session.Session().region_name
class ZipSrc:
def __init__(self, src, stage):
self... | nilq/baby-python | python |
########################################################
# neweggQuickSearch.py is a script which automates
# automates the process of searching for products
# and returns important information back in a CSV.
# Libraries Used: urllib.request and bs4 (BeautifulSoup)
# neweggQuickSearch.py asks the user to inp... | nilq/baby-python | python |
from django.forms import ModelForm
from workouts.models import WorkoutSession
class WorkoutSessionForm(ModelForm):
class Meta:
model = WorkoutSession
fields = [
'name',
'description',
'location',
'workout_date',
]
| nilq/baby-python | python |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import dash
dash.__version__
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output
import dash_bootstrap_components as dbc
import plotly.io as pio
import os
print(os.getcwd())
df_input_l... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 12 22:57:49 2021
@author: kylei
"""
import matplotlib.pyplot as plt
import time
import numpy as np
import matplotlib as mpl
import copy
# plt.style.use("science")
mpl.rcParams["figure.dpi"] = 300
plt.style.use("ieee")
class GAAP:
def __init__(
self,
... | nilq/baby-python | python |
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | nilq/baby-python | python |
# Kivy stuff
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.properties import ObjectProperty, ListProperty
from kivy.graphics import Color, Ellipse, Line
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.cor... | nilq/baby-python | python |
import scraper.adorama
import scraper.amazon
import scraper.bestbuy
import scraper.bhphotovideo
import scraper.canadacomputers
import scra... | nilq/baby-python | python |
from django.contrib import admin
from django_admin_listfilter_dropdown.filters import RelatedDropdownFilter
from chartofaccountDIT.exportcsv import (
_export_historical_comm_cat_iterator,
_export_historical_exp_cat_iterator,
_export_historical_fco_mapping_iterator,
_export_historical_inter_entity_iter... | nilq/baby-python | python |
# This file is part of nbplot. See LICENSE for details.
import logging
import string
import sys
# Extending string.Template to add the . to the idpattern
# expression and support ${input.xxx}
class StringTemplateWithDot(string.Template):
idpattern = '(?a:[_a-z][._a-z0-9]*)'
class LoggingLevelContext(object):
... | nilq/baby-python | python |
import unittest
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
_my_num = 0
def guess(num):
if _my_num < num:
return -1
elif _my_num > num:
return 1
return 0
class Solution:
def gue... | nilq/baby-python | python |
from .cron import Cron
| nilq/baby-python | python |
"""
This code is based on https://github.com/ekwebb/fNRI which in turn is based on https://github.com/ethanfetaya/NRI
(MIT licence)
"""
import numpy as np
import torch
from torch.utils.data.dataset import TensorDataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.autograd import V... | nilq/baby-python | python |
import yfinance as yf
import datetime as dt
import pandas as pd
from stonklib import returnFinraShortData
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from datetime import date
# start date, end date exclusive
tickerString = "GME"
startDateString = '2021-01-07'
endDateString = '2021-05-1... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-11-19 00:07
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0017_auto_20161119_0005'),
]
operations =... | nilq/baby-python | python |
try:
__PHASEPORTRAIT_MODULE_IMPORTED__
except NameError:
__PHASEPORTRAIT_MODULE_IMPORTED__= False
if not __PHASEPORTRAIT_MODULE_IMPORTED__:
from .RetratoDeFases2D import RetratoDeFases2D
from .RetratoDeFases3D import RetratoDeFases3D
from .Trayectorias3D import Trayectoria3D
from .Trayectorias2... | nilq/baby-python | python |
"""
TimeSeries Datasets
-------------------
"""
try:
# Base classes for training datasets:
from .training_dataset import (
TrainingDataset,
PastCovariatesTrainingDataset,
FutureCovariatesTrainingDataset,
DualCovariatesTrainingDataset,
MixedCovariatesTrainingDataset,
... | nilq/baby-python | python |
__all__ = [
'transformer',
'logistic_regression',
]
from . import logistic_regression
from .transformer import transformer
| nilq/baby-python | python |
########################################
# script for merging all valid pairs files
########################################
import os
import logging
import subprocess
from python_bits.helpers import clean_dir
def merge_validpairs(Configuration, inputs):
"""take inputs and cat into a merged valid ... | nilq/baby-python | python |
from datetime import datetime
from origin_takehome.services.risk_profile import RiskProfileService
def test_calculate_base_score_should_return_3():
profile = {
"age": 35,
"dependents": 1,
"house": {"ownership_status": "wrong"},
"income": 1500,
"marital_status": "married",
... | nilq/baby-python | python |
"""
This file uses the configuration.json in the root folder and
collects all current role assignemnts for each identified sub.
Configuration Settings
subscriptions - List of subscription ID's
principals.roleDirectory - Directory to put assignments in
Outputs all data into
./[principals.roleDirectory]/[... | nilq/baby-python | python |
import logging
from plugin import Plugin
log = logging.getLogger('discord')
class PluginManager:
def __init__(self, mee6):
self.mee6 = mee6
self.db = mee6.db
self.mee6.plugins = []
def load(self, plugin):
log.info('Loading plugin {}.'.format(plugin.__name__))
plugin_i... | nilq/baby-python | python |
from random import random
class Triplet():
def __init__(self, entity_1, relation, entity_2, score = random()):
self.__entity_1 = entity_1
self.__relation = relation
self.__entity_2 = entity_2
self.__score = float(score) # for developing purposes
def __repr__(self):
... | nilq/baby-python | python |
# coding: utf-8
x = stencil(shape=(100,100), step=(2,2))
c1 = eval('pyccel.calculus', 'compute_stencil_uniform', (2, 4, 0.0, 0.25))
c2 = eval('pyccel.calculus', 'compute_stencil_uniform', (2, 4, 0.0, 0.25))
for i1 in range(0, 100):
for i2 in range(0, 100):
for k1 in range(-2, 2+1):
for k2 in ... | nilq/baby-python | python |
import json
import logging
import os
import copy
from pathlib import Path
from urllib.parse import urljoin
from typing import Optional
from gssutils.csvw.mapping import CSVWMapping
from gssutils.csvw.namespaces import URI
from gssutils.utils import pathify
class Cubes:
"""
A class representing multiple data... | nilq/baby-python | python |
from core.abstract.serializers import AbstractSerializer
from core.user.models import User
class UserSerializer(AbstractSerializer):
class Meta:
model = User
# List of all the fields that can be included in a request or a response
fields = ['id', 'username', 'name', 'first_name', 'last_nam... | nilq/baby-python | python |
# 名言
famous_name = 'Albert Einstein'
message = ' once sai,"A person who never made a mistake never tried anything new.'
print(famous_name + message)
| nilq/baby-python | python |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""add secondary contact columns
Revision ID: 555130f0a817
Revises: 44d5969c897b
Create Date: 2015-03-01 13:14:06.935565
"""
# revision identifiers, used by Alembic.
revision = '555130f0a817'
down_revisio... | nilq/baby-python | python |
# =============================================================================
# periscope-ps (blipp)
#
# Copyright (c) 2013-2016, Trustees of Indiana University,
# All rights reserved.
#
# This software may be modified and distributed under the terms of the BSD
# license. See the COPYING file for details.
#
# ... | nilq/baby-python | python |
# coding=utf-8
class CommonDisambiguationError(Exception):
def __init__(self, options):
self.options = options
def __unicode__(self):
return "There are more than one articles for that query"
| nilq/baby-python | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | nilq/baby-python | python |
import os
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['NUMEXPR_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
import sys,argparse
import random
import numpy as np
import math as m
import scipy.optimize as opt
from matplotlib import pyplot as plt
from mpl_toolkits.m... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.