text
stringlengths
1
927k
#MIT License #Copyright (c) 2021 SUBIN #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, distr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- words = { 1: 'one', 2: 'two', 3: 'three', 4: 'four' } dict_items = words.items() new_words = dict(zip(words.values(), words.keys())) print(new_words)
# ============================================================================== # Copyright 2018-2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://ww...
import pickle import numpy as np from PIL import Image def load_pickle_file(path_to_file): """ Loads the data from a pickle file and returns that object """ ## Look up: https://docs.python.org/3/library/pickle.html ## The code should look something like this: # with open(path_to_file, 'rb') as...
from setuptools import setup def read(fname): import os return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='pdtweak', version='0.1.1', description='pandas utility functions', long_description=read('README.md'), long_description_content_type='text/markdown',...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2016 Eric Jacob <erjac77@gmail.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 #...
from common.person import Person from random import randint class PersonTest(Person): def __init__(self, position: list = [0, 0], color: list = [255, 255, 255], size: int = 20, default_position_range=None) -> None: self.color2 = [randint(2, 50), randint(100, 200), randint(10,50)] self.color3 = [ra...
# Generated by Django 2.2.2 on 2019-07-18 13:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0004_auto_20190718_1315'), ] operations = [ migrations.CreateModel( name='Node', fields=[ ...
#!/usr/bin/env python # Copyright 2019 Google 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...
import numpy as np import pickle import argparse import re """ Convert pre-trained Glove embeddings into npy file Run using: python3 generate_embeddings.py -d data/glove.6B.300d.txt --npy_output data/embeddings.npy --dict_output data/vocab.pckl --dict_whitelist data/polaritydata.vocab """ def parse_args(): parser...
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # 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; either version 2 # of the...
#!/usr/bin/env python3 # license removed for brevity #策略 機械手臂 四點來回跑 import rospy import os import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * import math import enum import Hiwin_RT605_ROS as ArmTask pos_feedback_times = 0 mode_feedback_times = 0 msg_feedback ...
_base_ = [ '../_base_/models/fcn_hr18.py', '../_base_/datasets/cityscapes.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_120k.py', ] model = dict( pretrained=None, backbone=dict( type='RevBiFPN_S', arch='revbifpn_s1', strict=False, classes=Non...
import cv2 import numpy as np import six import sys import pickle as pkl from tqdm import tqdm def compress(path, output): with np.load(path, mmap_mode="r", encoding='latin1') as data: images = data["images"] array = [] for ii in tqdm(six.moves.xrange(images.shape[0]), desc='compress'): im = imag...
from .pa_rb_env import ( PAEnv, Node ) import numpy as np from pathlib import Path log2 = np.log2 cues = { 0: Node(0.1, 0, 'cue'), 1: Node(-0.1, 0, 'cue'), } devices = { 0: { 't_device': Node(0, 0.5, 't_device'), 'r_devices': { 0: Node(0, 0.6, 'r_device') } ...
import unittest import commands.flip as flip import pandas as pd class TestFlip(unittest.TestCase): def test_use(self): cycles = 50000 series = pd.Series(flip.use(None) for _ in range(cycles)) self.assertAlmostEqual(len(series[series == "Heads"]) / cycles, 0.4998, delta=0.01) self.a...
from .custom import CustomDataset from .xml_style import XMLDataset from .coco import CocoDataset from .voc import VOCDataset from .loader import GroupSampler, DistributedGroupSampler, build_dataloader from .utils import to_tensor, random_scale, show_ann, get_dataset from .concat_dataset import ConcatDataset from .repe...
import cv2 import numpy as np """ 黑帽: 黑帽= 原图 - 闭运算 morphologyEx(img, MORPH_BLACKHAT, kernel) 保留噪点 """ img = cv2.imread(r'E:\PycharmProjects\funnyPython\opencv_py\data\imgs\dotinj.png') # kernel = np.ones((7, 7), np.uint8)# 手动创建 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) print(kernel) res = cv2.morpholo...
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import pandas as pd import sqlalchemy from config.config import symbol,backward_steps import joblib from df_functions import * def prepare_single_dataset(df,remove_from_heads:int,remove_from_tails:int,label:int): ...
from .routes.users import router as user_router from .application import app import sys sys.path.extend(["./"]) ROUTERS = (user_router,) for r in ROUTERS: app.include_router(r) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8888, log_level="info")
#!/usr/bin/env python import tempfile import unittest from pprint import pprint import otterwiki.storage class TestStorage(unittest.TestCase): def setUp(self): self.tempdir = tempfile.TemporaryDirectory() self.path = '/tmp/xxx' # self.tempdir.name self.path = self.tempdir.name se...
import sys import time from cleversheep3.TTY_Utils import RichTerm, registerForWinch class Status: """A fairly general purpose status line for a simple terminal. """ def __init__(self, startActive=True): self.setTerm(RichTerm.RichTerminal(sys.stdout)) self.spinner = None self.pre...
# -*- coding: utf-8 -*- import unittest import sys, os sys.path.append('../../') from etk.core import Core import json import codecs class TestExtractionsFilterResults(unittest.TestCase): def test_filter_results(self): doc = { "url":"http:www.testurl.com", "doc_id": "19B0EAB211CD...
#!/usr/bin/python # # Cityscapes labels # from collections import namedtuple #-------------------------------------------------------------------------------- # Definitions #-------------------------------------------------------------------------------- # a label and all meta information Label = namedtuple( 'Label...
import math class Solution: def isRectangleCover(self, rectangles: 'List[List[int]]') -> 'bool': area = 0 x1 = y1 = math.inf x2 = y2 = -math.inf table = set() for rec in rectangles: x1 = min(x1, rec[0]) y1 = min(y1, rec[1]) x2 = max(x2, rec...
import os import tempfile import time import unittest from qftplib.client import FTPClient class FTPTest(unittest.TestCase): host = os.environ.get('SFTP_HOST_TEST') user = os.environ.get('SFTP_USER_TEST') password = os.environ.get('SFTP_PASS_TEST') dir = os.environ.get('SFTP_DIR_TEST') port = 22 ...
from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """...
# Generated by Django 2.2 on 2021-03-18 17:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0003_auto_20210307_1711'), ] operations = [ migrations.AlterField( model_name='post', ...
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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...
# -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding 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 require...
import unittest from translator import english_to_french, french_to_english class TestEnglishToFrench(unittest.TestCase): def testE2F(self): self.assertEqual(english_to_french("Hello"), "Bonjour") self.assertNotEqual(english_to_french("Null"), "") class FrenchEnglishToEnglish(unittest.TestCase):...
""" This module tests cadquery creation and manipulation functions """ # system modules import math, os.path, time, tempfile from random import choice from random import random from random import randrange from itertools import product from pytest import approx, raises # my modules from cadquery import * from c...
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v2.model_utils import ( # noqa: F401 ApiTypeError, Mo...
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance_1024.py', '../_base_/schedules/schedule_20e.py', '../_base_/default_runtime.py', ] optimizer = dict(lr=0.01) model = dict( pretrained=\ './checkpoints/lesa_pretrained_imagenet/'+\ 'lesa_resnet50_pre...
from typing import Union, Set from injectable import InjectionContainer from injectable.common_utils import get_dependency_name from injectable.container.injectable import Injectable from injectable.constants import DEFAULT_NAMESPACE def clear_injectables( dependency: Union[type, str], namespace: str = None ) ->...
#! /usr/bin/env python # coding=utf-8 import os from setuptools import setup, find_packages from fnmatch import fnmatchcase from distutils.util import convert_path def read(*parts): return open(os.path.join(os.path.dirname(__file__), *parts)).read() # Provided as an attribute, so you can append to these instea...
""" Provides the :class:`Arrow <arrow.arrow.Arrow>` class, an enhanced ``datetime`` replacement. """ import calendar import sys from datetime import date from datetime import datetime as dt_datetime from datetime import time as dt_time from datetime import timedelta from datetime import tzinfo as dt_tzinfo from math...
# pylint: disable=no-value-for-parameter import click from utils.misc import delfile from utils.configs import validate, parse_yaml_config from utils.cert import prepare_ca, SSL_CERT_KEY_PATH, SSL_CERT_PATH, get_secret_key from utils.db import prepare_db from utils.jobservice import prepare_job_service from utils.reg...
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
import tltk_mtl as MTL import tltk_mtl_ext as MTLE def testNextRule(): preds = {} preds['pred1'] = MTL.Predicate('pred1', 1, 2) preds['pred2'] = MTL.Predicate('pred2', 2, 4) preds['pred3'] = MTL.Predicate('pred3', 4, 8) assert isinstance(MTLE.parse_mtl('next pred1', preds), MTL.Next), printFail(1) printPass(1)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 30 20:49:32 2019 @author: rluo """ import keras import matplotlib.pyplot as plt from keras.models import load_model import pickle history = pickle.load(open('history.p','rb')) plt.plot(history['loss']) #plt.plot(history['val_loss']) plt.title('mod...
import logging from simpletransformers.seq2seq import Seq2SeqModel logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogger("transformers") transformers_logger.setLevel(logging.ERROR) model = Seq2SeqModel(encoder_decoder_type="bart", encoder_decoder_name="outputs") while True: original ...
from PyQt5.QtWidgets import QApplication,QWidget,QTextEdit,QVBoxLayout,QPushButton from link_converter import convert_url import pyperclip import sys class LinkConverter(QWidget): def __init__(self,parent=None): super().__init__(parent) self.setWindowTitle("Ensemblevideo Link Converter - Dennis Fa...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
"""Functional test.""" import os import os.path from jicbioimage.core.image import MicroscopyCollection from jicbioimage.core.io import ( AutoName, DataManager, FileBackend, _md5_hexdigest_from_file, ) from plasmodesmata_analysis import plasmodesmata_analysis def test_plasmodesmata_analysis(): o...
# 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...
import pyperclip import pandas as pd from modulos.conecao import * def copiar(objeto): # função para copiar os objetos para área de transferência global copiar # para resolver o porblema UnboundLocalError: local variable 'copiar' referenced before assignment: opcao = int(input('Deseja copiar para área de tr...
import datetime from django.contrib.admin import ModelAdmin from django.contrib.admin.templatetags.admin_list import date_hierarchy from django.contrib.admin.templatetags.admin_modify import submit_row from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.test import R...
import logging from typing import Any, Dict, List, Tuple import difflib import sqlparse from overrides import overrides import torch from allennlp.common.util import pad_sequence_to_length from allennlp.data import Vocabulary from allennlp.data.fields.production_rule_field import ProductionRuleArray from allennlp.sem...
from charms.reactive import ( Endpoint, set_flag, clear_flag ) from charms.reactive import ( when, when_not ) class ContainerRuntimeRequires(Endpoint): @when('endpoint.{endpoint_name}.changed') def changed(self): set_flag(self.expand_name('endpoint.{endpoint_name}.available')) ...
#!/usr/bin/env python3 import argparse class Formatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser( description='''Read EXIF data Author: Kiyoon Kim (yoonkr33@gmail.com)''', formatter_class=Formatter) parser.add_argument('i...
from django.urls import path from ProductApp.views import ( HomePageView, CategoriesView, ProductDetailView, CategoryDetailView, ) urlpatterns = [ path("categories/<slug:slug>/", CategoryDetailView.as_view(), name="category-detail"), path("categories/", CategoriesView.as_view(), name="categor...
""" Chembl uploader """ # pylint: disable=E0401, E0611 import os import glob import pymongo import biothings.hub.dataload.storage as storage from biothings.hub.dataload.uploader import ParallelizedSourceUploader from hub.dataload.uploader import BaseDrugUploader from hub.datatransform.keylookup import MyChemKeyLookup f...
from __future__ import division import argparse from mmcv import Config from mmcv.runner import load_checkpoint from mmfashion.apis import get_root_logger, init_dist, test_cate_attr_predictor from mmfashion.datasets.utils import get_dataset from mmfashion.models import build_predictor def parse_args(): parser =...
from ..ioc import interface, model from ..types import HTTPResponse, UUID, Timestamp, Optional, List from ..util.generate_spec import generate_spec @model class CriterionModel: ''' type: object required: - user - name properties: id: type: string description: Criterion ID example: d29...
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Lorenzo De Santis <lorenzo.de-santis@u-psud.fr> # # License: BSD (3-clause) from functools import partial import glob import os impor...
import torch import torch.nn as nn """ usage z_rand = generate_noise([1,nzx,nzy], device=opt.device) z_rand = z_rand.expand(1,3,Z_opt.shape[2],Z_opt.shape[3]) z_prev1 = 0.95*Z_opt +0.05*z_rand """ def upsampling(im, sx, sy): m = nn.Upsample(size=[round(sx), round(sy)], mode='...
import argparse from hugsvision.nnet.VisionClassifierTrainer import VisionClassifierTrainer from hugsvision.dataio.VisionDataset import VisionDataset from torchvision.datasets import ImageFolder from transformers import DeiTFeatureExtractor, DeiTForImageClassification parser = argparse.ArgumentParser(description='Im...
''' This problem was recently asked by Google: Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions? Example: Input: 4 -> 3 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 2 -> 3 -> 4 -> NULL ''' class ListNode(object): def __init__(self, x): self....
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path from time import monotonic from typing impor...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Experiment with a gaussian naive bayes model with a variety of balancing techniques on the cleaned data set """ __author__ = "John Hoff" __email__ = "john.hoff@braindonor.net" __copyright__ = "Copyright 2019, John Hoff" __license__ = "Creative Commons Attribution-...
############################################################################## # # Copyright (c) 2001, 2002, 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution...
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from .flags import FlagGroups from .wsr import WSRFile class CSRFile: '''A model of the CSR file''' def __init__(self) -> None: self.flags = FlagGroups() ...
#!/usr/bin/env python # 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 applicab...
from .tool.func import * def api_raw_2(conn, name): curs = conn.cursor() if acl_check(name, 'render') != 1: curs.execute("select data from data where title = ?", [name]) data = curs.fetchall() if data: json_data = { "title" : name, "data" : render_set(title = name, data = d...
# Generated by Django 2.2 on 2020-01-15 06:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rates', '0002_auto_20200113_0757'), ] operations = [ migrations.CreateModel( name='Rating', fields=[ (...
import setuptools from variations import __version__ with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='sphinx-variations', version=__version__, author='D. Lawrence', author_email='trea@treamous.com', description='Create multiple variations of your Sphinx H...
import json from django import http from django.core.exceptions import PermissionDenied from django.test import RequestFactory, TestCase from nose.tools import eq_ from sumo.decorators import json_view rf = RequestFactory() JSON = 'application/json' class JsonViewTests(TestCase): def test_object(self): ...
#!/usr/bin/python """ This python script was created to find missing files in given folders. Copyright (c) 2016 Thomas Richard Following MIT license (see copying.txt) The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, f...
import time import os def pp(message, mtype='INFO'): mtype = mtype.upper() print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message) def ppi(channel, message, username): print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), ...
import tkinter as tk from PIL import ImageTk, Image from file_import import FileImport class Buttons: def __init__(self, parent, player): self.player = player self.parent = parent #clean these up unskip_img = ImageTk.PhotoImage(Image.open("assets/unskip.png").resize((25,25))) ...
import asyncio import pytest import pytest_asyncio from chia.simulator.simulator_protocol import FarmNewBlockProtocol from chia.types.peer_info import PeerInfo from chia.util.ints import uint16, uint32, uint64 from tests.setup_nodes import self_hostname, setup_simulators_and_wallets from chia.wallet.did_wallet.did_wall...
class Gender: NEUTRAL = 1 FEMALE = 2 MALE = 3 GENDER_STRINGS = {NEUTRAL: "neutral", FEMALE: "female", MALE: "male" } def __init__(self, gender: int = 1): self.gender: int = gender def __str__(self): return self....
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test logic for setting nMinimumChainWork on command line. Nodes don't consider themselves out of "initial b...
import numpy as np import scipy from scipy.sparse import linalg from sklearn.metrics import accuracy_score class LSSVM: def __init__(self, kernel = 'linear', C = 1.0,gamma = 1.0, d = 2.0): kernels = { 'rbf':self.rbf, 'poly':self.polynomial, 'linear':self.linear }...
''' - Leetcode problem: 56 - Difficulty: Medium - Brief problem description: Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Inpu...
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.EGL import _types as _cs # End users want this... from OpenGL.raw.EGL._types import * from OpenGL.raw.EGL import _errors from OpenGL.constant import Constant as _C import ctype...
import cv2 import numpy as np cap = cv2.VideoCapture(0) kernel = np.ones((5, 5), np.uint8) while True: success, img = cap.read() cv2.imshow("Cam", cv2.Canny(img, 100, 100)) if cv2.waitKey(1) & 0xFF == ord('q'): break
O = input() soma = count = 0 for linha in range(12): for coluna in range(12): num = float(input()) if linha <= 4 and (10 - linha) >= coluna > linha: soma += num count += 1 if O == "S": print(f"{soma:.1f}") elif O == "M": media = soma / count print(f"{media:.1f}")
def isPointInSquare(x, y): return 1.0 >= x >= -1.0 and 1.0 >= y >= -1.0 x = float(input()) y = float(input()) if isPointInSquare(x, y) == True: print('YES') else: print('NO')
from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('<str:name>', views.greet, name="greet"), # path('david/', views.david, name="david"), ]
from django import forms from django.utils.translation import gettext_lazy as _ from .models import Diary class DiaryModelForm(forms.ModelForm): class Meta: widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), 'daily_record': forms.Textarea(attrs={'rows': 4, 'class': 'cked...
from ast import literal_eval import enum import logging from . import db from .Base import Base LOG = logging.getLogger(__name__) class ValueType(enum.Enum): Int = (1, int, int) Bool = (2, bool, lambda b: b == 'True') Float = (3, float, float) Text = (4, str, lambda s: s) Tuple = (5, tuple, lite...
import cv2 import numpy as np from random import randint, uniform import string, random def addNoise(image): row,col = image.shape s_vs_p = 0.4 amount = 0.01 out = np.copy(image) # Salt mode num_salt = np.ceil(amount * image.size * s_vs_p) coords = [np.random.randint(0, i - 1, int(num_...
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import url from django.contrib import admin from django.forms.models import modelform_factory from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .. import settings as filer_settings from .....
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from indico.modules.events.reminders.controllers import (RHAddRem...
from datetime import datetime from flask import current_app, jsonify from flask_bcrypt import Bcrypt import json from api.extensions import db, Base, ma class User(db.Model): """ This model holds information about a user registered """ __tablename__ = "user" id = db.Column(db.Integer, primary_key...
import sys import re import string # dictionary to store clean data. cleaned_data = {} # list of professors professors = [] # list of courses courses = [] def createdict(profname, course_list): new_course_list = [] is_course_match = False profname = profname.title() prof_courses = course_list.split('...
from typing import Any, List from thinc.neural.ops import get_array_module from spacy.pipeline import Pipe from spacy.tokens import Doc from spacy.vocab import Vocab from spacy.util import minibatch from ..wrapper import PyTT_Wrapper from ..model_registry import get_model_function from ..activations import Activations...
#!/usr/bin/env python3 import argparse import logging import numpy as np import pystella as ps from pystella.model.sn_tau import StellaTauDetail mpl_logger = logging.getLogger('matplotlib') mpl_logger.setLevel(logging.WARNING) __author__ = 'bakl' # todo Show filters # todo show valuse for filters # todo compute SE...
''' PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GRA...
#!/usr/bin/env python # # 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 struct import time import six from six import iteritems from .batch import Batch def _check_table_existence(method): def wrap(table, *args, **kwargs): if not table._exists(): raise IOError('TableNotFoundException: %s' % table.name) return method(table, *args, **kwargs) retu...
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
import torch # import torchtext import torch.nn as nn # from torchtext.vocab import Vocab, build_vocab_from_iterator # from torchtext.utils import unicode_csv_reader # from torchtext.data.datasets_utils import _RawTextIterableDataset from torch import Tensor from typing import Iterable, List # import sentencepiece as s...
# -*- coding: utf-8 -*- """ Module for reading/writing data from/to legacy PyNN formats. PyNN is available at http://neuralensemble.org/PyNN Classes: PyNNNumpyIO PyNNTextIO Supported: Read/Write Authors: Andrew Davison, Pierre Yger """ from itertools import chain import numpy import quantities as pq import...
""" WSGI config for class_book project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SE...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Read obs from NDBC and Co-opc Generate csv data files functions to write and read the data Observations will be chosen based on the hurricane track to avoid more than neccessary download. """ __author__ = "Saeed Moghimi" __copyright__ = "Copyright 2018, UCAR/NOAA" __...
# -*- coding: utf-8 -*- """ OpenCV Python image average color detection script. You can use this to finding darkest color. Coded by : Lakmal Niranga. 2016 """ import os import cv2 from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return ...