content stringlengths 5 1.05M |
|---|
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
import tensorflow as tf
import xlnet
import numpy as np
import model_utils
import random
import json
import collections
import re
import sentencepiece as spm
from sklearn.utils import shuffle
from prepro_utils import preprocess_text, encode_ids
from malaya.text.funct... |
import numpy as np
import scipy.sparse as sp
def bwdmean(center_array, w):
## Input Parameters
# center_array: 3D array of values defined at cell centers
# w: 'x' or 'y' or 'z' direction in which average is taken
## Out Parameter
# avg_array: 2D array of averaged values
shift = 1
if(w == '... |
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 OpenStack Foundation
# Copyright 2012 Grid Dynamics
# Copyright 2013 OpenStack Foundation
# 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... |
# Legacy:
def save_to_disfeval_file(p, g, w, f, filename, incremental=False):
'''
INPUT:
p :: predictions
g :: groundtruth
w :: corresponding words
f :: original input gold standard file
OUTPUT:
filename :: name of the file where the predictions
are written. In right format for disf... |
import sqlite3
import logging
import datetime
class Model(object):
CREATE_USER_TABLE = '''CREATE TABLE IF NOT EXISTS user_table(
created_ts TIMESTAMP NOT NULL,
id INTEGER PRIMARY KEY,
email VARCHAR(200) NOT NULL UNIQUE,
phone_number VARCHAR(20) NOT NULL UNIQUE,
full_name... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import sys
import torch
from image_synthesis.utils.io import write_args, save_config_to_yaml
from image_synthesis.distributed.distributed import is_primary
import torch.utils.tensorboard a... |
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
import app.views.post_views
import app.views.user_views
from app.views import views, post_views, user_views
app_name = 'app'
urlpatterns = [
path('api_test', views.api_test, name='api_test'),
# path('api/... |
import numpy as np
from PIL import Image
import caffe
# load image, switch to BGR, subtract mean, and make dims C x H x W for Caffe
# im = Image.open('pascal/VOC2010/JPEGImages/2007_000129.jpg')
im = Image.open('/home/inoue/external_data/VOCdevkit/VOCdevkit/VOC2007/JPEGImages/000001.jpg')
in_ = np.array(im,dtype=np.fl... |
import socket
import time
import random
if __name__ == "__main__":
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(("postgres", 5432))
print("Postgres had started")
break
except socket.error:
... |
#!/usr/bin/python3
import RPi.GPIO as GPIO
from time import sleep
import time, math
dist_meas = 0.00
km_per_hour = 0
rpm = 0
elapse = 0
sensor = 17
pulse = 0
start_timer = time.perf_counter()
speed = 0
def init_GPIO(): # initialize GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(sensor... |
from ..abstractvector import DocumentVector
class EmptyVector(DocumentVector):
pass
|
import tensorflow as tf
import numpy as np
import time
import os
from utils import decode_captions, write_bleu
from bleu import evaluate
from math import ceil
class Solver(object):
def __init__(self, model, data, **kwargs):
"""
Required Arguments:
- model: caption generating model
... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
__config__ = pulumi.Config('ecl')
au... |
import datetime
DATE_FORMAT = '%Y-%m-%d'
DATE_FOLDER_FORMAT = '%Y%m%d'
def date_format(date, f='%Y-%m-%d'):
return date.strftime(f)
def date_folder_format(date):
return date.strftime(DATE_FOLDER_FORMAT) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from irc3.plugins.command import command
from irc3.compat import asyncio
from irc3.compat import Queue
from datetime import datetime
import irc3
import requests
import objectpath
"""
Helsinki area public transport route planning IRC bot.
"""
class HSL:
"""
Helsi... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: unversioned
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "Licens... |
#!/usr/bin/python
import sys
import json
if len(sys.argv) != 2:
print >> sys.stderr, " Usage: python ExtractBuildArgs.py <ArgName>"
exit (-1)
try:
data = json.load(open('BuildSpec.json'))
if sys.argv[1] == "cmakeFlags" and data["cmakeFlags"] != "":
print(data["cmakeFlags"])
elif sys.arg... |
from typing import Tuple
import numpy as np
from numpy.random import Generator
from delayed_bandit.policies.policy import Policy
class UniformRandom(Policy):
def __init__(self, num_arms: int, rng: Generator):
"""
Create a policy choosing an arm uniformly at random.
"""
self._num_... |
# Copyright (c) 2021 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 appli... |
# -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
"""
from ..feature_importance_test import TestPermutationImportance as _TestPermutationImportance
from . import if_cuml_ready, is_cuml_installed
if is_cuml_installed:
import cudf
@if_cuml_ready
class TestCumlPermutationImportance(_TestPermutationImportance):
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from __future__ import division, print_function
'''
Image features detection.
All angles shalt be described in degrees with zero pointing east in the
plane of the image with all positive rotations going counter-clockwise.
Therefore a rota... |
from rpython.rtyper.module.support import OOSupport
from rpython.rtyper.module.ll_os_path import BaseOsPath
class Implementation(BaseOsPath, OOSupport):
pass
|
# coding=utf-8
from flask import Flask
# 导入flask_sqlalchemy扩展包
from flask_sqlalchemy import SQLAlchemy
from config import Config
app = Flask(__name__)
# 指定数据库的配置信息
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@localhost/python24'
# 使用配置文件
app.config.from_object(Config)
# 创建sqlalchemy对象,两种实例化形式
db = SQL... |
# -*- coding: utf-8 -*-
from .datasets.rgb_sod import rgb_sod_data
from .methods import (
rgb_sod_methods,
)
total_info = dict(
rgb_sod=dict(
dataset=rgb_sod_data,
method=dict(
drawing=rgb_sod_methods.methods_info_for_drawing,
selecting=rgb_sod_methods.methods_info_for_s... |
from libmyrepo.spam.models import Usuario
def test_salvar_usuario(sessao):
usuario = Usuario(nome='Enos', email='enos@test.com')
sessao.salvar(usuario)
assert isinstance(usuario.id, int)
def test_listar_usuario(sessao):
usuarios = [Usuario(nome='Enos', email='enos@test.com'),
Usuario... |
# coding: utf-8
import typing
import functools
import logging
import uuid
import json
X_APPLICATION_TRACE_ID: str = 'x-application-trace-id'
class LamBlackBox():
class Logger():
def __init__(self, trace_id: str, debug: bool = False) ->None:
self.trace_id = trace_id
self.logger =... |
# django imports
from django import forms
from django.db import models
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
# portlets imports
from portlets.models import Portlet
# lfs imports
from lfs.catalog.models imp... |
import pentacene as pen
import numpy as np
import math
import os
def main(aggWeight, aggDistance, aggCount, aggChance):
#after some testing, it seems like the desired effect does
#not happen until aggDistance > 0.20
#so that is why this is our lower bound
for b in np.linspace(0.20, aggDistance, 5):
... |
"""
flare profiles for paper Bisikalo et al. 2018
https://doi.org/10.3847/1538-4357/aaed21
import warnings
warnings.filterwarnings('ignore')
"""
import matplotlib.pyplot as plt
from sunpy.timeseries import TimeSeries
from sunpy.time import TimeRange, parse_time
from sunpy.net import hek, Fido, attrs as a
import ... |
# Given an array of integers arr, return true if and only if it is a valid mountain array.
#
# Recall that arr is a mountain array if and only if:
# arr.length >= 3
# There exists some i with 0 < i < arr.length - 1 such that:
# arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
# arr[i] > arr[i + 1] > ... > arr[arr.le... |
"""
Django settings for horseradish project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...... |
from func import set_discovery_issuer
from func import set_webfinger_resource
from jwkest import BadSignature
from oic.exception import IssuerMismatch
from oic.exception import PyoidcError
from otest.func import set_op_args
from otest.func import set_request_args
from oidctest.op.oper import AccessToken
from oidctest... |
"""Flag for whether a date falls on a public holiday in Singapore."""
from h2oaicore.transformer_utils import CustomTransformer
import datatable as dt
import numpy as np
import pandas as pd
# https://github.com/rjchow/singapore_public_holidays
def make_holiday_frame():
return dt.fread(
"""
Date,Na... |
#!/usr/bin/python
# -*- coding: utf-8 -*-f
#Import modules for CGI handling
import cgi, cgitb
import Cookie, os, time
try:
import pigpio
except:
pass
#============================ config ALERT ===================== #
import ConfigParser
Config = ConfigParser.ConfigParser()
setting = Config.read('setting/confi... |
Sigma_1 = np.diag(1 / img_flat)
np.linalg.inv(X.T @ Sigma_1 @ X) @ X.T @ Sigma_1 @ img_flat
|
import logging
import numpy as np
import os
import re
from pystella.rf import band
from pystella.rf.lc import SetLightCurve, LightCurve
__author__ = 'bakl'
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class StellaTt:
def __init__(self, name, path='./'):
"""Creates a StellaTt mode... |
#pytest_getattr_mwe.py
def __getattr__(key):
return None
# raise AttributeError(key)
def test_1():
return 1
|
from time import time
def main():
for i in range(1, 1_000_000): 1+1
if __name__ == '__main__':
start = time()
main()
end = time()
print("main method executed in %fs" % (end-start)) |
__version__ = "v1.0"
__copyright__ = "Copyright 2021"
__license__ = "MIT"
__lab__ = "Adam Cribbs lab"
import time
import pysam
import pandas as pd
from mclumi.util.Console import console
class read(object):
def __init__(self, bam_fpn, verbose=False):
"""
# pos_last = 0
# chr_last = 0
... |
#!/usr/bin/python
import time
from time import sleep
import datetime
import os
import sys
import subprocess
from subprocess import Popen
import pynma
p = pynma.PyNMA( "12842c4d5f6061eb9543674248c3518edda9dd83343ebe19" )
application="alertpi boot"
event="DoorBell OnBoot"
description="doorbell just turned on"
priority=2
... |
# -*- coding: utf-8 -*-
"""Module grouping utility functions for DOV XML services."""
import os
from owslib.etree import etree
from pydov.util.errors import XmlParseError
from pydov.util.hooks import HookRunner
from pydov.util.net import SessionFactory
def build_dov_url(path):
"""Build the DOV url consisting of... |
from . import auth
from flask_login import login_user,logout_user,login_required
from flask import request,redirect,url_for,flash,render_template
from .forms import RegistrationForm,LoginForm
from app.models import User
from app import db
@auth.route("/login",methods=['GET','POST'])
def login():
if request.method ... |
__version__ = '1.2.0'
__author__ = 'Aashutosh Rathi <aashutoshrathi@gmail.com>'
__all__ = []
|
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Brandon Nielsen
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
import datetime
from collections import namedtuple
from functools import partial
from aniso8601.builders impo... |
import logging
from kubedriver.kegd.model import ReadyResult
from kubedriver.keg import CompositionLoader
from kubedriver.sandbox import Sandbox, SandboxConfiguration, SandboxError, ExecuteError
from kubedriver.kegd.scripting import KegCollection, ReadyResultHolder
logger = logging.getLogger(__name__)
#Different to r... |
from syntax.transformers.tissue_mask.otsu import OtsuTissueMask
|
''' This example shows how the read_timeout() method works. This
example models an attendant that goes to drink water in each 3
seconds, and returns to attend customers. The customers request,
at different times, the call center services.
'''
from pade.acl.messages import ACLMessage
from pade.behaviours.types import C... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Mar-29-21 18:37
# @Author : Kan HUANG (kan.huang@connect.ust.hk)
# @RefLink : https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.html
from __future__ import unicode_literals, print_function, division
from io import open
import glob
impo... |
import numpy as np
def rank(data, axis=1):
"""Transform matrix to matrix of ranks along the axis
Parameters
----------
data : array
Array to sort.
axis : int, default : 1
Rank the values along the axis.
Returns
-------
array, shape (n_rows, n_cols)
Ranked data array.
... |
'''
Copyright 2020 The Rook 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 law or agreed to... |
from norminette.rules import Rule
types = ["INT", "FLOAT", "CHAR", "DOUBLE", "LONG", "SHORT"]
class CheckFuncDeclaration(Rule):
def __init__(self):
super().__init__()
self.depends_on = ["IsFuncDeclaration", "IsFuncPrototype"]
def run(self, context):
"""
Maximum 4 arguments in... |
import re
# Taken from inflection library
def underscore(word):
word = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', word)
word = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', word)
word = word.replace('-', '_')
return word.lower()
|
import astropy.units as u
import numpy as np
import pytest
from ndcube import utils
missing_axes_none = [False] * 3
missing_axes_0_2 = [True, False, True]
missing_axes_1 = [False, True, False]
axes_length = 3
extra_coords_dict = {"time": {"axis": 0, "value": u.Quantity(range(axes_length), unit=u.pix)},
... |
def to_dictionary(text_path='', code='utf-8'):
with open(text_path, 'rb') as file:
info_list = [part.decode(code, 'ignore').strip() for part in file.readlines()]
string = ''.join(info_list)
setting = set(string)
dictionary = {key : value for key, value in enumerate(setting)}
return dictionary
if __name__ ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
import datetime as dt
from pyuploadcare.d... |
# -*- coding: utf-8 -*-
import pytest
from marshmallow import Schema, fields, class_registry
from marshmallow.exceptions import RegistryError
def test_serializer_has_class_registry():
class MySchema(Schema):
pass
class MySubSchema(Schema):
pass
assert 'MySchema' in class_registry._regi... |
"""A library allowing you to create an auto method-binding dict.
Mainly used for event handlers, a binding dict consists of a mapping between
any events or keys, to their appropriate handler functions within a class.
Upon key lookup, the dict will bind the appropriate function to the instance
of the class.
For an exa... |
import json
import os
from helper import FileHelper, AwsHelper, S3Helper
from metadata import DocumentLineageClient, PipelineOperationsClient
PIPELINE_STAGE = "EXTENSION_DETECTOR"
syncBucketName = os.environ.get('TARGET_SYNC_BUCKET', None)
asyncBucketName = os.environ.get('TARGET_ASYNC_BUCKET', None)
metadataTopic =... |
import instaloader
import pandas as pd
import sys
import os
import re
class InstaloaderException(Exception):
'''Copied from source code to hadnle error'''
pass
class QueryReturnedNotFoundException(InstaloaderException):
'''Copied from source code to hadnle error'''
pass
def scraper(username = None, maxPostLimit ... |
#!/usr/bin/env python3
"""
Creates an file with a list of sha1 hashes in the same directory as the raw data
under /data/spectro. This script run like
boss_sha1sum.py MJD [MJD2] [MJD3]...
Created by Stephen Bailey (LBNL) Fall 2011
2020-06-01 dgatlin Completely rewrote it for Python 3 and modern
librari... |
import numpy as np
import pymc as pm
from IPython.core.pylabtools import figsize
from ch1 import count_data
import matplotlib.pyplot as plt
plt.style.use('ggplot')
colors = ["#348ABD", "#A60628", "#7A68A6", "#467821"]
n_count_data = len(count_data)
alpha = 1. / count_data.mean()
lambda_1 = pm.Exponential("lambda_1"... |
# Part of Speach (POS) Based Entity Extraction
# Aimed at Extracting Relationships
# Use regex matching to identify relational phrases
# VP?
# V(W*P)?
#
# V1: 'RB'
# V2: 'MD', 'VB', 'VBD', 'VBP', 'VBZ', 'VBG', 'VBN'
# V3: 'RP', 'RB'
# (V1)? + (V2) + (V3)?
#
# P1: 'RB'
# P2: 'IN', 'TO', 'RP'
# P3: 'RB'
# (P1)? + (P2) ... |
"""
Abstract Summarization
===============================================================================
>>> from techminer2 import *
>>> directory = "data/"
>>> abstract_summarization(
... texts=["fintech", "blockchain"],
... n_phrases=5,
... directory=directory,
... )
The research on data science a... |
#! /usr/bin/env python
"""Read infofiles.
"""
import glob
import os, os.path
import sys
import threading
import time
import skytools
import cc.util
from cc import json
from cc.daemon import CCDaemon
from cc.message import is_msg_req_valid
from cc.reqs import InfofileMessage
class InfoStamp:
def __init__(self,... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Pivot m... |
#
# PySNMP MIB module A3COM-HUAWEI-LswMSTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-LswMSTP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:05:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
# -*- coding=UTF-8 -*-
# pyright: strict
from typing import Text
from .. import action, config, templates, template
def daily_race(race_name: Text):
while True:
tmpl, pos = action.wait_image(
templates.DAILY_RACE_TICKET_NOT_ENOUGH,
templates.CONNECTING,
templates.RETR... |
c=input("enter city name:").strip()
if c=='Gujarat':
print('namaste')
elif c=='Hydrabad':
print('vannakam')
else:
print('city not availabel') |
"""Added teams table and team-user relation
Revision ID: 5197815c452d
Revises: 6336478c122c
Create Date: 2020-09-17 13:22:58.294645
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5197815c452d'
down_revision = '6336478c122c'
branch_labels = None
depends_on = N... |
import sys
from screen import *
from place import Place
from PyQt5 import QtWidgets, QtCore
import matplotlib
import matplotlib.dates as mdates
import logging
from manager import Manager
import constants
_translate = QtCore.QCoreApplication.translate
matplotlib.use('QT5Agg') # Use QT5Agg as backend
class DialogApp... |
from django.contrib import admin
from .models import Person, Property, ManageGroup, InstrGroup
# Register your models here.
admin.site.register(Person)
admin.site.register(Property)
admin.site.register(ManageGroup)
admin.site.register(InstrGroup) |
# -*- coding: utf-8 -*-
import pandas as pd
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
data = {'domain': pd.Series(['google.com'], index=['google']),
'user': pd.Series(['f2a'], index=['google']),
... |
# -*- coding: utf-8 -*-
# Copyright (C) Cardiff University (2018-2021)
# SPDX-License-Identifier: MIT
"""Tests for :mod:`gwosc.utils`
"""
import pytest
from .. import utils
__author__ = 'Duncan Macleod <duncan.macleod@ligo.org>'
def test_url_segment():
seg = utils.url_segment('X-TEST-123-456.ext')
assert ... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
n=0
suma = 0
while n!=-1:
n = input('Inserta un numero')
n = int(n)
if n!=-1:
suma = suma +n
print('La suma vale', suma)
|
# Licensed to Tomaz Muraus under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# Tomaz muraus licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in... |
from django.contrib import messages
from django.shortcuts import render, redirect
from django.db import transaction
from airmozilla.base.utils import paginate
from airmozilla.main.models import Channel
from airmozilla.manage import forms
from airmozilla.staticpages.models import StaticPage
from .decorators import (
... |
# -*- coding: utf-8 -*-
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
# Author: Sara Borroni <sara.borroni@pangeaformazione.it>
# Contributor: Alessio Cimarelli <jenkin@dataninja.it>
import requests, pickle, time, telebot
from dateutil.parser import parse
from thre... |
from tests.utils import W3CTestCase
class TestFlexbox_MarginLeftEx(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_margin-left-ex'))
|
import pytest
import Bhaskara
class TestBhaskara:
@pytest.fixture
def b(self):
return Bhaskara.Bhaskara()
def testa_uma_raiz(self, b):
assert b.calcula_raiz(1, 0, 0) == (1, 0)
def testa_duas_raizes(self, b):
assert b.calcula_raiz(1, -5, 6) == (2, 3, 2)
def testa_zero... |
# coding: utf-8
###################################################################
# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #
# #
# Author: Marius Retegan #
# ... |
#!/usr/bin/env python
#Created by Spencer Hance and Trevor Gale on January 18th 2015
#Northeastern University Computer Architecture Research Group
#Licensed under MIT License
import sys
import matplotlib.pyplot as plt
import numpy as np
from pylab import cm
import re
import random
from scipy.misc import comb
import a... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
clean_html,
int_or_none,
str_or_none,
try_get
)
from ..compat import (
compat_str
)
import re
class HanimetvBaseIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://
... |
from bokeh.core.json_encoder import pd
from . import get_logger, freeze, subdict
from sklearn import preprocessing
_LOG = get_logger('Recsys')
def process_user_info():
HPs = pd.read_excel('/Users/bekyilma/Documents/Projects/vr/Multi-Stakeholder_Recommendation/Data/Alberto.xlsx', index_col=0)
HPs = HPs[['How l... |
# Author: Michael Lissner
# Date created: 2013-06-06
import re
import requests
from datetime import date
from datetime import datetime
from juriscraper.opinions.united_states.state import nd
from juriscraper.DeferringList import DeferringList
class Site(nd.Site):
def __init__(self, *args, **kwargs):
su... |
"""
...
"""
# ...
ANSWER = 42
def test_simple():
assert True
|
from sympy.printing.pycode import PythonCodePrinter
from sympy.printing.printer import Printer
from sympy import Add, Mul
class SymEnginePrinter(Printer):
def _print_Pow(self, expr):
return "pow({0}, {1})".format(self._print(expr.base), self._print(expr.exp))
def _print_Add(self, expr):
if l... |
from django.shortcuts import render
import requests
from requests.api import get
import covid
from covid import Covid
import datetime
from datetime import date
import json
import os
from dotenv import load_dotenv
load_dotenv()
list_cont = []
chart_cases = [['date','active','recovered','total']]
covid = Covid()
#co... |
class Grafo:
def __init__(self, V):
self.V = V
self.lista = [[] for i in range(V)]
def add_aresta(self, orig, dest):
self.lista[orig].append(dest)
def dfs(self, v):
pilha, pilha_rec = [], []
visitados = [False for i in range(self.V)]
pilha_rec = [False for... |
def lif_neuron_inh(n_steps=1000, alpha=0.5, beta=0.1, exc_rate=10, inh_rate=10):
""" Simulate a simplified leaky integrate-and-fire neuron with both excitatory
and inhibitory inputs.
Args:
n_steps (int): The number of time steps to simulate the neuron's activity.
alpha (float): The input scaling factor... |
"""Example Process class."""
class Process(object):
"""Example process."""
def __init__(self, num=0):
"""Initialize a new Process.
:num: Number
"""
self.num = num
def get_double(self):
"""Return the number."""
return {"double": (2 * self.num)}
|
#!/usr/bin/env python
# uuid: a2a8bd34-9d35-4648-9500-d6c62a2557c9
# MIT License+uuid License
# For details of these license see
# https://github.com/a-bentofreire/uuid-licenses/blob/master/MIT-uuid-license.md
# Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
#
# Permission is hereby granted, free o... |
del_items(0x800A0CD8)
SetType(0x800A0CD8, "void VID_OpenModule__Fv()")
del_items(0x800A0D98)
SetType(0x800A0D98, "void InitScreens__Fv()")
del_items(0x800A0E88)
SetType(0x800A0E88, "void MEM_SetupMem__Fv()")
del_items(0x800A0EB4)
SetType(0x800A0EB4, "void SetupWorkRam__Fv()")
del_items(0x800A0F44)
SetType(0x800A0F44, "... |
import json
from instaloader import Instaloader, Profile
with open('auth.json') as f:
auth = json.load(f)
login_name = auth['login']
target_profile = auth['target_profile']
loader = Instaloader()
# login
try:
loader.load_session_from_file(login_name)
except FileNotFoundError:
loader.context.log("Sessi... |
#!/usr/bin/env python
"""my-new-package setup script."""
from setuptools import find_packages, setup
# https://github.com/PyCQA/pylint/issues/3826
with open("README.rst", encoding="utf8") as readme_file:
readme = readme_file.read()
with open("HISTORY.rst", encoding="utf8") as history_file:
history = history... |
from absl import app
from absl import flags
from typing import Text
import os
import tensorflow as tf
import tensorflow_model_analysis as tfma
from tfx.components import CsvExampleGen, StatisticsGen, SchemaGen, Trainer, Transform, Evaluator, Pusher, ResolverNode, BulkInferrer
from tfx.components.base import executor_s... |
#!/usr/bin/env python
#
# maths.py
#
# Copyright © 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# 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... |
'''
Exercise 2 :
Write a function concat_dico(dico1, dico2) that takes two dictionaries as parameters
and returns a single dictionary containing the pairs from both dictionaries. An important
requirement is that both dictionaries are NOT modified by the function.
For example:
>>> concat_dico ({“one”:1, “two”:2, “three”... |
# import unittest
# from Tiptabs.TiptabsDB import *
# class testTiptabsDB(unittest.TestCase):
# #TODO: Add setup for DB for further testing of storage / input.
# def testCheckInputs(self):
# input = ['users', 'Gary', 'Gary', 'JPYtoUSD']
# expected = [True, "Valid input entered."]
# ... |
#!/usr/bin/env python3
"""Example evaluation script to evaluate a policy.
This is an example evaluation script for evaluating a "RandomPolicy". Use this
as a base for your own script to evaluate your policy. All you need to do is
to replace the `RandomPolicy` and potentially the Gym environment with your own
ones (s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.