content stringlengths 5 1.05M |
|---|
'''
Box-and-whisker plot
100xp
Making a box plot for the petal lengths is unnecessary because the iris data set is
not too large and the bee swarm plot works fine. However, it is always good to get
some practice. Make a box plot of the iris petal lengths. You have a pandas DataFrame,
df, which contains the petal lengt... |
from django.conf.urls import url
from . import views
urlpatterns = [
# /maps/
url(r'^$', views.index, name='maps'),
# /maps/[map_id]
url(r'^(?P<map_id>[0-9]+)$', views.rest, name='maps_rest'),
# /maps/[map_id]/editor
url(r'^(?P<map_id>[0-9]+)/editor', views.editor, name='maps_editor')
] |
from biosimulators_test_suite import __version__
from biosimulators_test_suite.data_model import TestCase
from biosimulators_test_suite.results.data_model import TestCaseResult, TestCaseResultType
from biosimulators_test_suite.results.io import write_test_results
from biosimulators_test_suite.warnings import TestCaseWa... |
"""
:Authors: cykooz
:Date: 06.12.2016
"""
try:
import pytest
pytest.register_assert_rewrite(
'restfw.testing.resource_testing',
'restfw.testing.webapp',
)
except (ImportError, AttributeError):
pass
from .resource_testing import assert_resource
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""subcmd_eprimer3.py
Provides the eprimer3 subcommand for pdp
(c) The James Hutton Institute 2017-19
Author: Leighton Pritchard
Contact: leighton.pritchard@hutton.ac.uk
Leighton Pritchard,
Information and Computing Sciences,
James Hutton Institute,
Errol Road,
Invergo... |
#!/usr/bin/env python
from resync.resource import Resource
from resync.resource_list import ResourceList
from resync.list_base_with_index import ListBaseIndexError
import sys
try:
max_sitemap_entries = int(sys.argv[1])
except:
max_sitemap_entries = 2
print "### max_sitemap_entries=%d" % max_sitemap_entries
ba... |
# Algebraic-only implementation of two's complement in pure Python
#
# Written by: Patrizia Favaron
def raw_to_compl2(iRaw, iNumBits):
# Establish minimum and maximum possible raw values
iMinRaw = 0
iMaxRaw = 2**iNumBits - 1
# Clip value arithmetically
if iRaw < iMinRaw:
iRaw = iMinRaw
if iRaw > iMaxRaw:
... |
import os, io, boto3, json, csv
# grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
runtime= boto3.client('runtime.sagemaker')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
data = json.loads(json.dumps(event))
payload = data['data']
p... |
# class to represent a graph object
class Graph:
# Constructor
def __init__(self, edges, N):
# A List of Lists to represent an adjacency list
self.adjList = [[] for _ in range(N)]
# stores in-degree of a vertex
# initialize in-degree of each vertex by 0
self.indegree = [0] * N
# add edges to the undir... |
import obspython as _obs
import threading
import traceback
from . import data as _data
from . import _helper
class Future:
_NOTSET = object()
_EXCEPTION = object()
_INTERRUPT = object()
_WAITING = []
def __init__(self):
self._result = self._NOTSET
self._exception = None
se... |
#!/usr/bin/env python
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
SITE_ID = 1
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.contenttypes',
'jsonfield_schema',
'tests'
]
D... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import warnings
import numbers
import numpy as np
from scipy import sparse
from . i... |
# Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import traceback
from PyQt5 import Qt
from lxml import etree
from lxml import html
# pip install cssselect
from lxml.cssselect import CSSSelector
def to_str(x):
try:
# return etree.tounicode(x, method='html')
return etre... |
from pydex.core import designer
|
#!/usr/bin/env python
# Copyright 2016 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 requi... |
from django.conf.urls.defaults import *
from django.views.generic import TemplateView, RedirectView
from democratica import settings
from democratica.deputados.models import MP, Party, Mandate, LinkSet, Legislature, Fact, FactType, Activity
import democratica.deputados.views as views
import democratica.dar.views as dar... |
import torch
import scipy
import numpy as np
def to_numpy(tensor):
if torch.is_tensor(tensor):
return tensor.cpu().numpy()
elif type(tensor).__module__ != 'numpy':
raise ValueError("Cannot convert {} to numpy array"
.format(type(tensor)))
return tensor
def to_tor... |
import os
import pandas as pd
import json
from danlp.download import DEFAULT_CACHE_DIR, download_dataset, _unzip_process_func, DATASETS
class DanNet():
"""
DanNet wrapper, providing functions to access the main features of DanNet.
See also : https://cst.ku.dk/projekter/dannet/.
Dannet consists of a ... |
import pandas as pd
import numpy as np
import pytest
from visions.core.dtypes.boolean import BoolDtype
@pytest.mark.parametrize(
"series,expected_values,expected_dtype",
[
(pd.Series([True, False], dtype="Bool"), (True, False), "Bool"),
(pd.Series([True, False], dtype=bool), (True, False), bo... |
import numpy as np
import flask
from flask import Flask, request, jsonify, render_template
from flask import Flask,render_template,session,url_for,redirect
import pandas as pd
from rdkit import DataStructs
from rdkit import Chem
from rdkit.Chem import Descriptors, Lipinski
from rdkit.Chem import rdMolDescriptors
import... |
"""
Decorrelation experiment shows that the initial overlap in input data 'x'
is decreased due to the w_hy weights that inhibit the overlapped area strongly
than non-overlapped areas.
"""
import numpy as np
from experiment import run_experiment
from networks import *
# Fix the random seed to reproduce the results
np... |
"""Defines methods that call the unversioned Mesos HTTP endpoints"""
from __future__ import unicode_literals
import json
import urllib2
from node.resources.node_resources import NodeResources
from node.resources.resource import ScalarResource
def get_agent_resources(hostname, port, agent_ids):
"""Returns the to... |
"""Utility functionality of the adhtools.
"""
import pandas as pd
from lxml import etree
from tqdm import tqdm
import re
def stemmer_xml2df(fname):
"""Convert SAFAR stemmer XML into a pandas dataframe with words and stems.
"""
result = []
# Extract the words
context = etree.iterparse(fname, events... |
def extractDreamsofyesteryearWordpressCom(item):
'''
Parser for 'dreamsofyesteryear.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return False
if item['title'].startswith("Chapter "):
return buildReleas... |
import os
from pymongo import MongoClient
### IMPORRTANT: make sure to load all these into the env on the running script!!!
def get_client():
DB_URL = os.environ['DB_URL'] or 'mongodb://localhost:27017/github'
DB_USER = os.environ['DB_USER']
DB_NAME = 'github'
DB_PWD = os.environ['DB_PASSWORD']
M... |
from datetime import date
from datetime import time
from datetime import datetime
def main():
#get current date
today = date.today()
print('Today\'s date is', today)
#get current date component
print('Date Components:', today.day, today.month, today.year)
#get week component
prin... |
import numpy as np
from sklearn.datasets import make_circles
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils import data
import matplotlib.pyplot as plt
torch.manual_seed(7388)
#Number of sampled data points we need to generate.
n_samples = 1500
class makeCircles(data.Dataset):
... |
from typing import List, Any
def get_success_response(result: List[Any], message: str):
return {
"status": "success",
"message": message,
"result": result
}
def get_error_response(message: str, result: List[Any] = None):
return {
"status": "error",
"message": mess... |
import tensorflow as tf
import argparse
import json
import os
from core.data import load_records
from core.model import RNNModel
from core.callbacks import get_callbacks
from core.losses import MaskedCrossEntropy
from core.metrics import MaskedACC, CustomAccuracy
from tensorflow.keras.losses import CategoricalCrossen... |
# Copyright 2021 IBM 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
# Copyright 2021 MONAI Consortium
# 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, s... |
#!/usr/bin/env python
import re
import sys
# Cnv definition
convlist = ('UpperCnv', 'LowerCnv')
# Create the cnv map
convmap = dict()
for (i, v) in enumerate(convlist):
convmap[v] = str(i)
# RE stuff
timere = r'\d{2}:\d{2}:\d{2}:\d{3}'
cnvre = r'(?P<cnv>%s)' % r'|'.join(convlist)
hexare = r'(?P<hex>0x[0-9a-f]+)... |
#!/usr/bin/env python
import argparse
import random
import time
from pybullet_tools.pr2_utils import set_arm_conf, get_other_arm, arm_conf, REST_LEFT_ARM, \
get_carry_conf, get_gripper_link, GET_GRASPS, IR_FILENAME, get_database_file, DRAKE_PR2_URDF, \
set_group_conf, get_group_conf, get_base_pose
from pybull... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from pyNNsMD.models.mlp_nac2 import NACModel2
from pyNNsMD.scaler.nac import NACStandardScaler
from pyNNsMD.utils.loss import ScaledMeanAbsoluteError,NACphaselessLoss
from pyNNsMD.plots.pred import plot_scatter_prediction
# Load data
x = np.lo... |
coordinates_E0E1E1 = ((125, 139),
(126, 109), (126, 111), (126, 138), (126, 140), (127, 108), (127, 110), (127, 111), (127, 112), (127, 113), (127, 118), (127, 127), (127, 137), (127, 138), (127, 141), (128, 106), (128, 114), (128, 115), (128, 116), (128, 119), (128, 127), (128, 128), (128, 131), (128, 133), (128, 13... |
from dbconn import *
from yt_api import *
from flask import Flask,render_template, flash, request
from sendMail import sendMail
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
import json
from sendMail import sendMail
from yt import *
from thumbnail import *
from flask import Fl... |
from os import walk
from os import makedirs
from os.path import exists
from shutil import copyfile
from time import time
from datetime import datetime
from exifpy import exifread
def printTime(label, time):
ms = time * 1000
s, ms = divmod(ms, 1000)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
prin... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# <div style='background-image: url("share/baku.jpg") ;... |
from collections import OrderedDict
from functools import partial
from typing import Dict, Union, Optional, Sequence
from einops import rearrange, repeat
import numpy as np
import torch
import torch.nn as nn
import torch_scatter
from climart.models.MLP import MLPNet
import climart.models.GNs.constants as gn_constants
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os.path
import io
from googleapiclient.http import MediaIoBaseDownload
from zdrive import DriveAPI
from multiprocessing import Process
class Downloader(DriveAPI):
def __init__(self):
super(Downloader, self).__ini... |
import tensorflow as tf
import tensorflow_text as tf_text
def convert_huggingface_tokenizer(huggingface_tokenizer,
suffix_indicator="##",
max_chars_per_token=None,
split_unknown_characters=True,
... |
# Copyright (C) 2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
import argparse
import sys
import os
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('video_file',
type=str,
help='Path to video file')
parser.add_argument('meta_directory',
type=str,
... |
from abc import ABC, abstractmethod
from fastapi import Header, HTTPException, FastAPI, APIRouter
from fastapi.responses import JSONResponse
from typing import TypeVar, Generic
from typing import Optional, Tuple, List
from pydantic import BaseModel
from pydantic.generics import GenericModel
from db.models import Use... |
#!/usr/bin/python3
import mido
import pigpio
from numpy import interp
import board
import neopixel
pixels = neopixel.NeoPixel(board.D18, 300)
port = mido.open_input('f_midi') # open USB port
red = 0
green = 0
blue = 0
while True:
try:
for msg in port.iter_pending():
if(msg.type == 'note_on')... |
import functools
import inspect
import os
from collections import defaultdict
from typing import Optional
import pandas as pd
from . import GLOBAL_LOGGER
LOGGER = GLOBAL_LOGGER.getChild(os.path.basename(os.path.splitext(__file__)[0]))
__all__ = ['Decorator', 'NestedClass']
class Decorator(object):
@classmetho... |
import json
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, fsolve
def logistic_function(x, a, b, c):
return c/(1+np.exp(-(x-b)/a))
with open('country_wise_data.json', 'r+') as f:
country_wise_data = json.load(f)
COUNTRIES = ['Italy', 'South Korea', 'Spain', 'Iran']... |
from tests import app
from flask import request
@app.route("/expect", methods=['POST'])
def expect():
assert request.headers['Expect'] == '100-continue'
s = request.data.decode("utf-8")
assert s == '''data'''
return ''
|
from bson import ObjectId
from django.conf import settings
from .models import Account
from pymongo import MongoClient
def get_account(user_id=None, email=None):
client = MongoClient(settings.USERDB_HOST,
username=settings.USERDB_USERNAME,
password=settings.USERDB_... |
import argparse
import logging
import re
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.utils import parse_json
log = logging.getLogger(__name__)
class BTV(Plugin):
arguments = PluginArgumen... |
schema_registry = {}
def get_python_type(schema_name):
"""
Get the python type for a given schema name
"""
field = schema_registry[schema_name]
return field.Meta.python_type
|
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
import kivent_core
class TestGame(Widget):
def on_kv_post(self, *args):
self.gameworld.init_gameworld([], callback=self.init_game)
def init_game(self):
self.setup_states()
self.set_state()
def setup_states(sel... |
'''Start Module'''
import argparse
from Logic.options import Options
from Logic.video_analysis import VideoAnalysis
def create_parser():
'''Responsible for creating a parser that handles program arguments'''
formatter = lambda prog: argparse.HelpFormatter(prog, width=140, max_help_position=50)
parser ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class CompendiumPack:
"""Class to represent a processed Research Compendium
"""
def __init__(self, file, metadata):
self._file = file
self._metadata = metadata
@property
def file(self):
return self._file
@prop... |
#!/usr/bin/env python
import config
import json
import sys
"""
Copyright (c) 2020, Cisco Systems, Inc. and/or its affiliates
Creates a list of all repos using a JSON file generated from
the Learning Labs api/gits endpoint.
Usage:
python llapi_repos_names.py llgitsresponse.json > devnet_repos.txt
"""
def get_repos(fil... |
'''
Created on 2019年3月30日
@author: 余创
'''
import os
import sys
import random
from PIL import Image
import math
import numpy as np
import skimage.io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import cv2
import time
from mrcnn.config import Config
from datetime import datetime
# Root direc... |
import os
from pathlib import Path
from submission import iris_svm_predict
class Submission(object):
def run(self, test_file, out_file):
# Additional data required by the prediction algorithm
model_file = Path(__file__).absolute().parent/'model'/'iris_svm_model'
iris_svm_predict(model_fi... |
# Create your models here.
import uuid
from enum import Enum
from typing import List
from django.core.exceptions import ValidationError
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Case, When
def _validate_non_negative_number(value):
""" ensures that the... |
"""Test cases for the __main__ module."""
from aioresponses import aioresponses
from aioresponses.core import RequestCall # type:ignore
from click.testing import CliRunner
from tests import fixtures
from yarl import URL
from . import initialise_credential_store
from renault_api.cli import __main__
def test_charge_h... |
from collections import namedtuple
from typing import Type, Dict, Callable, Union
from webdnn.backend.code_generator.injectors.kernel_name_injector import KernelNameInjector
from webdnn.backend.webgl.generator import WebGLDescriptorGenerator
from webdnn.backend.webgl.kernel import Kernel
from webdnn.backend.webgl.kern... |
#!/user/bin/env python3.6
import os
import urllib.request
import json
from pymongo import MongoClient
from helpers.log_to_logfile import add_to_log
OTS_API_KEY = os.environ['OTS_API_KEY']
DB_URI = os.environ['DB_URI']
client = MongoClient(DB_URI)
db = client.ots_database
collection = db.ots_collection... |
import itertools
import time
import binascii
import numpy as np
result = []
def FakeSmartRowerData(f,deque_input):
#print("in the function")
for index, line in enumerate(itertools.islice(f, 1, None, 2)):
#print(line)
line = line.strip()
#print(line)
line = line.split(' ')[-1]
... |
from typing import List
from .abstract_effect import AbstractEffect
from .canvas import Canvas
from .configure_logging import logging
from .effect_parade import AbstractEffectParade
from .pixel import Pixel
class EffectController:
def __init__(self, parade: str, duration: int, repeat: int,
brig... |
from torch.utils.data import Dataset
from datasets.mongo import get_by_id
import numpy as np
import torch
from pymongo import MongoClient
class TriageDataset(Dataset):
def __init__(self,data,labels=None,stft_fun=None,transforms=[]):
self.data=data
self.labels=labels
self.stft_fun=stft_f... |
from django.contrib.auth.models import User
from django.forms import ModelForm
from .models import Cell, Room
class RoomCreationForm(ModelForm):
class Meta:
model = Room
fields = ["room_name", "height", "width"]
class RoomCloneForm(ModelForm):
class Meta:
model = Room
fields... |
#1
def DecimalToBinary(n):
s = ""
str1 = []
helperFunc(n,str1)
return s.join(str1)
def helperFunc(n, str1):
if n==0:
return
helperFunc(int(n/2), str1)
str1.append(str(n % 2))
print("7 -- ",DecimalToBinary(7))
print("13 -- ",DecimalToBinary(13))
print("36 -- ",DecimalToBinary(36))
|
from __future__ import unicode_literals
import random
from datetime import timedelta
from django.utils import timezone
from django.utils.six import string_types
from django.core.mail import mail_managers
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.template.load... |
#!/usr/bin/python
import sys
import os
import shutil
# this tool applies the database linking trick,
# which is useful to be able to run a test suite / simulation without having to use comm
# WARNING: run this before RTDB clients start to read/write
# user should specify database strings, for example
# /tmp/rtdb_M... |
"""Connect to the Constellix API
"""
import logging
import hashlib
import hmac
import os
import requests
import base64
import urllib.parse
import time
from json import JSONDecodeError
import util
_CONSTELLIX_APISECRET = None
"""string: The Constellix API secret
Generated in the Constellix dashboard.
"""
if 'CONSTEL... |
import click
from aer import __version__
@click.command()
@click.version_option(__version__)
def main():
click.echo("Hello, World!")
|
class Provider:
""" A provider returns parameter values dynamically based on its configuration. """
def __init__(self, config):
self.config = config
def run(self):
raise NotImplementedError("Please implement this method") |
import logging
import cv2
import numpy as np
from lib.helpers import calculate_relative_contours, pop_if_full
class Contours:
def __init__(self, contours, resolution):
self._contours = contours
self._rel_contours = calculate_relative_contours(contours, resolution)
scale_factor = resolut... |
import json
from collections import defaultdict
f1 = open('string_to_func_dict_wind')
wind = json.load(f1)
f1.close()
f2 = open('string_to_func_dict_ppc')
ppc = json.load(f2)
f2.close()
def inverter(orig_dict):
to_dict = defaultdict(list)
for k,v in orig_dict.items():
for entry in v:
t... |
# Copyright 2017 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 agreed to in writing, ... |
from django.contrib import admin
from django.urls import include, path
from rest_framework.documentation import include_docs_urls
urlpatterns = [
path('', include('stock_reading.urls')),
path('admin/', admin.site.urls),
path('api-docs/',
include_docs_urls(title='API Docs', authentication_classes... |
from base_classes import Component
from typing import Dict, Union, List, NoReturn
import xml.etree.ElementTree as ElementTree
import importlib
import inspect
import logging
class ComponentLoadError(Exception):
""" Raised when a component's file does not exist or when a component
of the correct type cannot... |
from __future__ import print_function
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2016 Microsoft Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the... |
# -*- coding: utf-8 -*-
r"""MCCD CLASS.
This module contains the main MCCD class.
:Authors: Tobias Liaudat <tobias.liaudat@cea.fr>
Jerome Bonnin <https://github.com/jerome-bonnin>
Morgan Schmitz <https://github.com/MorganSchmitz>
"""
from __future__ import absolute_import,... |
import json
import logging
from typing import List, Optional
from .recognizer_result import RecognizerResult
from .recognizer_registry import RecognizerRegistry
from .entity_recognizer import EntityRecognizer
from .app_tracer import AppTracer
from .nlp_engine import NlpEngine, NlpEngineProvider
logger = logging.getL... |
from .objects import Product, ProductPurchaseEntry, GRNEntry, ProductSalesEntry, SalesOrder, PurchaseOrder, GoodsReceiptNote, Consumer, Vendor, Company, PurchaseInvoice, SalesInvoice
from .states import FilterColumn, FilterState
from .misc import Object, EventCard, EventType, ObjectModel, HistoryFilterState
from .reuse... |
"""HTTP API endpoint
"""
from collections import defaultdict
import dateutil.parser
import smif
from flask import current_app, jsonify, request
from flask.views import MethodView
from smif.exception import (SmifDataError, SmifDataInputError,
SmifDataNotFoundError, SmifException,
... |
import pandas as pd
import numpy as np
import os
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
"""
The following code is licensed by www.udacity.com
"""
def select_first_encounter(df):
"""
INPUT:
- df (Pandas DataFrame): ... |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1181
#!/usr/bin/env python2.7
linha = int(raw_input())
array = [[0 for j in xrange(12)] for k in xrange(12)]
operacao = raw_input()
for p in xrange(12):
for k in xrange(12):
array[p][k]=float(raw_input())
if operacao == "S":
print "... |
# -*- coding: utf-8 -*-
#
# Name: Seth menghi
# E-mail Address: swm36@georgetown.edu
# Platform: MacOS
# Language/Environment: python
#
# In accordance with the class policies and Georgetown's Honor Code,
# I certify that, with the exceptions of the class resources and those
# items noted below, I have neither given no... |
# Augur: A Step Towards Realistic Drift Detection in Production MLSystems - Code
# Copyright 2022 Carnegie Mellon University.
#
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITH... |
from tinydb import TinyDB, Query
from stlprintbrowser.stlmodel import STLModel
STL_MODELS = 'stl_models'
class STLDatabase:
def __init__(self, settings):
self.db = TinyDB(settings.database_path + '/stldatabase.json')
def get_stl_models(self):
models = []
for model in ... |
from django.contrib.auth.models import User, Group, AnonymousUser
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import TestCase
from django.test import RequestFactory
from django.utils import timezone
from tally_ho.apps.tally.models.audit import Audit
from tally_ho.apps.tally.mo... |
import chpl_compiler, chpl_hwloc, chpl_llvm, chpl_locale_model, chpl_mem
import third_party_utils
from utils import memoize
@memoize
def get_uniq_cfg_path():
def_uniq_cfg = third_party_utils.default_uniq_cfg_path()
lm = chpl_locale_model.get();
target_mem = chpl_mem.get('target')
hwloc = chpl_hwloc.ge... |
#
# PySNMP MIB module ASYNCOS-MAIL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASYNCOS-MAIL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:29:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
########################################################################
# Copyright 2021, UChicago Argonne, LLC
#
# Licensed under the BSD-3 License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a
# copy of the License at
#
# https://opensource.org/licenses/BSD-... |
# -*- coding=utf-8 -*-
import requests
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import os
webhook_url = "https://app.qun.qq.com/cgi-bin/api/hookrobot_send"
mirror_url = "https://sm.ms/api/v2/upload"
suo_url = "http://m.6du.in/api_mobileweb_json.php"
# qq群webhook key
Key = os.getenv('QQHook_... |
from typing import Union
import numpy as np
import scipy.sparse
import scipy.stats
def poisson_fit(umis: Union[np.ndarray, scipy.sparse.spmatrix]) -> np.ndarray:
"""Takes an array of UMI counts and calculates per-gene deviation from a poisson
distribution representing even expression across all cells.
:... |
import random
import json
import numpy as np
import torch
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class AttrDict(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
class Activation(object):
def forward(self, inp):
raise NotImplementedError
de... |
#! /usr/bin/env python
#
# MicroPython Driver for MAX3221E onboard the PYBD Expansion Board.
#
# This file is part of micropython-pybd-expansion.
# https://github.com/bensherlock/micropython-pybd-expansion
#
#
# MIT License
#
# Copyright (c) 2020 Benjamin Sherlock <benjamin.sherlock@ncl.ac.uk>
#
# Permission is hereby ... |
from IPython.core.display import HTML
def styling():
return HTML('css.css')
|
creds = {
"hostname": "somehost.somecounty.here",
"username": "someusername",
"password": "somepassword"
}
|
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
from abc import ABCMeta, abstractmethod
import tensorflow as tf
import warnings
import datetime
import numpy as np
def weight_variable(name, shape):
# initial = tf.truncated_normal(shape, stddev=0.2)
# return tf.Variable(initial)
xavier = tf.contrib.layers.xavier_initializer()
return tf.get_variable(n... |
import torch.nn as nn
import collections
class BasicHead(nn.Sequential):
def __init__(self, in_channels, out_channels, **kwargs):
super().__init__()
class PreActHead(nn.Sequential):
def __init__(self, in_channels, out_channels, normalization, activation, **kwargs):
super().__i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.