content stringlengths 5 1.05M |
|---|
import re
import time
import logging
from datetime import timedelta
from common.config_parser.config_dto import WebDriverSettingsDTO
logger = logging.getLogger(__name__)
def assert_should_be_equal(actual_value, expected_value, message=None,
silent=False, timeout=None):
"""
Assert ... |
import json
import os
path = 'C:/Users/fried/Desktop/images_json'
files = os.listdir(path)
for file in files:
file_name, file_extension = os.path.splitext(file)
file_path = '{}/{}'.format(path, file)
if file_extension.lower() == '.json':
with open(file_path) as f:
data = json.load(f)
if (data['label'] == 'n... |
#
# Copyright (C) 2018 Codethink 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 agre... |
import numpy as np
from skimage import io,transform
import os
src_dir = '/home/lss/ModelNet10/ModelNet10'
train_dst_dir = '/home/lss/PycharmProjects/cnn/test/2/train'
val_dst_dir = '/home/lss/PycharmProjects/cnn/test/2/val'
sub_dirs=['bed','chair','dresser','monitor','sofa','table','toilet']
size=112
def create_... |
# coding: utf-8
from flask.ext.script import Manager
from application import create_app
# Used by app debug & livereload
PORT = 8080
app = create_app()
manager = Manager(app)
@manager.command
def run():
"""Run app."""
app.run(port=PORT)
if __name__ == "__main__":
manager.run() |
#!/usr/bin/env python
import json
import os
import platform
import sys
import time
from modules.endpoint import Endpoint
from modules.payloads.netflow_v9 import *
from modules.pcapfile import PcapFile
from modules.utils import random_ephemeral_port
OPTIONS_COMMAND = "generate"
STRICT = False
VERSION = 9
OPTIONS_OUTPU... |
from typing import Callable
__all__ = ['check_input_types']
def check_input_types(fn: Callable):
pass |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, Mathijs Dumon
# All rights reserved.
# Complete license can be found in the LICENSE file.
import logging
logger = logging.getLogger(__name__)
import numpy as np
from scipy import stats
from scipy.interpolate import interp1d
from mvc.models.properties import ... |
from gtts import gTTS
myt = input()
language = 'en'
hm = gTTS(text=myt, lang=language, slow=False)
hm.save("C:/Users/Hp/PycharmProjects/my_first/Am.mp3")
import os
os.startfile("C:/Users/Hp/PycharmProjects/my_first/Am.mp3")
|
import logging
import sys
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
handler.setLevel(logging.DEBUG)
log.addHandler(handler)
|
import argparse
import shutil
import datetime
import json
import os
#import matplotlib.pyplot as plt
import time
from types import SimpleNamespace
import numpy as np
import scipy.stats as st
import torch
import torch.nn.functional as F
from tensorboardX import SummaryWriter
import utils
from arguments import parse_ar... |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 735752244
"""
"""
random actions, total chaos
"""
board = gamma_new(6, 5, 6, 3)
assert board is... |
import math
import unittest
def first_solution(array, size):
chunked = []
for i in range(0, math.ceil(len(array) / size)):
tmpArr = []
for j in range(0, size):
if (i * size + j) < len(array):
tmpArr.append(array[i * size + j])
chunked.append(tmpAr... |
#!/usr/bin/env python
#
from threading import Lock
import Queue
"""
Read config and server yaml files.
"""
update_lock = Lock()
# Line below MUST come after update_lock...
from config_functions import read
# Config section...
# IMPORTANT - config.yaml should be ../config.yaml and servers.yaml should be ../servers.... |
import os
import requests
import time
class Timer:
def __init__(self, time_between=5):
self.start_time = time.time()
self.time_between = time_between
def can_send(self):
if time.time() > (self.start_time + self.time_between):
self.start_time = time.time()
... |
# coding=utf-8
# Copyright 2020 The Tensor2Tensor Authors.
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:featureSelection
Description : 特征选择
Email : autuanliu@163.com
Date:2017/12/26
"""
from sklearn.feature_selection import VarianceThreshold
X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, ... |
#!/usr/bin/env python
'''This webserver will handle the requests for the user interface. We
use a long polling technique that only returns the results from a
request if something has changed in the robot state.
Author: Mark Desnoyer (markd@cmu.edu)
Date: July 2010
'''
import roslib; roslib.load_manifest('reefbot')
imp... |
frase = str(input('Digite qualquer frase: ')).upper().strip()
print('A frase possui {} letras A'.format(frase.count('A')))
print('A letra A aparece na posição {} pela primeira vez'.format(frase.find('A')+1))
print('A letra A aparece na posição {} pela última vez'.format(frase.rfind('A')+1))
|
import click
import numpy as np
import vpype as vp
from pyembroidery import EmbPattern
_EMB_SCALE_FACTOR = 2.645833333333333
@click.command()
@click.argument("filename", type=click.Path(exists=True))
@vp.global_processor
def eread(document: vp.Document, filename: str):
pattern = EmbPattern(filename)
for stit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
__title__ = 'shanbay-assistant'
__version__ = '0.3.0'
__author__ = 'mozillazg'
__email__ = 'mozillazg101@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2014 mozillazg'
|
import operator
from functools import partial
from paths_cli.wizard.parameters import ProxyParameter
from paths_cli.wizard.plugin_classes import (
LoadFromOPS, WizardParameterObjectPlugin, WizardObjectPlugin,
WrapCategory
)
from paths_cli.wizard.helper import EvalHelperFunc, Helper
from paths_cli.wizard.core im... |
from collections import deque
price_per_bullet = int(input())
barrel_size = int(input())
bull = list(map(int, input().split()))
bullets = deque(bull[::-1])
locks = deque(list(map(int, input().split())))
intelligence_value = int(input())
total_money = 0
local_barrel = int(barrel_size)
while bullets and locks:
c... |
"""Plots results of novelty detection."""
import os.path
import argparse
import numpy
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot
from gewittergefahr.deep_learning import cnn
from gewittergefahr.deep_learning import novelty_detection
from gewittergefahr.scripts import plot_input_examples as p... |
from os.path import join as jn
import numpy as np
from torchvision import transforms
from transform_image import *
def transformdef(opt, homepath):
# exec(open(jn(homepath, "transform"+opt.transappendix+".py")).read())
# if not opt.noise_output and opt.minmax:
# tmean = np.genfromtxt(
# jn(... |
### settings post-checks
# here we do stuff that should be checked or fixed after ALL settings from any source are loaded
# this is called by __init__.py
from celery.schedules import crontab
def post_process_settings(settings):
# check secret key
assert 'SECRET_KEY' in settings and settings['SECRET_KEY'] is ... |
import numpy as np
from Florence import QuadratureRule, FunctionSpace, Mesh
from Florence.FiniteElements.LocalAssembly._KinematicMeasures_ import _KinematicMeasures_
from Florence.VariationalPrinciple._GeometricStiffness_ import GeometricStiffnessIntegrand as GetGeomStiffness
from .DisplacementApproachIndices import Fi... |
import os
import logging
import json
from abc import ABC, abstractmethod
import numpy as np
import tensorflow as tf
import cv2
#################################################################################
#
# OBJECT DETECTOR BASE CLASS
#
#####################################################################... |
import sys
from edge.config import EdgeConfig
from edge.state import EdgeState
import questionary
def get_model_endpoint(model_name: str):
with EdgeConfig.context(silent=True) as config:
if config.models is None or model_name not in config.models:
questionary.print("Model is not initialised. ... |
from typing import Generic, TypeVar, Iterable
import asyncio
import logging
from aioreactive.core import AsyncDisposable, AsyncCompositeDisposable
from aioreactive.core import AsyncObserver, AsyncObservable
from aioreactive.core import AsyncSingleStream, chain
log = logging.getLogger(__name__)
T = TypeVar('T')
clas... |
import collections
import statsmodels.api as sm
from statsmodels.formula.api import ols
from sherpa.algorithms import Repeat
from sherpa.core import TrialStatus, AlgorithmState
import pandas
import math
class SequentialTesting(Repeat):
"""
Implements repeated trials based on a
group sequential testing des... |
import threading
print(threading.enumerate())
|
import asyncio
async def handle_client(reader, writer):
print("New client...")
while True:
request = await reader.readline()
if len(request) == 0:
break
print(f"Received: {request}")
response = request
writer.write(response)
await writer.drain()
... |
from time import sleep_ms
from math import ceil
from splitflap.utils.matrix import *
DELAY_MS = 0
class SplitFlap(object):
def __init__(self, num_col, num_row, spi, col_rclk, start_rclk, face_load):
self._num_col = num_col
self._num_row = num_row
self._bytes_col = ceil(num_col/8)
s... |
import numpy as np
from . import BaseAnnotationDefinition
class Ellipse(BaseAnnotationDefinition):
"""
Ellipse annotation object
"""
type = "ellipse"
def __init__(self, x, y, rx, ry, angle, label, attributes=None, description=None):
super().__init__(description=description, attribute... |
#!/usr/bin/env python3
#
# Copyright 2019 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 ... |
from django import forms
from django.template import TemplateDoesNotExist
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from .models import Quote
class QuotePluginForm(forms.ModelForm):
model = Quote
def clean_style(self):
style = self.cle... |
# -*- coding: utf-8 -*-
from django import template
from django.core.urlresolvers import reverse_lazy
from configurable_elements.models import get_legend_rows
from disease.models import CustomizedTag
register = template.Library()
@register.inclusion_tag('includes/data_table.html', takes_context=True)
def data_tabl... |
import contextlib
from .exc import SchemaError
from .imp import import_fqname, get_type_fqname
#------------------------------------------------------------------------------
NO_DEFAULT = object()
def to_array(obj):
return obj if isinstance(obj, list) else [obj]
@contextlib.contextmanager
def check_schema... |
from office365.runtime.client_value import ClientValue
class Reminder(ClientValue):
"""A reminder for an event in a user calendar."""
def __init__(self, eventId=None):
"""
:param str eventId: The unique ID of the event. Read only.
"""
super(Reminder, self).__init__()
... |
# 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
from .. import _utilities, _tables
from ... |
import pandas as pd
import os
DATA = "/data/users/sarthak/comcast-data/"
for folder in os.listdir(DATA + "final/"):
for filename in os.listdir(DATA + "final/"+folder+"/"):
filepath = DATA + "final/"+folder+"/"+filename
print filepath
# Device_number 547 was repeated exactly in control5 and... |
#! /usr/bin/env python3
"""
usb_strings.py - a tool to dump USB string
Copyright (C) 2012, 2015, 2017 Free Software Initiative of Japan
Author: NIIBE Yutaka <gniibe@fsij.org>
This file is a part of Gnuk, a GnuPG USB Token implementation.
Gnuk is free software: you can redistribute it and/or modify it
under the term... |
"""
This module contains the command line interface of Maestral. Keep all heavy imports
local to the command or method that requires them to ensure a responsive CLI.
"""
from .cli_main import main
__all__ = ["main"]
|
#!usr/bin/pyhon
from array import*
def split_str(plainText):
plainTextArray = [ch for ch in plainText]
return plainTextArray
def encrypt(plainText, offset):
alphabetSize = 26
letterA = 65
lettera = 97
encodedText = ""
plainTextArray = split_str(plainText)
n = 1
for i in range(0,... |
"""
-*- coding: utf-8 -*-
========================
AWS Lambda
========================
Contributor: Chirag Rathod (Srce Cde)
========================
"""
import json
import boto3
def extract_text(response, extract_by="LINE"):
line_text = []
for block in response["Blocks"]:
if block["BlockType"] == ext... |
import tensorflow as tf
from . import ops as ops
from .config import cfg
def embedding_op(qIndices, embInit):
with tf.variable_scope("qEmbeddings"):
embInit = tf.to_float(embInit)
embeddingsVar = tf.get_variable(
"emb", initializer=embInit, dtype=tf.float32,
trainable=(not... |
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.distributions import Categorical
def initialize_weights_he(m):
if isinstance(m, nn.Linear) or isinstance(m, nn.RNN):
torch.nn.init.kaiming_uniform_(m.weight)
if m.bias is not None:
torch.nn.init.constant... |
import re
gold = "shiny gold"
bagreg = r"\d*\s*(\w+\s*\w+)\s*bag."
bagreg_numbers = r"(\d*)\s*(\w+\s*\w+)\s*bag."
nobag = "no other"
def get_bags(input: list) -> int:
rules = []
bags_with = set()
for rule in input:
bags = re.findall(bagreg, rule)
if any(nobag in s for s in bags) is False:... |
# -*- test-case-name: twisted.words.test -*-
# Copyright (c) 2001-2005 Twisted Matrix Laboratories.
# See LICENSE for details.
""" A temporary placeholder for client-capable strports, until we
sufficient use cases get identified """
from twisted.application import strports
def _parseTCPSSL(factory, domain, port):
... |
from abc import ABC
import operator
from functools import reduce
import numpy as np
def product(args):
return reduce(operator.mul, args, 1)
def get_lengths(shapes):
""" get vector of lengths (number of elements) of weight matrices """
return [product(shape) for shape in shapes]
def unpack(w, shapes, l... |
from django.db import models
class TimestampedModel(models.Model):
class Meta:
abstract = True
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class NamedModel(models.Model):
class Meta:
abstract = True
ordering = ('name'... |
# Copyright 2019 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, ... |
""" Class LocalStorageInterface handles with local file/folder objects
Class LocalStorageInterface contains
open method, which is the same python built-in 'open' method
isfile and isdir methods for checking object status
... |
import pickle
import numpy as np
from sklearn.cross_validation import StratifiedKFold
import h2o
from blender import blend_predictions
import json
from h2o.grid.grid_search import H2OGridSearch
h2o.init(max_mem_size=4)
train = h2o.import_file('output/baseline_lvl1_train_20.csv', destination_frame='train')
target = h2... |
"""Baseball Team Manager file I/O."""
import csv
FILENAME: str = "players.txt"
def read_players() -> list[dict]:
"""Read players file and return a list of dictionaries."""
try:
players: list = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
... |
#
# 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, software
# ... |
'''
Module to check an OpenShift Git BuildConfig and determine if the latest build matches the requested git ref. If not, an oc start-build will be run.
'''
import subprocess
import yaml
from ansible.module_utils.basic import AnsibleModule
def start_build(module):
return run_command(['oc', 'start-build', '-n', m... |
import tensorflow as tf
def which_device():
# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=... |
import pytest
from sqlalchemy import text
from flaskr.db import get_db
@pytest.mark.parametrize("path", ("/1/purchase",))
def test_login_required(client, path):
response = client.post(path)
assert response.headers["Location"] == "http://localhost/auth/login"
@pytest.mark.parametrize("path", ("/4/purchase"... |
from bootstrapvz.base import Task
from bootstrapvz.common import phases
import os
class VirtIO(Task):
description = 'Install virtio modules'
phase = phases.system_modification
@classmethod
def run(cls, info):
modules = os.path.join(info.root, '/etc/initramfs-tools/modules')
with open(... |
import json
import zlib
import io
import time
from collections import OrderedDict
import floppy
from floppy.runner import Runner, sendCommand, RGIConnection
from socket import AF_INET, SOCK_STREAM, socket #, SHUT_RDWR, timeout, SHUT_RDWR, SO_REUSEADDR, SOL_SOCKET
from threading import Thread, Lock
from queue import Que... |
__version__ = "0.13.0.7"
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-10-30 16:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('petition', '0016_auto_20181027_1635'),
]
operations = [
migrations.AddFiel... |
"""
'||
... ... .... ... ... ... ... .... ||
||' || '|. | || || | '' .|| ||
|| | '|.| ||| ||| .|' || ||
||...' '| | | '|..'|' .||.
|| .. |
'''' ''
Created by Dylan Araps.
"""
import os
import platform
__version__ = "3.3.1"... |
"""Create the flask app from the factory in the run package."""
import os
from run import create_app, db
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
@app.shell_context_processor
def make_shell_context():
"""Add a shell context processor."""
from run.models import Meter, Poet, Poem, Role, User
... |
# -*- coding: utf-8 -*-
"""Process source files.
"""
import json
import sys
from typing import Optional, NoReturn, List
import pydantic
from omoide import commands
from omoide import constants
from omoide import infra
from omoide.migration_engine import classes
from omoide.migration_engine import entities
from omoid... |
import sqlite3
from sqlite3 import Error
from sqlalchemy import create_engine
import pandas as pd
import geojson
import os
import io
import math
import reverse_geocoder
def distance(origin, destination):
"""
Haversine formula example in Python
Author: Wayne Dyck
https://gist.github.com/rochacbruno/288... |
import pygame
import random
import sys
pygame.init()
block_size = 20
header_margin = 80
frame_color = (0, 255, 200)
white_color = (255, 255, 255)
blue_color = (200, 255, 255)
apple_color = (255, 0, 0)
snake_color = (0, 155, 0)
header_color = (0, 200, 150)
blocks_number = 20
margin = 1
size = [block_size * blocks_numbe... |
import gzip
import os
import pickle
import sys
import pdf2image
import PyPDF2
import pytesseract
from pathlib import Path
import pandas as pd
BASE_PATH = Path(os.path.abspath(os.path.dirname(__file__)))
def store_pickle(obj, filename):
"""
Store a compressed "pickle" of the object in the "pickle_data" dire... |
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten, Merge, Permute, Reshape
from keras.layers.wrappers import TimeDistributed
from keras.layers.embeddings import Embedding
from keras.layers import Bidirectional,Input,merge
from keras.layers.recurrent import LSTM, GRU
f... |
#!/usr/bin/env python2
__author__ = "Ryon Sherman"
__email__ = "ryon.sherman@gmail.com"
__copyright__ = "Copyright 2015, Ryon Sherman"
__license__ = "MIT"
# define log format
LOG_FORMAT = "[%(asctime)s] (%(levelname)s) %(message)s"
import sys
import time
import random
import logging
from PyQt4 import QtCor... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
__author__ = 'Folaefolc'
"""
Code par Folaefolc
Licence MIT
"""
from constantes import DEBUG_LEVEL, ree, POL_ANTIALISING
def println(*args, sep=" ", end="\r\n"):
if DEBUG_LEVEL >= 1:
print(*args, sep=sep, end=end)
def onscreen_debug(ecran, font, *debug_infos, **kwargs):
if DEBUG_LEVEL >= 2:
... |
def foo(x):
<selection>try:
pass
except Exception:
raise</selection>
print(1) |
"""
If there are 23 students in your class, what are the chances that two of you have the same
birthday? You can estimate this probability by generating random samples of 23 birthdays
and checking for matches.
Hint: you can generate random birthdays with the randint function in the random module.
"""
import random... |
from datetime import datetime
from flask import redirect
from google.cloud import bigquery
def insert_status(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Res... |
from dal import autocomplete
from django import forms
from orders.models import Order
class UserAutocompleteForm(forms.ModelForm):
class Meta:
model = Order
fields = '__all__'
widgets = {
'user': autocomplete.ModelSelect2(url='user-autocomplete')
}
|
"""Provide tests for node statistics."""
def test_statistics(mgr):
"""Test statistics."""
response_json = {
"ackChannel": 0,
"averageRequestRTT": 31,
"averageResponseRTT": 47,
"extendedTXSupported": False,
"hops": 0,
"lastFailedLinkFrom": 0,
"lastFailedL... |
#!/usr/bin/env python3
"""
Empty NCP-host Example Application.
"""
# Copyright 2021 Silicon Laboratories Inc. www.silabs.com
#
# SPDX-License-Identifier: Zlib
#
# The licensor of this software is Silicon Laboratories Inc.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event wil... |
from django.contrib import admin
from .models import Listing
class ListingAdmin(admin.ModelAdmin):
list_display = ( 'id', 'title', 'is_published', 'list_date')
list_display_links =('id','title')
list_filter=('title',)
list_editable=('is_published',)
admin.site.register(Listing, ListingAdmin)
# Registe... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chatroom', '0003_auto_20151217_0640'),
]
operations = [
migrations.RemoveField(
model_name='entry',
... |
import os
from pyhyp import pyHyp
baseDir = os.path.dirname(os.path.abspath(__file__))
surfaceFile = os.path.join(baseDir, "plate_surf.cgns")
volumeFile = os.path.join(baseDir, "plate_vol.cgns")
options = {
# ---------------------------
# Input Parameters
# ---------------------------
"inputFil... |
import os
import re
from setuptools import setup, find_packages
VERSION_RE = re.compile(r"""__version__ = ['"]([0-9.]+)['"]""")
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*args):
"""Reads complete file contents."""
return open(os.path.join(HERE, *args)).read()
def get_version():
"""Re... |
# -*- coding: utf-8 -*-
'''
torstack.scheduler.handler
scheduler executor definition.
:copyright: (c) 2018 by longniao <longniao@gmail.com>
:license: MIT, see LICENSE for more details.
'''
from __future__ import absolute_import, unicode_literals
from tornado import gen
from tornado.web import url
from torstack.hand... |
from collections import defaultdict
import numpy as np
#import leidenalg
from numpy import inf
def count_triangles(graph):
return len(graph.cliques(min=3, max=3))
def cluster_coef(graph):
return graph.transitivity_avglocal_undirected(mode='zero')
def count_edges(graph):
return len(graph.es)
def count_ve... |
"""
Filename: model_resnet.py
File Description: An example of non-sequential deep learning model is ResNet. ResNet50 pretrained model from keras is used here.
The model can be retrieved using get_model(). One must specify the input shape and number of output class labels for
... |
from .models_GCN import GCN
from .models_GCN_LFR import GCNLFR
__all__ = ['GCN', 'GCNLFR']
|
# Generated by Django 2.2.2 on 2019-11-07 16:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0017_auto_20191107_1627'),
]
operations = [
migrations.RemoveField(
model_name='distributionupload',
name='datase... |
from typing import List
import rasa.utils.plotting
import numpy as np
import pytest
@pytest.mark.parametrize(
"data, num_bins, expected_bins",
[
# We write `n + 1` to highlight that we include `n`
([[1, 3, 8], [2, 3, 3]], 7, list(range(1, 9 + 1))),
([[3, 8], [2, 3, 3]], 6, list(range(2... |
from import_export import resources
from backend.models import Registro,Eletiva, Aluno
class RegistroResource(resources.ModelResource):
class Meta:
model = Registro
fields =('aluno__sige','aluno__nome','aluno__serie','aluno__turma','eletiva__codigo','eletiva__nome','eletiva__dia','eletiva__periodo'... |
from flask import render_template
from . import main
@main.errorhandler(404)
def four_zero_four(error):
'''
Function that Renders the 404 Page
'''
return render_template('404.html'), 404
|
# Templates for the production of a LaTeX presentation.
texTemplate=r"""%Offline Alignment Validation presentation.
%Time of creation: [time]
%Created with produceOfflineValidationTex.py
\documentclass{beamer}
\usepackage[latin1]{inputenc}
\usepackage{color}
\usepackage{longtable}
%\usepackage{siunitx}
%\usepackage{ep... |
#!/usr/bin/env python3
import asyncio
import telepot
import yaml
import datetime
import random
import math
import dataset
from . import help, task
def format_seconds_as_mm_ss(seconds):
return "{}:{:02}".format(
math.floor(seconds/60.0), math.floor(seconds) % 60)
class Tomato(telepot.helper.ChatHandler):... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2019 Huawei Technologies Co., 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 ... |
import platform
from .location import Location
from .robot import Robot
from .sikulpy import unofficial
from ..version import VERSION
class Env(object):
@staticmethod
def addHotkey(key, modifiers, handler):
raise NotImplementedError(
"Env.addHotKey(%r, %r, %r) not implemented" % (key, mod... |
"""Algorithms for time series analysis.
Algorithms for analysis of time-series derived from neuroimaging data
1. Coherency: calculate the pairwise correlation between time-series in the
frequency domain and related quantities
2. Spectral estimation: calculate the spectra of time-series and cross-spectra
between time... |
OUT= ["Inge yaaaaaaa", 1] |
from unittest.mock import MagicMock, patch
import pytest
from app.runner import FactoryProcess
class TestThirdPartyService:
@patch('app.runner.FactoryProcess._call_rapid_api')
def test_call_rapid_api(self, mock_call_rapid_api):
mock_call_rapid_api.return_value = [
{"region": "Asia"}, {"... |
from __future__ import division, print_function
import time
import mmtbx.model
import iotbx.pdb
from mmtbx.hydrogens import connectivity
from libtbx.utils import null_out
pdb_str = """\
CRYST1 17.955 13.272 13.095 90.00 90.00 90.00 P 1
ATOM 1 N TYR A 139 10.241 7.920 5.000 1.00 10.00 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.