content
stringlengths
5
1.05M
from logging import getLogger import urlparse import requests import pylons.config as config from pylons import request as req import ckan.logic as logic import ckan.lib.base as base from ckan.common import _ from ckan.plugins.toolkit import asint log = getLogger(__name__) MAX_FILE_SIZE = asint(config.get('ckan.re...
import functools import os import re import random import time from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor from twisted.logger import Logger, LogLevel, ILogObserver, formatEvent from cobe.brain import Brain from zope.interface im...
from conans import ConanFile, CMake, tools class ExtracmakemodulesConan(ConanFile): name = "extra-cmake-modules" version = "5.57.0" license = "MIT" author = "Alexis Lopez Zubieta contact@azubieta.net" url = "https://github.com/appimage-conan-community/conan-extra-cmake-modules" description = "...
# -*- coding: utf-8 -*- import numpy as np import pdb import math import copy from . data_generator import Metrics from . utilities.image_tools import ImageTools class ROIHelpers(object): """Assists in the calculation of regions of interest (ROIs).""" def __init__(self, config, overlap_thresh=0.9, max_boxes=300)...
# Settings.py import sys import configparser import curses from optparse import OptionParser import os # Actual #user_prefs_filename = os.path.expanduser( '~/.umergerc' ) #etc_prefs_filename = '/etc/umerge.conf' # For testing. I used the ini extension so emacs uses the right mode. user_prefs_filename = 'umergerc.i...
import requests from bs4 import BeautifulSoup import pandas import datetime import time class stock_data(object): def __init__(self,stockList): self.stock_list=stockList @property def get_stock_list(): return self.stock_list def real_time_price(self,stock_sym...
# Adapted from this response in Stackoverflow # http://stackoverflow.com/a/19053800/1072990 def to_camel_case(snake_str: str) -> str: components = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'capitalize' method and join them together. return co...
def main(): sum = 0 for _ in xrange(input()): sum += input() print str(sum)[0:10] if __name__ == '__main__': main()
#!/usr/bin/env python import click as ck import numpy as np import pandas as pd import gzip from collections import Counter from aminoacids import MAXLEN, to_ngrams import logging logging.basicConfig(level=logging.INFO) @ck.command() @ck.option( '--data-file', '-df', default='data/swissprot_exp_2021_03.pkl', ...
# Generated by Django 2.2.3 on 2019-08-13 15:36 from django.db import migrations, connection, ProgrammingError def generate_table_name(apps, _): model = apps.get_model("datasets", "ReferenceDataset") for r in model.objects.all(): original_table_name = "refdata__{}".format(r.id) if r.table_nam...
def ArrayLength(arr, n): dt = {} s = 0 res = 0 dt[0] = 0 for i in range(n): if arr[i]: s += 1 else: s += -1 try: l = i+1 - dt[s] if l > res: res = l print(res) except: dt[s] = i+...
from typing import Generic, List, Tuple, Dict, Union, Sequence from collections.abc import Iterable from numpy.typing import NDArray from ._types import State, Action, Policy import numpy as np from .base import FiniteMDP class StateValueFunction(Generic[State, Action]): """State value function for an MDP. H...
# -*- coding: utf-8 -*- """ Created on Thu Apr 16 20:31:43 2020 @author: balajiramesh """ icd_cols=['PRINC_DIAG_CODE', 'OTH_DIAG_CODE_1', 'OTH_DIAG_CODE_2', 'OTH_DIAG_CODE_3', 'OTH_DIAG_CODE_4', 'OTH_DIAG_CODE_5', 'OTH_DIAG_CODE_6', 'OTH_DIAG_CODE_7', 'OTH_DIAG_CODE_8', 'OTH_DIAG_CODE_9', 'E_CO...
from app.api.v1.views.utils import PartyValidator, OfficeValidator from . import unittest class TestValidator(unittest.TestCase): def setUp(self): self.valid_party = { "name": "my party", "logoUrl": "photo.com", "hqAddress": "Nairobi" } self.valid_offic...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # The MIT License (MIT) # Copyright (C) 2018 Seeed Technology Co.,Ltd. # # This is the library for Grove Base Hat # which used to connect grove sensors for Raspberry Pi. ''' This is the code for - `OLED Display 1.12" <https://www.seeedstudio.com/Grove-OLED-Display...
#!/usr/bin/env python3 ''' Write a function that takes a list and returns a new list with unique positive (more than 0) numbers. ''' def unique_lst(lst): coll = [] for i in lst: if i > 0 and i not in coll: coll.append(i) print(coll) #Alternative solution return sorted(set(i for i in lst...
import yaml import pathlib import os import pandas as pd class FileStateGateway: def __init__(self): self.dir = pathlib.Path(__file__).parent.absolute() def create_metadata_storage(self): pass def health(self): pass def __metadata_dump(self, sql, *multiparams, **p...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
# 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...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2014-2018 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
""""my project""" from flask import jsonify, Flask, request, redirect, url_for from flask_restful import reqparse app = Flask(__name__) app.config["SECRET_KEY"] = 'silasomurunga' user_details = dict() user_questions = { 'question1': {'silas': 'what does YOYO mean?'}, 'question2': {'paul': 'How is KISS DRY conc...
from functools import wraps class NestingError(Exception): pass def nevernest(n=1): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): if wrapper.__nnest == n: raise NestingError(f'Function has been nested {n} time(s)!') wrapper.__nnest += 1 ...
""" Support for Alexa skill service end point. For more details about this component, please refer to the documentation at https://home-assistant.io/components/alexa/ """ import asyncio import logging import voluptuous as vol from homeassistant.helpers import config_validation as cv from .const import ( DOMAIN,...
"""Functions to create Action objects to send keys to webpage elements""" from screenplay import Action, Actor, log_message from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from screenplay_seleni...
'''Main tests in API''' import unittest from test.stubs.repository import StubHadoopRepository class StubRepositoryCustomPartition(StubHadoopRepository): ''' Fake repo to test instance methods ''' DEFAULT_PARTITIONING = '' class StubRepositoryCustomPartitionMultipleValues(StubHadoopRepository): ''' Fake ...
# -*- coding: utf-8 -*- __all__ = ["__version__", "ehrlich_aberth"] from .ehrlich_aberth_jax import ehrlich_aberth from .ehrlich_aberth_jax_version import version as __version__
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None from collections import deque class Solution: from collections import deque def isSymmetric(self, root): """ :type root: TreeNode ...
from unittest import TestCase from February11th import LinkedList class TestLinkedList(TestCase): def test_append_and_get(self): # Arrange first = 1 second = 2 third = 3 linked_list = LinkedList() linked_list.append(first) linked_list.append(second) ...
# -*- coding: utf-8 -*- d = {} n = int(input()) for _ in range(n): lang = input() d[lang] = input() m = int(input()) for _ in range(m): print(input()) print(d[input()]) print('')
import discord from discord.ext import commands import itertools from typing import Tuple class MyHelpCommand(commands.HelpCommand): def divideInTwoColumns(self, text: str) -> Tuple[str, str]: half = text.index("\n\n", len(text) // 2) return text[:half], text[half:] # This functi...
import unittest import yaml from programy.services.config import ServiceConfiguration class ServiceTestCase(unittest.TestCase): def _load_conf_file(self, client_context, conf_file): with open(conf_file, 'r+', encoding="utf-8") as yml_data_file: yaml_data = yaml.load(yml_data_file, Loader=yaml...
from unittest.mock import MagicMock, patch from django.test import TestCase from django_orghierarchy.utils import get_data_source_model, swapper from django_orghierarchy.models import DataSource class TestGetDataSourceModel(TestCase): def test_get_data_source_model_return_default_model(self): model = g...
import os from contextlib import contextmanager from refabric.context_managers import sudo from refabric.contrib import blueprints from .. import git __all__ = [ 'app_root', 'project_home', 'git_root', 'use_virtualenv', 'virtualenv_path', 'git_repository', 'git_repository_path', 'python_path', 'sudo_project'...
#! /usr/bin/env python script_name = 'socks-proxy-tester' __version__ = '0.1.2' upgrade_check = 'https://raw.githubusercontent.com/DD-L/socks-proxy-tester/master/version.py' filelist = ['version.py', 'socks-proxy-test.py'] path = 'https://raw.githubusercontent.com/DD-L/socks-proxy-tester/master/'
from typing import Tuple import numba as nb import numpy as np from lin_kernighan.algorithms.utils.abc_opt import AbcOpt from lin_kernighan.algorithms.utils.utils import swap class TwoOpt(AbcOpt): """ Локальный поиск: 2-opt Ищем два ребра, которые можно перецепить, чтобы уменьшить длину тура. Продолжаем...
""" A module containing tools to download and process trips data from capital bike share Washington DC """ import logging import pandas as pd import holidays as hld from biketrips.utils import years_query from biketrips.utils import search_config from biketrips.loader import Trip from biketrips.loader import RENAME_DI...
from discord.ext import commands import discord import os from keep_alive import keep_alive from utils.json_loader import read_json, write_json from datetime import datetime from disputils import BotEmbedPaginator, BotConfirmation, BotMultipleChoice from discord import Embed from discord import utils intents = discord...
from flightrising import extract_dragon_id class TestClass: def test_valid_link(self): assert ( extract_dragon_id( "http://flightrising.com/main.php?p=lair&id=430187&tab=dragon&did=52548928" ) == "52548928" ) def test_invalid_link(self): ...
import requests, urllib3, yaml, os urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) dir = os.path.dirname(__file__) CONFIG_FILE_PATH = os.path.abspath( os.path.join(dir, '..', 'configfile', 'user_config.yml') ) with open(CONFIG_FILE_PATH, 'r') as f: config = yaml.safe_load(f) CLIENT_ID = conf...
class environment(): def __init__(self): make_cordinate() make_traffic() self.stae = [] # 初始化state pass def step(sefl, action): """ 输入动作,返回R值 action:即某卫星和某卫星建立连接 """ update_cordinate(self) # 更新所有卫星坐标 update_traffic(self) # 更新所有卫...
# START LAB EXERCISE 03 print('Lab Exercise 03 \n') # This week is the begining of the Chinese New Year and # the Spring Festival. Let's learn more! # We are writing a function with two positional arguments here. # (Learn about python functions: https://www.w3schools.com/python/python_functions.asp) # SETUP (DO NOT C...
""" Django settings for bikeshop project. Generated by 'django-admin startproject' using Django 1.9.4. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os ...
# v2 pbzx stream handler # My personal writeup on the differences here: https://gist.github.com/pudquick/29fcfe09c326a9b96cf5 # # Pure python reimplementation of .cpio.xz content extraction from pbzx file payload originally here: # http://www.tonymacx86.com/general-help/135458-pbzx-stream-parser.html # # Cleaned up C v...
from .tool.func import * def topic_tool_2(conn, name, sub): curs = conn.cursor() curs.execute("select id from topic where title = ? and sub = ? limit 1", [name, sub]) topic_exist = curs.fetchall() if not topic_exist: return re_error('/topic/' + url_pas(name) + '/sub/' + url_pas(sub)) ...
totmaior = tothomem = tot20f = 0 while True: print('-'*24) print('{:^24}'.format('CADASTRE UMA PESSOA')) print('-'*24) sexo = parar = '.' idade = int(input('Idade: ')) # try: # idade = int(idade) # TODO o que é tudo isso? (try) # except ValueError: # prin...
"""Mixture model for matrix completion""" from typing import Tuple import numpy as np from scipy.special import logsumexp from common import GaussianMixture def estep(X: np.ndarray, mixture: GaussianMixture) -> Tuple[np.ndarray, float]: """E-step: Softly assigns each datapoint to a gaussian component Args: ...
""" @author: Junguang Jiang @contact: JiangJunguang1123@outlook.com """ import torch.nn.functional as F import math def robust_entropy(y, ita=1.5, num_classes=19, reduction='mean'): """ Robust entropy proposed in `FDA: Fourier Domain Adaptation for Semantic Segmentation (CVPR 2020) <https://arxiv.org/abs/2004.054...
# 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 -------------------------------------------------------------- # -- P...
#dataDict.py import numpy as np import pandas as pd data_dict = {"1 to 10": np.arange(10), "ones":np.ones(10), "zeroes": np.zeros(10)} data_DF = pd.DataFrame(data_dict) print(data_dict) print([key + str(data_dict[key][5:]) for key in data_dict]) print(data_DF)
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import numpy as np import matplotlib.pyplot as plt import sys import tensorflow as tf from deepv2d.geometry.transformation import VideoSE3Transformation sys.path.append('deepv2d') from deepv2d.data_stream.kitti import KittiRaw from deepv2d.modules.depth import Dept...
# -*- coding: utf-8 -*- """ S3 Extensions for gluon.dal.Field, reusable fields @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: 2009-2021 (c) Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ...
# -*- encoding: UTF-8 -*- from .CFBFScanner import CFBFScanner
# Generated by Django 2.2.16 on 2020-10-13 12:46 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("traffic_control", "0027_parkingarea_parkingareacategory"), ] operations = [ migrations.RemoveField( ...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 IBM Corp. # 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/lice...
# 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...
# Generated by Django 3.1.12 on 2021-06-16 23:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('snacks', '0001_initial'), ] operations = [ migrations.AlterField( model_name='snack', name='id', field=...
# -*- coding: utf-8 -*- ################################################################################ # # Copyright (c) 2010-2011, 2013, 2degrees Limited. # All Rights Reserved. # # This file is part of deployrecipes: # <http://packages.python.org/deployrecipes/>. # # deployrecipes is subject to the provisions of th...
#!/usr/bin/env python # coding: utf-8 import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import src.similarities.similarities as sim # Change path to similarity package from os import listdir from statistics import mean, stdev impor...
# Copyright (c) 2014 Museum Victoria # This software is released under the MIT license (see license.txt for details) '''iBoot Original Node''' ### Libraries required by this Node import socket import struct ### Parameters used by this Node PORT = 80 PASSWORD = "3000" param_ipAddress = Parameter('{"title":"IP addre...
cse_user = "sumedsearch@gmail.com" cse_pass = "plyCEC01"
import pymysql class Connection: def __init__(self,host,port,user,pwd,db_name): # create connection self.connection = pymysql.connect(host=host, port=int(port), user=user, pas...
from time import sleep from datetime import datetime # Define a function that identifies the data the script was run; derived from datatime. Call on this function from other scripts. def downloaddate(): ddate = datetime.today().strftime('%Y%m%d') print(ddate) return ddate #downloaddate()
from argparse import ArgumentParser import cProfile from functools import wraps from io import StringIO, BytesIO from numpy import random import pstats from requests_toolbelt import MultipartEncoder from streaming_form_data.parser import StreamingFormDataParser from streaming_form_data.targets import ValueTarget def...
# -*- coding: utf-8 -*- # This is an updated copy of lektor-atom plugin # which replaces the deprecated Werkzeug's atom with Pelican's feedgenerator. from setuptools import setup setup( author=u'A. Jesse Jiryu Davis', author_email='jesse@emptysquare.net', install_requires=['MarkupSafe', 'feedgenerator'], ...
"""Settings for audio reactive LED strip""" from __future__ import print_function from __future__ import division import os LED_PIN = 18 """GPIO pin connected to the LED strip pixels (must support PWM)""" LED_FREQ_HZ = 800000 """LED signal frequency in Hz (usually 800kHz)""" LED_DMA = 5 """DMA channel used for gener...
# from http.server import BaseHTTPRequestHandler, HTTPServer # from urllib.parse import urlparse, parse_qs # import os # import json # from dotenv import load_dotenv # load_dotenv() # from models.location import Location # from models.weather import Forecast # class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): ...
def converte_para_decimal(binario: int): # converte para string pra acessar cada dígito separado binario_str = str(binario) # inverte a string, pra começar da direita pra esquerda binario_str = binario_str[::-1] potencia = 0 # cada dígito do valor binario representa o valor de uma potencia de 2, ...
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .receipt import ReceiptProtocolEntity from yowsup.layers.protocol_acks.protocolentities import OutgoingAckProtocolEntity class IncomingReceiptProtocolEntity(ReceiptProtocolEntity): ''' delivered: <receipt to="xxxxxxxxxxx@s.whatsapp.net" id=...
''' Function: using output files under /DFS-L/DATA/pritchard/hongcheq/OLD/scratch /hongcheq/HCforcing_sim2_WADA_CTR_TOPO_ENSEMBLE_post-processing_h2_tapes_New_Modifications LHFLX Date: 2019/06/11 ''' import numpy as np import xarray as xr import matplotlib.pyplot as plt data_path = '/DFS-L/DATA/pritchard/hongcheq/OL...
from enum import Enum from nipype.interfaces.base import BaseInterfaceInputSpec, BaseInterface, File, TraitedSpec, traits from nipype import Node, Workflow, Function, MapNode import nipype.interfaces.io as nio import nipype.interfaces.fsl as fsl from nipype.algorithms.confounds import TSNR import pandas as pd import js...
import numpy as np def get_rstar_server(max_logit, batch_size, num_classes, exp): r_star = max_logit + np.random.uniform( low=-2 ** exp, high=2 ** exp, size=(batch_size, num_classes)) return r_star
import copy class Address: def __init__(self, street, suit, country): self.street = street self.suit = suit self.country = country def __str__(self): return f'{self.street}, # {self.suit}, {self.country}' class Employee: def __init__(self, name, address): self.na...
from argparse import Namespace as _Namespace from typing import Optional, Any, Sequence class Namespace(_Namespace): """Simple namespace object returned when parsing a Schema""" def get(self, key: str, default: Optional[Any] = None) -> Any: """Get an attribute from the namespace, provide an optional ...
from influxdb import InfluxDBClient from config.common import INFLUXDB_ADDRESS, INFLUXDB_DBNAME, INFLUXDB_PASSWORD, INFLUXDB_PORT, INFLUXDB_USERNAME from db.model import db_session, select, Message, db def migrate(): client = InfluxDBClient(INFLUXDB_ADDRESS, INFLUXDB_PORT, INFLUXDB_USERNAME, INFLUXDB_PASSWORD, I...
from django.utils.translation import ugettext_lazy as _ from django.shortcuts import render_to_response from django.contrib.admin.views.decorators import staff_member_required from django import template from django.core.urlresolvers import reverse from django.contrib import admin from django.utils.safestring import m...
from player import Player from hand import Hand class Human(Player): def __init__(self, name: str): super().__init__(name) self.hand = Hand() def discard(self): if(self.hand == None or len(self.hand) <= 0): raise RuntimeError('No cards to discard') print('{0}\'s Han...
""" Will drop and re-create all measurements and continuous queries and backfill the measurements from the main login measurement """ import logging from influxdb import InfluxDBClient VALID_PERIODS = ["day", "week", "month", "quarter", "year"] VALID_GROUP_BY = ["day", "week"] def append_measurement(l, period, post...
from __future__ import print_function import boto3 from boto3.dynamodb.conditions import Key, Attr from decimal import * # Helper for quering DynamoDB table def dynamo_request(table_obj, request_dict): resp = table_obj.get_item(Key=request_dict) if resp.has_key('Item') and resp['Item']: return resp['...
from django.urls import path from api.views import field_views as views urlpatterns = [ path('', views.getFields, name="fields"), path('create/', views.createField, name="field-create"), path('<str:field_id>/', views.getField, name="field"), path('update/<str:field_id>/', views.updateField, name="...
import datetime import os from dataclasses import dataclass from datetime import timezone from io import BytesIO from pathlib import Path from typing import List, Optional from urllib.parse import urlparse import imagehash import requests from PIL import Image from reddit_grabber.exceptions import RedditGrabberExcep...
# -*- coding: utf-8 -*- """Task_2 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1dvHSe2pYEoD1XZioivQ_sPGvZwMEgsfo **Task 2** **From the given ‘Iris’ dataset, predict the optimum number of clusters and represent it visually** **Dataset : https:...
# Copyright 2016 Canonical 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 in writing, softwar...
from .aerodynamics import * class vlm2(AeroProblem): # Vortex-Lattice Method legacy_aerodynamics code written from the ground up with lessons learned from writing VLM1. # Should eventually eclipse VLM1 in performance and render it obsolete. # # Notable improvements over VLM1: # # Specifically wri...
import time import json import argparse from pathlib import Path from typing import Tuple, List, Optional import numpy as np from deepdrivemd.utils import Timer from deepdrivemd.data.api import DeepDriveMD_API from deepdrivemd.data.utils import get_virtual_h5_file from deepdrivemd.selection.latest.select_model import g...
from torch import nn def get_kl_layers(model): return [ module for module in model.modules() if type(module) != nn.Sequential and hasattr(module, "_kl_divergence_") ] def accumulate_kl_div(model): return sum(map(lambda module: module._kl_divergence_, get_kl_layers(model))) def ...
""" TCKDB backend app models electronic structure software (ess) module """ from sqlalchemy import Column, Integer, String from tckdb.backend.app.db.base_class import Base from tckdb.backend.app.models.common import MsgpackExt class ESS(Base): """ A class for representing a TCKDB ESS item (ESS = electr...
from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.core.urlresolvers import reverse from .forms import ContactForm class ContactView(FormView): template_name = 'contact/contact.html' form_class = ContactForm def get_success_url(self): ret...
# @copyright@ # Copyright (c) 2006 - 2018 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ # # @rocks@ # Copyright (c) 2000 - 2010 The Regents of the University of California # All rights reserved. Rocks(r) v5.4 www.rocksclusters.org # ...
import os import click from ...utils.env_keys import REPORT_ERROR_KEY from ...utils.http_client import get_base_url from ...utils.ingester_image import ingester_image from ...utils.java import get_java_command jar_file_path = os.path.normpath(os.path.join( os.path.dirname(__file__), "../../jar/exe_deploy.jar")) ...
#!/usr/bin/env python # Created by MikBac on 2020 import os import sys import kenlm LM = os.path.join(os.path.dirname(__file__), 'train', 'dataIn.arpa') model = kenlm.LanguageModel(LM) for line in sys.stdin: sentence = line.strip() sentence = sentence.lower() def score(s): return sum(prob for prob, _, _ i...
# Lint as: python3 # Copyright 2018, The TensorFlow Federated 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 ...
from typing import List from copy import deepcopy, copy import paddle import paddlenlp.metrics from paddleseq import SEQNetwork from paddleseq import SEQDevice from paddleseq import SEQTask from .unit.re_loss import SmoothCE from paddleseq.module.task_manager import * class AutoModel(paddle.Model): def __init_...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools from typing import List, Any, Tuple, Dict, Optional, Callable import numpy as np from ..common.typetools...
from etna.analysis.feature_selection.mrmr_selection import AGGREGATION_FN from etna.analysis.feature_selection.mrmr_selection import AggregationMode from etna.analysis.feature_selection.mrmr_selection import mrmr
# mobihf v0.1, Quantum Chemistry on mobile!, (c) V.Ganesh, GPL # Based on quantumj (http://quantumj.dev.java.net) # and PyQuante (http://pyquante.sf.net) from math import sin,cos,acos,pi,sqrt,floor,pow,exp,log from string import * radii = {"H":0.23, "C":0.77, "N":0.75, "O":0.73} atmnum = {"H":1, "C":6, "N":7, "O...
import numpy as np def diversity(X): N, _ = X.shape if N == 1: return 1. _, counts = np.unique(X > 0, axis=0, return_counts=True) value = 1 - (counts * (counts - 1)).sum()/(N * (N - 1)) assert 0 <= value <= 1 return value def density(X): N, M = X.shape value = np.sum(X > 0) / ...
from django.urls import path from . import views app_name = 'cms' urlpatterns = [ path('blog/', views.blog_index, name='blog_index'), path('<slug>/', views.page, name='page'), ]
import numpy as np import pandas as pd from datetime import datetime from yahoofinancials import YahooFinancials import pickle import joblib end_date= datetime.strftime(datetime.today(),'%Y-%m-%d') start_date = "2020-01-02" date_range = pd.bdate_range(start=start_date,end=end_date) values = pd.DataFrame({ 'Date': da...
# -*- coding: utf-8 -*- # # Get stocks financial information import csv import os import scrapy class FinancialsSpider(scrapy.Spider): """Stock financials scraper""" name = "financials" _URL_BASE = "https://klse.i3investor.com/servlets/stk/{}.jsp" _FINANCIALS_FILE = "KLSE_financials.csv" _TICK...
from .absclient import * from .cliutils import * from .dirhelper import * from .fileconfman import * from .parsemetrics import * __all__ = [] __all__.extend(absclient.__all__) __all__.extend(cliutils.__all__) __all__.extend(dirhelper.__all__) __all__.extend(fileconfman.__all__) __all__.extend(parsemetrics.__all__)