text stringlengths 2 999k |
|---|
# Copyright 2017 The TensorFlow 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 applica... |
filename = 'learning_python.txt'
print("---Reading in the entire file:---")
with open(filename) as file_object:
contents = file_object.read()
print(contents)
print("---Looping over the lines:---")
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print("---Storing the ... |
# Copyright 2017-2018 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
class PolicyFilter:
pass
|
"""
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
Thi... |
import socket
import struct
import time
class MasterEtherCAT:
def __init__(self, NickName):
"""
:param str NickName:
"""
ether_type = 0x88A4
self.lowlevel = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) # CAUTION: does not work on OSX
timeval = struct.pack('ll', ... |
import unidecode
from krcg import twda
def unpack(s):
if not isinstance(s, str):
return s
return s.split("|") if "|" in s else [s]
def normalize(s):
"""Normalize a string for indexing: unidecode and lowercase."""
if not isinstance(s, str):
return s
return unidecode.unidecode(s).l... |
from typing import Set, Dict, List
from collections import OrderedDict
from mypy_extensions import TypedDict
KeyBinding = TypedDict('KeyBinding', {
'keys': Set[str],
'help_text': str,
'excluded_from_random_tips': bool,
}, total=False)
KEY_BINDINGS = OrderedDict([
('HELP', {
'keys': {'?'},
... |
import random
# Input: A set of kmers Motifs
# Output: CountWithPseudocounts(Motifs)
def CountWithPseudocounts(Motifs):
count = {}
t = len(Motifs)
k = len(Motifs[0])
for symbol in "ACGT":
count[symbol] = []
for j in range(k):
count[symbol].append(1) # pseudo=1
... |
import json
import math
from pandas.io.json import json_normalize
from src.data.fetch_trend_data_utils import display_max_cols, save_dictionary_to_csv
display_max_cols(10)
jfile = "/home/randilu/fyp_impact analysis module/impact_analysis_module/data/external/events/Kelani_Valley_Plantaitions_PLC_v2.json"
with open(jfi... |
# Copyright 2020 Huawei Technologies Co., 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 required by applicable law or agreed to... |
"""Comment will be changed. Only valid with '--force'."""
from typing import List # this comment should not be deleted
var2: List[int]
|
# -*- coding: utf-8 -*-
import csv
import datetime
import logging
import os.path
from functools import wraps
from html import escape
from io import StringIO
from itertools import chain
from time import time
import gevent
from flask import Flask, make_response, jsonify, render_template, request, send_file
from flask_b... |
# coding: utf-8
"""
SQE API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
impor... |
from ProjectEulerCommons.Base import *
from ProjectEulerCommons.PrimeNumbers import is_prime
def generate_prime_diagonal_ratio():
count_prime = 0
for layer_n in count(1):
diagonals = (4 * layer_n**2 - 8 * layer_n + 5, 4 * layer_n**2 - 10 * layer_n + 7, 4 * layer_n**2 - 6 * layer_n + 3, (layer_n + 1)**2... |
from mitmproxy.net.http import url
from mitmproxy.types import multidict
from . import base
class ViewURLEncoded(base.View):
name = "URL-encoded"
prompt = ("urlencoded", "u")
content_types = ["application/x-www-form-urlencoded"]
def __call__(self, data, **metadata):
try:
data = da... |
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket 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 required by applica... |
import numpy
def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> numpy.allclose(M, numpy.ide... |
#Author: Sepehr Roudini
#University of Iowa
#Department of Chemical Engineering
#Date: 12/28/2017
#Purpose: Convert calendar date to julian day
#--------------------------------------------------------------------------------------------#
#defin function and import necessary libraries
#-------------------------------... |
# Copyright 2015 The TensorFlow 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 applica... |
#! /usr/bin/env python
"""
File: Polynomial
Copyright (c) 2016 Chinmai Raman
License: MIT
Course: PHYS227
Assignment: 7.27
Date: April 14th, 2016
Email: raman105@mail.chapman.edu
Name: Chinmai Raman
Description: Regular Polynomial class
"""
from __future__ import division
import matplotlib.pyplot as plt
import numpy ... |
#!/usr/bin/env python
#
# Program: 3D Slicer
#
# Copyright (c) Kitware Inc.
#
# See COPYRIGHT.txt
# or http://www.slicer.org/copyright/copyright.txt for details.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT ... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from aws_cdk import aws_dms
from aws_cdk import core
import boto3
class GlobalArgs():
"""
Helper to define global statics
"""
OWNER = "Redshift POC SSA team"
ENVIRONMENT = "development"
REPO_NAME = "redshift-demo"
VERSION = "2021_03_15"
class DmsOnPremToRedshiftStack(core.Stack):
def... |
from typing import Dict, List, Optional, Tuple, Union
from captum.attr import visualization as viz
from transformers import PreTrainedModel, PreTrainedTokenizer
from .sequence_classification import SequenceClassificationExplainer
SUPPORTED_ATTRIBUTION_TYPES = ["lig"]
class MultiLabelClassificationExplainer(Sequenc... |
from jynx.lib.hibernate import*
from jynx.lib.util.table import Table as SQLTable
from com.ziclix.python.sql import zxJDBC
derbyConn = zxJDBC.connect("jdbc:derby:hiberynxdb",
"kay",
"",
"org.apache.derby.jdbc.EmbeddedDriver")
curs... |
#----------------------------------------------
#--- Author : Ahmet Ozlu
#--- Mail : ahmetozlu93@gmail.com
#--- Date : 27th July 2019
#----------------------------------------------
# Imports
import tensorflow as tf
# Object detection imports
from utils import backbone
from api import obje... |
import math
import matplotlib.pyplot as plt
t = [i+1 for i in range(200)]
s = [math.sin(i) for i in t]
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('simple plotting test')
plt.grid(True)
plt.show()
|
#Exercício Python 52: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
num = int(input('Digite um número: '))
tot = 0
for c in range(1, num + 1):
if num % c == 0:
print('\033[33m', end='')
tot = tot + 1
else:
print('\033[31m', end='')
print('{}'.fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
from spampy import dataset_downloader
class DatasetDownloaderTests(unittest.TestCase):
def test_download_enron_dataset(self):
dataset_downloader.download_enron_dataset()
self.assertTrue(os.path.exists('spampy/datasets/enron')... |
import socket
import time
HOST = '127.0.0.1'
# HOST = socket.gethostname()
PORT = 1243
HEADERSIZE = 10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
while True:
# now our endpoint knows about the OTHER endpoint.
clientsocket, address = s.accept()
print(f"Connect... |
from __future__ import absolute_import, unicode_literals
import sys
import unittest
from unittest import TestCase
from wsgiref.util import setup_testing_defaults
from prometheus_client import CollectorRegistry, Counter, make_wsgi_app
from prometheus_client.exposition import _bake_output, CONTENT_TYPE_LATEST
class W... |
import sys
import os
import torch.distributed as dist
import torch
from pathlib import Path
def get_tmp_dir():
if 'JOB_DIR' in os.environ:
tmp_dir = Path(os.environ['JOB_DIR']) / 'tmp'
else:
tmp_dir = Path('/tmp/cosypose_job')
tmp_dir.mkdir(exist_ok=True)
return tmp_dir
def sync_mode... |
import datetime
import uuid
from xml.etree import cElementTree as ElementTree
from django.template.loader import render_to_string
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.models import CommCareCase
from dimagi.utils.parsing import json_format_datetime
from corehq.apps.receiverwrapper.util ... |
import numpy as np
import pandas as pd
from PIL import Image
from tqdm import tqdm
import os
# making folders
outer_names = ['test', 'train']
inner_names = ['angry', 'disgusted', 'fearful', 'happy', 'sad', 'surprised', 'neutral']
os.makedirs('data', exist_ok=True)
for outer_name in outer_names:
os.makedirs(os.pat... |
from .Assembly import Assembly
class Instruction(Assembly):
def __init__(self,a1,a2=None,a3=None,a4=None,a5=False):
if isinstance(a3,list):
self.mnemonic = a1
self.suffix = a2
self.operands = a3
self.need_relocation = a4
else :
if a4 != No... |
"""YOLO_v3 Model Defined in Keras."""
from functools import wraps
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate, MaxPooling2D
from tensorflow.keras.layers import LeakyReLU
#from tensorflow.... |
# -*- coding: utf-8 -*-
from . static import Base_RM_Field
class RM_Field_FEFILT0_IPVERSION_IPVERSION(Base_RM_Field):
def __init__(self, register):
self.__dict__['zz_frozen'] = False
super(RM_Field_FEFILT0_IPVERSION_IPVERSION, self).__init__(register,
'IPVERSION', 'FEFILT0.IPVERSION.... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 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 multiple RPC users."""
from test_framework.test_framework import BitcoinTestFramework
from test_f... |
import json
from redis import Redis
from platypush.backend import Backend
from platypush.context import get_plugin
from platypush.message import Message
class RedisBackend(Backend):
"""
Backend that reads messages from a configured Redis queue (default:
``platypush_bus_mq``) and posts them to the applic... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for kanging stickers or making new ones. Thanks @rupansh"""
import io
import math
import urllib.req... |
#! python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import os
import sys
import time
from .parser import gsea_edb_parser,gsea_rank_metric,gsea_gmt_parser,gsea_cls_parser
from .algorithm import enrichment_score,gsea_compute,preprocess,ranking_metric
from .gsea_plot impor... |
#!/usr/bin/env python
#
# Download raw test data files, check integrity and untar
from __future__ import print_function, unicode_literals
import hashlib
import io
import os
import os.path
import urllib
import shutil
import sys
import tarfile
try:
from urllib.request import urlretrieve
except ImportError:
from ... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.backend.codegen.soap.java import extra_fields
from pants.backend.codegen.soap.java.extra_fields import Jav... |
'''
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
Each 0 marks an empty land which you can pass by freely.
Each 1 marks a building which you cannot pass t... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 13:55:21 2018
@author: mir-lab
"""
from PIL import Image
import os.path, sys
from config import Config
path = "/home/mir-lab/Desktop/2018-02-12-17-10-41"
dirs = os.listdir(path)
#Before using this code, remove the .csv or .txt files from that folder
def crop():
... |
import aiohttp_jinja2
from app.handlers.abstract import AbstractView
from app.log import get_logger
log = get_logger()
class AdminEntities(AbstractView):
@aiohttp_jinja2.template('admin_entities.jinja2')
async def get(self):
return {}
async def post(self):
return {}
|
import os
pwd = os.getcwd()
opencvFlag = 'keras'
IMGSIZE = (608,608)
keras_anchors = '8,11, 8,16, 8,23, 8,33, 8,48, 8,97, 8,139, 8,198, 8,283'
class_names = ['none','text',]
kerasTextModel=os.path.join(pwd,"models","text.h5")
darknetRoot = os.path.join(os.path.curdir,"darknet")
yoloCfg = os.path.join(pwd,"models"... |
import pytest
class DatabaseTestBase(object):
def make_db(self, request):
database = self.database
conn = database.connection
database.execute(
"CREATE TABLE table1 (id SERIAL PRIMARY KEY, name TEXT)")
conn.commit()
self.schema = self.schema_cls.create_from_con... |
from pedal import (set_source, next_section, execute)
from pedal.assertions import *
# Validate source code file
set_source(sections=6, independently=False)
# Start off in section 0
# Usually, that's just header (e.g., author names), so we want to advance to the
# next section.
# So now we'll go to Section 1
# Probl... |
import asyncio
import logging
from typing import List, Optional, Set, Tuple
import aiosqlite
from blspy import G1Element
from src.types.blockchain_format.sized_bytes import bytes32
from src.util.ints import uint32
from src.wallet.derivation_record import DerivationRecord
from src.wallet.util.wallet_types import Walle... |
import tensorflow as tf
from shutil import rmtree
class TensorBoardCallback:
def delete_graphs(self):
if tf.io.gfile.exists(self.logdir):
rmtree(self.logdir)
print(f"[*] {self.logdir} has deleted with shutil's rmtree")
def initialize(self, delete_if_exists: bool = False):
... |
import numpy as np
#
# testing helper functions
#
class TestStatTracker():
'''
Tracks statistics of interest while running inference on the
validation or test sets
'''
def __init__(self):
self.loss_sum = 0.0
self.total_loss_count = 0
self.cnf_err_sum = 0.0
self.cnf... |
# 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... |
#!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import logging
import os
from applicationinsights.logging import enable
from applicationinsights import TelemetryClient
from flask import Flask
from flask_cors import CORS
from flask_restful_swagger_2 ... |
# coding: utf-8
from io import BytesIO
import pytest
from pandas.io.msgpack import BufferFull, OutOfData, Unpacker
class TestPack:
def test_partial_data(self):
unpacker = Unpacker()
msg = "No more data to unpack"
for data in [b"\xa5", b"h", b"a", b"l", b"l"]:
unpacker.feed(d... |
import numpy as np
import sklearn.metrics
import torch
from torch.nn.functional import mse_loss
import plot
from utils import tensor2numpy
def compute_centroids(embeddings, classes):
embeddings = tensor2numpy(embeddings)
classes = tensor2numpy(classes)
embeddings = embeddings
centroids = np.zeros((i... |
import logging
import math
import higher
import torch
from torch import nn, optim
import numpy as np
from torch.utils import data
from transformers import AdamW
import datasets
import models.utils
from models.base_models import ReplayMemory, TransformerClsModel, TransformerNeuromodulator
logging.basicConfig(level=... |
# Taken from distlib
# PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
# --------------------------------------------
#
# 1. This LICENSE AGREEMENT is between the Python Software Foundation
# ("PSF"), and the Individual or Organization ("Licensee") accessing and
# otherwise using this software ("Python") in source or bin... |
# This module defines a workflow for FFopting a molecule and then analyzing its
# electron density critical points with Critic2.
from fireworks import Workflow
from atomate.qchem.fireworks.core import CubeAndCritic2FW, FrequencyFlatteningOptimizeFW
from atomate.utils.utils import get_logger
__author__ = "Samuel Blau... |
#!/usr/bin/env python
from setuptools import find_packages, setup
import os
# You need install_requires if you don't have a ROS environment
install_requires = [ # ] if os.environ.get('AMENT_PREFIX_PATH') else [
# build
'setuptools',
# runtime
'pydot'
]
tests_require = ['flake8', 'mypy==0.812', 'nose... |
import os
import pickle
# import pickle5 as pickle
import random
import warnings
from distutils.util import strtobool
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from environments.parallel_envs import make_vec_envs
device = torch.device("cuda:0" if torch.cuda.is_availab... |
# -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from __future__ import unicode_literals
from django.contrib import admin
from .models import BBCNews, NewsWebsite, ReutersNews, ReutersWebsite
from .models import AljazeeraNews, AljazeeraWebsite
from .models import PoliticoNews, PoliticoWebsite
from .models import Economist, EconomistNews
from .models import WikiWebsit... |
#! /usr/bin/env python2
import os
from roboTraining.analysis import *
if __name__ == "__main__":
# Simulate best individu in each folder
i = 0
for path, subdirs, files in os.walk("/home/gabs48/edu/Data/powereff_low_E_d_with_k/data"):
if not subdirs:
if not os.path.isfile(path + "/sim.mp4"):
an = Analysis... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False # PyTorch does not suppo... |
import configparser
import os
import boto3
import json
import time
import botocore.exceptions
from botocore.session import Session
def check_aws_config_file():
config = None
aws_config_file = os.environ['HOME'] + "/.aws/config"
if os.path.isdir(os.environ['HOME'] + "/.aws"):
if os.path.isfile(aws... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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, ... |
import itertools
import json
import logging
import os
import platform
import shutil
import subprocess
import textwrap
from argparse import ArgumentParser
from pathlib import Path
from subprocess import PIPE
def main() -> None:
parser = ArgumentParser()
parser.add_argument('--toolchain')
parser.add_argumen... |
# coding=utf-8
# Copyright 2019 The TensorFlow GAN Authors.
#
# 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 applicabl... |
import pytest
import numpy as np
import astropy.units as u
from numpy.testing import assert_allclose
from gammapy.modeling import Covariance
from gammapy.modeling.models import (
BackgroundModel,
GaussianSpatialModel,
Models,
PointSpatialModel,
PowerLawSpectralModel,
SkyModel,
FoVBackgroundM... |
"""
SOLR module
Generates the required Solr cores
"""
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import (
col,
explode,
collect_set,
concat,
flatten,
monotonically_increasing_id,
)
from pyspark.sql.types import StringType
ONTOLOGY_MP_MAP = {
"mp_id": "id"... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.22
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
import threading as thd
def do_this(what):
whoami(what)
def whoami(what):
print("Thread {} says: {}".format(thd.current_thread(), what))
if __name__ == "__main__":
whoami("I'm the main program.")
for n in range(4):
t = thd.Thread(target=do_this, args=("I'm function {}".format(n),))
t... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2020 Intel Corporation
"""
This is the Optimizer plugin
"""
from .optimizer import (
OptimizerConfig,
OptimizerContext,
Optimizer,
)
from .parameter_grid import ParameterGrid
|
import sys
from static import Cling
def run():
host, port, directory = sys.argv[1:4]
app = Cling(directory)
try:
from wsgiref.simple_server import make_server
make_server(host, int(port), app).serve_forever()
except KeyboardInterrupt:
print("Cio, baby!")
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 14 21:48:53 2018
@author: donny
"""
def find_person(dict_users, strU):
if dict_users.has_key(strU):
return dict_users[strU]
else:
return 'Not Found'
if __name__ == "__main__":
dict_users = {'Tom':88888,'Jerry':5555555,'Snoopy':11111,... |
import io
import os
import re
import sys
import csv
import json
import importlib
importlib.reload(sys)
if __name__ == '__main__':
path = "E:/Demo/python/enum.txt"
result = set()
with open(path, 'r') as f:
lines = f.readlines()
newLines1 = []
newLines2 = []
for line in lines... |
import unittest, sys
import numpy as np
from src.nodes.multiclass_svm_loss import MulticlassSVMLoss
from src.utils.numeric_gradient import evaluate_gradient
class TestMulticlassSVMLoss(unittest.TestCase):
def setUp(self):
self.model= MulticlassSVMLoss()
def test_forward(self):
scores= np.ar... |
#!/usr/bin/env vpython3
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from blinkpy.web_tests.stale_expectation_removal import (
remove_stale_expectations)
import sys
if __name__ == '__main__':
... |
# A python script to upload safety reports to Elasticsearch
import elasticsearch as es
from elasticsearch import helpers
import logging
import base64
from os import listdir
from os.path import isfile, join
import hashlib
import pandas as pd
# DEFINITIONS ----------------------------------------------------------
path... |
# -*- coding:utf-8 -*-
import json
import logging
import numpy as np
from collections import defaultdict
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
import dist_train_config
import dist_params
import varserverapi
from dataset_loader import DatasetLoader
from weight_pack import WeightPack
logging... |
from __future__ import print_function
import os
import os.path
import json
import sys
import shutil
import time
import subprocess
src_path = os.path.join(os.getcwd(), "src")
sys.path.insert(0, src_path)
from rez.utils._version import _rez_version # noqa
# max number of result artifacts to store
MAX_ARTIFACTS = 100... |
from abc import ABC, abstractmethod
from typing import Dict, Tuple, Union, Optional, Generator
from aio_bomber.models import ServiceModel
class AbstractCache(ABC):
@abstractmethod
def __getitem__(self, item):
pass
@abstractmethod
def __setitem__(self, key, value):
pass
@abstract... |
import os
import pytest
from rgd.models.mixins import Status
from rgd_fmv.models import FMVMeta
NO_KWIVER = os.environ.get('NO_KWIVER', False)
@pytest.mark.django_db(transaction=True)
def test_populate_fmv_entry_from_klv_file(fmv_klv_file):
# Since we provide the KLV file and the factory provides a dummpy MP4 f... |
import sysconfig
# Category metadata.
# Category icon show in the menu
ICON = "icons/star2.svg"
# Background color for category background in menu
# and widget icon background in workflow.
BACKGROUND = "light-blue"
# Location of widget help files.
WIDGET_HELP_PATH = (
# No local documentation (There are problems... |
#!/usr/bin/python
import sys, os
testdir = os.path.dirname(__file__)
#srcdir = '../'
srcdir = '/app'
sys.path.insert(0, os.path.abspath(os.path.join(testdir, srcdir)))
from config import config
import psycopg2
from flask import Flask, request, jsonify, json, make_response
from flask_restful import reqparse, abort, Api... |
# Generated by Django 3.2.7 on 2021-10-05 11:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='recipe',
name='slug',
),
]
|
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from django.db import models
from django.db.models import CASCADE
class SfaStorageSystem(models.Model):
class Meta:
app_label = "chroma_core"
uuid = mo... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 23 23:51:26 2018
@author: Mostafa
"""
#%library
import numpy as np
# functions
from Hapi import GISpy as GIS
from Hapi import Inputs
"""
this function prepare downloaded raster data to have the same align and
nodatavalue from a GIS raster (DEM, flow accumulation, flow di... |
import pandas as pd
#Make the graphs a bit prettier, and bigger
from matplotlib import pyplot as plt
plt.style.use('default')
pd.set_option('display.line_width', 5000)
pd.set_option('display.max_columns', 60)
fundings = pd.read_csv('TechcrunchcontinentalUSA.csv')
print "Type of funding:\n", fundings[:5]['round']
#Se... |
r"""Rank-based cost function (CostRank)"""
import numpy as np
from numpy.linalg import pinv, LinAlgError
from scipy.stats.mstats import rankdata
from ruptures.base import BaseCost
from ruptures.costs import NotEnoughPoints
class CostRank(BaseCost):
r"""
Rank-based cost function
"""
model = "rank"
... |
# Generated by Django 2.2.24 on 2021-12-15 21:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Property',
fields=[
('id', models.AutoFiel... |
# Copyright (c) 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, so... |
from pathlib import Path
import requirements
from requirements.requirement import Requirement
def test_deps_consistency():
IGNORE = ["flake8", "isort", "mypy", "pydocstyle", "importlib_metadata", "tensorflow-cpu"]
# Collect the deps from all requirements.txt
REQ_FILES = ["requirements.txt", "requirement... |
from direct.distributed.DistributedObject import DistributedObject
class DistributedGoofy(DistributedObject):
""" THIS IS A DUMMY FILE FOR THE DISTRIBUTED CLASS"""
def __init__(self, cr):
DistributedObject.__init__(self, cr)
|
import paramiko
class GetSolarisData:
def __init__(self, ip, ssh_port, timeout, usr, pwd, use_key_file, key_file,
get_serial_info, get_hardware_info, get_os_details, add_hdd_as_parts,
get_cpu_info, get_memory_info, ignore_domain, upload_ipv6, debug):
self.machine_n... |
from .card import MetaflowCard, MetaflowCardComponent
class TestMockCard(MetaflowCard):
type = "test_mock_card"
def __init__(self, options={"key": "dummy_key"}, **kwargs):
self._key = options["key"]
def render(self, task):
task_data = task[self._key].data
return "%s" % task_data
... |
""" Working with Images in Python
What is Pul?
PIL stands for Python Imaging Library
PIL allows me to manipulate imagesdatetime A combination of a date and a time. Attributes: ()
"""
|
'''
Read data according to the JetScape 1.0 stat specification
'''
import numpy as np
import os
import pickle
from pathlib import Path
def ReadDesign(FileName):
# This is the output object
Result = {}
Version = ''
Result["FileName"] = FileName
# First read all the header information
for Li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.