text stringlengths 2 999k |
|---|
#!/usr/bin/python
from __future__ import print_function
import struct
import sys
import usb.core
import usb.util
from intelhex import IntelHex
scrambleCode = (0x29, 0x52, 0x8C, 0x70)
stats = [0xff, 0x02, 0x00, 0xf5, 0xe5, 0x75, 0x03, 0x04,
0x80, 0x05, 0xd2, 0x01, 0xe4, 0xef, 0x82, 0x83,
0x08, 0x24,... |
###
# Copyright (c) 2004-2005, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of co... |
import textwrap
import aiohttp
from aiostripe import error
def new_default_http_client(*args, **kwargs):
return AsyncioClient(*args, **kwargs)
class HTTPClient(object):
def __init__(self, verify_ssl_certs=True):
self._verify_ssl_certs = verify_ssl_certs
def request(self, method, url, headers,... |
"""
Base settings to build other settings files upon.
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (algerian_library/config/settings/base.py - 3 = algerian_library/)
APPS_DIR = ROOT_DIR.path('algerian_library')
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False... |
# Zbiór przedziałów [(a[1], b[1]), ..., (a[n], b[n])], każdy przedział należy do [0, 1]. Opisać algorytm
# który sprawdzi czy jest możliwy taki wybór przedziałów, aby cały przedział [0, 1] zawierał się
# w wybranych odcinkach. Przedział ma składać się z jak najmniejszej ilości odcinków.
def minimum_intervals(T):
... |
# Copyright 2014 Mirantis, 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This python program saves test XMLs from denon receiver to current directory.
Usage: python denon_receiver_xml.py --host 192.168.0.250 --prefix AVR-X4100W
:copyright: (c) 2017 by Oliver Goetz.
:license: MIT, see LICENSE for more details.
"""
import argparse
from io im... |
import logging
from sqlalchemy import Column, INT
from sqlalchemy_utc import UtcDateTime
from pajbot import utils
from pajbot.managers.db import Base
log = logging.getLogger(__name__)
class Roulette(Base):
__tablename__ = "roulette"
id = Column(INT, primary_key=True)
user_id = Column(INT, index=True, ... |
# python3
import sys
def fib_slow(n):
'''Dumb (slow) example solution.
'''
if (n <= 1):
return n
return fib_slow(n - 1) + fib_slow(n - 2)
def fib_countup(n):
'''Less-dumb 'count up as you go' solution.
'''
if (n <= 1):
return n
x, y = 0, 1
for i in range(n):
... |
'''
Copyright 2017-present, Airbnb 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, sof... |
# 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
# distributed under the Li... |
# Generated by Django 2.2.12 on 2020-05-01 03:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('issues', '0005_auto_20200501_0350'),
]
operations = [
migrations.AlterFie... |
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import unittest
from context import xml_bibs as xb
class TestGetSubjectFields(unittest.TestCase):
"""Tests parsing of subjects from marcxml"""
def setUp(self):
tree = ET.parse("sample_marcxml.xml")
self.data1 = tree.getroot()
... |
import pickle
import argparse
import pandas as pd
import numpy as np
import math
from tqdm import tqdm
from sklearn import decomposition
CENTER_X = int(960 / 3 / 2)
CENTER_Y = int(540 / 3 / 2)
# CENTER_X = 0
# CENTER_Y = 0
def load_data(path, data_size=None):
with open(path, 'rb') as f:
data = pickle.l... |
#!/usr/bin/env python3
## How many clusters have more than one organisms as it's members
import sys
import pandas as pd
import logging
def main():
clstr_table = sys.argv[1]
output = sys.argv[2]
clstr_df = pd.read_table(clstr_table, header=0)
clstr_df["organism"] = clstr_df["id"].apply(lambda x: x.spl... |
from http import HTTPStatus
from rest_framework import views, viewsets
from rest_framework.exceptions import ParseError
from rest_framework.request import Request
from rest_framework.response import Response
from scraper import models, serializers, tasks
from scraper.utils import get_random_working_proxy
class Webs... |
from ..apibits import *
from ..endpoints import GeneratorsEndpoint
from ..endpoints import GeneratorRowsEndpoint
class Generator(ApiResource):
@classmethod
def all(cls, params={}, headers={}):
res = cls.default_client().generators().all(params, headers)
return res
@classmethod
def ret... |
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2010-2021, The Limnoria Contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain t... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
# do not change this line manually
# this is managed by git tag and updated on every release
__version__ = '0.6.8'
# do not change this line manually
# this is managed by proto/build-proto.sh and updated on every exe... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/l... |
#
# Copyright 2019 The FATE 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... |
#!/usr/bin/env python
#*-----------------------------------------------------------------------*
#| |
#| Copyright (c) 2013 by Paul Scherrer Institute (http://www.psi.ch) |
#| ... |
import gym
from gym import logger
from core.states import StateSerializer
from core.runner import Runner
from agents.dqn_agent import DQNAgent
logger.set_level(logger.INFO)
env_name = 'CartPole-v0'
env = gym.make(env_name)
env._max_episode_steps = 500
serializer = StateSerializer(env.observation_space.shape)
agent ... |
__author__ = 'luke.beer'
import subprocess
import threading
import logging
import socket
import time
import questions
import states
class Executor(threading.Thread):
def __init__(self, r, channel):
threading.Thread.__init__(self)
self.redis = r
self.channel = channel
self.pubsub =... |
import re
import json
from color_print import *
# read rules from json file
with open("rules.json", "r", encoding="utf-8") as json_data:
rules = json.load(json_data)
# create new rules by replacing 'is' to 'was', 'has been', ...
def augment(sentence):
"""change 'is' in the sentence to was, has been,... |
# -*- coding: utf-8 -*-
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import csv, gzip, os
from pyqtgraph import Point
class GlassDB:
"""
Database of dispersion coefficients for Schott glasses
+ Corning 7980
"""
def __init__(self, fileName='schott_glasses.csv'):
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/tasks_v2/proto/task.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1"))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _... |
# Copyright Tom SF Haines, Reinier de Blois, Aaron Snoswell
#
# 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... |
#
# Run NN, multinomial logistic regression using simple gradient descent.
#
import config
import numpy as np
import tensorflow as tf
from tensorflow import (Variable, constant, global_variables_initializer,
truncated_normal, zeros)
from tf_training_helper import TrainingHelper
class TF_notMN... |
import inspect
import math
import re
from functools import singledispatch, partial
from itertools import chain, cycle
from .api import (
always_break,
annotate,
concat,
contextual,
flat_choice,
fill,
group,
nest,
NIL,
LINE,
SOFTLINE,
HARDLINE
)
from .doc import (
Ann... |
#!/usr/bin/python2.7
#coding:utf-8
def getFunc(n):
return lambda x, y: x**n + y**n
f = getFunc(2)
print '1**2 + 2**2 = ', f(1,2)
print '2**2 + 3**2 = ', f(2,3)
f = getFunc(3)
print '1**3 + 2**3 = ', f(1,2)
print '2**3 + 3**3 = ', f(2,3)
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/71_callback.tensorboard.ipynb (unless otherwise specified).
__all__ = ['TensorBoardCallback']
# Cell
from ..basics import *
# Cell
import tensorboard
from torch.utils.tensorboard import SummaryWriter
from .fp16 import ModelToHalf
# Cell
class TensorBoardCallback(Callb... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
try:
from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import (
AnsibleArgSpecValidator,
)
except ImportError:
ANSIBLE_UTILS_IS_INST... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. 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 ... |
import os
import yaml
import pandas as pd
import xml.etree.ElementTree as ET
from types import SimpleNamespace
from sklearn.model_selection import train_test_split
from utils.experiment_utils import create_linspace
from utils.preprocess import *
SOURCE_PATH = './source_data'
DATA_PATH = './data'
CONFIG_PATH = './c... |
from django import template
from django.contrib.admin.models import LogEntry
register = template.Library()
class AdminLogNode(template.Node):
def __init__(self, limit, varname, user):
self.limit, self.varname, self.user = limit, varname, user
def __repr__(self):
return "<GetAdminLog Node>"
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 15:53:46 2018
@author: Eric S. Russell
Laboratory for Atmospheric Research
Dept. of Civil and Environmental Engineering
Washington State University
eric.s.russell@wsu.edu
Not all of these functions are used in the column rename script; these are potentially to be used... |
#!/usr/bin/env python
ph = float(input('enter pH level: '))
if ph < 7.0:
print(ph, "is acidic")
|
import os
import pytest
def test_wrong_select_db_index(cli):
cli.sendline("select 1")
cli.expect(["OK", "127.0.0.1"])
cli.sendline("select 128")
cli.expect(["DB index is out of range", "127.0.0.1:6379[1]>"])
if int(os.environ["REDIS_VERSION"]) > 5:
text = "value is not an integer or out ... |
import sys
from distutils.version import LooseVersion
if sys.version_info.major < 3:
print('[!] You are running an old version of Python. '
'This tutorial requires Python 3.')
sys.exit(1)
with open('requirements.txt') as f:
reqs = f.readlines()
reqs = [(pkg, ver) for (pkg, _, ver) in
(... |
from math import ceil
S, D = [int(i) for i in input().split()]
cont = [0 for i in range(S)]
for d in range(D):
t = [int(i) for i in input().split()]
for i in range(S):
cont[i] += t[i]
media = ceil(sum(cont) / D)
pref = cont.index(max(cont))
print(str(media))
print(str(pref + 1))
|
#!/scratch_net/nudel/esandstroem/venvs/tsdf_fusion_env/bin/python
import os
app_path = '/scratch_net/nudel/esandstroem/venvs/tsdf_fusion_env/bin'
os.environ["PATH"] = app_path + os.pathsep + os.environ["PATH"]
from TSDFHandle import *
import numpy as np
import cv2
from utils import extract_mesh_marching_cubes
from vis... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from edward.models import Bernoulli, Normal
from edward.util import get_descendants
class test_get_descendants_class(tf.test.TestCase):
def test_v_structure(self):
"""a -> b ->... |
# Copyright 2017 Google Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
import os
import pytest
import sqlalchemy as sa
from libweasyl.configuration import configure_libweasyl
from libweasyl.models.meta import registry
from libweasyl.models.tables import metadata
from libweasyl.test.common import NotFound
from libweasyl.test.common import media_link_formatter
from libweasyl import cache
... |
#!/usr/bin/env python
import time
import sys
import iothub_client
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult
from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError
# String containing Hostname, Device Id & Device Key in the form... |
import sys
time = input().strip()
splitted = time.split(':')
hours_12 = int(splitted[0])
mins = splitted[1]
secs = splitted[2][:2]
is_pm = splitted[2].endswith("PM")
if (is_pm):
if (hours_12 >= 1 and hours_12 < 12): # between 1pm and 11:59pm
hours_12 += 12
else:
if (hours_12 == 12):
hours_... |
"""
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 use this ... |
#!/usr/bin/env python3
# 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.
"""
Transformer Agents.
"""
from typing import Optional
from parlai.core.params import ParlaiParser
from parlai.core.opt i... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/protobuf/config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... |
"""This package contains interfaces and functionality to compute pair-wise document similarities within a corpus
of documents.
"""
from gensim import parsing, corpora, matutils, interfaces, models, similarities, summarization, utils # noqa:F401
import logging
__version__ = '3.5.0'
class NullHandler(logging.Handler... |
# coding: utf-8
"""
Intersight REST API
This is Intersight REST API
OpenAPI spec version: 1.0.9-262
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class BootSanRef(object):
"""
NOTE: This class is a... |
import json
import configparser
import re
import logging
from modules.exceptions import SettingsError
log = logging.getLogger(__name__)
def readjson(jfile):
"""... just for reading json file and return data :)"""
with open(jfile) as descriptor:
data = json.load(descriptor)
return data
def read... |
# -*- coding:utf-8 -*-
import base64
bs='iVBORw0KGgoAAAANSUhEUg....'
imgdata=base64.b64decode(bs)
file=open('2.jpg','wb')
file.write(imgdata)
file.close()
|
# 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
from ... import _utilities, _tables
from... |
from .BasicTypeAttr import BasicTypeAttr
class StringAttr(BasicTypeAttr):
def __init__(self, attr):
BasicTypeAttr.__init__(self, attr)
if self.get('Max') is not None:
self['Max'] = int(self['Max'])
if self.get('Min') is not None:
self['Min'] = int(self['Min'])
... |
import datetime
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context
from equipment.models import ItemType, Item, ItemEr... |
from numba import jit
import sys
@jit
def fib(n):
return 1 if n < 3 else fib(n-1) + fib(n-2)
if __name__ == "__main__":
n = int(sys.argv[1])
print("{}".format(fib(n)))
|
import contextlib
import json
import os
import pprint
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
from cytoolz import (
merge,
valmap,
)
from eth_utils.curried import (
apply_formatter_if,
is_bytes,
is_checksum_address,
is_dict,
is_same... |
import networkx as nx
class FeatureExtractor:
"""
Extracting some hand-crafted x1_features for the x1_graphs
- Number of (effective nodes)
- Average
"""
def __init__(self, g: nx.Graph, node_attr_name='op_name', s='input', t='output'):
"""
g: a valid networkx graph
node... |
import os
import sys
import numpy as np
import pandas as pd
from torch.utils.data import Subset
from torch.utils.data.dataset import Dataset # For custom datasets
from torchvision import transforms
PROJECT_PATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.append(PROJECT_PATH)
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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 ... |
from .. import Provider as LoremProvider
class Provider(LoremProvider):
"""Implement lorem provider for ``hy_AM`` locale.
Sources:
- https://www.101languages.net/armenian/armenian-word-list
"""
word_list = (
"ես",
"դու",
"նա",
"մենք",
"դուք",
"նրա... |
""" support for skip/xfail functions and markers. """
from _pytest.config import hookimpl
from _pytest.mark.evaluate import MarkEvaluator
from _pytest.outcomes import fail
from _pytest.outcomes import skip
from _pytest.outcomes import xfail
def pytest_addoption(parser):
group = parser.getgroup("general")
grou... |
import torch
import torch.nn as nn
import os
from common import base_data_path
from typing import List
import pandas as pd
CONTEXT_SIZE = 1 # 1 words to the left, 1 to the right
EMDEDDING_DIM = 3
word_to_ix = {}
ix_to_word = {}
def make_context_vector(context, word_to_ix):
idxs = [word_to_ix[w] for w in contex... |
import functionality.planets as planets
import assets.tools as tools
from assets.variables import *
# TODO: Also add logger to code and display errors correctly
# TODO: Make one pixel correspond to 1/10 au so that acceleration works more realistic
class SolarSystem(metaclass=tools.Singleton):
"""This creates the... |
import pytest
from katrain.core.constants import AI_STRATEGIES_RECOMMENDED_ORDER, AI_STRATEGIES
class TestAI:
def test_order(self):
assert set(AI_STRATEGIES_RECOMMENDED_ORDER) == set(AI_STRATEGIES)
|
""" Enums used in different API endpoints """
from enum import Enum
class PluginStatusState(str, Enum):
"""State of the plugin"""
NOTRUNNING = "NotRunning"
STARTING = "Starting"
RUNNING = "Running"
FAILEDTOSTART = "FailedToStart"
FAILEDTOSTAYRUNNING = "FailedToStayRunning"
STOPPING = "Sto... |
from __future__ import absolute_import, division, print_function
import sys
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
EPOCHS = 1000
# The patience parameter is the amount of epoch... |
#!/usr/bin/env python
#
# test_probe_ports.py
#
"""Shows how to probe for available MIDI input and output ports."""
import sys
from rtmidi import *
try:
raw_input
except NameError:
# Python 3
raw_input = input
apis = {
API_MACOSX_CORE: "OS X CoreMIDI",
API_LINUX_ALSA: "Linux ALSA",
API_UNIX_JAC... |
#-
# Copyright (c) 2015 Khilan Gudka
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research programme.
#
# @BERI_LICENSE_HEADER_START@
#
# Licensed to BE... |
import logging
import typing
import web3
from util import constants
from web3tools import web3util, account
logger = logging.getLogger(__name__)
def randomWeb3Wallet():
private_key = account.randomPrivateKey()
return Web3Wallet(private_key=private_key)
class Web3Wallet:
"""Signs txs and msgs with an acc... |
import asyncio
import codecs
import dataclasses
import functools
import io
import re
import sys
import traceback
import warnings
from hashlib import md5, sha1, sha256
from http.cookies import CookieError, Morsel, SimpleCookie
from types import MappingProxyType, TracebackType
from typing import (
TYPE_CHECKING,
... |
from django.contrib import admin
from .models import Document
admin.site.register(Document)
|
#!/usr/bin/env python2.4
import sys
from z3c.rml import rml2pdf
for arg in sys.argv[1:]:
rml2pdf.go(arg)
|
from django.contrib import admin
from .models import Receipt, Item, User, Cover, Payment
admin.site.register(Receipt)
admin.site.register(Item)
admin.site.register(User)
admin.site.register(Cover)
admin.site.register(Payment)
|
from pathlib import Path
import subprocess
root_path = Path(__file__).parent.parent.resolve()
extensions = [
'sphinx.ext.todo',
'sphinxcontrib.drawio',
]
version = (root_path / 'VERSION').read_text().strip()
project = 'hat-stc'
copyright = '2020-2021, Hat Open AUTHORS'
master_doc = 'index'
html_theme = 'fu... |
"""***********************************************************************
This file was created by Astraea, Inc., 2018 from an excerpt of the
original:
Copyright (c) 2013-2018 Commonwealth Computer Research, Inc.
All rights reserved. This program and the accompanying materials
are made available under ... |
"""Joystick action space for controlling agent avatars."""
from . import abstract_action_space
from dm_env import specs
import numpy as np
class Joystick(abstract_action_space.AbstractActionSpace):
"""Joystick action space."""
def __init__(self, scaling_factor=1., action_layers='agent',
con... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_geocodio
----------------------------------
Tests for `geocodio.data` module.
"""
import json
import os
import unittest
from geocodio.data import Address
from geocodio.data import Location
from geocodio.data import LocationCollection
class TestDataTypes(unitt... |
# -*- coding: utf-8 -*-
#
# Sphinx configuration
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show t... |
from machinetranslation import translator
from flask import Flask, render_template, request
import json
app = Flask("Web Translator")
@app.route("/englishToFrench")
def englishToFrench():
textToTranslate = request.args.get('textToTranslate')
translation = translator.englishToFrench(englishText=textToTranslate... |
import os
import pprint
import inspect
import tensorflow as tf
pp = pprint.PrettyPrinter().pprint
def class_vars(obj):
return (k:v for k, v in inspect.getmembers(obj))
if not k.startswith("__") and not callable()
class base_model(object):
def __init__(self, config):
self._saver = None
self.config... |
"""
This file offers the methods to automatically retrieve the graph Lachnospiraceae bacterium NK4A144.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: prote... |
#
# Copyright 2019 Xilinx 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... |
# -*- coding: utf-8 -*-
from typing import Any, Iterable, List, Optional
from aiohttp import FormData as _FormData
import aiohttp.multipart as multipart
class FormData(_FormData):
def __init__(
self,
fields: Iterable[Any] = (),
quote_fields: bool = True,
charset: Optional[str] = N... |
# podd_utils.py
# Utility functions for Podd SCons build
import os
from SCons.Action import ActionFactory
from SCons.Script.SConscript import SConsEnvironment
SConsEnvironment.OSCommand = ActionFactory(os.system,
lambda command : 'os.system("%s")' % command)
import SCons.Util
def list_to_path(lst):
... |
import os
import math
import torch
import argparse
import numpy as np
from tqdm import tqdm
from medpy import metric
import torch.nn.functional as F
from Configs.config import config
from Model.Vnet import VNet as Vnet
from cc3d import connected_components
from Dataloader.dataset import LAHeartDataset
"""
# https://gi... |
# 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
from ... import _utilities, _tables
from... |
import re
import urllib
import time
from django.shortcuts import render, redirect, get_object_or_404
from django import http
from django.db.utils import DatabaseError
from django.db import transaction
from django.db.models import Count
from django.conf import settings
from django.core.urlresolvers import reverse
from ... |
import spacy
from textblob import TextBlob
import pandas as pd
# Import functions from other files
from tweet_handlers import pullTweetsFromCSV, tweetPulls
### Declare functions to standardize, identify, and analyze input text
# Will ultimately take in a list of tweets and return:
# - Word counts
# - Split of positiv... |
# X10G Development code
# UDP Receive with Trailer Recognition
# Rob Halsall 23-11-2011
import sys, socket
#from msvcrt import *
if len(sys.argv) == 3:
ip = sys.argv[1]
port = int(sys.argv[2])
else:
print "use: python udp_rx_ll_mon_trl.py 192.168.9.2 61650"
exit(0)
sock = socket.socket(socket.AF_INET, socket.... |
from anndata import read_h5ad
import sys
from time import time
from scipy import stats, sparse
import numpy as np
import collections
import pickle
from sklearn.preprocessing import normalize
import os
from collections import Counter
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.m... |
import endpoints
from google.appengine.ext import ndb
def get_by_urlsafe(urlsafe, model):
try:
key = ndb.Key(urlsafe=urlsafe)
except TypeError:
raise endpoints.BadRequestException('Invalid Key')
except Exception, e:
if e.__class__.__name__ == 'ProtocolBufferDecodeError':
... |
import glob
import os
import warnings
from datetime import datetime
from copy import deepcopy
import numpy as np
import pyedflib
import scipy.io as sio
from config import cfg
from thirdparty.cerebus import NsxFile, NevFile
from thirdparty.nex import Reader as NexReader
from .utils import find_nearest_time
def _load... |
#!/usr/bin/python
#
# bitehist.py Block I/O size histogram.
# For Linux, uses BCC, eBPF. See .c file.
#
# USAGE: bitesize
#
# Ctrl-C will print the partially gathered histogram then exit.
#
# Copyright (c) 2016 Allan McAleavy
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 05-Feb-20... |
import torch.nn as nn
class LSTMClassifier(nn.Module):
"""
This is the simple RNN model we will be using to perform Sentiment Analysis.
"""
def __init__(self, embedding_dim, hidden_dim, vocab_size):
"""
Initialize the model by settingg up the various layers.
"""
super(L... |
import KratosMultiphysics
import KratosMultiphysics.RomApplication as romapp
import KratosMultiphysics.StructuralMechanicsApplication
from KratosMultiphysics.RomApplication.empirical_cubature_method import EmpiricalCubatureMethod
from KratosMultiphysics.RomApplication import python_solvers_wrapper_rom as solver_wrapper... |
# -*- coding: utf-8 -*-
"""
JoystickButton is a button with x/y values. When the button is depressed and the
mouse dragged, the x/y values change to follow the mouse.
When the mouse button is released, the x/y values change to 0,0 (rather like
letting go of the joystick).
"""
import initExample ## Add path to library... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.