text stringlengths 1 927k |
|---|
import uuid
import botocore
from flask import current_app
from notifications_utils.s3 import s3upload as utils_s3upload
from app.s3_client.s3_logo_client import get_s3_object
FILE_LOCATION_STRUCTURE = 'service-{}-notify/{}.csv'
def get_csv_location(service_id, upload_id, bucket=None):
return (
bucket o... |
from graph import Digraph, Node, WeightedEdge
def load_map(map_filename):
"""
Parses the map file and constructs a directed graph
Assumes:
Each entry in the map file consists of the following four positive
integers, separated by a blank space:
32 76 54 23
This entry wou... |
import json
import os
import shutil
import tempfile
import subprocess
import copy
from unittest import TestCase
from parameterized import parameterized
class TestCliWithHelloWorkflow(TestCase):
HELLO_WORKFLOW_MODULE = "hello_workflow.write_hello"
TEST_WORKFLOWS_FOLDER = os.path.join(os.path.dirname(__file__... |
from .vendor.Qt import QtCore, QtWidgets, QtGui
class AccordionItem(QtWidgets.QGroupBox):
trigger = QtCore.Signal(bool)
def __init__(self, accordion, title, widget):
QtWidgets.QGroupBox.__init__(self, parent=accordion)
# create the layout
layout = QtWidgets.QVBoxLayout()
layo... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import
def get_package_data():
return {'pystrometry.example_subpkg': ['data/*']} |
from muti import genu
import clickhouse_driver
import pandas as pd
from modeling.glm import glm
import numpy as np
import math
def build_model_formula(features_dict: dict, target: str):
"""
Builds the model formula for glm from modeling based on the features_dict specification.
Does not included embedded ... |
# import threading
from pathlib import Path
from multiprocessing.dummy import Pool as ThreadPool
from more_itertools import unique_everseen
import requests, json, datetime
from scripts.byteSize import human_byte_size
# Initialization
Total_Size = 0
Processed_URLs = 0
Progress = 0
Total_URLs = 0
Rate = 0
Re... |
# 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 or agreed to in writing, ... |
#
# Copyright 2018 Joachim Lusiardi
#
# 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 wri... |
"""
API MAPPING
"""
mapping_table = {
# Rest API: Organizations
'list_organizations': {
'path': '/organizations.json',
'method': 'GET',
'status': 200,
},
'show_organization': {
'path': '/organizations/{{organization_id}}.json',
'method': 'GET',
'status':... |
# 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 applicable law or a... |
#!/usr/bin/env python3
"""Pattoo classes that manage various data."""
# Standard imports
import os
import time
# Import project libraries
from pattoo_shared import log, files, converter
from pattoo.configuration import ConfigIngester as Config
from pattoo.constants import PATTOO_API_AGENT_NAME, PATTOO_INGESTER_NAME
... |
"""
The class wrapper for the networks
"""
# Built-in
import os
import time
# Torch
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from torchsummary import summary
# Libs
import numpy as np
# Own module
class Network(object):
def __init__(self, model_fn, flags, train_loader... |
#Forms
#On the web server
import cgi #used to invoke the request
<form action="cgi-bin/process-time.py" method="POST"> Enter a timing value: #action to take and method to envoke for the response, text
<input type="Text" name="TimeValue" size=40> #TimeValue will hold the users input
<br />
<input type="Submit" value="S... |
from wtforms.fields.choices import *
from wtforms.fields.choices import SelectFieldBase
from wtforms.fields.core import Field
from wtforms.fields.core import Flags
from wtforms.fields.core import Label
from wtforms.fields.datetime import *
from wtforms.fields.form import *
from wtforms.fields.list import *
from wtforms... |
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.core.exceptions import ValidationError
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.urls import reverse_lazy, reverse
from django.utils.... |
from .braille_cell import BrailleCell
from .braille_string import BrailleString
class BrailleTranslator(object):
_simple_cells = None
def __init__(self, text):
self.__raw_text = text
if BrailleTranslator._simple_cells is None:
self.__setup_class_simple_cells()
@property
d... |
#!/usr/bin/env python
"""
The documentation builder
It is the starting point for building documentation, and is
responsible to figure out what to build and with which options. The
actual documentation build for each individual document is then done
in a subprocess call to sphinx, see :func:`builder_helper`.
* The bui... |
import math
import os
import sys
import traceback
import discord
from discord.ext import commands
class Errors(commands.Cog):
"""
Error handler
"""
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Error cog loaded successfully... |
import unittest
from userlogin import User
class TestUser(unittest.TestCase):
"""
Test class to define test cases for the User class
Args:
unittest.TestCase: TestCase class creates test cases
""" |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread("imori.jpg").astype(np.float32)
H, W, C = img.shape
# RGB > YCbCr
Y = 0.2990 * img[..., 2] + 0.5870 * img[..., 1] + 0.1140 * img[..., 0]
Cb = -0.1687 * img[..., 2] - 0.3313 * img[..., 1] + 0.5 * img[..., 0] + 128.
Cr = 0.5 * i... |
# -*- coding: utf-8 -*-
#Name: Fractal Example - Exponential Curves
#Author: Sean Pope
#Example use of the fractal engine and coefficient block.
#Creates random coefficient blocks and draws frames to create a simple animation.
#This one is optimized for the exponential variation.
import matplotlib.pyplot as plt
impor... |
import requests
r = requests.get('https://www.baidu.com/')
print(f'status_code:{r.status_code}')
print(f'text:{r.text}')
r = requests.get('https://www.baidu.com/', params={'wd': 'python'})
print(f'url:{r.url}')
print(f'status_code:{r.status_code}')
print(f'text:{r.text}')
print(f'encoding:{r.encoding}') |
#!/usr/bin/env python3
import ethercalc
import argparse
import pprint
import sys
parser = argparse.ArgumentParser(description="Dump ethercalc sheet")
parser.add_argument("sheet", metavar='sheet', help="sheet name")
parser.add_argument("-f", "--format", dest="format",
help="format", default="socialca... |
from drone_squadron.api.base_api import BaseApi
from drone_squadron.crud.thruster_crud import ThrusterCrud
class ThrusterApi(BaseApi):
def __init__(self):
super().__init__(ThrusterCrud) |
from django.utils import timezone
class DurgoMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
start_time = timezone.now()
response = self.get_response(request)
end... |
from DepthFilling import DepthFilling
import cv2
DepthedImg = cv2.imread('../DataSet/Sequence/Warped/depth_0_w.bmp', 0)
DF = DepthFilling.DepthFilling(DepthedImg,63,63)
#depth_filled = DF.testKmeans(DepthedImg)
depth_filled = DF.depthfill()
cv2.imshow('depth', depth_filled)
cv2.imwrite('depthfill_book_0.bmp',depth_... |
"""Test util methods."""
from unittest.mock import MagicMock, patch
import pytest
from openpeerpower.components.recorder import util
from openpeerpower.components.recorder.const import DATA_INSTANCE
from tests.common import get_test_open_peer_power, init_recorder_component
@pytest.fixture
def opp_recorder():
"... |
# 导入必要的模块
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QInputDialog
from PyQt5.QtGui import QImage, QIcon, QPixmap
from PyQt5.QtCore import QTimer, QDateTime, QCoreApplication, QThread
import sys, os
import cv2, imutils
# 导入UI主界面
import main
# 导入信息采集框界面
import infoUI
#... |
import io
import json as _json
import logging
import zlib
from contextlib import contextmanager
from http.client import HTTPMessage as _HttplibHTTPMessage
from http.client import HTTPResponse as _HttplibHTTPResponse
from socket import timeout as SocketTimeout
from typing import (
TYPE_CHECKING,
Any,
Generat... |
from pyglet.window import key
import random
from pygletplus.controller import Controller
class PongController(Controller):
def __init__(self, scene):
super().__init__(scene)
self.keys = scene.keys
self.player = scene.player
self.cpu = scene.cpu
self.ball = scene.ball
... |
"""
WSGI config for greaterwms project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SE... |
from os import getenv, path
from django.core.exceptions import ImproperlyConfigured
DEBUG = True
TEMPLATE_DEBUG = True
USE_TZ = True
USE_L10N = True
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "onfido.db"}}
INSTALLED_APPS = (
"django.contrib.admin",
"django.contrib.auth",
"... |
__METADATA__ = {
"src_name": 'DOCM',
"src_url": 'http://docm.genome.wustl.edu/',
"version": None,
"field": "docm"
}
def load_data():
'''docm data are pre-loaded in our db.'''
raise NotImplementedError
def get_mapping():
mapping = {
"docm": {
"properties": {
... |
from absl import flags
from absl.flags import FLAGS
import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import (
Add,
Concatenate,
Conv2D,
Input,
Lambda,
LeakyReLU,
MaxPool2D,
UpSampling2D,
ZeroPadding2D,
)
from tensorflow.keras.... |
"""
Null Person Table Birth Date Fields
In the person table, the fields month_of_birth, day_of_birth, and birth_datetime should be nulled.
The year_of_birth field should remain unchanged.
Original Issue: DC-1356
"""
# Python imports
import logging
# Project imports
import constants.bq_utils as bq_consts
from cdr_cl... |
import sys
import pysam
idfile, fafile = sys.argv[1:]
fa = pysam.FastaFile(fafile)
with open(idfile) as fh:
for line in fh:
seqid = line.strip()
s = str(fa[seqid])
print(s) |
# 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... |
from datetime import datetime
import logging
import os
import time
from typing import Callable, Tuple, Optional, Sequence
import stopit
from sklearn.base import TransformerMixin, is_classifier
from sklearn.model_selection import ShuffleSplit, cross_validate, check_cv
from sklearn.pipeline import Pipeline
from gama.ut... |
"""
Shortest path algorithms for weighed graphs.
"""
from collections import deque
from heapq import heappush, heappop
from itertools import count
import networkx as nx
from networkx.algorithms.shortest_paths.generic import _build_paths_from_predecessors
__all__ = [
"dijkstra_path",
"dijkstra_path_length",
... |
_base_ = './faster_rcnn_r50_fpn_1x_coco.py'
model = dict(
pretrained='open-mmlab://resnext101_64x4d',
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN... |
from os import path
import autolens as al
"""
This script simulates `Imaging` of a strong lens where:
- The lens `Galaxy`'s total mass distribution is a *SphericalIsothermal*.
- The source `Galaxy`'s `LightProfile` is a *SphericalExponential*.
This dataset is used in chapter 2, tutorials 1-3.
"""
"""
The `dataset... |
from django.contrib.auth.models import User
from django.test import TestCase
from hc.accounts.models import Profile
class TeamAccessMiddlewareTestCase(TestCase):
def test_it_handles_missing_profile(self):
user = User(username="ned", email="ned@example.org")
user.set_password("password")
u... |
#
#------------------------------------------------------------------------------
# Copyright (c) 2013-2017, Christian Therien
#
# 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://ww... |
# 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 __future__ import annotations
import json
import logging
import subprocess
import sys
from pathlib import Path
from typing import fina... |
"""Support for Velux covers."""
from __future__ import annotations
from typing import Any
from pyvlx import OpeningDevice, Position
from pyvlx.opening_device import Awning, Blind, GarageDoor, Gate, RollerShutter, Window
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
Cover... |
"""
Tile real scn/svs files; used by Cutter.py
Created on 11/19/2018
*** Removed imlist storage to minimize memory usage 01/24/2019 ***
@author: RH
"""
from openslide import OpenSlide
import numpy as np
import pandas as pd
import multiprocessing as mp
import staintools
from PIL import Image
# check if a tile is ba... |
"""This module contains functions supporting custom PARMmenu.xml entries."""
# =============================================================================
# IMPORTS
# =============================================================================
# Standard Library
from typing import Dict, List
# Houdini
import hou
... |
# ipop-project
# Copyright 2016, University of Florida
#
# 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, m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import __main__
import json
import os
from ansible.cli.doc import DocCLI
from ansible.playbook import Play
from ansible.playbook.block import Block
from ansible.playbook.role import Role
from ansible.playbook.task im... |
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Training/decoding definition for the speech recognition task."""
import json
import logging
import os
import numpy as np
import torch
from espnet.asr.a... |
import functools
import click
from .. import configs, metadata, versions
def check_installation(version, *, installed=True, on_exit=None):
try:
installation = version.get_installation()
except FileNotFoundError:
if not installed: # Expected to be absent. Return None.
return Non... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class WebsiteRouteRedirect(Document):
pass |
from peewee import *
import json
from datetime import datetime
#set sane default log levels
import logging
logging.getLogger('peewee').setLevel(logging.INFO)
logging.getLogger("peewee.pool").setLevel(logging.DEBUG)
database = SqliteDatabase('detector.db')
class JSONField(TextField):
def db_value(self, value):
... |
# -*- encoding: utf-8 -*-
from .. import db
class EMI_Information(db.Model):
__tablename__ = "EMI_Information"
EMI_Identifier = db.Column(db.String(45),primary_key = True, nullable = False)
ItemName = db.Column(db.String(45), nullable = False)
ProductPrice = db.Column(db.Float, nullable = False)
... |
import cv2
import datetime
import imutils
import numpy as np
from centroidtracker import CentroidTracker
from collections import defaultdict
protopath = "MobileNetSSD_deploy.prototxt"
modelpath = "MobileNetSSD_deploy.caffemodel"
detector = cv2.dnn.readNetFromCaffe(prototxt=protopath, caffeModel=modelpath)
# Only enab... |
#!/usr/bin/env python3
import os
from setuptools import setup, find_packages
def get_version():
from pyxrd.__version import __version__
if __version__.startswith("v"):
__version__ = __version__.replace("v", "")
return "%s" % __version__
def get_install_requires():
return [
'setuptools... |
#! /usr/bin/env python
##############################################################################################################################################
# METHODS
##################################################################################################################################... |
from __future__ import absolute_import, print_function
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import (
encode_dss_signature,
)... |
# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
print """
1
2
weird error
^
3
unknown
""" |
"""
@file
@brief Optimisation of :epkg:`ONNX` graphs.
"""
from onnx.helper import make_graph
from ._onnx_optimisation_common import ( # pylint: disable=E0611
_rename_node_input,
_rename_node_output,
_apply_optimisation_on_graph,
_apply_remove_node_fct_node
)
def onnx_remove_node_identity(onnx_model, ... |
def example_function(first_parameter, second_parameter, third_parameter, fourth_parameter, fifth_parameter):
"""Example function to test the code formatter."""
parameter_sum = first_parameter + second_parameter + third_parameter + fourth_parameter + fifth_parameter
return parameter_sum |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
r"""Minimal Flask application example for development with orcid handler.
SPHINX-STA... |
# Generated by Django 3.2.7 on 2021-11-04 20:13
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='NotesModel',
fields=[
('id', models.BigAuto... |
#!/bin/python3
# Swaps case of all chars in provided string
def swap_case(s):
formattedStr = "".join(map(swapChar, s))
return formattedStr
def swapChar(char):
if char.islower():
return char.upper()
else:
return char.lower()
n=input()
if len(n)==1:
print(swapChar(n))
else:
... |
qte = int(input())
sim = 0
nao = 0
for i in range(qte):
valor = int(input())
if(valor >= 10 and valor <= 20):
sim += 1
else:
nao += 1
print("%d in" %sim)
print("%d out" %nao) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: sunnywalden@gmail.com
import os
from utils.get_logger import Log
def get_fonts_from_local():
log = Log()
logger = log.logger_generate('font_scanner')
# fonts_lists = []
for root, dirs, files in os.walk('../fonts'):
logger.info('File foun... |
import numpy as np
from ..util import slice_
def scnrm2(N, X, INCX):
"""Computes the Euclidean norm of the vector x
Parameters
----------
N : int
Number of elements in input vector
X : numpy.ndarray
A single precision complex array, dimension (1 + (`N` - 1)*abs(`INCX`))
INCX :... |
import logging
import pytest
from ocs_ci.framework.testlib import tier4, tier4a
from ocs_ci.ocs import constants
from ocs_ci.utility import prometheus
from ocs_ci.ocs.ocp import OCP
log = logging.getLogger(__name__)
@tier4
@tier4a
@pytest.mark.polarion_id("OCS-1052")
def test_ceph_manager_stopped(measure_stop_ceph... |
import json
from copy import deepcopy
from pathlib import Path
import pytest
from ..routes import SpecRouter
from ..validator import InvalidJSON, UnsupportedVersion
from ..validator import ihan_standards as ihan
# Note: It's easier to get some 100% valid spec and corrupt it
# instead of having multiple incorrect spe... |
#
# Author: Travis Oliphant 2002-2011 with contributions from
# SciPy Developers 2004-2011
#
from scipy._lib._util import getfullargspec_no_self as _getfullargspec
import sys
import keyword
import re
import types
import warnings
import inspect
from itertools import zip_longest
from collections import namedt... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'example.ui'
#
# Created: Sat May 17 20:31:42 2014
# by: PyQt5 UI code generator 5.2.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(sel... |
"""
File: pipeline_utils.py
Author: Jens Petit
Email: petit.jens@gmail.com
Github: https://github.com/j-petit
Description: Utility functions for filtering models
"""
import re
def createDiffs(model1, model2, filename):
"""Takes two models and creates constraint variables out of their paths.
Parameters
-... |
# Copyright (c) 2020-2021, NVIDIA CORPORATION.
import itertools as it
import random
import numpy as np
import pytest
from pandas import DataFrame, MultiIndex, Series, date_range
import cudf
from cudf import concat
from cudf.tests.utils import assert_eq, assert_exceptions_equal
# TODO: PANDAS 1.0 support
# Revisit d... |
"""Downloads prescribed data from the Internet, embed and store it."""
import logging
import numpy as np
import torch
from experiments.scrap import META_PATH
from mem.gen.stages import Extractor
logger = logging.getLogger(__name__)
MATRIX_PATH = 'matrix.npy'
NEW_META_PATH = 'processed_reddit_data.pth'
def main(_... |
# class node to create a node for the queue linked list
class Node :
def __init__(self, val) :
self.val = val
self.next = None
class Queue :
# contructor of the queue class
def __init__(self) :
self.front = None
self.rear = None
# method to insert an eleme... |
from __future__ import print_function, absolute_import, division
import tensorflow as tf
from tensorflow.contrib import layers
mu = 1.0e-6
@tf.custom_gradient
def f_norm(x):
f2 = tf.square(tf.norm(x, ord='fro', axis=[-2, -1]))
f = tf.sqrt(f2 + mu ** 2) - mu
def grad(dy):
return dy * (x / tf.sqrt... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from turbogears import testutil
from genshitest.controllers import Root
import cherrypy
cherrypy.root = Root()
def test_method():
"the index method should return a string called now"
import types
result = testutil.call(cherrypy.root.index)
assert type(result["now"]) == types.StringType
def test_index... |
#!/usr/bin/env python
# Copyright (c) 2015 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.
"""Parse an LLVM coverage report to generate useable results."""
import argparse
import json
import os
import re
import subproce... |
import os
import unittest
from urllib.parse import urlparse
import pytest
from w3lib.url import (
add_or_replace_parameter,
add_or_replace_parameters,
any_to_uri,
canonicalize_url,
file_uri_to_path,
is_url,
parse_data_uri,
parse_url,
path_to_file_uri,
safe_download_url,
saf... |
#!/usr/bin/python2.7
from Bio import SeqIO
"""
Supplementary Note 4: Read density per gene
Authors: Eugene Oh
Modified by: Johannes Asplund-Samuelsson (KTH)
inputFileP:
read density file for plus strand (Supplementary Note 2)
col0: position along genome
col1: read density at that position
inputFileM:
read... |
import pytest
from aoc_wim.aoc2017.q22 import mutate
test_data = """\
..#
#..
...
"""
@pytest.mark.parametrize("n,expected,part", [
(7, 5, "a"),
(70, 41, "a"),
(10000, 5587, "a"),
(100, 26, "b"),
(10000000, 2511944, "b")
], ids=["a_short", "a_medium", "a_long", "b_medium", "b_long_slow"])
def te... |
from itertools import islice
import numpy as np
from menpo.visualize import print_progress, bytes_str, print_dynamic
def dot_inplace_left(a, b, block_size=1000):
r"""
Inplace dot product for memory efficiency. It computes ``a * b = c``, where
``a`` will be replaced inplace with ``c``.
Parameters
... |
c=1
for i in range(5):
if i==1:
print("*",end="")
for j in range(i):
if c > 1:
for i in range(2,c):
if (c % i) == 0:
print("*",end="")
break
else:
print("#",end="")
c+=1
print() |
#!/bin/env python
from mimDrawer import *
print drawLine([0,0], [1,1], 10) |
import os
import io
import socket
import traceback
from django.conf import settings
import requests
from kombu import Connection
from PIL import Image
import olympia.core.logger
from olympia.amo import search
from olympia.amo.templatetags.jinja_helpers import user_media_path
monitor_log = olympia.core.logger.get... |
# Copyright 2015 FUJITSU LIMITED
#
# 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 writ... |
from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from pili.app import celery, mail
def send_email(to, subject, template, **kwargs):
"""Send email using either Celery, or Thread.
Selection depends on CELERY_INSTEAD_THREADING config variable.
"""
... |
# coding: utf-8
"""
Eclipse Kapua REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
i... |
from starlette_inertia.inertia import InertiaMiddleware, InertiaResponse
__all__ = ["InertiaMiddleware", "InertiaResponse"] |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.j... |
"""
Scripts to clean up the raw PUF before matching
"""
import numpy as np
# RECIDs for aggregate variables by PUF year
AGG_VARS = {
2009: [999999],
2010: [999998, 999999],
2011: [999996, 999997, 999998, 999999],
}
def preppuf(puf, year):
"""Prepares the PUF for mathcing
Args:
puf (DataF... |
# Copyright (c) 2012 OpenStack Foundation
# 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 ... |
from .base import Widget
class Box(Widget):
def __html__(self):
return """
<div id="toga_{id}" class="toga box container" style="{style}">
{content}
</div>
""".format(
id=self.interface.id,
content="\n".join(
child._impl._... |
'''
Make sure orbit plotting can still occur after chopping chains.
'''
import orbitize
from orbitize import driver, DATADIR
import multiprocessing as mp
def verify_results_data(res, sys):
# Make data attribute from System is carried forward to Result class
assert res.data is not None
# Make sure the data tables a... |
from djongo import models
from django.contrib.auth.models import User
class Minorista(models.Model):
readonly_fields = ('id',)
user = models.OneToOneField(User)
#first_name = models.CharField(max_length=100, default="", editable=False)
#last_name = models.CharField(max_length=100, default="", editable=... |
"""Class and function decorators."""
from functools import wraps, lru_cache, RLock
import inspect
from vectorbt.utils import checks
class class_or_instancemethod(classmethod):
"""Function decorator that binds `self` to a class if the function is called as class method,
otherwise to an instance."""
def ... |
"""
lambdata - a collection of data science helper functions for lambda school
"""
import setuptools
REQUIRED = [
"numpy",
"pandas"
]
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
setuptools.setup(
name="lambdata-alekslovesdata",
version = "0.1.1",
author = "alekslovesdat... |
import py
class DoctestPlugin:
def pytest_addoption(self, parser):
parser.addoption("--doctest-modules",
action="store_true", default=False,
dest="doctestmodules")
def pytest_collect_file(self, path, parent):
if path.ext == ".py":
if parent.config.getva... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.