content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""Valid URL Configuration for testing purposes"""
from django.views.generic import RedirectView
GITHUB = RedirectView.as_view(
url="https://github.com/jambonsw/django-url-check"
)
| python |
# 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... | python |
#!/usr/bin/env python3
import os
import sys
import argparse
import tempfile
import shutil
from saturation.utils import (normalize_args, export_to_file, get_macs_command_line, parse_outputs, save_plot)
def get_parser():
parser = argparse.ArgumentParser(description='SatScript', add_help=True)
parser.add_argumen... | python |
def decorate(func):
def decorated():
print("==" * 20)
print("before")
func()
print("after")
return decorated
@decorate
def target():
print("target 함수")
target()
## output
"""
========================================
before
target 함수
after
"""
def target2():
print(... | python |
"""This script is used to plot a gene2vec embedding"""
# imports
import argparse
import pandas as pd
import numpy as np
import plotly.express as px
import mygene
import math
import os
# describe program
parser = argparse.ArgumentParser(description='Plots an embedding of a gene2vec hidden layer.')
# arguments
parser.... | python |
class MedianFinder:
def __init__(self):
def addNum(self, num: int) -> None:
def findMedian(self) -> float:
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
| python |
from sys import stdin
mb_per_month = int(stdin.readline())
n_of_months = int(stdin.readline())
current_num_of_mb = mb_per_month
for n in range(n_of_months):
current_num_of_mb = (current_num_of_mb - int(stdin.readline())) + mb_per_month
print current_num_of_mb
| python |
# Copyright 2021 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, ... | python |
from typing import Any, Callable, List, TypeVar
from vkwave.bots.core.dispatching.filters.base import (
BaseFilter,
AsyncFuncFilter,
SyncFuncFilter,
)
from vkwave.bots.core.dispatching.handler.base import BaseHandler
from vkwave.bots.core.dispatching.handler.record import HandlerRecord
F = TypeVar("F", bo... | python |
#!/usr/bin/python
import os
import re
from optparse import OptionParser
SUFFIX=".out"
def main () :
global filename
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="the file to update", metavar="FILE")
parser.add_option("-n", "--name", dest="name",
... | python |
import vvx_nego
if __name__ == "__main__":
#hogeの部分をエンジンが有るpathに変更して実行してください
vvn = vvx_nego.VoicevoxNegotiation("hoge\\run.exe")
vvn.request_audio_query("これは", speaker=1)
vvn.request_synthesis(vvn.audio_query, speaker=1)
vvn.multi_synthesis.append(vvn.synthesis)
vvn.request_audio_quer... | python |
__author__ = 'Aditya Roy'
import unittest
from time import sleep
from WebAutomation.Test.TestUtility.ScreenShot import SS
from WebAutomation.Src.PageObject.Pages.ConfirmationPage import Confirmation
from WebAutomation.Src.PageObject.Pages.HomePage import Home
from WebAutomation.Src.TestBase.EnvironmentSetUp import Env... | python |
# 写入csv文件
import csv
with open('data.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['id', 'name', 'age'])
writer.writerow(['10001', 'Mike', 20])
writer.writerow(['10002', 'Bob', 22])
writer.writerow(['10003', 'Jordan', 21])
| python |
#!/usr/bin/env python
import decimal
import hashlib
import json
import sys
# Parse the query.
query = json.load(sys.stdin)
# Build the JSON template.
boolean_keys = [
'ActionsEnabled',
]
list_keys = [
'AlarmActions',
'Dimensions',
'InsufficientDataActions',
'OKActions',
]
alarm = {}
for key, v... | python |
from django.urls import path
from .ajax import CustomerRequirementAjaxView
urlpatterns = [
path('customer/', CustomerRequirementAjaxView.as_view(), name='customerRequirementAjax'),
]
| python |
import settings
from PyQt5.QtCore import QObject, QEvent
from PyQt5.QtCore import Qt
from enum import Enum
import cv2
import numpy as np
from skimage.draw import rectangle, line
#
# class Mode(Enum):
# SHOW = 1
# DRAW = 2
# ERASE = 3
class GrabCutToolInteractor(QObject):
def __init__(self, viewer, ... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 3 14:12:10 2018
@author: joshcole
#F1_Data Analysis Fake Loan Company
"""
import pandas as pd
loan_data=pd.read_csv("drop_location/train_loan data.csv")
print (loan_data)
| python |
import tensorflow_hub as hub
import tensorflow as tf
import numpy as np
def predict_image(im):
model = tf.keras.models.load_model('CNN_model.h5', custom_objects={'KerasLayer': hub.KerasLayer})
im = np.asarray(im)
image = tf.image.resize(im, (256, 256))
img = image/255.0
image = tf.expand_dims(img, ... | python |
#!/usr/bin/env python3
import os, sys, json
import numpy as np
import pandas as pd
import functools as fct
import collections as cols
from alignclf import create_clf_data
if __name__ == '__main__':
result_dnames = [
'clst-2018-12-generic_50-inc0-net1',
'clst-2018-12-generic_50-inc0-net2',
... | python |
from setuptools import setup
from setuptools import find_packages
version = '0.0.1'
classifiers = """
Development Status :: 3 - Alpha
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: JavaScript
Programming Language :: Python :: 3
Programming Language :: Python :: 3.5
Programm... | python |
#====creating a function for insertion sort==========
def insertion_sort(list1):
#===outer loop================
for i in range(1, len(list1)):
value = list1[i]
j = i-1
while j >= 0 and value < list1[j]:
list1[j+1] = list1[j]
j -= 1
... | python |
import pandas as pd
import requests
url = 'http://localhost:9696/predict'
sample_data_points = [
{'timestamp': '2016-12-22 08:00:00', 't1': 5.0, 't2': 2.0, 'hum': 100.0, 'wind_speed': 13.0, 'weather_code': 4, 'is_holiday': 0, 'is_weekend': 0, 'season': 3}, # actual=2510
{'timestamp': '2016-08-11 15:00:00', ... | python |
import random
from vprasanja import slovar, vprasanja_multiple_izbire, riziki
#======================================================================================
#Definicija konstant
#======================================================================================
STEVILO_DOVOLJENIH_NAPAK = 5
STEVILO_PRAVI... | python |
from .p2pnet import build
# build the P2PNet model
# set training to 'True' during training
def build_model(args, training=False):
return build(args, training) | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import abc
import json
import os
import random
from collections import OrderedDict
from pprint import pformat
import pydash as ps
import torch
import torch.nn as nn
import numpy as np
import t... | python |
import re
import geopandas as gpd
from ...tessellation import tilers
import shapely
import pytest
poly = [[[116.1440758191, 39.8846396072],
[116.3449987678, 39.8846396072],
[116.3449987678, 40.0430521004],
[116.1440758191, 40.0430521004],
[116.1440758191, 39.8846396072]]]
geom = [sh... | python |
from flask_wtf import FlaskForm
from wtforms import DecimalField, StringField, SubmitField
from wtforms.validators import DataRequired
class UpdateRatingMovieForm(FlaskForm):
new_rating = DecimalField("Your Rating Out of 10 e.g. 7.5", validators=[DataRequired()])
new_review = StringField("Your Review", validat... | python |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt._1btcxe import _1btcxe
class getbtc (_1btcxe):
def describe(self):
return self.deep_extend(super(getbtc, self).des... | python |
from __future__ import print_function
from __future__ import absolute_import
import myhdl
from myhdl import instance
# @todo: move "interfaces" to system (or interfaces)
from ...cores.sdram import SDRAMInterface
from ...system import MemoryMapped
# @todo: utilize FIFOBus
from ...system import FIFOBus
def sdram_co... | python |
array = []
for i in range (16):
# array.append([i,0])
array.append([i,5])
print(array) | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from Data_Structure.Linked_List import *
print("** Singly Linked List **")
list1 = Singly_Linked_List.Singly_Linked_List()
for i in range(1, 11):
list1.append(i)
print... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 26 05:59:46 2018
@author: zefa
"""
import os
import numpy as np
import cv2
MAX_HEIGHT = 720
def apply_mask(image, mask, color, alpha=0.5):
"""Apply the given mask to the image.
"""
for c in range(3):
image[:, :, c] = np.where(mask == 1,
... | python |
from xicam.plugins.datahandlerplugin import DataHandlerPlugin, start_doc, descriptor_doc, event_doc, stop_doc, \
embedded_local_event_doc
import os
import fabio
import uuid
import re
import functools
from pathlib import Path
class EDFPlugin(DataHandlerPlugin):
name = 'EDFPlugin'
DEFAULT_EXTENTIONS = ['.... | python |
import datetime as dt
def dt_to_str(dt_seconds):
"""
Converts delta time into string "hh:mm:ss"
"""
return str(dt.timedelta(seconds=dt_seconds))
| python |
'''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from datetime import timedelta
import json
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout, login
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django... | python |
#!/usr/bin/env python2.7
"""
Function-Class-Method browser for python files.
"""
# Copyright (c) 2013 - 2017 Carwyn Pelley
#
# 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 restricti... | python |
#!/usr/bin/env python
"""
utils.py
"""
import os, warnings, numpy as np, pandas as pd
from glob import glob
from typing import List
from itertools import accumulate, chain, repeat
from .constants import FRAME, TRACK, TRACK_LENGTH, PY, PX
######################
## TRACKS UTILITIES ##
######################
def trac... | python |
from django.conf import settings
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import TemplateView
from core.helpers import NotifySettings
from core.views import BaseNotifyFormView
from ukef.forms import UKEFContactForm
class HomeView(TemplateView):
t... | python |
import stackprinter
def test_frame_formatting():
""" pin plaintext output """
msg = stackprinter.format()
lines = msg.split('\n')
expected = ['File "test_formatting.py", line 6, in test_frame_formatting',
' 4 def test_frame_formatting():',
' 5 """ pin p... | python |
import sys
import getpass
from controllers.main_controller import MainController
from interface.main_menu import MainMenu
from utils.hospital_errors import *
from database_layer.database import *
from utils.hospital_constants import *
class StartMenu:
db = Database()
@classmethod
def run(cls):
pr... | python |
import json # importing json module
class Utils:
def stringify(self, obj):
return json.dumps(obj)
def parseJson(self, string):
try:
return json.loads(string)
#pass
except:
return string
#pass
| python |
from typing import List, Optional
from sqlalchemy import desc
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.sql.expression import select
from app.database.dbo.mottak import WorkflowMetadata as WorkflowMetadata_DBO
from app.domain.models.WorkflowMetadata import WorkflowMetadata, WorkflowMetad... | python |
import pickle
pickle_in=open("instances_dev.pickle","rb")
data=pickle.load(pickle_in)
for i in range(10):
print(data[i])
| python |
import FWCore.ParameterSet.Config as cms
from L1Trigger.VertexFinder.VertexProducer_cff import VertexProducer
L1FastTrackingJets = cms.EDProducer("L1FastTrackingJetProducer",
L1TrackInputTag = cms.InputTag("TTTracksFromTrackletEmulation", "Level1TTTracks"),
L1PrimaryVertexTag=cms.InputTag("VertexProducer", Ve... | python |
import wikipedia
while True:
ans = input("Question: ")
wikipedia.set_lang("es")
print (wikipedia.summary(ans, sentences=2))
| python |
import json
import sqlite3
#Initiating the database
connection=sqlite3.connect(database='roaster_db.sqlite')
curr=connection.cursor()#Cursor initiated
#Creating tables for the database
# Do some setup
curr.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
... | python |
import glob
import os
import json
import dateutil.parser
import datetime
import re
COMPLETE_NUM_ACTIONS=18
TECHNICAL_DIFFICULTIES = '7h9r8g p964wg jcqf4w 9qxf5g'.split()
# Also exclude this person, who wrote about things other than restaurants.
TECHNICAL_DIFFICULTIES.append('49g68p')
INCOMPLETE_BUT_OK = 'hfj33r'.spli... | python |
print('='*8,'Aluguel de Um Carro','='*8)
d = int(input('Por quantos dias o carro foi alugado?'))
km = float(input('Quantos km foram rodados com o carro?'))
pa = 60*d + 0.15*km
print('''O valor do aluguel a ser pago por este carro com {} dias alugados e {:.2f}km rodados sera de:
{}R${:.2f}{}.'''.format(d,km,'\033[32m',p... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains custom widgets to handle file/folder browser related tasks
"""
from __future__ import print_function, division, absolute_import
import os
import sys
import subprocess
from Qt.QtCore import Signal, Property, QSize
from Qt.QtWidgets import QSizeP... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
tl_stock.py
Copyright (c) 2015 Rob Mason
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 t... | python |
# -*- coding: utf-8 -*-
# Copyright 2017 Mobicage NV
#
# 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... | python |
import sys
sys.path.append('../')
import jupman
import local
def add(x,y):
#jupman-raise
return x + y
#/jupman-raise
def sub(x,y):
return help_func(x,y)
#jupman-strip
# stripped stuff is not present in exercises
def help_func(x,y):
return x - y
#/jupman-strip
#jupman-purge
# purged stuff n... | python |
import pytest
import os
from matplotlib.testing.compare import compare_images
gold = "testing/gold"
scratch = "testing/scratch"
def compare( a, b ):
results = compare_images( a, b, 1 )
return (results is None)
def test_cinema_image_compare():
try:
os.makedirs(scratch)
except OSError as e... | python |
from cloudshell_power_lib.Orchestration import power_off_resources_in_sandbox
from cloudshell.workflow.orchestration.sandbox import Sandbox
from cloudshell.workflow.orchestration.teardown.default_teardown_orchestrator import DefaultTeardownWorkflow
import cloudshell.helpers.scripts.cloudshell_dev_helpers as dev_helpers... | python |
"""
The base fighter implementation
"""
from __future__ import absolute_import, print_function, division
from cagefight.cagefighter import CageFighter
import random
import math
class LightningFighter(CageFighter):
"""
Lightning ball wars fighter
"""
def __init__(self, world, fighterid):
self.... | python |
from pydub import AudioSegment
import webrtcvad
import numpy as np
import speechpy
import torch
import torch.autograd as grad
import torch.nn.functional as F
from model.hparam import hp
import os
from model.frame import Frame
def get_logmel_fb(segment, len_window=25, stride=10, filters=40):
'''
Gives the ... | python |
"""
Silly placeholder file for the template.
"""
def hello() -> str:
return "Hello {{cookiecutter.project_slug}}"
| python |
"""
input:
1
5
1 5 2 3 4
output:
12
"""
def solve(N, a):
res = 0
for i in range(N - 1, 0, -1):
if a[i] < a[i - 1]:
a[i - 1] -= (a[i - 1] - a[i])
res += a[i]
return res + a[0]
T = int(input())
for _ in range(T):
N = int(input())
a = list(map(int, input().split()))
... | python |
from streamsvg import Drawing
s = Drawing()
s.addNode("a")
s.addNode("b", [(0,4), (5,10)])
s.addNode("c", [(4,9)])
s.addNode("d", [(1,3)])
s.addLink("a", "b", 2, 2, color='blue', width=3)
s.addLink("b", "d", 2, 2, color='blue', width=3)
s.addLink("a", "c", 5, 5, color='blue', width=3)
s.addLink("b", "c", 6, 6, color... | python |
# -*- coding: utf-8 -*-
#
# bifacial_radiance documentation build configuration file, created by
# sphinx-quickstart on Tuesday Sep 24 18:48:33 2019.
#
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
... | python |
import os
from oletools.olevba3 import VBA_Parser
# Set this to True if you would like to keep "Attribute VB_Name"
KEEP_NAME = False
def parse(workbook_path):
vba_path = workbook_path + '.vba'
vba_parser = VBA_Parser(workbook_path)
vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_ma... | python |
import django_filters
from django_filters import DateFilter, CharFilter
from .models import *
class Client_Filter(django_filters.FilterSet):
class Meta:
model = Client
fields = [
'name',
'address',
'phone_no'
]
class Staff_Filter(django_... | python |
from airypi.remote_obj import RemoteObj
from flask import session, request
from airypi import utils
import json
import gpio
from airypi.callback_dict import CallbackDict
from airypi import event_loop
class Device:
RPI = 'RASPBERRY_PI'
ANDROID = 'ANDROID'
handler_for_type = {}
event_loop_f... | python |
from math import exp
import numpy as np
import random
import time
class AnnealingSolver:
# 3*81: rows, cols, 3x3
optimal_energy = -243
# marks original values
def get_fixed_positions(self, sudoku):
original = []
for row in sudoku:
original.append([-1 if x > 0 else 0 for x... | python |
""" UDF is called user define function
UDF is very useful when you want to transform your data frame, and there is no pre-defined
Spark sql functions already available.
To define a spark udf, you have three options:
1. use pyspark.sql.functions.udf, this works for select, withColumn.
udf(lambda_function, return_typ... | python |
from flask.ext.restful import fields
from app import db
from . import User
class PlanEntry(db.Model):
eid = db.Column(db.Integer, primary_key=True)
plan_id = db.Column(db.Integer, db.ForeignKey('plan.pid'))
plan = db.relationship('Plan', back_populates='entries')
timestamp = db.Column(db.Time)
... | python |
import pyttsx3
import time
CALLS = {
"F": "Step Forwards",
"B": "Step Bak",
"L": "Step Left",
"R": "Step Right",
"ROT": "About turn",
"CLAP": "Clapp"
}
class Caller:
def __init__(self):
self.engine = pyttsx3.init()
self.engine.setProperty("rate", 140)
def say_command... | python |
from typing import List
from src import util
from PIL import Image, ImageDraw
from src.config import ConfigContentType
from .bounding_box import BoundingBox
from .effect_processor import EffectProcessor
from .text_procecssor import TextProcessor
from .shape_processor import ShapeProcessor
from src.font_scanner impo... | python |
#Copyright (c) 2017 Andre Santos
#
#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, distribute... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-06 23:56
from __future__ import unicode_literals
import brazil_fields.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [... | python |
from abc import abstractmethod
from typing import List, Dict
from src.bounding_box import BoundingBox
from src.utils.enumerators import BBType, BBFormat
import torch.nn.functional as F
class ModelEvaluator:
def __init__(self):
self._gt_bboxes = []
self._predicted_bboxes = []
self._img_cou... | python |
import torch
from typing import List, Dict, Tuple, Iterable
from ray import tune
from torch import optim
from tqdm import trange
from G2G.model.graph_wrapper import GraphWrapper
from G2G.model.model import Predictor
from G2G.utils import get_all_combo, prepare_input, get_score
from G2G.decorators.decorators import logg... | python |
print((2**int(input()))%(10**9+7)) | python |
from utils.db.mongo_orm import *
class TestCase(Model):
class Meta:
database = db
collection = 'testCase'
# Common Fields
_id = ObjectIdField()
name = StringField()
description = StringField()
isDeleted = BooleanField(field_name='isDeleted', default=False)
status = Boolean... | python |
# * Utils Function
from tools.Wave_Class import Wave
import math
def auto_frame_count(waves, h, w, tr):
max_time = 0.0
to_check = ((0, 0), (0, h), (0, w), (h, w))
for wave in waves:
temp_func = wave.distanceFunction()
for p in to_check:
temp_dist = temp_func(p[0], p[1])
... | python |
# Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 18:24:57 2019
@author: jone
"""
#%% Simple Demo
import cv2
import numpy as np
# callback 함수
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img, (x, y), 100, (255, 0, 0), -1)
# 빈 이미지 생성
img = np.zeros((5... | python |
# -*- coding: utf-8 -*-
import CTK
def commit():
print CTK.post
return {'ret': 'ok'}
def default():
submit = CTK.Submitter('/commit')
submit += CTK.RawHTML ("<h2>Can set, without initial value</h2>")
submit += CTK.StarRating ({'name': 'test_rate1', 'can_set': True})
submit += CTK.RawHTML ("... | python |
import hashlib
# Status definitions and subdir names
STATUS = {"PENDING": "queue",
"STARTED": "inprogress",
"DONE": "results",
"ERROR": "errors"}
def get_id(doc):
"""
Calculate the id (hash) of the given document
:param doc: The document (string)
:return: a task id (hash... | python |
from imported.submodules import submodulea
def bar():
print("imported.modulee.bar()")
submodulea.foo()
| python |
from flask import Flask, render_template, jsonify, request, url_for
import json
app = Flask(__name__)
values_list = ['id', 'summary', 'host_is_superhost', 'latitude', 'longitude',
'property_type', 'room_type', 'accomodates', 'bathrooms',
'bedrooms', 'beds', 'security_deposit', 'cleaning_... | python |
import cv2 as cv
import numpy as np
titleWindow = 'Introduction_to_svm.py'
print("Takes a moment to compute resulting image...")
# Set up training data
## [setup1]
labels = np.array([1, -1, -1, -1])
trainingData = np.matrix([[501, 10], [255, 10], [501, 255], [10, 501]], dtype=np.float32)
## [setup1]
# Train the SVM
##... | python |
import cv2
import numpy as np
import copy
from shapes.shape import Shape
from shapes.ep import p2e, e2p, column
class BBox(Shape):
@classmethod
def from_region(cls, region):
yx = region.centroid()
tmp = cls(yx[1], yx[0], -np.rad2deg(region.theta_), 2 * region.major_axis_, 2 * region.minor_axi... | python |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | python |
from .effector import Effector
from .evidence import Evidence
from .gene import Gene
from .operon import Operon
from .organism import Organism
from .pathway import Pathway
from .publication import Publication
from .regulator import Regulator
from .regulatory_family import RegulatoryFamily
from .regulatory_interaction i... | python |
"""
SHA-256 PRNG prototype in Python
"""
import numpy as np
import sys
import struct
# Import base class for PRNGs
import random
# Import library of cryptographic hash functions
import hashlib
# Define useful constants
BPF = 53 # Number of bits in a float
RECIP_BPF = 2**-BPF
HASHLEN = 256 # Number of bits in a... | python |
#
# Copyright (c) 2020 Saarland University.
#
# This file is part of AM Parser
# (see https://github.com/coli-saar/am-parser/).
#
# 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://... | python |
from django.db import IntegrityError
from django.db.models import Count, Q, IntegerField, CharField
from django.db.models.functions import Coalesce
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.per... | python |
import os
from flask import Flask
from flask import render_template
from flask_assets import Environment
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from config.environments import app_config
db = SQLAlchemy()
def get_config_name():
return os.getenv('FLASK_CONFIG') or 'developme... | python |
#
# Copyright (c) 2019 Juniper Networks, Inc. All rights reserved.
#
from cfgm_common.exceptions import BadRequest, NoIdError
from cfgm_common.exceptions import HttpError, RequestSizeError
from vnc_api.gen.resource_client import AccessControlList
from schema_transformer.resources._resource_base import ResourceBaseST
... | python |
#
# ==================================
# | |
# | Utility functions for CBGB |
# | |
# ==================================
#
from collections import OrderedDict
from modules import gb
import importlib
import modules.active_cfg
cfg = importlib.im... | python |
import numpy as np
from Bio.SVDSuperimposer import SVDSuperimposer
from sklearn.utils.validation import check_is_fitted
from sklearn.base import TransformerMixin, BaseEstimator
"""
BioPythonの関数をsklearnのモデルのように利用する関数/クラス群。
last update: 21 Jun, 2021
Authors: Keisuke Yanagisawa
"""
__all__ = [
"SuperImposer"
]
cl... | python |
"""Build IDE required files from python folder structure from command line.
"""
import argparse
from ideskeleton import build
def main():
"""Build IDE files from python folder structure."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormat... | python |
import pytest
from httpx import AsyncClient
from mock import patch
from models.schemas.status import StatusEnum
from resources import strings
pytestmark = pytest.mark.asyncio
@patch("api.routes.health.create_service_bus_status")
@patch("api.routes.health.create_state_store_status")
async def test_health_response_co... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/30 下午12:27
# @Title : 26. 删除排序数组中的重复项
# @Link : https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
QUESTION = """
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums =... | python |
__package__ = 'archivebox.core'
import uuid
from django.db import models
from django.utils.functional import cached_property
from ..util import parse_date
from ..index.schema import Link
class Snapshot(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
url = models.... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# IMPORT STANDARD LIBRARIES
import re
_LINE_ENDER = re.compile(r'(?P<prefix>\s*).+(?::)(?:#.+)?$')
def _get_indent(text):
'''str: Find the indentation of a line of text.'''
return text[:len(text) - len(text.lstrip())]
def _add_indent(text, indent=1):
'''A... | python |
#!/usr/bin/env python3
import csv
import typer
def read_csv(file_name: str):
print(f'FILE NAME {file_name}')
""" Opens a csv file and returns a list with the
contents of the first column (in reality returns a
list of all the rows contained in the file)
Args:
file... | python |
import sys
import java.lang.Class
import org.python.core.PyReflectedFunction as reflectedfunction
import org.python.core.PyReflectedField as reflectedfield
import java.lang.reflect.Field as Field
import java.lang.reflect.Method as Method
import java.lang.annotation.Annotation as JavaAnnotation
from java.lang... | python |
from ..model.elapsed_time_fractions import ElapsedTimeFractions
def calculate_time_fractions(elapsed_time_ns: int) -> ElapsedTimeFractions:
"""Elapsed time is in nanoseconds and should be calculated as difference between start and stop time using on the time.perf_counter_ns() function."""
microseconds, nanos... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.