text stringlengths 1 927k |
|---|
'''
Author: Luke Hebert
Date begun: December 16th, 2019
Description: finds either the intersection, union, or unique items from a set of n lists
especially useful for comparing lists of genes
inputs for unique option need to be .txt files; this could be easily tweaked though
all input and output are forced to upper ... |
import os
from PIL import Image, ImageDraw
from tqdm import tqdm
def label_bg_layer(img_path, label_path, img_type):
bg_data_list = os.listdir(img_path)
label_list = os.listdir(label_path)
label_prefix_list = []
for label in label_list:
label = os.path.splitext(label)[0]
label_prefix_li... |
"""Deaths indicators."""
from etl.common import to_json_stat, write_to_file
from etl.config_deaths import deaths_cfg as cfg
from etlstat.extractor.extractor import xlsx
import json
import pandas as pd
def transform(df, periods, prefix=''):
"""Slice dataframe. Generate time period column.
df (dat... |
from mollie.api.objects.chargeback import Chargeback
from .utils import assert_list_object
PAYMENT_ID = 'tr_7UhSN1zuXS'
CHARGEBACK_ID = 'chb_n9z0tp'
def test_get_payment_chargebacks_by_payment_id(client, response):
"""Get chargebacks relevant to payment by payment id."""
response.get('https://api.mollie.com... |
from math import sqrt
from itertools import izip
from numpy import mean
from py_variance_std import t_percentile
def calc_slope(r, sdy, sdx): return r * (float(sdy)/sdx)
def line_fitting(x_arr, y_arr):
"""
using straight line y = mx + c;
m(of a sample data points) = Covariance(X,Y)/Covariance(X,X) =
... |
import numpy as np
from scipy.integrate import simps
import scipy.constants as const
def compute(theta_in, f, beta, L, n=None):
"""compute number of photons due to Frank-Tamm and Fresen equations
theta (ndarray/list[float]): Angles in chosen wavelength range
f (ndarray/list[float]): Frequencies in chosen w... |
import numpy as np
import pickle
from model.loss import cross_entropy
from model.layers import Conv2D, Maxpool2D, Dense, Flatten, ReLu, Softmax
class LeNet5:
"""Implementation of LeNet 5 for MNIST
http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf
"""
def __init__(self, weights_path=None):
... |
"""
model.py
--------
This module provides a class and methods for building and managing a model with tensorflow.
By: Sebastian D. Goodfellow, Ph.D., 2018
"""
# Compatibility imports
from __future__ import absolute_import, division, print_function
# 3rd party imports
import os
import sys
import json
import pickle
imp... |
import setuptools
setuptools.setup(
name="wxparams",
version="1.5",
author="Yoshiki Kato",
# author_email="",
description="Weather Parameters Calculator",
long_description="This is a python module for calculating meteorological parameters.",
long_description_content_type="text/markdown",
... |
import numpy as np
import tensorflow as tf
def __perms(n):
if not n:
return
p = []
for i in range(0, 2**n):
s = bin(i)[2:]
s = "0" * (n-len(s)) + s
s_prime = np.array(list(map(lambda x: int(x), list(s))))
p.append(s_prime)
return p
def care(normal, bias, exa... |
# Name: gizmos.py
# Purpose: XML handlers for wx.gismos classes
# Author: Roman Rolinsky <rolinsky@femagsoft.com>
# Created: 09.07.2007
# RCS-ID: $Id$
import wx
import wx.xrc as xrc
import wx.gizmos as gizmos
class LEDNumberCtrlXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
... |
import os
import json
import yaml
from typing import OrderedDict
from yaml.loader import FullLoader
from paths import RANDO_ROOT_PATH
class loot_tables:
def get_loot_tables(self, options):
with (RANDO_ROOT_PATH / 'loot_table_categories.yaml').open('r') as loot_tables:
self.loot_table_list = y... |
#!/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... |
class CopyPixelOperation(Enum,IComparable,IFormattable,IConvertible):
"""
Determines how the source color in a copy pixel operation is combined with the destination color to result in a final color.
enum CopyPixelOperation,values: Blackness (66),CaptureBlt (1073741824),DestinationInvert (5570569),MergeCopy (1258... |
import pygame
from random import sample, randint, random
from tabulate import tabulate
config = {
"cell_width" : 50,
"cell_height" : 50,
"cell_color" : (235,235,235),
"cell_color_hover" : (220,220,255),
... |
# @file
# The application entry point. Run this file to use the FadZmaq Server.
#
# FadZmaq Project
# Professional Computing. Semester 2 2019
#
# Copyright FadZmaq © 2019 All rights reserved.
# @author Lachlan Russell 22414249@student.uwa.edu.au
# @author Jordan Russell jordanrussell@live.com
# @autho... |
# 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... |
"""Grasshopper - Terminal game combat function - Return remaining health after
taking damage.
# 1 Best Practices solution by ZozoFouchtra and others
def combat(health, damage):
return max(0, health-damage)
"""
def combat(health, damage):
"""Find remaining health after taking damage."""
return 0 if healt... |
#
# 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 re
def extract_libraries(files):
"""Extracts a list of imports that were used in the files
Parameters
----------
files : []string
Full paths to files that need to be analysed
Returns
-------
dict
imports that were used in the provided files, mapped against the langu... |
from unittest import TestCase
import python_gyg
import datetime
GYG_API_KEY = "<your_api_key>"
class TestLocation(TestCase):
def test_is_GetYourGuide_isntance(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s, python_gyg.GetYourGuide))
# def test_get_locatio... |
import gzip, zlib, base64
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
__copyright__ = """\
(c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved.
Published under Creative Commons License
(http://creativecommons.org/licenses/by-nc/3.0/)
restricted to non-... |
"""
Cart-pole balancing with independent discretization
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from rlpy.Domains import Pacman
from rlp... |
from datetime import date
from functools import wraps
from django.contrib import messages
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext
from django.views.decorators.http import require_POST
from ...discount.models import Vouch... |
#-*- encoding: utf-8 -*-
"""
Cuboid route
A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, sits in the opposite corner. By travelling on the surfaces of the room the shortest "straight line" distance from S to F is 10 and the path is shown on the diagram.
However, there are up ... |
from django.core.management.base import BaseCommand
from django.utils import timezone
from url_migration import models
class Command(BaseCommand):
def handle(self, **options):
for rule in models.UrlRegexpMapping.objects.filter(last_usage__isnull=False):
self._remove_if_unused(rule)
fo... |
# Copyright 2021 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
import json
import logging
import os
from urllib.parse import urlparse
from genson import SchemaBuilder
from .contract_renderer import ContractRenderer
from .strict_schema_builder import StrictSchemaBuilder
LO... |
"""
WSGI config for nifty 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.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTING... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from preggy import expect
import thumbor.metrics
from tests.base im... |
import numpy
import scipy
import glob
from matplotlib import pyplot
from scipy import misc
from numpy import random
random.seed(0)
SIZE = 128
ORIGINAL = '../data/offline-data/black-and-white-images/original'
HIGH = '../data/offline-data/black-and-white-images/train/high'
LOW = '../data/offline-data/black-and-white-ima... |
# Common libs
import time
import os
import sys
# Custom libs
from utils.config import Config
from utils.trainer import ModelTrainer
from models.KPFCNN_model import KernelPointFCNN
# Dataset
from datasets.ThreeDMatch import ThreeDMatchDataset
# ------------------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-rest-admin
------------
Tests for `django-rest-admin` models module.
"""
from django.test import TestCase
from django_rest_admin import models
class TestDjango_rest_admin(TestCase):
def setUp(self):
pass
def test_something(self):
... |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.11
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ... |
import os
RED = 31
GREEN = 32
BLUE = 34
MAGENTA = 35
def color(code, string):
return '\033[' + str(code) + 'm' + string + '\033[0m'
def display_path(path):
return color(MAGENTA, path)
def colon():
return color(BLUE, ':')
EXCLUDE_DIRS = ['.git', '.vagrant']
def project_path():
# One dirname fo... |
from insertion import insertion
def test_unique_values():
lst = [8,4,23,42,16,15]
expected = [4,8,15,16,23,42]
actual = insertion(lst)
assert actual == expected
def test_duplicate_value():
lst = [8,4,23,42,16,15,8,23]
expected = [4,8,8,15,16,23,23,42]
actual = insertion(lst)
assert act... |
# Copyright 2019 Nokia
#
# 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, softwa... |
from .directoryObj import DirectoryObj |
class User:
def __init__(self, id: str, name: str, color: str, studon: str):
self.id = id
self.name = name
self.color = color
self.studon = studon
class Role:
def __init__(self, id: str, name: str, color: str):
self.id = id
self.name = name
self.color = c... |
import numpy as np
from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver
class Unlensed(object):
"""
class of a single point source in the image plane, aka star
parameters: ra_image, dec_image, point_amp
"""
def __init__(self):
pass
def image_position(self,... |
# LinkedList implementation using a helper Element class
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
... |
"""
Performs a GridSearch to find the best parameters for the SuperVectorizer
among a selection.
"""
import logging
import pandas as pd
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from dirty_cat impo... |
import pyautogui
pyautogui.PAUSE = 5
while True:
# Click first email in list.
pyautogui.click(640, 345)
# Stop it
pyautogui.click(1760, 430)
pyautogui.click(980, 1020)
pyautogui.typewrite("STOP")
pyautogui.press('enter')
pyautogui.click(580, 220) |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dove.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... |
#!/usr/bin/env pnpython3
#
# Simple program to read and display SEG-Y file
#
# Steve Azevedo
#
import argparse
import logging
import os
from ph5.core import segy_h, ibmfloat, ebcdic
import construct
PROG_VERSION = '2019.14'
LOGGER = logging.getLogger(__name__)
SAMPLE_LENGTH = {1: 4, 2: 4, 3: 2, 4: 4, 5: 4, 8: 1}
S... |
#!/usr/bin/env python
#
# Copyright 2012 Splunk, 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 ... |
class palindrome:
def __init__(self):
self.a=""
def input(self,k1):
self.a=k1
def calculate(self):
f=0
j=len(k1)-1
while i<len(k1)/2:
if k1[i]!=k1[j]:
f=1
else:
i=i+1
j=j-1
if f==0:
print "self.a is palindrome"
else:
print "self.a is not a palindrome"
x=palindrome(... |
#!/usr/bin/python
#
# (c) 2017 Apstra Inc, <community@apstra.com>
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, or
# (at your opt... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import re
import scipy.stats as stats
from scipy.io import wavfile
import numpy as np
import os
raw_folder = './raw'
pattern_date = re.compile('[0-9]{8}')
female_pattern = re.compile('[Ff]emale')
male_pattern = re.compile('[Mm]ale')
american_pattern = r... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
__version__ = '1.61.55'
# -----------------------------------------------------------------------------
import asyncio
import concurrent.futures
import socket
import certifi
import aiohttp
import ssl
import sys
i... |
from __future__ import division, print_function
import six
from time import time, ctime
from subprocess import PIPE, CalledProcessError
if six.PY3:
from subprocess import run
else:
from subprocess import check_call
class Executor(object):
"""
Log and execute shell commands.
@param dryRun: If C{... |
infile = open('500_users_to_images.train', 'r')
outfile = open('pinterest.data', 'w')
for line in infile.readlines():
user_id, img_id, img_url = line.strip().split('\t')
dec_user_id = str(int(user_id) - 1)
outfile.write("{}\t{}\t{}\n".format(dec_user_id, img_id, img_url))
infile.close()
outfile.close() |
# Generated by Django 2.1.15 on 2020-08-24 07:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
... |
# Train multiple images per person
# Find and recognize faces in an image using a SVC with scikit-learn
"""
Structure:
<test_image>.jpg
<train_dir>/
<person_1>/
<person_1_face-1>.jpg
<person_1_face-2>.jpg
.
.
<p... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from aldryn_newsblog.utils.migration import rename_tables_old_to_new, rename_tables_new_to_old
class Migration(SchemaMigration):
def forwards(self,... |
from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
# from typing import cast as typecast
import json
import logging
import os
import yaml
from .config import Config
from .acresource import ACResource
from ..utils import parse_yaml, dump_yaml
AnyDict = Dict[str, Any]
HandlerResult = Optional[Tuple[st... |
"""
pyexcel.sheets
~~~~~~~~~~~~~~~~~~~
Core functionality of pyexcel, data model
:copyright: (c) 2014-2017 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
"""
# flake8: noqa
from .sheet import Sheet
from .matrix import Matrix, transpose, Row, Column |
from .tool.func import *
from . import main_error_404
def main_file_2(conn, data):
curs = conn.cursor()
if data == 'easter_egg.html':
return easy_minify(flask.render_template(skin_check(),
imp = ['easter_egg.html', wiki_set(), custom(), other2([0, 0])],
data = open('./views/mai... |
import os
import pandas as pd
from easysparql import *
ENDPOINT = "https://dbpedia.org/sparql"
MIN_NUM_OF_ENT_PER_PROP = 30 # the minimum number of entities per property (get_properties)
QUERY_LIMIT = "" # At the moment, we do not put any limit on the number of results
MIN_NUM_NUMS = 30 # The minimum number of valu... |
#
# Copyright (c) 2018-2020 by Kristoffer Paulsson <kristoffer.paulsson@talenten.se>.
#
# This software is available under the terms of the MIT license. Parts are licensed under
# different terms if stated. The legal terms are attached to the LICENSE file and are
# made available on:
#
# https://opensource.org/lice... |
from collections import OrderedDict
from functools import partial
from operator import attrgetter
from typing import TYPE_CHECKING, List, no_type_check
from funcy import post_processing
from dvc.dependency import ParamsDependency
from dvc.output import BaseOutput
from dvc.utils.collections import apply_diff
from dvc.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..builder import LOSSES
from .utils import weight_reduce_loss
eps = 0.000001
def cross_entropy_without_softmax(pred,
label,
weight=None,
... |
"""
WSGI config for sys_monitor 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/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
from __future__ import absolute_import
import numba
import numpy as np
@numba.jit(nopython=True)
def nms_cpu(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
... |
import pypro.core
import os
class CreateConfig(pypro.core.Recipe):
def __init__(self, source, destination):
self.source = source
self.destination = destination
def run(self, runner, arguments=None):
# Read the template file
content = ''
with open(self.source, 'r') as ... |
#350111
#a3-p10.py
#Gloria Giramahoro
#g.giramahoro@jacobs-university.de
#1.defining a function that prints a rectangle made of a character
def print_frame(n,m,c):
count = 1
if (n >= m):
product1 = n*c
print (product1)
for count in range(1,m-1):
words1 = str(' ')
... |
def nextPermutation(numbers):
size = len(numbers)
tmp = len(numbers) - 1
while (tmp >= 0) and (numbers[tmp - 1] > numbers[tmp]):
tmp -= 1
if (not tmp):
return False
i = tmp - 1
tmp = size - 1
while (tmp > i) and (numbers[tmp] < numbers[i]):
tmp -= 1
j = tmp
... |
from __future__ import absolute_import, division, print_function
import logging
import sys
logging.basicConfig(
stream=sys.stdout,
format='%(asctime)s %(name)s-%(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
import numpy as np
from sklearn.neural_network import MLPClassifier, MLPRegressor
from ... |
import sys
import os
import subprocess
import re
import time
from dataclasses import dataclass
from typing import List
import pandas
time_reg = re.compile("Checkpoint \d: ([\d\\.]{1,})")
def run_cmd(cmd):
print(f"Running {cmd}")
proc = subprocess.run(cmd, shell=True, capture_output=True)
stdout = proc.std... |
import paste.fixture
import pylons.config as config
import ckan.model as model
import ckan.tests.legacy as tests
import ckan.plugins as p
import ckan.lib.helpers as h
import ckanext.reclineview.plugin as plugin
import ckan.lib.create_test_data as create_test_data
import ckan.config.middleware as middleware
from ckan.... |
import numpy as np
from sklearn.cluster import KMeans
import time
from scipy.sparse.linalg import eigs
from scipy.sparse import csr_matrix
class Graph:
def __init__(self, data_name):
self.filename = data_name
self.n = None
self.k = None
self.edges = self.form_graph()
# sel... |
# -*- coding: utf-8 -*-
import re
import scrapy
from crawlstocks.items import GuchengStockCodeItem
class GuchengblockcodesSpider(scrapy.Spider):
name = 'GuchengBlockCodes'
allowed_domains = ['hq.gucheng.com']
custom_settings = {
'ITEM_PIPELINES' : {'crawlstocks.pipelines.file.GuchengCrawlList... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2018-2020 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 requi... |
import os
import re
import datetime
import unittest
from io import StringIO
from unittest.mock import patch
import pandas as pd
import EOD_api as eod
TOKEN = os.environ["EOD_TOKEN"]
def date_parser(string):
date_pattern = re.compile("([0-9]{4}-[0-9]{2}-[0-9]{2})[ ]", re.VERBOSE)
return date_pattern.sub(r"\... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RPmcmrplus(RPackage):
"""Calculate Pairwise Multiple Comparisons of Mean Rank Sums Extende... |
# encoding: utf-8
##################################################
# This script shows how to create animated plots using matplotlib and a basic dataset
# Multiple tutorials inspired the current design but they mostly came from:
# hhttps://towardsdatascience.com/how-to-create-animated-graphs-in-python-bb619cc2dec1
#... |
# -*- coding: utf-8 -*-
# Copyright 1999-2021 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... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
from django.contrib.auth.models import User, Group
from ..models import Team, Role, AccountUser, Organization
from .user import CustomUserAdmin
from .role import RoleAdmin
from .team import TeamAdmin
from... |
from __future__ import print_function
from six.moves import xrange
from theano.gof.type import Type
from theano.gof import graph
from theano.gof.graph import Variable, Apply
from theano.gof.op import Op
from theano.gof.opt import * # noqa
from theano.gof import destroyhandler
from theano.gof.fg import FunctionGraph,... |
# -*- coding: utf-8 -*-
# IgorNLP:ltp 词性标注模块
#
# Author: Igor
import os
import tempfile
from subprocess import PIPE
from nltk.internals import overridden, compat
from inlp.tag.api import TaggerI
from inlp.utils import ltp_cmd
class LtpPosTagger(TaggerI):
'''
ltp 词性标注模块
#test:
sentences = [['这', '是... |
from boa3.builtin import public
@public
def Main(a: bool, b: bool) -> bool:
return a == b |
"""Tasks for use with Invoke.
(c) 2020-2021 Network To Code
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Distances in a grid
# jill-jenn vie et christoph durr - 2014-2015
from collections import deque
# snip{
def dist_grid(grid, source, target=None):
"""Distances in a grid by BFS
:param grid: matrix with 4-neighborhood
:param (int,int) source: pair of row, c... |
"""
Copied and modified from the dev branch of:
https://github.com/genepattern/HierarchicalClustering
on 2018-01-31
"""
import sys
import numpy as np
from statistics import mode
from sklearn.metrics import pairwise
from sklearn import metrics
from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as p... |
from threading import Thread
import socket
import select
import time
import os
import clingo
import argparse
from PyQt5.QtCore import *
class VisualizerSocket(object):
def __init__(self, default_host = '127.0.0.1', default_port = 5000, socket_name = 'socket'):
self._host = default_host
se... |
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA, KernelPCA
from umap import UMAP
from sklearn.preprocessing import MinMaxScaler
RUNEMBEDDINGS = False
if RUNEMBEDDINGS:
#simple PCA
pcaembedding = PCA(n_components=2).fit_transform(XASV.fillna(0))
#base embedding (kernel pca)
... |
class Enterprise:
def __init__(self, name):
if len(name.strip()) == 0:
raise ValueError("Name must be specified.")
self._name = name
def get_name(self):
return self._name |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SelectField, IntegerField
from wtforms.validators import InputRequired, EqualTo, Regexp, Length, NumberRange, Optional, Email
from reminder.custom_wtforms import MxRecordValidator
class NewUserForm(FlaskForm):
"""
Validators for ... |
from ... import BaseModel, db
class Role(BaseModel):
__tablename__ = "role"
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
name = db.Column(db.String())
can_triage_jobs = db.Column(db.Boolean())
can_edit_settings = db.Column(db.Boolean())
can_create_users = db.Column(db.Bo... |
#! /usr/bin/env python
#-----------------------------------------#
#Copyright [2015] [Kelcey Jamison-Damage]
#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/L... |
#
# 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... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sqlalchemy as sa
from h.models import Group, User
from h.models.group import ReadableBy
from h.util import group as group_util
class GroupService(object):
def __init__(self, session, user_fetcher):
"""
Create a new groups se... |
"""Base implementation of event loop.
The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.
Whenever a public API takes a c... |
import unittest
from config import Config
class CommitteeTestCase(unittest.TestCase):
def testCreateCommittee(self):
params = {
"url": " ",
"account": "1.2.25"
}
gph = Config().gph
try:
print("CreateCommittee:", gph.committee_member_create(**par... |
from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import printOut
from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import GenParticle
def findStatus1Leptons(particle):
'''Returns status 1 e and mu among the particle daughters'''
leptons = []
for i in range( particle.numberOfDaughters() ):
... |
from fractions import Fraction
import math
def compute_factors(n):
"""
Return a list of all factors (proper divisors) of a number n, including the factor 1
"""
factors = [1]
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
factors.append(i)
factors.append(n /... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.conf import settings
from django.utils.timezone import (
get_default_timezone, localtime, is_naive, make_aware)
from datetime import datetime
from uw_sws import SWS_DAO, sws_now
from abc import ABC, abstractmethod
... |
#!/usr/bin/python3
"""
Generate a markdown changelog for the rclone project
"""
import os
import sys
import re
import datetime
import subprocess
from collections import defaultdict
IGNORE_RES = [
r"^Add .* to contributors$",
r"^Start v\d+\.\d+(\.\d+)?-DEV development$",
r"^Version v\d+\.\d+(\.\d+)?$",
]
... |
import torch
import numpy as np
import dnnutil.network as network
import time
__all__ = ['calculate_accuracy', 'Trainer', 'ClassifierTrainer', 'AutoencoderTrainer']
def calculate_accuracy(prediction, label, axis=1):
'''calculate_accuracy(prediction, label)
Computes the mean accuracy over a batch of pre... |
"""
This script uses python to build a `.nec` file. This allows
for the use of variables and other arithmetic which is much
easier in python. For information on the cards specified by the
arguments, e.g. EX or RP, check out https://www.nec2.org/part_3/cards/
"""
from datetime import datetime as dt
from math import *
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.