content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
'''Test WAF Access settings'''
#TODO: make so waflz_server only runs once and then can post to it
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import pytest
import subpro... |
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth import login
from django.contrib.auth.views import LoginView
from django.views.generic.edit import FormView
from .fo... |
import unittest
from Solutions import Lesson04
class FrogRiverOneTests(unittest.TestCase):
def test_frog_river_one_example_test_01(self):
x = 5
a = [1, 3, 1, 4, 2, 3, 5, 4]
res = Lesson04.frog_river_one(x, a)
self.assertEqual(6, res)
|
# -*- coding: utf-8 -*-
import logging
from os.path import join as pjoin
import numpy as np
from africanus.constants import minus_two_pi_over_c
from africanus.util.jinja2 import jinja_env
from africanus.rime.phase import PHASE_DELAY_DOCS
from africanus.util.code import memoize_on_key, format_code
from africanus.uti... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: fish.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflecti... |
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from Metadata.models import Metadata
import json
User = get_user_model()
class TestViews(TestCase):
def setUp(self):
self.register_url = reverse('register')
self.login_url = reverse('lo... |
# from api.serializers import UserSerializer
import functools
import operator
from datetime import datetime, timedelta
# Facebook
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
# Twitter
from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter
from api.models imp... |
from flask import Flask
from flask_cors import CORS
import os
from nakiri.routes import index
from nakiri.routes import user
from nakiri.models.db import db, migrate
def create_app():
app = Flask(__name__)
CORS(app)
app.register_blueprint(user.blueprint)
app.register_blueprint(index.blueprint)
... |
# Sorting an array using Selection Sort Technique
from array import *
def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
# Swap the minimum valu... |
import tweepy
import pandas
from collections import Counter
from TwitterSecrets import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
auth_api = tweepy.API(auth)
account_list = ["aguialabs", "wehlersdesign", "LeReveduDogon", "SkagerakDanmark","vanw... |
# Run the below to set up the notebook, you need to have Tensorflow installed for this exercise.
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Input, Dense
from sklearn.metrics import accuracy_score
from sklearn.pre... |
#!/usr/bin/env python
from .pure_market_making import PureMarketMakingStrategy
from .asset_price_delegate import AssetPriceDelegate
from .order_book_asset_price_delegate import OrderBookAssetPriceDelegate
from .api_asset_price_delegate import APIAssetPriceDelegate
__all__ = [
PureMarketMakingStrategy,
AssetPri... |
# ------------------------------------------------------------------------------
# Program: The LDAR Simulator (LDAR-Sim)
# File: LDAR-Sim main
# Purpose: Interface for parameterizing and running LDAR-Sim.
#
# Copyright (C) 2018-2020 Thomas Fox, Mozhou Gao, Thomas Barchyn, Chris Hugenholtz
#
# This prog... |
from .sfd_detector import SFDDetector as FaceDetector
|
from django import forms
class CartForm(forms.Form):
product_id = forms.IntegerField(required=True, widget=forms.HiddenInput())
quantity = forms.IntegerField(
min_value=1, required=True, widget=forms.NumberInput({'class': 'form-control', 'value': 1}))
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import torch
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
from sklearn.model_selection import train_test_split
from .dataset.data_loader import load_dataset
from .models.deepconv... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 15:00:21 2017
Adopted from
https://github.com/SanPen/GridCal/blob/master/UnderDevelopment/GridCal/
gui/GuiFunctions.py
Ing.,Mgr. (MSc.) Jan Cimbálník, PhD.
Biomedical engineering
International Clinical Research Center
St. Anne's University Hosp... |
import unittest
import cupy
from cupy import testing
import cupyx.scipy.special
import numpy
try:
import scipy.special
_scipy_available = True
except ImportError:
_scipy_available = False
@testing.gpu
@testing.with_requires('scipy')
class TestSpecial(unittest.TestCase):
@testing.for_dtypes(['f', '... |
# 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.
# pylint: disable=protected-access
import datetime
import functools
import os
import inspect
import types
import warnings
def Cache(obj):
"""Decorator fo... |
### BEGIN LICENSE ###
### Use of the triage tools and related source code is subject to the terms
### of the license below.
###
### ------------------------------------------------------------------------
### Copyright (C) 2011 Carnegie Mellon University. All Rights Reserved.
### ------------------------------------... |
# Copyright 2017 Google Inc. 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... |
#!/usr/bin/env python
#Takes as input schtats output files,
#one per SMRTcell and graphs them.
#file names are expected to be from the deplex
#script
import sys
from itertools import chain, imap, cycle
from operator import itemgetter
import math
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as pl... |
from __future__ import annotations
from cmath import exp, polar, sqrt
from types import FunctionType
from itertools import dropwhile, zip_longest
from math import comb, factorial, inf, pi
from operator import not_
from typing import Literal, Iterable, Iterator, Protocol, TypeVar, Union
__all__ = ("Polynom",)
T = Typ... |
def mergingLetters(s, t):
#edge cases
mergedStr = ""
firstChar = list(s)
secondChar = list(t)
for i, ele in enumerate(secondChar):
if i < len(firstChar):
mergedStr = mergedStr + firstChar[i]
print('first pointer', firstChar[i], mergedStr)
if i < len(second... |
"""
API implementation for chart.client.utils.
"""
from __future__ import annotations
from typing import Any, Dict, Optional, Union
from . import objects, sessions
async def _request(type, uri, headers, data, output):
session = sessions.Session()
return await session.request(type, uri, headers, data, outpu... |
#!/usr/bin/env python
from networks.imagenet.imagenet_model import ImagenetModel
from tensorflow.keras import applications
class ResNet50(ImagenetModel):
def __init__(self, args):
self.name = f"ResNet-50"
self.model_class = applications.ResNet50
ImagenetModel.__init__(self, args)
class ... |
import io
import os
import json
class ConfigurationFile(object):
def __init__(self, filepath, mod="fill"):
self.filepath = filepath
self.mod = mod
self.content = {}
# create the file if does not exist
if(not os.path.exists(self.filepath)):
print("Creating the fil... |
from unittest.mock import patch
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory
from comment.tests.test_api.test_views import BaseAPITest
from comment.api.permissions import (
IsOwnerOrReadOnly, FlagEnabledPermission, CanChangeFlaggedCommentState, SubscriptionEnabled,
... |
""" Provide a framework for querying the CAST source data
"""
# Generic/Built-in
import os
import logging
# Computation
import pickle
import numpy as np
import pandas as pd
# BAYOTA
from bayota_settings.base import get_source_pickles_dir, get_source_csvs_dir, get_metadata_csvs_dir
from castjeeves.sqltables import S... |
## VM based authorization for docker volumes
# Copyright 2016 VMware, Inc. 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... |
try:
f = open('curruptfile.txt')
# if f.name == 'currupt_file.txt':
# raise Exception
except IOError as e:
print('First!')
except Exception as e:
print('Second')
else:
print(f.read())
f.close()
finally:
print("Executing Finally...")
print('End of program') |
# -*- coding: utf-8 -*-
#
# "Fuel" documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 25 14:02:29 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... |
SAVE_DIR="data/"
PORT="/dev/ttyUSB0"
COMPRESS=70
# leave these default
BAUD_START=115200
BAUD_PEAK=1500000 #1000000
SLEEP_TIME=0.00
WAIT_TIME=20
BOOT_TIME=3 #wait for booting to settle before injecting our kernel
MCU_CODE="mcu-kernel.py"
PROMPT=b'\r\n>>> '
LOG_READ=True
LOG_WRITE=True
|
import json
class UserNotFoundError(Exception):
pass
class InvalidTaskIdError(Exception):
pass
def fetch_task_id(event):
task_id = ''
if 'pathParameters' in event and 'task_id' in event['pathParameters']:
task_id = event['pathParameters']['task_id']
return task_id
else:
... |
import os
import subprocess
from backend.blueprints.spa_api.errors.errors import AuthorizationException
from backend.server_constants import BASE_FOLDER
from backend.utils.checks import is_admin, is_local_dev
try:
import config
update_code = config.update_code
if update_code is None:
update_code =... |
#!/usr/bin/env python
# encoding:utf8
"""
flask 异步demo
"""
|
"""
Created on Sun Apr 5 2020
@author: Ruksana Kabealo, Pranay Methuku, Abirami Senthilvelan, Malay Shah
Class: CSE 5915 - Information Systems
Section: 6pm TR, Spring 2020
Prof: Prof. Jayanti
A Python 3 script to perform the following tasks in order:
1) look at source directory,
2) extract xml annotations
... |
List1 = []
List2 = []
List3 = []
List4 = []
List5 = [13,31,2,19,96]
statusList1 = 0
while statusList1 < 13:
inputList1 = str(input("Masukkan hewan bersayap : "))
statusList1 += 1
List1.append(inputList1)
print()
statusList2 = 0
while statusList2 < 5:
inputList2 = str(input("Masukkan hewan berkaki 2 : ")... |
#!/usr/bin/env python
# coding=utf-8
"""TrainingPreparator engine action.
Use this module to add the project main code.
"""
from .._compatibility import six
from .._logging import get_logger
from marvin_python_toolbox.engine_base import EngineBaseDataHandler
__all__ = ['TrainingPreparator']
logger = get_logger('... |
from __init__ import *
import optparse
import sys
sys.path.insert(0, ROOT+'apps/python/')
from pipe_options import *
def parse_args():
help_str = \
'"new" : from scratch | "existing" : compile and run | "ready" : just run'
parser.add_option('-m', '--mode',
type='choice',
... |
# Day 12 Project: Reading List
# Project details: https://teclado.com/30-days-of-python/python-30-day-12-project/
# Users should be able to add a book to their reading list by providing a book title, an author's name, and a year of publication. The program should store information about all of these books
# in a Pyth... |
from .base import BaseTestCase
from elevate.signals import grant, revoke
from elevate.utils import has_elevated_privileges, grant_elevated_privileges
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out
class SignalsTestCase(BaseTestCase):
def test_gr... |
#!python3
import json
import requests
from pprint import pprint
r = requests.get(
"https://us.api.battle.net/wow/character/Cenarion%20Circle/Ardy?fields=mounts&locale=en_US&apikey="
)
data = json.loads(r.text)
for item in data.items():
print(item)
# Hard to read
for item in data.items():
pprint(item)
... |
from .dispatcher import Dispatcher
from .bot import VkBot
from .updater import Updater
from .objects.vk_obj import Message, Geo, Attachment, Update, VkEventType, VkEvent
from .objects.keyboard import Keyboard, Action
from .handler import Handler, CommandHandler, MessageHandler, State, FsmHandler, BaseHandler
__all__ =... |
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.pad import pad as pad_function
from gdsfactory.port import select_ports_electrical
from gdsfactory.routing.route_quad import route_quad
from gdsfactory.types import ComponentOrFactory
@gf.cell
def add_electrical_pads_shortes... |
import logging
from json import dumps, loads
from random import random
import matplotlib.pyplot as plt
import psycopg2
import seaborn as sns
from django.http import HttpResponse
from django.shortcuts import render
from kafka import KafkaConsumer, KafkaProducer
from .utils import plot_graph
# Create your views here.
... |
import unittest
from datetime import datetime
from decimal import Decimal
from botocore.exceptions import ClientError
import pytest
from _pytest.monkeypatch import MonkeyPatch
from falcano.model import Model
from falcano.attributes import (
UnicodeAttribute,
UTCDateTimeAttribute,
NumberAttribute,
ListAt... |
# Copyright (c) 2019 The Felicia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import felicia_py as fel
import felicia_py.command_line_interface as cli
from felicia.core.protobuf.channel_pb2 import ChannelDef
from felicia... |
num1 = float(input("Numero 1: "))
num2 = float(input("Numero 2: "))
num3 = float(input("Numero 3: "))
numeros = [num1,num2,num3]
lista = sorted(numeros,key=int, reverse=True)
print(lista) |
#! python3
# Chapter 14 Project Fetching Current Weather Data
# Prints the weather data for a location from the command line.
import json
import requests
import sys
if len(sys.argv) < 2:
print('Usage: script.py location')
sys.exit()
location = ' '.join(sys.argv[1:])
url = 'http://api.openweath... |
import pytest
import numpy as np
import toppra.cpp as tac
pytestmark = pytest.mark.skipif(
not tac.bindings_loaded(), reason="c++ bindings not built"
)
@pytest.fixture
def path():
c = np.array([
[-0.500000, -0.500000, 1.500000, 0.500000, 0.000000, 3.000000, 0.000000, 0.000000],
[-0.500000, -0.... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
Counting prime numbers from 0 to 10000000 with help of Apache Spark map-reduce
+ compare time of parallel (Spark-based) vs sequantial calculation
To see parallelism of apache spark you can open 'top' command in separate
terminal while running thi... |
from time import sleep
from random import choice
from fastapi.responses import StreamingResponse
from fastemplate.module import MOCK_FRIDGE, MOCK_CELSIUS_TEMPERATURES
def list_fridge():
"""
List all items in the frigde.
:return: dict with all items and amounts
:rtype: dict
"""
return MOCK_F... |
from tornado.web import HTTPError
from tornado import gen
from biothings.web.api.es.handlers.base_handler import BaseESRequestHandler
from biothings.web.api.es.transform import ScrollIterationDone
from biothings.web.api.es.query import BiothingScrollError, BiothingSearchError
from biothings.web.api.helper import Biothi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
--------------------------------------------------------------------------
OpenMS -- Open-Source Mass Spectrometry
--------------------------------------------------------------------------
Copyright The OpenMS Team -- Eberhard Karls University Tuebin... |
from google.appengine.ext import ndb
class Character(ndb.Model):
species = ndb.StringProperty(required = True)
class Born(ndb.Model):
born_1 = ndb.StringProperty(required = True)
born_2 = ndb.StringProperty(required = True)
born_3 = ndb.StringProperty(required = True)
owner = ndb.KeyProperty(Chara... |
# Copyright David Abrahams 2005. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
import polymorphism2
polymorphism2.test()
|
import logging
from typing import Dict, Tuple, Type, List
import gym
import numpy as np
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_action_dist import (Categorical)
from ray.rllib.models.torch.torch_action_dist import TorchCategorical
from ray.rlli... |
"""
tests.gunicorn.conftest
~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2017 by ConsenSys France.
:license: BSD, see LICENSE for more details.
"""
import os
import pytest
@pytest.fixture(scope='session')
def files_dir(test_dir):
yield os.path.join(test_dir, 'gunicorn', 'files')
@pytest.fixt... |
from tri.delaunay.helpers import ToPointsAndSegments
from grassfire import calc_skel
from simplegeom.wkt import loads
"""Church in Naaldwijk
"""
if True:
import logging
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging... |
def get_provider_info():
return {
"package-name": "airflow_provider_db2",
"name": "DB2 Airflow Provider",
"description": "A custom DB2 provider to implement a conn type that uses ibm_db library, a workaround to use SECURITYMECHANISM parameter to connect to DB2",
"hook-class-names": [... |
import logging
from typing import Optional, Any
from boto3 import client, Session
from b_lambda_layer_common.ssm.fetcher import Fetcher
from b_lambda_layer_common.ssm.refreshable import Refreshable
logger = logging.getLogger(__name__)
class SSMParameter(Refreshable):
"""
SSM Parameter implementation.
"... |
# -*- coding: utf-8 -*-
"""
ARRI ALEXA Wide Gamut Colourspace
=================================
Defines the *ARRI ALEXA Wide Gamut* colourspace:
- :attr:`colour.models.ALEXA_WIDE_GAMUT_COLOURSPACE`.
See Also
--------
`RGB Colourspaces Jupyter Notebook
<http://nbviewer.jupyter.org/github/colour-science/colour-noteb... |
import pytest
# APP Flask Factory
from controller.controller_sql.factory import create_app
# Repo.py Factory para poblar la base de datos test
from repository.repository_sql.models.db_model import db as _db
from repository.repository_sql.repo import Factory
# Importamos también el modelo
from repository.repository_s... |
import numpy as np
np.set_printoptions(edgeitems=30, linewidth=100000)
def part1(lines: list) -> int:
split_index = lines.index("")
sheet_values = lines[:split_index]
values = lines[split_index+1:]
sheet_values_mapped = list(map(lambda x: x.split(","), sheet_values))
# max_x = int(max(sheet_values_... |
# Implementation for MGMA Module.
import torch.nn as nn
import numpy as np
import torch
import copy
import math
class MGMA(nn.Module):
def __init__(self, input_filters, output_filters, mgma_config, freeze_bn=False, temporal_downsample=False, spatial_downsample=False):
super(MGMA, self).__init__()
... |
# Time: O(n)
# Space: O(sqrt(n))
# 1265
# You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface:
# - ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
# You need to use the following functions to access... |
from snowflake_dir.snowflake_connect import SnowflakeConnection
import yaml
from snowflake_dir.data_objects import Stage, Table, File_Format, Pipe, View, Integration
import logging
logger = logging.getLogger(__name__)
class DBModel():
def __init__(self, object_properties):
self.conn = SnowflakeConnection(... |
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from post.models import Follow
# Create your models here.
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.forma... |
# Generated by Django 3.0.5 on 2020-11-28 15:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cole', '0008_alumne_to_many'),
]
operations = [
migrations.AlterModelOptions(
name='alumne',
options={'ordering': ['num_llis... |
from .wth_file import WTHFile
|
#PROBLEM NUMBER 03
import math
from sympy.ntheory import factorint
def isprime(n):
if n == 2:
return True
if n % 2 == 0 or n <= 1:
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2):
if n % divisor == 0:
return False
return True
def tria... |
"""fixtures for ecommerce tests"""
from collections import namedtuple
from decimal import Decimal
from types import SimpleNamespace
import pytest
# pylint:disable=redefined-outer-name
from ecommerce.api import ValidatedBasket
from ecommerce.factories import (
BasketItemFactory,
CouponEligibilityFactory,
C... |
"""
iaBot
This is the setup.py file that can be used
to build or install the project.
"""
import setuptools
with open("requirements.txt", "r") as fh:
requirements = fh.read().split("\n")
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="iaBot",
version="0.0.7... |
from itertools import product
from base64 import b32encode
from io import BytesIO
from typing import List
from lor_deckcodes.utils import write_varint
from lor_deckcodes.constants import CURRENT_FORMAT_VERSION, faction_mapping
def _encode_card_block(data_stream: BytesIO, cards: List[object]) -> None:
set_faction... |
from base.service import Service
from abc import abstractmethod
from base.option_descriptor import OptionDescriptor
from base.input_program import InputProgram
from base.output import Output
import subprocess
import time
from threading import Thread
class DesktopService(Service):
"""Is a specialization for a Deskt... |
import numpy as np
from copy import deepcopy
from astropy.convolution import Kernel2D, convolve_fft
from astropy.convolution.kernels import _round_up_to_odd_integer
__all__ = ["Pk", "gen_pkfield"]
def Pk(k, alpha=-11.0 / 3, fknee=1):
"""Simple power law formula"""
return (k / fknee) ** alpha
def gen_pkfie... |
# Generated by Django 3.0.11 on 2021-03-24 20:04
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.embeds.blocks
import wagtail.images.blocks
class Migration(migrations.Migration):
dependencie... |
# Always prefer setuptools over distutils
from os import path
from setuptools import setup, find_packages
# io.open is needed for projects that support Python 2.7
# It ensures open() defaults to text mode with universal newlines,
# and accepts an argument to specify the text encoding
# Python 3 only projects can skip t... |
print("HIde module 2") |
# Generated by Django 3.2.3 on 2021-06-22 09:29
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('wanted', '0005_auto_20210622_1821'),
]
operations = [
migrations.AddField(
model_name='quest',... |
#!/usr/bin/env python
import argparse
import multiprocessing
import os
import tempfile
from ferrit import ssh
from ferrit import rest
def main():
key = ssh.KEY
logpath = ssh.LOG_PATH
parser = argparse.ArgumentParser()
parser.add_argument('-k', '--key', default=key,
help='Path ... |
## @package net_builder
# Module caffe2.python.net_builder
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, context
from caffe2.python.task import Task, TaskGroup
from caffe2.python.contr... |
from generate import list
def bubble_sort(l):
for i in range(len(l)):
sorted = True
for j in range(len(l) - i - 1):
if l[j] > l[j + 1]:
sorted = False
l[j], l[j + 1] = l[j + 1], l[j]
if sorted: break
return l
for i in range(100):
test =... |
#! /usr/bin/env python
from __future__ import print_function
import csv
import argparse
import sys
import collections
import numpy
# Parse command line
parser = argparse.ArgumentParser(description='Summarize results')
parser.add_argument('-i', '--infile', metavar='results.tsv', required=True, dest='infile', help='LAM... |
"""
Script that builds whole database.
Set database connection information in file: settings.py
Read about database structure in docs.
Data is scrapped from next two sources:
- http://www.tennis-data.co.uk/alldata.php
- https://github.com/JeffSackmann/tennis_atp
"""
START_YEAR = 2003
END_YEAR = 2015
__author__ = 'ri... |
import enum
import logging
import re
from nameko.dependency_providers import Config
from nameko.rpc import rpc, RpcProxy
from .models import Loc
from .schemas import ChangeSchema, CommentSchema, FunctionSchema, LocSchema
logger = logging.getLogger(__name__)
NEWLINE_RE = re.compile(r'\r\n?|\n')
class Flag(enum.IntF... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.25 on 2019-11-08 12:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprofile', '0001_initial'),
]
operations = [
migrations.AddField(
... |
#!/usr/bin/python
""" producer.py
Produces random data samples for the EQ sliders.
Uses the Hookbox REST api for publishing the data
on channel "chan1".
--- License: MIT ---
Copyright (c) 2010 Hookbox
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... |
#function practice
print("print the last character of my string: ")
def last_char(name):
return name[-1]
print(last_char("Beenash"))
print("function is odd or even: ")
num = int(input("Enter a number: "))
def odd_even(num):
if num%2 == 0:
return "Even Number"
#else:
return "odd NUmber"
print(o... |
import numpy as np
from sklearn.isotonic import IsotonicRegression
from sklearn.utils import check_array, check_consistent_length
class IsotonicRegressionInf(IsotonicRegression):
"""
Sklearn implementation IsotonicRegression throws an error when values are Inf or -Inf when in fact IsotonicRegression
can h... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
import yfinance as yf
yf.pdr_override()
import datetime as dt
# input
symbol = 'AAPL'
start = dt.date.today() - dt.timedelta(days = 365*4)
end = dt.date.today()
# Read data
df = yf.download(symbo... |
def vat_faktura(lista):
suma = sum(lista)
return suma * 0.23
def vat_paragon(lista):
lista_vat = [item * 0.23 for item in lista]
return sum(lista_vat)
zakupy = [0.2, 0.5, 4.59, 6]
print(vat_paragon(zakupy))
print(vat_faktura(zakupy))
print(vat_faktura(zakupy) == vat_paragon(zakupy)) |
from plenum.test import waits
from plenum.test.helper import sdk_send_random_and_check, assertExp
from plenum.test.node_catchup.helper import waitNodeDataEquality
from plenum.test.pool_transactions.helper import sdk_add_new_steward_and_node
from plenum.test.test_node import checkNodesConnected
from stp_core.loop.eventu... |
import unittest
from main import remove_duplicate_words
class TestSum(unittest.TestCase):
def test(self):
self.assertEqual(remove_duplicate_words("alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"), "alpha beta gamma delta")
self.assertEqual(remove_duplicate_words("... |
from typing import Dict, Optional
from code_base.excess_mortality.decode_args import *
from code_base.utils.file_utils import *
from code_base.excess_mortality.url_constants import *
class GetBulkEurostatDataBase(SaveFileMixin):
def __init__(self, eurostat_data: str,
add_current_year: bool = Fal... |
#from django.forms import ModelForm
from .models import *
# ubah bentuk form
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder, Submit
# login and registration form
from django.contrib.auth.forms import UserCreationForm
... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any
class DataProviderError(Exception):
"""Base Exception for Ax DataProviders.
The typ... |
import netifaces
interfaces = netifaces.interfaces()
for i in interfaces:
if i == 'lo':
continue
iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
if iface != None:
for j in iface:
print j['addr']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.