content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import matplotlib.pyplot as plt
from .plot_utils import density_scatter
def plot_params_vs_tbr(df, params, n_rows=3, n_columns=3, density_bins=80):
'''Plot multiple params vs. TBR. Supplied parameters are expected to be tuples of column names and human-readable names (for labels).'''
fig = plt.figure()
... | python |
# benchmark.py
#
# A micro benchmark comparing the performance of sending messages into
# a coroutine vs. sending messages into an object
# An object
class GrepHandler(object):
def __init__(self,pattern, target):
self.pattern = pattern
self.target = target
def send(self, line):
if self... | python |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... | python |
# Copyright (c) 2018 PaddlePaddle 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 app... | python |
try:
import oct2py
except OSError as e:
print(e)
| python |
# -*- coding: utf-8 -*-
'''
Module for managing Infoblox
Will look for pillar data infoblox:server, infoblox:user, infoblox:password if not passed to functions
.. versionadded:: Boron
:depends:
- requests
'''
from __future__ import absolute_import
# Import salt libs
from salt.exceptions import CommandExecut... | python |
import numpy as np
import streamlit as st
import pandas as pd
from builder.helpers import *
from builder.portfolio_builder import PortfolioBuilder
def app():
model = st.container()
pb0 = PortfolioBuilder(probability_weighted=False).init_data()
with model:
st.header("Original model presented by B... | python |
keyboard.send_key("<left>") | python |
from __future__ import print_function
x = 42
print("Hello, World")
| python |
# -*- coding: utf-8 -*-
#
# Copyright nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# ... | python |
# -*- coding: utf-8 -*-
from . import misc, excepts
from .compat import unicode, bool_compat
@bool_compat
class FD(object):
TAGS = {
# тэг: (тип значения, признак обязательности соблюдения длины, максимальная длина)
# телефон или электронный адрес покупателя
1008: (unicode, False, 64)
... | python |
# Copyright 2017 The Bazel 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 la... | python |
#!/usr/bin/env python
import time
import threading
import logging
import sys
import signal
import hollywood.actor
import hollywood.exceptions
# Clean shutdown with ctrl-c
def signal_handler(sig, frame):
System.halt()
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
class System(object):
addre... | python |
import random
import time
try:
from colorama import init, Fore, Back
init(autoreset=True)
blue = Fore.LIGHTCYAN_EX
red = Fore.LIGHTRED_EX
green = Fore.GREEN
res = Fore.RESET
except:
if (int(input("\nYou don't have colorama installed, do you want to install it? (Type 1 if you do): "))==1):
... | python |
from rxbp.init.initsubscriber import init_subscriber
from rxbp.init.initsubscription import init_subscription
from rxbp.mixins.flowablemixin import FlowableMixin
from rxbp.observable import Observable
from rxbp.observerinfo import ObserverInfo
from rxbp.scheduler import Scheduler
from rxbp.schedulers.trampolineschedule... | python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also availabl... | python |
import scancel
import sys
if __name__ == "__main__":
scancel.main(sys.argv)
| python |
#!/usr/bin/python
"""Command set for the Onkyo TX-NR708.
This file was automatically created by raw_commands_massager.py
from the source file: onkyo_raw_commands.txt
Each command group in the documentation has a seperate list,
and all commands are available in ALL."""
######################
### Power
##############... | python |
import cProfile
import palingrams_optimized
cProfile.run('palingrams_optimized.find_palingrams()')
| python |
from setuptools import setup
setup(
name="horsephrase",
version="0.6.0",
description="Secure password generator.",
long_description=(
"Like http://correcthorsebatterystaple.net/ except it's not a web page"
" which is logging your passwords and sending them all to the NSA."
),
a... | python |
from core.errors import ANCCError
class ParseError(ANCCError):
def __init__(self, lookahead_literal, non_terminal, *args):
super().__init__(*args)
self.lookahead_literal = lookahead_literal
self.non_terminal = non_terminal
def __str__(self):
return super().__str__() + ", unex... | python |
# -*- coding: utf-8 -*-
import os
import time
import argparse
import os.path as osp
import sys
sys.path.append('.')
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision.transforms import Compose
from network.mainnetwork import VLFTrans
from utils... | python |
from typing import List
from ..regularization_operator import RegularizationOperator
from .block_operator import BlockOperator
from .null_operator import NullOperator
def make_block_operator(operator_list: List) -> RegularizationOperator:
"""
Given a list of regularization operators, creates a block operato... | python |
#!/usr/bin/env python2
from setuptools import setup, find_packages
setup(name='polyjit.buildbot',
version='0.1',
url='https://github.com/PolyJIT/buildbot',
packages=find_packages(),
install_requires=["buildbot>=0.9.7",
"buildbot-console-view",
"bui... | python |
from django.contrib import admin
from apps.sistema.models import registro,compra,tarjetas
# Register your models here.
admin.site.register(registro)
admin.site.register(compra)
admin.site.register(tarjetas) | python |
"""
Fixer for dictcomp and setcomp:
{foo comp_for} -> set((foo comp_for))
{foo:bar comp_for} -> dict(((foo, bar) comp_for))"""
from lib2to3 import fixer_base
from lib2to3.pytree import Node, Leaf
from lib2to3.pygram import python_symbols as syms
from lib2to3.pgen2 import token
from lib2to3.fixer_util import parenthesi... | python |
'''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p, constants as _cs, arrays
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_map_buffer_range'
def _f( function ):
return _p.createFunction( function,_p.GL,'GL_ARB_map_buffer_range',False)
_p.unpack_const... | python |
import numpy as np
# Nonlinearity functions (Numpy implementation)
nl_linear = lambda x: x
nl_tanh = lambda x: np.tanh(x)
nl_sigmoid = lambda x: 1./(1+np.exp(-x))
nl_rect = lambda x: np.clip(x, 0, np.inf)
nl_shallow_rect = lambda x: np.clip(0.1*x, 0, np.inf)
nl_clip = lambda x: np.clip(x, 0, 1)
nl_softplus = lambda ... | python |
from tensorhive.core.managers.TensorHiveManager import TensorHiveManager
from connexion import NoContent
from flask_jwt_extended import jwt_required
@jwt_required
def get_metrics(hostname: str, metric_type: str = None):
try:
infrastructure = TensorHiveManager().infrastructure_manager.infrastructure
... | python |
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
def k_fold(n, value_est):
kf = KFold(n_splits=5)
def expend_feature_test(df):
"""
Return a dataframe with expension of sequence for test set prediction
Args:
d... | python |
#!/usr/bin/env python
# Copyright (c) 2015, Carnegie Mellon University
# All rights reserved.
# Authors: David Butterworth <dbworth@cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of sour... | python |
# import os
# import yaml
# from click.testing import CliRunner
# from mangum.cli.commands import init
# def test_cli(tmpdir) -> None:
# name = "test"
# bucket_name = "my-bucket-1"
# region_name = "ap-southeast-1"
# runner = CliRunner()
# config_dir = tmpdir.mkdir("tmp")
# os.chdir(config_di... | python |
from importlib import import_module
from importlib.machinery import SourceFileLoader
from chainercmd.config.base import ConfigBase
class Extension(ConfigBase):
def __init__(self, **kwargs):
required_keys = []
optional_keys = [
'dump_graph',
'Evaluator',
'Expon... | python |
from copy import deepcopy
from ..base import BaseAutoModel
class BaseHeteroModelMaintainer(BaseAutoModel):
def __init__(self, num_features, num_classes, device, dataset=None, **kwargs):
super().__init__(num_features, num_classes, device, **kwargs)
self._registered_parameters = {}
if dataset... | python |
from django.conf import settings
# IPStack Configuration
# Use it like this:
# GET '%scheck%s' % (IPSTACK_BASE_URL, IPSTACK_APIKEY)
# notice the url param 'check'
IPSTACK_BASE_URL = 'http://api.ipstack.com/'
IPSTACK_APIKEY = '?access_key=%s' % settings.IPSTACK_APIKEY
def get_ipstack_url(ip):
"""Return the ready... | python |
import os
import requests
import sys
import re
from configs.config import Config
from utils.vpn import connect
import logging
class hold_proxy(object):
def __init__(self):
self.proxy = os.environ.get("http_proxy")
self.logger = logging.getLogger(__name__)
def disable(self):
os.environ... | python |
from rest_framework import generics, authentication, permissions
from rest_framework import status
from django.http.response import HttpResponse
from django.contrib.auth import authenticate, login
from rest_framework_jwt.settings import api_settings
from mentorbot.serializers.mentordetailsserializers import MentorPro... | python |
import math
import keras
from keras import optimizers
from keras import regularizers
from keras.callbacks import LearningRateScheduler, TensorBoard, ModelCheckpoint
from keras.datasets import cifar10
from keras.initializers import he_normal
from keras.layers import Conv2D, Dense, Input, add, Activation, GlobalAverageP... | python |
import os
from copy import deepcopy
from .base import BoundaryCondition
from .base import BCFile
from inspect import cleandoc
default_value = 0.0064879
field_template = cleandoc("""
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield ... | python |
#################### Importing Requirements ####################
import spacy
import pandas as pd
import warnings
import os
warnings.filterwarnings('ignore')
nlp = spacy.load("ur_model") # Make sure to Download and Install model from https://github.com/mirfan899/Urdu
################## Longest COmmon Subsequence ###... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of the pyqualtrics package.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/Baguage/pyqualtrics
#
# Licensed under the Apach... | python |
import unittest
class TestBaseStegoImage(unittest.TestCase):
def test__pack_pixels(self):
self.fail()
def test__insert_data(self):
self.fail()
def test__extract_data(self):
self.fail()
if __name__ == '__main__':
unittest.main() | python |
import textwrap
import requests
import jwt
import enum
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend
TIMEOUT = 2 # timeout for all HTTP requests
class Errors(enum.Enum):
MetadataUrlUnreachable = "Unable to reach metadata URL."
MetadataUrlHtt... | python |
''' This program tests simples operations( addition,multiplication)
on constants and matrices tensors (matmul)
'''
import tensorflow as tf
tf.enable_eager_execution()
a = tf.constant(1)
b = tf.constant(1)
c = tf.add(a, b) # equivalent of a + b
print(c)
A = tf.constant([[1, 2], [3, 4]])
B = tf.constant([[5, 6]... | python |
ENTRY_POINT = 'vowels_count'
#[PROMPT]
FIX = """
Add more test cases.
"""
def vowels_count(s):
"""Write a function vowels_count which takes a string representing
a word as input and returns the number of vowels in the string.
Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
vowel, ... | python |
import numpy as np
import time
feature_dict = {}
for i in range(190190):
if i % 1001 == 1 :
t1 = time.time()
class_video_name = np.random.randint(190)
np_as_line = np.random.rand(4014)
if class_video_name in feature_dict.keys():
feature_dict[class_video_name] = np.concatenate(
... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2022, libracore (https://www.libracore.com) and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from datetime import datetime
import json
from mvd.mvd.doctype.dru... | python |
# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time
import math
from serial import *
#Setting up Serial port
#for raspberry pi use serialPort = "/dev/ttyACM0"
#serialPort = "/dev/tty.usbmodem1411
#serialPort = "/dev/cu.usbmodemFA131"
#baudRate = 115200
#ser = Serial(serialPort , baud... | python |
#-------------------------------------------------------------------------------
# Name: opan_const
# Purpose: Test objects for opan.const
#
# Author: Brian Skinn
# bskinn@alum.mit.edu
#
# Created: 10 Mar 2016
# Copyright: (c) Brian Skinn 2016
# License: The MIT License; see "li... | python |
import pytest
# test_specials.py
# Tests the special abilities of each character
import helpers as H
def test_bob_kill_hunter():
# Get a game containing Bob
gc, ef, p = H.get_game_with_character("Bob")
# Check that Bob hasn't won initially, or with 4 equips
assert not p.character.win_cond(gc, p)
... | python |
'''
Created on 12. 10. 2016
@author: neneko
'''
from lxml import etree
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
import hashlib
import uuid
from eet_ns import *
from string import Template
import base64
from utils import find_node
envelope_template = Temp... | python |
# Breaking down configuration File here!
import json
import os
import sys
from os import path
from .constants import MANAGER_SCOPE, APPLICATION_SCOPE
from .exceptions import ImplementorTypeNotFoundException
class Settings:
def __init__(self):
# Loading and Reading from Config file
self.conf_path... | python |
# Copyright (c) Glow Contributors. See CONTRIBUTORS file.
#
# 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 ... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask_marshmallow import Schema
from marshmallow import fields
class UserSchema(Schema):
id = fields.String(required=True)
email = fields.String(required=True)
name = fields.String()
bio = fields.String()
user_schema = UserSchema()
| python |
__author__ = 'surya'
import xml.etree.cElementTree as ET
from datetime import datetime
import experimentInfo, participantInfo
def makePSIMIXMLFile(NewHitFile,exportPathFile,baitName):
#<entrySet/>
root = ET.Element("entrySet")
root.set("minorVersion","0")
root.set("version","0")
root.set("level","3")... | python |
import struct, csv, pprint
def calculate_mode_mask(index, ttc_comm, adcs, rw, imu, st, mtr, css, fss, cp):
mode_value = 0
mode_value |= (ttc_comm & 0x1) << 0
mode_value |= (adcs & 0x1) << 1
mode_value |= (rw & 0x1) << 2
mode_value |= (imu & 0x1) << 3
mode_value |= (st & 0x1) << 4
mode_val... | python |
#!/usr/bin/python2.4
# Copyright (c) 2006-2008 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.
'''Unit tests for TxtFile gatherer'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.... | python |
from django import forms
from .models import Post
class NewPostForm(forms.ModelForm):
class Meta:
model = Post
exclude = ['author','url','likes'] | python |
from plugnparse import entrypoint, ParserFactory
| python |
# -*- coding: utf8 -*-
# ============LICENSE_START====================================================
# org.onap.vvp/validation-scripts
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===========================================... | python |
# -*- coding: utf-8 -*-
# Python implementation of the LexRank algorithm.
# Reference - LexRank: Graph-based Centrality as Salience in Text Summarization
# Reference URL - http://tangra.si.umich.edu/~radev/lexrank/lexrank.pdf
# Author - Janu Verma
# email - jv367@cornell.edu
# http://januverma.wordpress.com/
# @januve... | python |
from .transaction import TxInput, TxOutput, Transaction, InsufficientFunds
from .unspent import Unspent
| python |
import unittest
from app import db
from app.models import User,BlogPost
class BlogPostTest(unittest.TestCase):
def setUp(self):
self.user_john = User(username = 'john',password = 'johnjohn')
self.new_blog = Blog(content='johnjohnjohn')
def test_check_instance_variable(self):
self.assertEqu... | python |
import pandas as pd
from sosia.processing.caching import insert_data, retrieve_authors,\
retrieve_authors_from_sourceyear
from sosia.processing.querying import query_pubs_by_sourceyear, stacked_query
def get_authors(authors, conn, refresh=False, verbose=False):
"""Wrapper function to search author data for a... | python |
from math import cos, sin, radians
from random import random
import pygame
from events_handler import check_win
from player import Player
pygame.mixer.init()
class Ball:
RADIUS: int = 17
SPEED: int = 4
click_sound = pygame.mixer.Sound("./assets/click.wav")
wall_sound = pygame.mixer.Sound("./assets/ball_wall.w... | python |
# Support code for building a C extension with xxhash files
#
# Copyright (c) 2016-present, Gregory Szorc (original code for zstd)
# 2017-present, Thomas Waldmann (mods to make it more generic, code for blake2)
# 2020-present, Gianfranco Costamagna (code for xxhash)
# All rights reserved.
#
... | python |
import os
from collections import defaultdict
import json
import logging
import dateutil
from django.contrib import messages
from django.db import transaction
from django.db.models import Count, Sum, Q
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from djan... | python |
'''
module for importing
all functions
'''
from pyalgo import *
'''
PyAlgo - Maths
'''
from pyalgo.maths import *
from pyalgo.maths.catalan_numbers import catalan
from pyalgo.maths.factorial import factorial
from pyalgo.maths.fibonnaci_numbers import fibonacci
from pyalgo.maths.gcd import gcd, lcm
from pyalgo.maths.... | python |
#!/usr/bin/env python
# coding: utf-8
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Created on Jul 2021.
@author: Wanderson Neto
"""
import os
from convert import convert
def inicio():
print('###################')
print(' ##############')
print(' ##########')
print(' #####')
pr... | python |
import sys
fileName = "C:\\Users\\suagrawa\\Optimization-Python\\Regression\\input"
data = []
def readFromFile(fileName):
with open(fileName) as f:
content = f.readlines()
content = [x.strip() for x in content]
for item in content:
row = [int(el) for el in item.split(',')]
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 18:56:24 2019
@author: descentis
"""
import os
from multiprocessing import Process, Lock
import time
import numpy as np
import glob
import difflib
import xml.etree.ElementTree as ET
import math
import textwrap
import html
import requests
import ... | python |
# Copyright 2011 OpenStack Foundation
# Copyright 2013 Rackspace Hosting
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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 co... | python |
# Imagekit options
from imagekit import processors
from imagekit.specs import ImageSpec
class Options(object):
""" Class handling per-model imagekit options
"""
image_field = 'image'
crop_horz_field = 'crop_horz'
crop_vert_field = 'crop_vert'
preprocessor_spec = None
cache_dir = 'cache'
... | python |
import numpy as np
import pandas as pd
from typing import Any, Union
def get_timestamp(value: Union[int, str]) -> Union[pd.Timestamp, None]:
if value is None or isinstance(value, pd.Timestamp):
return value
if isinstance(value, (int, np.integer)):
return pd.Timestamp(value, unit='s')
retu... | python |
'''
# Devs: Ali; Rakib;
'''
from setuptools import setup, find_packages
# Setup configuration for the tool
setup(
name='OEDA-Backend',
version='1.0',
long_description="",
packages=find_packages(),
include_package_data=False,
zip_safe=False,
install_requires=[
# Tempita is a small ... | python |
import logging
from pint import UnitRegistry, DimensionalityError, DefinitionSyntaxError, \
UndefinedUnitError
from discord import Embed
from discord.ext import commands
log = logging.getLogger(f'charfred.{__name__}')
class UnitConverter(commands.Cog):
def __init__(self, bot):
self.bot = bot
... | python |
import pytest
EXAMPLE = """\
{
"version": "2020-11-30",
"data": [
{
"jisx0402": "13101",
"old_code": "100",
"postal_code": "1008105",
"prefecture_kana": "",
"city_kana": "",
"town_kana": "",
"town_kana_raw": "",
"prefecture": "東京都",
"city": "... | python |
# Comment section
# spoil written by Korbelz
# current scope: spoil Calc
print ('*** This app is a fuel/supply spoilage calc ***')
print ('*** Written by Korbelz ***')
print ('*** Feedback/Bugs: Discord: Korbelz#3504 ***')
input('Press ENTER to continue')
port = input("what size is the port? ")
port = int(port)
air... | python |
#!/usr/bin/env python3
import pytest
import glooey
from vecrec import Rect
def test_misspelled_alignment():
with pytest.raises(glooey.UsageError) as err:
glooey.drawing.align('not an alignment', None, None)
def test_parent_changed():
child, parent = Rect.null(), Rect.null()
def change_parent(chi... | python |
# from typing import NamedTuple
from monkey.tokens import token
from collections import OrderedDict
class Node:
# this method used only for debugging
def token_literal(self): pass
def string(self): pass
class Statement(Node):
node = None
# dummy method
def statement_node(self): pass
class Exp... | python |
################################################################################
# Copyright (c) 2009-2020, National Research Foundation (SARAO)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the License at
#
# ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import cw
sys.setrecursionlimit(1073741824)
def main():
if len(cw.SKIN_CONV_ARGS) > 0:
os.chdir(os.path.dirname(sys.argv[0]) or '.')
try:
app = cw.frame.MyApp(0)
app.MainLoop()
finally:
... | python |
from flask_appbuilder.security.manager import AUTH_OAUTH
from airflow.www.security import AirflowSecurityManager
from auth import config
WTF_CSRF_ENABLED = True
AUTH_TYPE = AUTH_OAUTH
AUTH_USER_REGISTRATION_ROLE = 'Admin'
AUTH_USER_REGISTRATION = True
AUTH_ROLES_SYNC_AT_LOGIN = True
OAUTH_PROVIDERS = [
{
... | python |
# !/usr/bin/python
# vim: set fileencoding=utf8 :
#
__author__ = 'keping.chu'
import multiprocessing as mp
from threading import Thread
import aiohttp
import easyquotation
import time
from easyquant import PushBaseEngine
from easyquant.event_engine import Event
class FixedDataEngine(PushBaseEngine):
EventType ... | python |
from ted_sws.core.model.notice import Notice
from ted_sws.core.model.manifestation import XMLManifestation
class FakeNotice(Notice):
ted_id: str = 'fake-notice-id'
xml_manifestation: XMLManifestation = XMLManifestation(
object_data='<?xml version="1.0" encoding="UTF-8"?><TED_EXPORT xmlns:xlink="http:/... | python |
# -*- coding: utf-8 -*-
"""
Last modified June 2021
@author: pauliuk
see: https://github.com/IndEcol/openLCA_ecoinvent_Material_Footprint_LCIA
"""
# Script ei_LCIA_MF_populate.py
# Import required libraries:
#%%
import openpyxl
import numpy as np
import os
import uuid
import json
import mf_Paths
###############... | python |
"""
pg_seldump -- package objects
"""
from .consts import VERSION as __version__ # noqa
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Server
from app.utils import get_env
def create_app():
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
def get_config(x=None):
return {
'development':... | python |
# engine/interfaces.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Define core interfaces used by the engine system."""
from .. import util
fr... | python |
import tensorflow as tf
import numpy as np
def set_gpu(config_str):
import os
os.environ["CUDA_VISIBLE_DEVICES"] = config_str
###########################################################
#define weight and bias initialization
def weight(shape,data=None,dtype=None):
if dtype is None:
dtype = tf.float3... | python |
# 2020.09.06
# Problem Statement:
# https://leetcode.com/problems/text-justification/
class Solution:
def modified(self, temp, maxWidth, count_char, count_word, count_char_list):
# check corner case, if only one word
if count_word == 1:
temp = temp + " "*(maxWidth-len(temp))
... | python |
import sys, os, json
import SteamUtil, ServiceUtil
class AutoUpdater():
def __init__(self, config):
self.APP_ID = config["app_id"]
self.VERSION_FILE = config["version_file"]
self.STEAM_API_KEY = config["steam_api_key"]
self.STEAM_DIR = config["steamcmd_location"]
self.STEAMCMD_EXE = config["steamcmd_exe"]
... | python |
# Copyright 2016-2021 The Van Valen Lab at the California Institute of
# Technology (Caltech), with support from the Paul Allen Family Foundation,
# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.
# All rights reserved.
#
# Licensed under a modified Apache License, Version 2.0 (the "License");... | python |
from stan import StanDict
if __name__ == '__main__':
dict_1 = StanDict()
dict_2 = StanDict()
dict_1['metric_1'] = 1
dict_1['metric_2'] = 2
dict_2['metric_3'] = 3
dict_2['metric_4'] = 4
print(dict_1)
print(dict_2)
print(dict_1 + dict_2)
print(dict_1['missing_key'])
| python |
"""
What if we wish to apply decorator for all the methods of a class??
It's possible with the help of class decorator.
Limitation: Class decorator do not work for class methods and
static methods
Let's see how setattr works before we use class decorator
Syntax : setattr(obj, var, val)
Parameters :
obj : Object whose... | python |
# -*- coding: utf-8 -*-
from . import wizard_wxwork_contacts_sync
from . import wizard_wxwork_sync_tag
from . import wizard_wxwork_sync_user
| python |
import numpy as np
import pandas as pd
def calculate_ROIC(data):
"""gets a data frame with the following fields: OperatingIncome, TaxRate, LongTermDebt, CurrentDebt, StockholderEquity and Cash
and calculate the ROIC of the company per year
Arguments:
data {pd.Dataframe} -- Dataframe with ... | python |
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# -- Libraries ----------------------------------------------------------------
import pywapi
import pprint
import time
# -- Confiurations ------------------------------------------------------------
# the city name you want to search
CITY_NAME = 'York, YOR, United Kin... | python |
#!/usr/bin/env python3
import sys
from argparse import ArgumentParser
from collections import defaultdict
def parse_args():
p = ArgumentParser('Constructs vocabulary file.')
p.add_argument(
'--input',
type=str, metavar='FILE', required=True, help='source corpus')
p.add_argument(
'--output',
... | python |
class PointMath:
"""Math with points and lines"""
# Taken from:
# https://stackoverflow.com/questions/1811549/perpendicular-on-a-line-from-a-given-point/1811636#1811636
# Accessed November 21, 2017
def perpendicularIntersection(point, linePoint1, linePoint2):
"""
Return the point of intersection of the line t... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.