content stringlengths 5 1.05M |
|---|
from django.test import TestCase
from accounts.models import Account
class AccountsModelsTestCase(TestCase):
fixtures = ["tests/test_data/accounts.json"]
def setUp(self):
"""Set up accounts"""
self.user = Account.objects.get(is_superuser=False)
self.superuser = Account.objects.get(is... |
from odata_pretty_printer.odata_tools import pretty_print
def make_result(text):
"""Template for the "result = (...)" value generator
Arguments:
text {str} -- The output from the pretty printer
Returns:
str -- Formatted result ready to be pasted into the test
Example:
prin... |
from abc import abstractmethod
import uuid
import sys
import time
import copy
import logging
from global_config import config_parameters
from util.resources import Resource
from util.s3_utils import S3Helper
class TaskManager(object):
def __init__(self):
self.tasks = {}
self.completed_successfully... |
import numpy as np
def brocher(z, vs):
model = np.zeros([len(z), 5])
for i in range(len(vs)):
vp = (0.9409 + 2.0947 * vs[i] - 0.8206 * vs[i]**2 +
0.2683 * vs[i]**3 - 0.0251 * vs[i]**4)
rho = (1.6612 * vp - 0.4721 * vp**2 + 0.0671 * vp**3
- 0.0043 * vp**4 + 0.000106... |
# By Kirill Snezhko
import requests
from bs4 import BeautifulSoup
import datetime
import re
import smtplib
# Airport Code
# Barcelona GRO
# Wien XWC
# Cologne CGN
# Larnaca LCA
# Milan - Bergamo BGY
# Milan - Centrum XIK
# Munich - Memmingen FMM
#... |
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup
setup(name='pysensu',
version='0.5',
description='Utilities for working with Sensu',
author='K. Daniels',
author_email='[email protected]',
url='https://github.com/kdaniels/pysensu',
packages=['pysensu'],
... |
import json
import logging
import os
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import numpy as np
import os.path as osp
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
JSON_CONTENT_TYPE = 'application/json'
logger = logging.getLogger(__name__)
def m... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-14 04:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event'... |
from devsim import *
print("coordinates")
coordinates=[]
for i in range(0,11):
coordinates.extend([float(i), 0.0, 0.0])
print(coordinates)
print()
print("elements")
elements=[]
for i in range(0,5):
# line type, physical region 0
x=[1, 0, i, i+1]
print(x)
elements.extend(x)
for i in range(5,10):
... |
"""
CUR matrix decompostion based on:
CUR matrix decompositions for improved data analysis
Michael W. Mahoney, Petros Drineas
Proceedings of the National Academy of Sciences Jan 2009, 106 (3) 697-702;
DOI: 10.1073/pnas.0803205106
"""
from gaptrain.log import logger
import numpy as np
from scipy.linalg import svd
def... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from workouts.models import Session
@login_required
def index(request):
# TODO: Filter on user and friends
# TODO: Pagination
sessions = (
Session.objects.all().select_related("workout").order_by("-times... |
from . import calendar
from . import show
from . import videometadata
from .top import cli, main
__all__ = ['cli', 'main', 'calendar', 'show', 'videometadata']
|
from django.test import TestCase
from django.forms.models import model_to_dict
from django.contrib.auth.hashers import check_password
from nose.tools import eq_, ok_
from .factories import UserFactory
from ..serializers import CreateUserSerializer
class TestCreateUserSerializer(TestCase):
def setUp(self):
... |
mysql_config = {
"user":"root",
"password":"g@KgUnHhcYUYu7.",
"host":"192.168.255.128",
"database":"data_speaker",
"port":"33305"
}
vrchat_config = {
"id":"kalraidai",
"password":"tJt!424j=#L27m?",
}
|
'''
##############################################################################
# Copyright 2019 IBM Corp.
#
# 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... |
from cfgparser.packet import Packet
from runner.runner import Runner
from cfgparser.iptables import ParseIPTables
from cfgparser.ipaddrs import ParseIPAddrs
from cfgparser.iproutes import ParseIPRoutes
from cfgparser.ipsets import ParseIPSets
from colorama import init
from prompt_toolkit.completion import WordCompleter... |
"""
Publish/Subscribe tool
@author Paul Woods <[email protected]>
"""
import webapp2
from google.appengine.ext import db
from google.appengine.api import taskqueue
import json
import urllib2
import os
from taskqueue import TaskQueue
class Subscription (db.Model):
event = db.StringProperty()
url = db.S... |
from fixture.db import DbFixture
from fixture.orm import ORMFixture
from fixture.group import Group
# db1 = DbFixture(host="127.0.0.1", name="addressbook", user="root", password="")
#
# try:
# contacts = db1.get_contact_list()
# for contact in contacts:
# print(contact)
# print(len(contacts))
# fin... |
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2009 Doug Hellmann All rights reserved.
#
"""
"""
#end_pymotw_header
import csv
import sys
csv.register_dialect('escaped',
escapechar='\\',
doublequote=False,
quoting=csv.QUOTE_NONE,
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/xtark/ros_ws/src/third_packages/rosbridge_suite/rosbridge_library/msg/Num.msg;/home/xtark/ros_ws/src/third_packages/rosbridge_suite/rosbridge_library/msg/TestChar.msg;/home/xtark/ros_ws/src/third_packages/rosbridge_suite/rosbridge_library/msg/Te... |
import pytest
from unify_idents.engine_parsers.base_parser import BaseParser
def test_uninitialized_parser_compatiblity_is_false():
input_file = (
pytest._test_path / "data" / "test_Creinhardtii_QE_pH11_xtandem_alanine.xml"
)
compat = BaseParser.check_parser_compatibility(input_file)
assert c... |
#!/bin/python3
# -*- coding: utf-8 -*-
import yaml
import json
import sys
import os
import pathlib
from jinja2 import Environment, FileSystemLoader
from pprint import pprint
def ensure_folder(folderTest):
"""[Check if folder exist and create it]
Args:
folderTest (string): [folder to test existance]
... |
#!/usr/bin/env python
import os
import sys
import subprocess
import json
import platform
import argparse
import mmap
import traceback
import ConfigParser
from distutils import dir_util
from utils.space_checker_utils import wget_wrapper
def create_directory(directory):
"""Create parent directories as necessary.
... |
from rrb3 import *
from random import randint
rr = RRB3(8, 6)
i = 0
while True:
speedl = randint(0, 100) / 100.0
speedr = randint(0, 100) / 100.0
dl = randint(0, 1)
dr = randint(0, 1)
rr.set_motors(speedl, dl, speedr, dr)
time.sleep(3)
i += 1
print(i)
|
from flask import Flask
from heapsy import HeapDendrogram
app = Flask(__name__)
class LeakObj(object):
data = 1
leakable = []
@app.route('/leakable')
def leak():
global leakable
leakable.append(LeakObj())
return f'hi {len(leakable)}'
@app.route('/metrics')
def heap_usage():
hd = HeapDendro... |
import numpy as np
import numpy.matlib
from scipy.special import roots_hermite
def sampling(n_samp, dim, randtype = 'Gaussian', distparam = None):
'''
returns a matrix of (n_samp) vectors of dimension (dim)
Each vector is sampled from a distribution determined by (randtype) and (distparam)
@ Params
... |
from mongoengine import Document, fields
from bson import ObjectId
from graphene_mongo_extras.tests.conftest import setup_mongo
class Packaging(Document):
name = fields.StringField()
class Toy(Document):
meta = {'allow_inheritance': True}
id = fields.ObjectIdField(primary_key=True, default=ObjectId)
... |
"""bootstraphistogram
A multi-dimensional histogram. The distribution of the histograms bin values is computed with the Possion bootstrap
re-sampling method. The main class is implemented in :py:class:`bootstraphistogram.BootstrapHistogram`.
Some basic plotting functions are provided in :py:mod:`bootstraphistogram.plo... |
'''
We are making n stone piles! The first pile has n stones. If n is
even, then all piles have an even number of stones. If n is odd, all
piles have an odd number of stones. Each pile must have more stones
than the previous pile but as few as possible. Write a Python
program to find the number of stones in each pile. ... |
# package indicator for spin Graphics
# $Id$
version_maj_number = 1.1
version_min_number = 0
version = "%s.%s" % (version_maj_number, version_min_number)
|
from test import cmd as test_cmd
def test_ls():
_, err = test_cmd('ls .')
assert err is None
if __name__ == '__main__':
test_ls()
|
# **************************************************************************** #
# #
# ::: :::::::: #
# pomodoro_procedure.py :+: :+: :+: ... |
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
import intake
from intake_orc.source import ORCSource
|
from datetime import datetime
from typing import List, Dict
from gateway.schema.customfeedinfo import CustomFeedInfo
class SiteHost:
def __init__(
self,
host: str,
last_seen: datetime = None,
feeds: Dict[str, CustomFeedInfo] = None,
):
self.host = host
self.las... |
import sys
import ConfigParser
import logging
import logging.config
import tweepy
from tweepy.auth import OAuthHandler
from tweepy.streaming import StreamListener, Stream
class twitterManager:
def __init__(self, log ):
self.logger = log
config = ConfigParser.ConfigParser()
config.read("./twitter.confi... |
#!/usr/bin/python
import Queue
class Queuer(object):
def __init__(self, entry_point, should_print):
print 'Crawling %s...' % entry_point
self.unvisited = Queue.Queue()
self.unvisited.put(entry_point.decode('utf-8'))
self.visited = []
self.invalid = []
self.result... |
import commodity_model as commodity
com1=commodity.Commodity(1,20,156,1,'Cigarette')
com1.myprint()
print('\n')
New_ID=2
New_price=21
Incre=100
Decre=1
New_Shelf=2
New_Type='Alcohol'
com1.Change_ID(New_ID)
com1.myprint()
print('\n')
com1.Change_Price(New_price)
com1.myprint()
print('\n')
com1.Ad... |
import pandas as pd
import numpy as np
def export_wind_profile_shapes(heights,
u_wind, v_wind,
output_file=None,
do_scale=True,
ref_height=100.):
"""
From given wind profile return forma... |
from django.contrib import admin
from .models import Designations, Batch
from .models import Faculty, Staff, UndergraduateStudents, MscStudents, PhdStudents, PhdAlumni, Publication
# Register your models here.
admin.site.register(Designations, verbose_name_plural="Designations")
admin.site.register(Faculty, verbose_n... |
"""
Definition of urls for soldajustica.
"""
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'... |
# -*- coding: utf-8 -*-
import logging
from concurrent.futures.thread import ThreadPoolExecutor
from urllib.parse import quote_plus
from lncrawl.core.crawler import Crawler
logger = logging.getLogger(__name__)
search_url = 'https://booknet.com/en/search?q=%s'
get_chapter_url = 'https://booknet.com/reader/get-page'
... |
from typing import Union
class OrExpression:
def __init__(self):
self.and_expression = []
def evaluate(self, bindings: dict) -> bool:
"""
This function evaluates all the and expressions using boolean OR operator
:param bindings:
:return: True or False or the expression itself if there's only one expressi... |
import info
from Package.CMakePackageBase import *
class subinfo(info.infoclass):
def setTargets(self):
self.svnTargets["master"] = "https://invent.kde.org/network/neochat.git"
self.defaultTarget = "master"
self.displayName = "NeoChat"
self.description = "A client for matrix, the ... |
from aat.config import Side
from aat.core import Instrument, OrderBook, Order
from .helpers import _seed
_INSTRUMENT = Instrument("TE.ST")
class TestMarketOrder:
def test_order_book_market_order(self):
ob = OrderBook(_INSTRUMENT)
_seed(ob, _INSTRUMENT)
assert ob.topOfBook()[Side.BUY] =... |
#coding=utf-8
from django.conf.urls import url
from django.views.generic import TemplateView
from app.views.phone.device import index, historical, information_details
from app.views.phone.user import my_information, login, logout, personal,workorder,warning
urlpatterns = [
url(r'index/$', index, name="phone_index")... |
#!/usr/bin/env python
from ciscoconfparse import CiscoConfParse
cisco_cfg = CiscoConfParse("cisco_ipsec.txt")
crypto_maps = cisco_cfg.find_objects_w_child(parentspec=r"^crypto map", childspec=r"pfs group2")
for i in crypto_maps:
print i.text
for child in i.children:
print child.text
|
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
from abc import abstractmethod
class Action:
def __init__(self):
self.condition = None
self.attempt_limit: int = 0
self.time_limit: int = 0
self.start_callback = None
self.finished_callback = None
self.action_id: int = 0
@abstractmethod
def execute(self):
... |
from GNN.globals import *
import math
from GNN.utils import *
from GNN.graph_samplers import *
from GNN.norm_aggr import *
import torch
import scipy.sparse as sp
import scipy
import numpy as np
import time
import hashlib
def _coo_scipy2torch(adj, coalesce=True, use_cuda=False):
"""
convert a sc... |
import gym
import torch
from .QLearning import QLearning
from Gym.tools.utils import env_run
from Gym.tools.atari_wrappers import wrap_env
env = wrap_env(gym.make("PongDeterministic-v4"))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
agent = QLearning(
device=device,
n_actions=env.a... |
# -------------------------------------------------------------------------
# * This is an Java library for random number generation. The use of this
# * library is recommended as a replacement for the Java class Random,
# * particularly in simulation applications where the statistical
# * 'goodness' of the random num... |
#!/usr/bin/env python3
import unittest
import re
import file_utils
class TestFileUtils(unittest.TestCase):
def setUp(self):
# seconds decimal point . followed by 6 digits at end of string
# self.regex_timestamp_end = re.compile(r"\.\d{6}$")
self.regex_timestamp_end = re.compile(r"\d{8}T\... |
# @Author: Brett Andrews <andrews>
# @Date: 2019-05-28 14:05:49
# @Last modified by: andrews
# @Last modified time: 2019-06-20 09:06:65
"""Visualization utilities."""
from pathlib import Path
from astropy.visualization import make_lupton_rgb
from matplotlib import pyplot as plt
import numpy as np
import pandas a... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import numpy as np
from scipy.interpolate import griddata
def calc_psi_norm(R, Z, psi, xpt, axis_mag):
# normalize psi
# psi_interp = Rbf(R, Z, psi)
# psi_min = psi_interp(axis_mag[0], axis_mag[1])
#
# psi_shifted = psi - psi_min # set center to zero... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# pylint: disable=unused-import
"""Ancestry display module constants."""
from app.analysis_results.constants import ANCESTRY_NAME as MODULE_NAME
from app.tool_results.ancestry.constants import MODULE_NAME as TOOL_MODULE_NAME
|
import spotlight
import requests
SPOTLIGHT_URI = "https://api.dbpedia-spotlight.org"
def spotlight_lookup(x, lang='en', conf=0.01):
url = '{}/{}/annotate'.format(SPOTLIGHT_URI, lang)
try:
results = spotlight.annotate(url, x)
matches = []
for result in results:
result = res... |
import multiprocessing
import numpy as np
import os
import pickle
import sys
import time
from FDApy.representation.functional_data import MultivariateFunctionalData
from FDApy.clustering.fcubt import Node, FCUBT
from joblib import Parallel, delayed
from sklearn.metrics import adjusted_rand_score
NUM_CORES = multipro... |
from rest_framework import serializers
from rdmo.conditions.models import Condition
from ..models import OptionSet, Option
from ..validators import OptionSetUniqueKeyValidator, OptionUniquePathValidator
class OptionSetIndexOptionsSerializer(serializers.ModelSerializer):
class Meta:
model = Option
... |
'''初始化'''
from .food import Apple
from .snake import Snake
from .endInterface import endInterface
from .utils import drawGameGrid, showScore |
# Problem: https://www.hackerrank.com/challenges/python-division/problem
# Score: 10
a, b = int(input()), int(input())
print(a // b, a / b, sep='\n')
|
import unittest
from unittest.mock import patch
from mongoengine import connect, disconnect
from spaceone.core.unittest.result import print_data
from spaceone.core.unittest.runner import RichTestRunner
from spaceone.core import config
from spaceone.core import utils
from spaceone.core.model.mongo_model import MongoMod... |
from pioneer.das.api.sensors.sensor import Sensor
from pioneer.das.api.sensors.pixell import Pixell
from pioneer.das.api.sensors.motor_lidar import MotorLidar
from pioneer.das.api.sensors.camera import Camera
from pioneer.das.api.sensors.imu_sbg_ekinox import ImuSbgEkinox
from pioneer.das.api.sensors.encoder import Enc... |
from sqlalchemy import create_engine, Column, Table, ForeignKey, MetaData
from sqlalchemy.orm import relationship # , foreign
from sqlalchemy.ext.declarative import declarative_base # DeclarativeBase
from sqlalchemy import (
Integer, String, Date, DateTime, Float, Boolean, Text)
from scrapy.utils.project import g... |
f_name = input()
f = open(f_name, "r")
text = f.read().split("\n")
f.close()
f = open("out-"+f_name, "w+")
for k, v in enumerate(text):
if k % 2 != 0:
f.write("{}\n".format(v))
f.close()
|
#!/usr/bin/python3
from math import sqrt
def lmapi(*args, **kwargs):
return list(map(int, *args, **kwargs))
def sign(x):
return 0 if x == 0 else x // abs(x)
def test(vx, vy, sx, ex, sy, ey):
x, y = 0, 0
ymax = 0
while True:
x += vx
y += vy
ymax = max(ymax, y)
if s... |
import argparse
import gdown
import os
urls_fns_dict = {
"USPTO_50k": [
("https://drive.google.com/uc?id=1pz-qkfeXzeD_drO9XqZVGmZDSn20CEwr", "src-train.txt"),
("https://drive.google.com/uc?id=1ZmmCJ-9a0nHeQam300NG5i9GJ3k5lnUl", "tgt-train.txt"),
("https://drive.google.com/uc?id=1NqLI3xpy30... |
## run 10 motif split simulation script
import logging
import click
import numpy as np
from pathlib import Path
import torch
from torch import optim
from raptgen import models
from raptgen.models import CNN_Mul_VAE, LSTM_Mul_VAE, CNNLSTM_Mul_VAE
from raptgen.models import CNN_AR_VAE, LSTM_AR_VAE, CNNLSTM_AR_V... |
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.utils.translation import activate
from kirppu.views.accounting import accounting_receipt
class Command(BaseCommand):
help = 'Dump accounting CSV to standard output'
def add_arguments(self, parser):
parser.add_arg... |
# Generated by Django 2.0.3 on 2018-05-15 16:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('queueapp', '0002_related_names'),
]
operations = [
migrations.AddField(
model_name='issue',
name='number_tries',
... |
from styx_msgs.msg import TrafficLight
import rospy
import cv2
import tensorflow as tf
import numpy as np
#import time
import os
from keras.models import Sequential, model_from_json
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from keras.layers.core import Activation
from keras.optimizers import adam... |
# -----------------------------------------------------------------------------
# Autor: Eduardo Yuzo Nakai
#
# Description: A program for Syntax Analysis.
# -----------------------------------------------------------------------------
import ply.yacc as yacc
from lexical import tokens
import sys
from graphviz import ... |
from django.db import models
import random
import os
from django.db.models.signals import pre_save, post_save
from django.urls import reverse
from blazemarketplace.utils import unique_slug_generator
def upload_image_path(instance, filename):
print(instance)
print(filename)
new_filename = random.randint(1... |
n, m = map(int, input().split())
print(int(input()) * int(input()))
|
"""
Serve 'dank', 'random' request from MgClient with ZMQ.
"""
import os
from gensim.models import KeyedVectors
import numpy as np
from collections import OrderedDict
import re
from random import randint
import random
from lxml import objectify
import base64
import json
import threading
import zmq
from .helper import... |
# import biopython
from Bio import SeqIO
from joblib import Parallel, delayed
from tqdm import tqdm
import pathlib
import subprocess
def process(idx: int, id: str, seq: str):
if len(seq) > 1024:
return
folder = "MSA/%04d" % (idx % 1000)
if pathlib.Path(f"{folder}/{id}.a2m").exists():
retur... |
from predict_popularity import predict as P_Predict
from predict_genre import predict as G_Predict
def runPrediction(audioFileName, transcripts):
text = ''
if len(transcripts) > 0:
text = transcripts[0]['text'] or ''
print("I got these transcripts")
print(transcripts)
return {
'hotness': P_Predict(au... |
SECRET_KEY = '123456789'
FEEDLY_DEFAULT_KEYSPACE = 'test'
FEEDLY_CASSANDRA_HOSTS = [
'127.0.0.1', '127.0.0.2', '127.0.0.3'
]
CELERY_ALWAYS_EAGER = True
import djcelery
djcelery.setup_loader()
|
import os
import readline
import paramiko
from lib.connections import *
from lib.autocomplete import *
import configparser
from pathlib import Path
def workspace_ini_creator(config_path, append=False, ws_path=None):
Config = configparser.ConfigParser()
if append:
Config.read(os.path.join(ws_... |
import warnings
from typing import Sequence
import numpy as np
import torch
from .base import Flow
from .inverted import InverseFlow
__all__ = ["SplitFlow", "MergeFlow", "SwapFlow", "CouplingFlow", "WrapFlow", "SetConstantFlow"]
class SplitFlow(Flow):
"""Split the input tensor into multiple output tensors.
... |
from setuptools import setup
with open("pimp/__version__.py") as fh:
version = fh.readlines()[-1].split()[-1].strip("\"'")
setup(
name='PyImp',
version=version,
packages=['pimp', 'pimp.epm', 'pimp.utils', 'pimp.utils.io', 'pimp.evaluator', 'pimp.importance',
'pimp.configspace'],
entr... |
################################################################################
#
# MEASURE input file for acetyl + O2 reaction network
#
################################################################################
title = 'acetyl + oxygen'
description = \
"""
The chemically-activated reaction of acetyl with o... |
from typing import Optional
from pyvisa import ResourceManager
from .scpi.operation import Operation
from .visa_instrument import VisaInstrument
class Instrument(VisaInstrument):
idn = Operation('*IDN?')
def __init__(self, name: str, address: str, read_term: str = '\n', write_term: str = '\n',
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import aiounittest
from unittest.mock import MagicMock
from botbuilder.core import TurnContext, BotState, MemoryStorage, UserState
from botbuilder.core.adapters import TestAdapter
from botbuilder.schema import Activity
from ... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
__title__ = "flask-boilerplate"
__description__ = "Boilerplate for Flask API"
__url__ = "https://github.com/openboilerplates/flask-boilerplate"
__version__ = "1.0.4"
__author__ = "Fakabbir Amin"
__author_email__ = "[email protected]... |
"""
author OW
last reviewed/run 19-04-2020
"""
import matplotlib.pyplot as plt
import numpy as np
from oneibl.one import ONE
import ibllib.plots as iblplt
from brainbox.processing import bincount2D
from brainbox.io import one as bbone
T_BIN = 0.05
D_BIN = 5
# get the data from flatiron and the current folder
one = ... |
#******************************************************************************
# (C) 2018, Stefan Korner, Austria *
# *
# The Space Python Library is free software; you can redistribute it and/or *
... |
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4], dtype=np.uint8)
y = x**2 + 1
plt.plot(x, y)
plt.grid('on')
plt.show()
|
N = int(input())
lst = [int(x)-1 for x in input().strip().split()][::-1]
lst[-2], lst[-1] = lst[-1], lst[-2]
ans = ((1<<N) - 1) * 2
for i in range(N-1, -1, -1):
if lst[2*i] != 2 * i:
if i == 0:
ans += 1
else:
ans += (1<<i) * 2
lst[2*i-2], lst[2*i-1] = lst[2*i-1], lst[2*i-2]
print(ans)
|
#!/usr/bin/env python
""" generated source for module Proposition """
# package: org.ggp.base.util.propnet.architecture.components
import org.ggp.base.util.gdl.grammar.GdlSentence
import org.ggp.base.util.propnet.architecture.Component
#
# * The Proposition class is designed to represent named latches.
#
@Suppres... |
from __future__ import absolute_import
from .data_obs_client import DataObsClient
from .sql_client import SQLClient
__all__ = [
'SQLClient',
'DataObsClient'
]
|
import json
filename = 'names.json'
with open(filename) as f:
username = json.load(f)
print(f"Welcome back {username}! ") |
from .plots import four_plots, three_plots, two_plots, one_plot
def summary(data):
'''
Function to display summaryof the dataframe
Returns: Summary object
Args::
Takes in the dataframe object
'''
print(f'Title: Petrophysical Summary of the Parameters Evaluated')
return da... |
from django_pg import models
class Game(models.Model):
label = models.CharField(max_length=100)
number = models.PositiveIntegerField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Moogle(models.Model):
game = models.ForeignKey(Game)
l... |
"""Define one dimensional geometric entities."""
__author__ = "Daniel Ching, Doga Gursoy"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = [
'Line',
'Segment',
]
import logging
from math import sqrt
import numpy as np
from xdesign.geometry.entity im... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from xgboost import XGBClassifier
from data import load_data_train_test_data, load_test_data, write_accuracy, write_logloss, \
... |
# Generated by Django 2.2.9 on 2021-03-10 21:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0014_auto_20200804_1527'),
]
operations = [
migrations.AddField(
model_name='parametros',
name='especificaco... |
"""
#lookup.py
This file contains all the mappings between hickle/HDF5 metadata and python types.
There are four dictionaries and one set that are populated here:
1) types_dict
types_dict: mapping between python types and dataset creation functions, e.g.
types_dict = {
list: create_listlike_dataset... |
import logging
def assertSimilar(a, b):
if a != b:
raise AssertionError('Assertion failed: Value mismatch: %r (%s) != %r (%s)' % (a, type(a), b, type(b)))
def assertEqual(a, b):
if type(a) == type(b):
assertSimilar(a, b)
else:
raise AssertionError('Assertion failed: Type mismatch %... |
from StatementGame.database import conn, c, d, get_table_id
import StatementGame.question as question
def get_round(rid, game):
d.execute("SELECT * FROM round WHERE round={} AND game={}".format(rid, game))
rs = d.fetchone()
if rs is None:
return new_round(rid, game)
return rs
def new_round(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.