content stringlengths 5 1.05M |
|---|
"""Filex."""
import random
from utils import timex
MIN_INT, MAX_INT = 10 ** 15, 10 ** 16 - 1
def read(file_name):
"""Read."""
with open(file_name, 'r') as fin:
content = fin.read()
fin.close()
return content
def write(file_name, content, mode='w'):
"""Write."""
with open(f... |
# -*- coding: utf-8 -*-
"""
fudcon.ui
------
fudcon ui application package
"""
|
from enigma import eRect, eServiceReference, iServiceInformation, iPlayableService
from Screens.Screen import Screen
from Screens.ServiceInfo import ServiceInfoList, ServiceInfoListEntry
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Pixmap import Pixmap
from Components.Label import Label
f... |
'''
Content under Creative Commons Attribution license CC-BY 4.0,
code under MIT license (c)2018 Sergio Rojas (srojas@usb.ve)
http://en.wikipedia.org/wiki/MIT_License
http://creativecommons.org/licenses/by/4.0/
Created on march, 2018
Last Modified on: may 15, 2018
'''
def myfuncPrimeFactors(n):
"""
This f... |
import hashlib
from settings import SIZE
class Address:
def __init__(self, ip, port):
self.ip = ip
self.port = port
def __key(self):
return f"{self.ip}{self.port}".encode()
def __hash__(self):
"""
Python uses a random hash seed to prevent attackers from tar-pitti... |
# -*- coding:utf-8 -*-
import logging
from time import sleep
import bigsuds
from networkapi.plugins import exceptions as base_exceptions
from networkapi.system.facade import get_value as get_variable
log = logging.getLogger(__name__)
class Lb(object):
def __init__(self, hostname, username, password, session=T... |
import image, touch, gc, time
from machine import I2C
from board import board_info
from fpioa_manager import fm
from Maix import GPIO
import time
from machine import SPI
from micropython import const
from sx127x import SX127x
board_info=board_info()
i2c = I2C(I2C.I2C3, freq=1000*1000, scl=24, sda=27) # amigo
devices =... |
#!/usr/bin/env python
import boto3
import botocore
import argparse
import sys
parser = argparse.ArgumentParser(description='Check if the given AWS VPC exists.')
parser.add_argument('--region_name', dest='region_name', action='store', required=True, help='AWS Region name, e.g. eu-west-1')
parser.add_argument('--vpc_nam... |
def arrays(arr):
# complete this function
# use numpy.array
return(numpy.array(arr,float))[::-1]
|
# Copyright 2004-2018 Tom Rothamel <pytom@bishoujo.us>
#
# 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... |
# # -*- coding: utf-8 -*-
from collections import Counter
from tests.testapp.tests.base_tests import BaseRedisTestCase
from tests.testapp.tests.multi_server_tests import MultiServerTests
from django.test import TestCase, override_settings
LOCATION = "unix://:yadayada@/tmp/redis0.sock?db=15"
LOCATIONS = [
"unix:/... |
import os
import logging
# (windows only for now)
if os.name == 'nt':
try:
logging.info('Looking for CUDA and adding it to path...')
# some python versions fail to load the path variables, so we're doing it manually here before importing tf
loaddir = "C:/Program Files/NVIDIA GPU Comput... |
import os
import getpass
import hashlib
os.system('cls')
print("Done...")
if 'MainDrive' in os.listdir('.'):
os.rmdir("MainDrive")
os.mkdir('MainDrive/')
os.mkdir('MainDrive/Users/')
username = input("Username: ")
password = getpass.getpass("Password (No echo): ")
encp = password.encode()
d = hash... |
# -*- encoding: utf-8 -*-
"""
@File : Surprise_SGD.py
@Time : 2020/11/21 14:41
@Author : biao chen
@Email : 1259319710@qq.com
@Software: PyCharm
"""
from surprise import Dataset
from surprise import Reader
from surprise import BaselineOnly, KNNBasic
from surprise import accuracy
from surprise.model... |
########
# Copyright (c) 2016 GigaSpaces Technologies 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
#
# Unless... |
#########################################################################
# Copyright/License Notice (Modified BSD License) #
#########################################################################
#########################################################################
# Copyright (c) 2008, Da... |
from .test_helper import argv_kiwi_tests
import sys
import mock
from mock import patch
import azurectl
from pytest import raises
from azurectl.commands.storage_account import StorageAccountTask
from azurectl.azurectl_exceptions import AzureInvalidCommand
class TestStorageAccountTask:
def setup(self):
sy... |
def mySqrt(x):
r = x
precision = 10 ** (-10)
print(precision)
while abs(x - r * r) > precision:
r = (r + x / r) / 2
return r
print(mySqrt(25))
print(mySqrt(36))
|
from restkit.handlers.http_mrg_handlers import query_handler as chandler_0 # noqa
from restkit.handlers.http_mrg_handlers.http_report_handlers import report_csv_handler as chandler_1 # noqa
__all__ = [
'chandler_0',
'chandler_1',
]
|
from dart_fss.api import filings
def test_get_corp_code():
res = filings.get_corp_code()
actual = res[0].keys()
expected = ['corp_code', 'corp_name', 'stock_code', 'modify_date']
for act in actual:
assert act in expected
def test_get_corp_info():
se = filings.get_corp_info('00126380')
... |
from urllib.parse import urlencode
import requests
from module_pipedrive.pipedrive import exceptions
from module_pipedrive.pipedrive.activities import Activities
from module_pipedrive.pipedrive.deals import Deals
from module_pipedrive.pipedrive.filters import Filters
from module_pipedrive.pipedrive.leads import Leads... |
#!/usr/bin/python
"""
Copyright (C) International Business Machines Corp., 2005
Author: Dan Smith <danms@us.ibm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; under version 2 of the Licen... |
r"""Analyze Traffic Images
This executable is used to annotate traffic images to highlight vehicle types and to produce stats
and graphs for the amount of time bicycle lanes and bus stops are blocked by vehicles:
Example usage:
./analyzeimages \
-path_images ./data/rawimages/
-path_labels_map dat... |
import json
import random
from locoloco.models.db_orm import db
from locoloco.models.db_models import User
from locoloco.models.db_models import Country
from locoloco.models.db_models import DistributionCenter
from locoloco.models.db_models import StoreStatus
from locoloco.models.db_models import Store
from locoloco.... |
from pdfrw import PdfObject, PdfReader, PdfWriter
import os
defaultlang = 'en-US'
#read all files in the folder called 'files'
files = os.listdir('files')
for file in files:
print(file)
fixlist = []
trailer = PdfReader('files\\'+file)
print("Lang: ",trailer.Root.Lang)
if trailer.Root.Lang == None:
fixlist.appe... |
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2021, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import oci
import os
from ads.common import utils
def api_keys(
oci_config: str = os.path.join(os.path.... |
import sys
def print_line(to_file=None):
if to_file:
print("--------------------------------------------------",
file=to_file)
else:
print("--------------------------------------------------")
def print_header():
print_line()
print("NAS Parallel Benchmark v3.2")
print... |
import asyncio
import os
from telethon import TelegramClient
TELETHON_SESSION_FILE: os.path = input("Please insert path to telethon session file: ")
API_ID: int = int(input("Please insert session api id: "))
API_HASH: str = input("Please insert session api hash: ")
TG_USERNAME_RECIPIENT: str = input(
"Please inse... |
import logging
from sklearn.dummy import DummyClassifier, DummyRegressor
from amlb.benchmark import TaskConfig
from amlb.data import Dataset
from amlb.results import save_predictions
from amlb.utils import Timer, unsparsify
log = logging.getLogger(__name__)
def run(dataset: Dataset, config: TaskConfig):
log.in... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Persons import Person, Persons
from PLC.Auth import Auth
class DeletePerson(Method):
"""
Mark an existing account as deleted.
Users and techs can only delete themselves. PIs can only delete
thems... |
#-------------------------------------------------------------------------------
#
# An abstract base class implementation of the ITemplateDataNameItem interface
# that looks for all specified values in its input context or optionally any of
# its sub-contexts and outputs a context containing all such values found.
... |
import itertools
import math
def Solution():
N: int
T = int(input("테스트 수행횟수 입력:")) # 갯수
for i in range(0, T):
N = int(input("입력데이터: "))
sData = str(input("값 추가 \n"))
ans = math.trunc(sortMaxMin(sData, N))
print(ans)
def sortMaxMin(inputData: str, N: int):
maxNumber : ... |
#!/usr/bin/python3
"""
We want to use quad trees to store an N x N boolean grid. Each cell in the grid
can only be true or false. The root node represents the whole grid. For each
node, it will be subdivided into four children nodes until the values in the
region it represents are all the same.
Each node has another t... |
#!/usr/bin/env python
# Small web app to allow a user to top up their personal PaperCut balance
# Add a custom URL to the PaperCut user web page, which is used by end users
# when they want to add credit to their PaperCut personal account. The url
# should refer to this small web app When the user clicks on the URL l... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
from distutils.core import setup, Extension
import os
import sys
prefix = os.environ.get("prefix", "/usr")
from distutils.core import setup, Extension
import subprocess as S
setup(name="polkit",
version="1.0.2",
description="Python bindings for polkit-1",
l... |
"""
Loading data and events submodule.
"""
from ..signal import find_events
#from .eeg_preprocessing import *
import numpy as np
import pandas as pd
import mne
import os
# ==============================================================================
# =================================================================... |
import json
your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(type(your_json))
print(type(parsed))
#print(json.dumps(parsed, indent=4, sort_keys=True)) |
# Time complexity: O(n)
# Approach: Implementation using 2 arrays.
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minStack = []
def push(self, val: int) -> None:
if len(self.minStack)==0:
self.s... |
from celery.utils.log import get_task_logger
from flask.ext.celery import Celery
from datetime import datetime, timedelta
import time
from app import app, db
from models import Agency, Prediction
from nextbus import Nextbus
"""
Celery is a task queue for background task processing. We're using it
for scheduled tasks, ... |
"""
Контекстный процессор для меню.
"""
from .utils import get_menus
def menu_processor(request):
"""
Контекстный процессор для возможности отображения всех меню на сайте.
Меню обычно распологаются на нескольких страницах, поэтому вынесено сюда.
"""
current_path = request.path
context = {
... |
from typing import Union
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch import Tensor
from .functions import ActivationModule
from activations.utils.utils import _get_auto_axis_layout
def tent_activation(x, delta):
"""
Functional implementation of TentActivati... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import numpy as np
import operator as op
from NumPyNet.exception import LayerError
from NumPyNet.utils import check_is_fitted
from NumPyNet.layers.base import BaseLayer
__author__ = ['Mattia Ceccarelli... |
try:
from libs.layers import *
from libs.utils_ft import *
except:
from layers import *
from utils_ft import *
import copy
import os
import sys
from collections import defaultdict
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn import MultiheadAtte... |
from django.conf.urls import url
from authen import views
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
url(r'^api/user/(?P<pk>[0-9]+)/$', views.person_detail),
url(r'^api/add_group/(?P<pk>[0-9]+)/$', views.add_group),
url(r'^api/user/$', views.person_list),
url(r'^$', vi... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
# Copyright (c) 2021, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import os
import unittest
import numpy as np
import torch
from warp_drive.managers.data_manager im... |
# Copyright (c) 2017 OpenStack Foundation.
#
# 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... |
import re
from model.contact import Contact
def test_contact_info_from_home_page(app, db):
app.navigation.open_home_page()
contact_from_home_page = sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
def clean(contact):
return Contact(id=contact.id, firstname=contact.firstname.strip(), ... |
x = [0.0, 3.0, 5.0, 2.5, 3.7] #define array
print(type(x))
x.pop(2) #remove third element
print(x)
x.remove(2.5) #remove element equal to 2.5
print(x)
x.append(1.2) #add an element at the end
print(x)
y = x.co... |
import datetime
import itertools
import functools
import io
import os
import pathlib
import string
import tqdm
import pytz
import requests
import apiclient.http
import fuzzywuzzy.fuzz
from .info import Conference, ConferenceInfoSource, Session
from apiclient.discovery import build
from google_auth_oauthlib.flow impo... |
from microbit import display
from microbit import Image
from KitronikClipDetector import Detector
sensor = Detector()
while True:
if sensor.readDigitalSensor("P2", "Dark") is True:
display.show(Image.HAPPY)
else:
display.show(Image.SAD) |
"""Urls for the Zinnia entries short link"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.views.shortlink import EntryShortLink
urlpatterns = patterns(
'',
url(r'^(?P<pk>\d+)/$',
EntryShortLink.as_view(),
name='zinnia_entry_shortlink'),
)
|
'''
SOLED
Scrapy settings
For simplicity, this file contains only settings considered important or
commonly used. You can find more settings consulting the documentation:
http://doc.scrapy.org/en/latest/topics/settings.html
http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
http://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... |
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
# required for test discovery |
# Copyright 2021 Victor I. Afolabi
#
# 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... |
# Created By: Virgil Dupras
# Created On: 2009-04-23
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licens... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.classify.naivebayes import NaiveBayesClassifier
class NaiveBayesClassifierTest(unittest.TestCase):
def test_simple(self):
training_features = [
({'nice': True, 'good': True}, 'positive')... |
# -*- coding: utf-8 -*-
import os
from youtube_title_parse import get_artist_title
class MetaTestSequence(type):
def __new__(mcs, name, bases, attrs):
def should_skip(test_params):
if not test_params:
return False
if "skip" in test_params and test_params["skip"] is ... |
# -*- coding: utf-8 -*-
import pickle
import numpy as np
import pandas as pd
import pystan
import os, sys
import stan_utility
import patsy
import arviz as az
GLMEdata = pd.read_csv('GLMEdata.csv')
GLMEdata = GLMEdata[GLMEdata.exp == 1]
GLME = stan_utility.compile_model('GLME.stan', model_name="GLME")
fixeff_form = "... |
from django.db import models
# Create your models here.
MALE = 'M'
FEMALE = 'F'
UNKNOWN = 'U'
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
(UNKNOWN, 'Unknown'))
class AdmissionsByGender(models.Model):
PRIMARY = 'P'
SECONDARY = 'S'
DIAGNOSIS_CHOICES = (
(PRIMARY, 'Primary'),... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Project : stock_quant
# @Date : 2022/1/18 23:29
# @Author : Adolf
# @File : info_push.py
# @Function:
import json
import requests
import logging
def post_msg_to_dingtalk(title="", msg="", token="", at=None, type="text"):
if at is None:
at = []
ur... |
import unittest
import json
from mock import patch
from provider.utils import unicode_encode
from provider.execution_context import S3Session
from tests.activity.classes_mock import FakeS3Connection
from tests import settings_mock
class TestS3Session(unittest.TestCase):
@patch("provider.execution_context.S3Sessio... |
import pyopencl as cl
import numpy as np
np.set_printoptions(linewidth=128)
BOARD_SIZE = 10
SHIP_SIZES = [5,4,3,3,2]
STATE_MISS = 0
STATE_HIT = 1
STATE_UNKNOWN = 2
def bool2IntArray(boolArray):
ret = []
for array in boolArray:
ret.append(np.packbits(array))
return ret
def int2BoolArray(boolArray):
ret = []
... |
from sklearn.metrics import mean_absolute_percentage_error as mape
from sklearn.metrics import r2_score
def mean_absolute_percentage_error(actual, forecast) -> float:
"""
calculate mean absolute percentage error (MAPE)
:param actual: actual values
:param forecast: forecast (prediction) values
:ret... |
################################################################################
# #
# RUN ALL TESTS AND CHECK FOR ACCURACY #
# ... |
from typing import Any, Dict
import numpy
import scipy.special
from mlxtk.util import memoize
@memoize
def binom(n: int, k: int) -> int:
return int(scipy.special.binom(n, k))
# @jit
def build_number_state_table_bosonic(N: int, m: int) -> numpy.ndarray:
number_of_states = binom(N + m - 1, m - 1)
number... |
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
import numpy as np
import nltk
from nltk.corpus import stopwords
nltk.download('punkt')
stop_words = set(stopwords.w... |
import torch.nn as nn
from .torch_helpers import NamedTensor
class Module(nn.Module):
def register_parameter(self, name, tensor):
if isinstance(tensor, NamedTensor):
param = nn.Parameter(tensor.values)
super(Module, self).register_parameter(
"_" + name + "_named", p... |
import json
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.admin.templatetags.admin_static import static
from django.template import Template, Context
from django.utils.encoding import force_text
from django.template.loader import get_template
from django.forms.models import BaseModel... |
import ray
import torch
from models import Model
import numpy as np
import random
from atari_wrappers import make_atari, wrap_deepmind
@ray.remote
class Player:
def __init__(self, checkpoint, replay_buffer, share_storage, test_mode):
self.game = make_atari(checkpoint["game"]+"NoFrameskip-v4")
self... |
# Generated by Django 3.0.9 on 2020-08-17 14:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('filer', '0011_auto_20190418_0137'),
]
operations = [
migrations.AddField(
model_name='file',
name='description_en',
... |
import unittest
import test, app
import nltk
from nltk.tokenize import word_tokenize
import json
class TestGetRAD(unittest.TestCase):
def test_word_classifier(self):
keyword = 'I coughed a lot and vomited. I also have a headache.'
words = word_tokenize(keyword)
# returns tag name of part ... |
from __future__ import print_function, division
from argparse import ArgumentParser
from sys import exc_info
from time import ctime
from datetime import datetime
from decimal import Decimal
from traceback import print_tb
from random import randint
from tqdm import trange
from .api import TradewaveAPI
from .data impo... |
import copy
import floppyforms as forms
from crispy_forms.bootstrap import Tab, TabHolder
from crispy_forms.layout import HTML, Field, Fieldset, Layout
from django import forms as django_forms
from django.forms.models import modelform_factory
from django.utils.text import slugify
from django.utils.translation import ... |
#! /usr/bin/env python3
# Copyright 2022 Tier IV, 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 la... |
from setuptools import setup
setup(
name='django-subquery',
version='1.0.4',
description='SubQuery support in Django < 1.11',
url='https://github.com/schinckel/django-subquery/',
author='Matthew Schinckel',
author_email='matt@schinckel.net',
packages=['django_subquery']
)
|
from easygraphics import *
x = 0
y = 0
def draw_compositon(x, y, mode, alpha_value):
set_background_color(Color.TRANSPARENT)
set_font_size(18)
set_line_width(3)
set_color("black")
set_composition_mode(CompositionMode.SOURCE)
draw_rect_text(x, y + 175, 200, 25, mode)
set_fill_color(to_alph... |
#!/usr/bin/python3
import tensorflow as tf
import numpy as np
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
class Addressing(Model):
def __init__(self, memory_locations=128, memory_vector_size=20, maximum_shifts=3, reading=True):
super(Addressing, self).__init__()
... |
# grep a csv file for an expression and copy the csv header into the output
import os
import sys
from misc import *
if len(sys.argv) < 3:
err("usage: csv_grep [pattern] [input csv file]")
pattern, filename = sys.argv[1], sys.argv[2]
grep_file = filename + "_grep" # grep results go here
a = os.system("grep " + pat... |
import glob
import os
import numpy as np
import pandas as pd
from common.paths import POWER_FC, ADHD, PLS_WEIGHTS, RIDGE_WEIGHTS, BIOBANK_LABELS
from common.power_atlas import to_power_fc_vector, get_power_fc_vector_labels
from common.wisc import WISC_LEVEL
def get_data(wisc_level=5, label_path=ADHD):
"""
G... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
s = input("Введите строку:")
count = 0
vowels = {'е', 'ы', 'а', 'о', 'э', 'я', 'и', 'ю'}
for letter in s:
if letter in vowels:
count += 1
print("Количество гласных равно:")
print(count)
|
try:
from sshtunnel import SSHTunnelForwarder
except ImportError:
from sshtunnel.sshtunnel import SSHTunnelForwarder
from cm_api.api_client import ApiResource, ApiException
from cm_api.endpoints.services import ApiService, ApiServiceSetupInfo
import paramiko
import json
import yaml
import requests
import subpro... |
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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 ... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... |
from abc import ABCMeta, abstractmethod
from copy import deepcopy
import attr
from utensor_cgen.utils import MUST_OVERWRITEN
class Morphism(object):
__metaclass__ = ABCMeta
@abstractmethod
def apply(self, from_op):
raise RuntimeError('abstract transform invoked')
@attr.s
class TypedMorphism(Morphism):
... |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
from essmc2.utils.registry import Registry
HOOKS = Registry("HOOKS")
|
## Yoni Schirris. 06/10/2020
## Exact copy of main.py (now main_unsupervised.py)
## Idea is to keep functionality of both supervised and unsupervised in here, with some switches that change only minor
## things to switch between supervised and unsupervised learning.
## Thus, in the end, we should again have a single "m... |
"""
Deuce Valere - Tests - API - System - Manager
"""
import datetime
import unittest
from deuceclient.tests import *
from deucevalere.api.system import *
class DeuceValereApiSystemManagerTest(unittest.TestCase):
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
... |
# sum_of_multiplications([(1, 2), (5, 10)]) should return 52
# because (1 * 2 + 5 * 10) is 52
def sum_of_multiplications(l):
sum = 0
for value1, value2 in l:
sum += value1 * value2
return sum
if __name__ == '__main__':
print(sum_of_multiplications([(1, 2), (5, 10)])) |
"""
This is the plugin code for threshold segmentation(binary) of rectilinear grid.
This plugin is designed to segment a grid such that cells with magnitude greater than the threshold value are
labelled as 1, otherwise labelled as 0. This provides the ground truth results for
such a fluid segmentation.
Accepted input d... |
"""
对Kaiming He新提出的MAE的简要实现
"""
# ----------------------------------------------------------------
# borrowed from https://github.com/IcarusWizard/MAE.git
# ----------------------------------------------------------------
import numpy as np, torch
import torch.nn as nn
from .transformer import Encoder
def random_ind... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('barsystem', '0037_auto_20150721_1500'),
]
operations = [
migrations.RenameField(
model_name='product',
... |
import unittest
from unittest.mock import Mock, MagicMock
import math
import shapely as sh
import shapely.geometry
import numpy as np
import numpy.testing
import shart
from shart.box import *
class TestMain(unittest.TestCase):
def test_attribute(self):
g = Group.rect(0, 0, 100, 100)
self.asse... |
#! /Users/bin/env Python
# Modified version of get_disease.py from ClinGen/LoadData. Creates JSON file
# with all Orphanet data for (initial) load into the server. Run this script
# before using this one:
# obtain_external_data_files.py -s orphanet
import json
from uuid import uuid4
from xml.etree import ElementTre... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bunch of fixtures to be used across the tests."""
import pytest
@pytest.fixture(scope="function")
def hello_world(request):
"""Create a test fixture."""
hw = "Hello World!"
def tear_down():
# clean up here
pass
request.addfinalizer(t... |
from __future__ import absolute_import
from datetime import timedelta
from celery.schedules import crontab
from .celery import app
from django.conf import settings
RESULT_BACKEND = 'django-db'
# Mitigate deprecation error:
# The 'BROKER_URL' setting is deprecated and scheduled for removal in
# version 6.0.0. ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.