text stringlengths 1 927k |
|---|
number = float(input('Please, type a number: '))
if number % 2 != 0:
print('This number is odd.')
else:
print('This number is even.')
# print('{number} is odd.') if (number %
# 2 != 0) else print('{number} is even.')
# Remember to limit your code down to 80 characters. |
"""Fitting function to evaluate with the fitting algorithm."""
import functools
from dataclasses import InitVar, dataclass, field
from typing import Callable, Optional, Dict
import numpy as np
from eddington.exceptions import FitFunctionRuntimeError
from eddington.fit_functions_registry import FitFunctionsRegistry
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.RechargeBill import RechargeBill
class AlipayCommerceCityfacilitatorDepositQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceCityfac... |
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
#loading Datasets
iris = datasets.load_iris()
# print(iris.DESCR)
features = iris.data
labels = iris.target
print(features[0], labels[0])
#Training the data
clf = KNeighborsClassifier()
clf.fit(features, labels)
#Prediction
pred = clf... |
# wsgi entrypoint for gunicorn
# https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04
from app import app
from flask import Flask
if __name__ == "__main__":
# Session(app)
app.debug = True
app.config["SESSION_TYPE"] = "filesystem"
# se... |
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='pytoml',
version='0.1.2',
description='A parser for TOML-0.4.0',
author='Martin Vejnár',
author_email='avakar@ratatanek.cz',
url='https://github.com/avakar/pytoml',
license='MIT',
packages=['pytoml'],
... |
from .bfp import BFP
from .fpn import FPN
from .fpn_carafe import FPN_CARAFE
from .hrfpn import HRFPN
from .nas_fpn import NASFPN
from .nasfcos_fpn import NASFCOS_FPN
from .pafpn import PAFPN
from .fsr_generator import FSRGenerator
__all__ = [
'FPN', 'BFP', 'HRFPN', 'NASFPN', 'FPN_CARAFE', 'PAFPN', 'NASFCOS_FPN', ... |
from django import forms
from django.contrib.auth.models import Permission, Group
from django.db.models import Q
from django.utils.translation import ugettext as _
from med_social.utils import slugify
from med_social.fields import MultiSelectizeModelField, SelectizeMultiInput
from med_social.forms.base import Deletabl... |
import os
import re
from theoops.utils import get_closest, replace_argument
from theoops.specific.brew import get_brew_path_prefix, brew_available
enabled_by_default = brew_available
def _get_formulas():
# Formulas are based on each local system's status
try:
brew_path_prefix = get_brew_path_prefix()... |
"""Docker file-system-info scan plugin."""
from DockerENT.utils import utils
import docker
import logging
import json
_log = logging.getLogger(__name__)
_plugin_name_ = 'files-info'
def scan(container, output_queue, audit=False, audit_queue=None):
"""Docker file-system-info plugin scan.
:param container: ... |
import dlen.dlen as dlen
def test_blank_console():
"""Test blank in command line."""
assert dlen.main() is None
def test_blank():
"""Test blank."""
assert dlen.DefLen(files_content=['']).show_console is False
def test_good_def():
"""Test good def."""
test_input = [(
'def demo_good_... |
# Joint copyright:
# - Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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 requ... |
import os
import csv
import glob
from datetime import datetime
timeformat = '%m/%d/%Y %H:%M:%S'
starttimes = []
for file in glob.glob('*2016*csv'):
print(file)
with open(file,'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader)
for row in reader:
starttimes.append(datetime.strptime(ro... |
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
# Considere US$1.00 = R$3.27.
reais = float(input("Quantos reais você tem na carteira? R$"))
cotdol = float(input("Qual a cotação do dólar hoje? 1$ == R$"))
dolares = reais / cotdol
print("Com R${:.2f} v... |
class Config:
def __init__(self, dataset, main_path, stop_file, processed_path):
# choose dataset name
self.dataset = dataset
# paths
self.main_path = main_path
self.stop_file = stop_file
self.processed_path = processed_path
self.full_path = processed_path ... |
#
# 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
# ... |
import json
from unittest.mock import patch, ANY
from django.urls import reverse
from rest_framework import status
from purplship.core.models import PickupDetails, ConfirmationDetails, ChargeDetails
from purpleserver.core.tests import APITestCase
class TesPickup(APITestCase):
def test_schedule_pickup(self):
... |
""" Sampling volume module. """
# ISC License
#
# Copyright (c) 2020–2021, Paul Wilhelm, M. Sc. <anfrage@paulwilhelm.de>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission noti... |
# coding=utf-8
# !/usr/bin/python3
from flask import Flask, jsonify, request
from manage.manageProxy import Proxymanager
app = Flask(__name__)
api_list = {
'get': u'get an usable proxy',
'refresh': u'refresh proxy pool',
'get_all': u'get all proxy from proxy pool',
'delete?proxy=127.0.0.1:8080': u'd... |
# Generated by Django 3.1.2 on 2020-10-02 23:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('farms', '0004_auto_20201002_2301'),
]
operations = [
migrations.RenameField(
model_name='datapoint',
old_name='date_type',
... |
""" support for skip/xfail functions and markers. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from _pytest.config import hookimpl
from _pytest.mark.evaluate import MarkEvaluator
from _pytest.outcomes import fail
from _pytest.outcomes import skip
from... |
import unittest
import paramak
class TestCenterColumnShieldFlatTopCircular(unittest.TestCase):
def setUp(self):
self.test_shape = paramak.CenterColumnShieldFlatTopCircular(
height=600, arc_height=400, inner_radius=100, mid_radius=150, outer_radius=200)
def test_default_parameters(self):... |
from strictdoc.backend.sdoc.document_reference import DocumentReference
from strictdoc.backend.sdoc.models.document import Document
from strictdoc.backend.sdoc.models.document_config import DocumentConfig
from strictdoc.backend.sdoc.models.object_factory import SDocObjectFactory
from strictdoc.backend.sdoc.models.refer... |
import json, requests, datetime, random, os
from bs4 import BeautifulSoup
__USER_AGENT_URL__ = 'http://www.useragentstring.com/pages/useragentstring.php?name={}'
class UserAgent(object):
__DATA_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data', 'useragent' + '.json'))
BROWSER_LIST = ['... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'', views.SucursalViewSet)
app_name = 'sucursal'
urlpatterns = [
path('', include(router.urls))
] |
# pylint: disable-msg=W0400,W0511,W0611,W0612,W0614,R0201,E1102
"""Tests suite for MaskedArray & subclassing.
:author: Pierre Gerard-Marchant
:contact: pierregm_at_uga_dot_edu
"""
from __future__ import division, absolute_import, print_function
__author__ = "Pierre GF Gerard-Marchant"
import warnings
import pickle
i... |
from __future__ import print_function
import torch.utils.data as data
from PIL import Image
import os
import os.path
import errno
import torch
import json
import codecs
import numpy as np
import sys
import torchvision.transforms as transforms
import argparse
import json
#Part Dataset
class PartDataset(data.Dataset):
... |
from django.template.defaultfilters import register
@register.filter
def cell_count(inline_form):
"""Returns the number of cells used in a tabular inline"""
count = 1 # Hidden cell with hidden 'id' field
for fieldset in inline_form:
# Loop through all the fields (one per cell)
for line in... |
import numpy as np
import scipy.stats as stats
import scipy.linalg
import pytest
import open_cp.kernels as testmod
import open_cp.data
import unittest.mock as mock
import shapely.geometry
def slow_gaussian_kernel_new(pts, mean, var):
"""Test case where `pts`, `mean`, `var` are all of shape 2."""
assert(len(pts... |
# Generated by Django 2.2.7 on 2019-11-10 08:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Issue',
fields=[
... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2012, 2015-2019 BigML
#
# 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... |
# Copyright 2013 Red Hat, Inc.
#
# 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... |
from mxnet import nd
from mxnet.gluon import nn
net = nn.Sequential()
net.add(
nn.Conv2D(
channels=6,
kernel_size=5,
activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Conv2D(
channels=16,
kernel_size=3,
activation='relu'),
nn.MaxPool2D(pool_siz... |
import os
import importlib
import logging
from glob import glob
root = os.path.dirname(__file__)
logger = logging.getLogger(__name__)
INVALID_MODULES = {}
def _get_valid_datasets():
datasets = glob(os.path.join(root, '*.py'))
valid_datasets = []
for dataset in datasets:
basename = os.path.basen... |
"""Heap queue algorithm (a.k.a. priority queue).
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0. For the sake of comparison,
non-existing elements are considered to be infinite. The interesting
property of a heap is that a[0] is always its smallest element.
Usag... |
import pandas as pd
import numpy as np
from Matriz_esferica import Matriz_esferica
from Individuo import Individuo, Fabrica_individuo
import random
from itertools import permutations
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from scipy.sparse import csr_matrix, lil_matrix
import math... |
"""
Use Mayavi to visualize the structure of a VolumeImg
"""
from mayavi import mlab
import numpy as np
x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j]
data = x*x*0.5 + y*y + z*z*2.0
mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
mlab.clf()
src = mlab.pipeline.scalar_field(x, y, z, data)
mlab.pipeline.surf... |
from collections import defaultdict
N,M,*AB = [int(x) for x in open(0).read().split()]
d = defaultdict(lambda: [])
for i in range(0, len(AB), 2):
a=AB[i]
b=AB[i+1]
d[a].append(b)
d[b].append(a)
for second in d[1]:
if N in d[second]:
print('POSSIBLE')
break
else:
print('IMPOSSIBLE... |
# -*- coding: utf-8 -*-
'''
Manage ini files
================
:maintainer: <akilesh1597@gmail.com>
:maturity: new
:depends: re
:platform: all
'''
__virtualname__ = 'ini'
def __virtual__():
'''
Only load if the ini module is available
'''
return __virtualname__ if 'ini.set_option' in __salt__ else ... |
import itertools
def flattened_ranges(range_lengths):
return list(itertools.chain.from_iterable(range(n) for n in range_lengths))
def take(n, gen):
"""Take the first n items from the generator gen. Return a list of that many items
and the resulting state of the generator."""
lst = list(itertools.isl... |
# Copyright (c) 2019 Huawei Technologies Co., Ltd.
# 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
#
# ... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import logging
import os
import sy... |
#!/usr/bin/env python
#
# 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 requir... |
from django.core.exceptions import ValidationError
from django.forms import modelformset_factory
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Res... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 28 22:26:40 2018
@author: Arvinder Shinh
"""
import tensorflow as tf
from PIL import Image
import numpy as np
import os
from tensorflow import saved_model as sm
imageFiles=os.listdir('image')
SerializedImgContainer=[]
LabelContainer=[]
for f in imageFiles:
if f.end... |
# coding=utf-8
# Copyright 2022 The Reach ML 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 law ... |
# NASNet Search Space https://arxiv.org/pdf/1707.07012.pdf
# code modified from DARTS https://github.com/quark0/darts
import numpy as np
from collections import namedtuple
import torch
from algs.nsga_net.model.micro_models import NetworkCIFAR as Network
Genotype = namedtuple('Genotype', 'normal normal_concat reduce r... |
#/usr/bin/python3
# function for parsing the data
def data_parser(text, dic):
for i, j in dic.iteritems():
text = text.replace(i,j)
return text
inputfile = open('test.dat')
outputfile = open('test.csv', 'w')
# sample text string, just for demonstration to let you know how the data looks
# my_text = '"2012-06-... |
from .battery_soc_comp import BatterySOCComp |
"""
MIT License
Copyright (c) 2021 Eugene
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, distri... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from jobbing.models.base_model_ import Model
from jobbing import util
class WorkingArea(Model):
def __init__(self,
working_area_id:int = None,
working_area_mun... |
from .DockerUtils import DockerUtils
from .PackageUtils import PackageUtils
from .WindowsUtils import WindowsUtils
import humanfriendly, os, platform, random
from pkg_resources import parse_version
# Import the `semver` package even when the conflicting `node-semver` package is present
semver = PackageUtils.importFile... |
#!/usr/bin/env python
# Copyright 2020 The Tekton 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... |
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
coords = []
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print 'x = %d, y = %d'%(ix, iy)
global coords
coords.append((ix, iy))
... |
# Generated by Django 3.1.7 on 2021-03-04 05:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('tweet', '0001_initial'),
migrations.swappable_dependency(settin... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "Difference", sigma = 0.0, exog_count = 20, ar_order = 12); |
#!/bin/env python3
import argparse, os
import fileformats, romfs, exefs, slb2, scecaf, self, ncch, ncsd
modes = {
"guess": fileformats.guess,
"romfs": romfs.process,
"exefs": exefs.process,
"slb2": slb2.process,
"scecaf": scecaf.process,
"self": self.process,
"ncch": ncch.process,
"nc... |
from os.path import abspath as absolute_path
from time import time
import aiofiles
from wbb import aiohttpsession as session
from wbb.core.tasks import add_task
def ensure_status(status_code: int):
if status_code < 200 or status_code >= 300:
raise Exception(f"HttpProcessingError: {status_code}")
async... |
def deleteDirectory (DIR_TO_BE_DELETED,RECURSIVE=False):
# This function will Clean the directory that is on disk directory. If Recursive is set to true then it will remove any Sub-directories too
try:
import os
import shutil
except Exception as e:
print(str(e))
sys.exit(-1)
if os.path.isdir(DIR... |
# Copyright (c) 2014 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality o... |
import os
import sys
import datetime
import strabulous
from fabric.api import (
local,
sudo,
lcd,
env,
hosts,
put,
run,
get,
settings,
shell_env,
)
from fabric import colors
from fabric.contrib.console import confirm
from baste import (
DiffCommand,
Git,
OrderedDict... |
# checking all settings
import settings
import warnings
print('Running SETTING Checks!')
if type(settings.PORT) is not int:
raise Exception('settings.PORT must be an integer')
if settings.PORT < 0:
raise Exception('settings.PORT Value cannot be negative')
if settings.PORT < 1024:
warnings.warn('You are ... |
norm_cfg = dict(type='BN', requires_grad=True)
custom_imports = dict(imports='mmcls.models', allow_failed_imports=False)
checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/convnext-xlarge_3rdparty_in21k_20220301-08aa5ddc.pth'
model = dict(
type='EncoderDecoder',
pretrained... |
from conans import ConanFile, tools, CMake
from conans.errors import ConanInvalidConfiguration
import functools
import os
required_conan_version = ">=1.43.0"
class SquirrelConan(ConanFile):
name = "squirrel"
description = "Squirrel is a high level imperative, object-oriented programming " \
... |
#!/usr/bin/env python
"""Tests for FASTA sequence format writer.
"""
from unittest import TestCase, main
from cogent3.core.alignment import Alignment
from cogent3.core.info import Info
from cogent3.core.sequence import Sequence
from cogent3.format.fasta import alignment_to_fasta
__author__ = "Jeremy Widmann"
__copyr... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from django.db import models
# Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import PermissionsMixin
from .managers import CustomUserManager
class Use... |
#coding:utf-8
#
# id: bugs.core_6086
# title: Creating of the large procedure crashes the server.
# decription:
# Confirmed bug on: WI-T4.0.0.1534, WI-V3.0.5.33141
# Checked on:
# 4.0.0.1535: OK, 2.051s.
# 3.0.5.33142: ... |
"""Test that workflows build."""
import pytest
import sys
from .. import fieldmap # noqa
from .. import pepolar # noqa
from .. import syn # noqa
@pytest.mark.parametrize(
"workflow,kwargs",
(
("sdcflows.workflows.fit.fieldmap.init_fmap_wf", {"mode": "mapped"}),
("sdcflows.workflows.fit.fie... |
# BSD 3-Clause License
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrig... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "ohlc.hoverlabel"
_path_str = "ohlc.hoverlabel.font"
_valid_props = {"color", "colorsrc", "fami... |
from unittest import TestCase
from esbo_etc.classes.sensor.PixelMask import PixelMask
import numpy as np
import astropy.units as u
class TestPixelMask(TestCase):
def setUp(self):
self.mask = PixelMask(np.array([10, 8]) << u.pix, 6.5 * u.um, center_offset=np.array([0.2, 0.5]) << u.pix)
def test___new_... |
#!/usr/bin/env python
# coding: utf-8
'''This script finds the best parameters for SVC and LGR models and fits the data to these two models and outputs the classification images and the classification reports as the csv documents.
Usage: src/model.py --data_input=<data_input> --result_output=<result_output>
Argument... |
import unittest
import torch
import torch_tensorrt.fx.tracer.acc_tracer.acc_ops as acc_ops
from parameterized import param, parameterized
from torch.testing._internal.common_utils import run_tests
from torch_tensorrt.fx.tools.common_fx2trt import AccTestCase
@unittest.skip(
"Current implementation is limited. A... |
# -*- coding:utf-8 -*-
__author__ = '何三'
from flask_wtf import FlaskForm
from flask_login import current_user
from wtforms import StringField,PasswordField, BooleanField, SubmitField, IntegerField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from app.models import User, Invitati... |
# Django settings for django_site project.
import sys, os
# Files created by plotty are globally read/write
os.umask(0)
DEBUG = not False
TEMPLATE_DEBUG = DEBUG
# Two-tailed confidence level (i.e. this value will be halved for calls to
# the inverse t function)
CONFIDENCE_LEVEL = 0.95
if 'PLOTTY_ROOT' in os.environ:... |
from setuptools import setup
with open('requirements.txt', 'rt') as f:
requirements_list = [req[:-1] for req in f.readlines()]
setup(
name='wbident',
version='0.0.1',
packages=['wbident', 'wbident.core'],
url='https://gitlab.com/limajj_articles/core/wbident',
license='',
author='Jeferson ... |
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming and providing OAuth 2.0 RFC6749.
"""
import logging
from oauthlib.common import Request
from .base import BaseEndpoint, catch_errors_and_unavailability
log = logging.getLogger(__name__)
class... |
from semantic_release.dist import build_dists
from . import pytest
@pytest.mark.parametrize('commands', [
'sdist bdist_wheel',
'sdist',
'bdist_wheel',
'sdist bdist_wheel custom_cmd'
])
def test_build_command(mocker, commands):
mocker.patch('semantic_release.dist.config.get', lambda *a: commands)
... |
#!/usr/bin/env python
# 2017 kojima changed https://github.com/davidavdav/audacity.py (c) 2016 David A. van Leeuwen
#
#
#
import xml.etree.ElementTree as ET
import wave, os, numpy, struct
class Aup:
def __init__(self, aupfile):
fqpath = os.path.join(os.path.curdir, aupfile)
dir = os.path.dirname(fqpath)
xml =... |
'''User implemented De Pierro MAPEM reconstruction
Real data implementation of De Pierro MAPEM, using a Bowsher weighted quadratic
penalty. The guidance image (here a T1-weighted MR image) must be pre-aligned
to the PET image and sampled on the same image grid.
Implemented by Sam Ellis (13th Feb 2019)
Usage:
dePier... |
#!/usr/bin/python3
# UVA 100: 3n+1 problem
LIMIT = 1000001
solutions = {}
solutions[0] = 0
solutions[1] = 1
def calc_and_get(index):
global solutions
if index <= 0:
return
if index in solutions:
return solutions[index]
else:
if index % 2 == 0:
val = calc_and_get(index / 2) + 1
else:
... |
import tkinter as tk
from tkinter import Button
import time
import numpy as np
from PIL import ImageTk, Image
PhotoImage = ImageTk.PhotoImage
UNIT = 100 # 픽셀 수
HEIGHT = 5 # 그리드월드 세로
WIDTH = 5 # 그리드월드 가로
TRANSITION_PROB = 1 #상태 변환 확률 값
POSSIBLE_ACTIONS = [0, 1, 2, 3] # 상, 하, 좌, 우
ACTIONS = [(-1, 0), (1, 0), (0, -1)... |
from sensor_msgs.msg import CameraInfo
import rospy
camera1 = CameraInfo()
camera2 = CameraInfo()
camera3 = CameraInfo()
# Created by Tim
"""
camera1 = {header: {seq: 0, stamp: {secs: 0, nsecs: 0}, frame_id: 'camera1'},
height: 342, width: 342, distortion_model: 'plumb_bob',
D: [0],
K: [500.0, 0.0, ... |
"""
test_grid:
==========
A module intended for use with Nose.
"""
from __future__ import absolute_import
import random
import string
from unittest import skip
from nose.plugins.attrib import attr
import plotly.plotly as py
from plotly.exceptions import InputError, PlotlyRequestError, PlotlyError
from plotly.graph... |
import torch
from torch.nn import functional as F
def sigmoid_hm(hm_features, training=False):
x = hm_features.sigmoid_()
if training:
x = x.clamp(min=1e-4, max=1 - 1e-4)
return x
def nms_hm(heat_map, kernel=3):
pad = (kernel - 1) // 2
hmax = F.max_pool2d(heat_map,
... |
import komand
from .schema import DnsInput, DnsOutput
# Custom imports below
from komand_mxtoolbox_dns.util import utils
class Dns(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="dns", description="Run a DNS query", input=DnsInput(), output=DnsOutput()
... |
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
name = "projectecho.users"
verbose_name = "Users"
def ready(self):
try:
import users.signals # noqa F401
except ImportError:
pass |
#!/usr/bin/env python
from __future__ import division, absolute_import, print_function
import numpy as np
__all__ = ['position']
def position(row=1, col=1, num=1,
left=0.125, right=0.9, bottom=0.1, top=0.9,
hspace=0.1, vspace=None, wspace=None,
width=None, height=None,
... |
import sys
import hashlib
import os
PY2 = sys.version_info[0] == 2
_identity = lambda x: x
if PY2:
import cPickle as pickle
from cStringIO import StringIO
import copy_reg as copyreg
from HTMLParser import HTMLParser
import urlparse
from htmlentitydefs import entitydefs, name2codepoint
imp... |
from elasticsearch import Elasticsearch
client = Elasticsearch("http://username:password@127.0.0.1:9200")
client.indices.create(index="index_name")
client.create(
index="index_name",
id=1,
document={
"sku": 134218478,
"name": "Rb-01 - Robô Aspirador De Pó Fast Clean Bivolt - Mondial",
... |
#
# 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 us... |
import sys, signal
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import Qt
class Application(QWidget):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.CustomizeWindowHint | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool... |
from torch import nn
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from core import resnet
import numpy as np
from core.anchors import generate_default_anchor_maps, hard_nms
from config import Config as cfg
class ProposalNet(nn.Module):
"""
Navigator Network
"""
def ... |
import sys
from copy import deepcopy
from six import iteritems, string_types, integer_types
import os
import imp
from collections import Iterable, Sequence, Mapping, MutableMapping
import warnings
import numpy as np
import ctypes
import platform
import tempfile
from enum import Enum
from operator import itemgetter
if ... |
import json
import os
from .config import API_KEY
import requests
from datetime import date
from w3lib.html import remove_tags
def save_data_to_json(file_name, data):
"""Save data to a json file creating it if it does not already exist
:parameter: file_name -> 'example' do not add the '.json'
:parameter:... |
# Extract one of the predefined indices from a hyperspectral datacube
import os
import numpy as np
import cv2
from plantcv.plantcv import params
from plantcv.plantcv._debug import _debug
from plantcv.plantcv import fatal_error
from plantcv.plantcv import Spectral_data
from plantcv.plantcv.transform import rescale
from... |
"""Django_05_Ajax URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
import csv
import json
from datetime import datetime
"""Useful for converting DynamoDB exports to CSV"""
data = []
with open('data') as f:
for line in f:
data.append(json.loads(line))
with open('data.csv', 'w', encoding='utf8') as csvf:
w = csv.writer(csvf, quoting=csv.QUOTE_MINIMAL)
w.writerow(... |
'''*-----------------------------------------------------------------------*---
Author: Jason Ma
Date : Oct 18 2018
TODO
File Name : pid.py
Description: TODO
---... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.