content stringlengths 5 1.05M |
|---|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import LogLocator
from tqdm import tqdm
import importlib
import math
import sys
if not '../aux/' in sys.path: sys.path.append('../aux/')... |
import random
STEVILO_DOVOLJENIH_NAPAK = 10
PRAVILNA_CRKA = '+'
PONOVLJENA_CRKA = '0'
NAPACNA_CRKA = '-'
ZMAGA = 'W'
PORAZ = 'X'
ZACETEK = 'Z'
class Igra:
def __init__(self, geslo, crke=[]):
self.geslo = geslo
self.crke = crke
def napacne_crke(self):
sez = []
for crka in self.c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenGL 3.2 Core Profile Example
# Authors:
# - Richard Petri <dasricht at gmail.com>
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to ... |
import json
import os
from pyecore.resources import ResourceSet, URI
from pygeppetto.model.model_factory import GeppettoModelFactory, SharedLibraryManager
from pygeppetto.model.model_serializer import GeppettoModelSerializer as GeppettoSerializer
def test_serializer():
# Initialize the factory and the resource ... |
import unittest
from easyneuron._testutils import log_errors
from easyneuron.math import euclidean_distance
class TestDistance(unittest.TestCase):
@log_errors
def test_euclidean(self):
self.assertEqual(euclidean_distance([1, 2, 3], [1, 2, 3]), 0)
self.assertEqual(euclidean_distance([1], [2]), 1)
sel... |
r"""LSTM layer."""
from flax import linen as nn
from flax.linen.recurrent import Array
from flax_extra import combinator as cb
LSTMState = tuple[Array, Array]
# TODO: add type annotation to `nn.LSTMCell`.
class LSTMCell(nn.LSTMCell):
r"""LSTM cell."""
def __call__( # type: ignore[override]
self,
... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2015,2016,2017,2018 Daniel Fernandez (daniel@dfmd.mx), Saul Pilatowsky (saul@dfmd.mx)
#
# 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 Licens... |
import scrapy
from scrapy.selector import Selector
from amazon.loaders import ReviewItemLoader
from amazon.items import Review
class ReviewsSpider(scrapy.Spider):
name = 'reviews'
def start_requests(self):
return [scrapy.FormRequest('http://www.amazon.com/hz/reviews-render/ajax/reviews/get/ref=cm_cr_othr_d_pagin... |
import random
a = ['Gas', 'Food', 'Gym', 'Health']
word = random.choice(a)
your_guess = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in your_guess:
print(char, end="")
else:
print("_", end=""),
failed += 1
if failed == 0:
p... |
class SlackAppNotInstalledProperlyException(Exception):
"""
Thrown if no entry for a Slack app exists in a Django DB.
"""
pass
class SlackAccountNotLinkedException(Exception):
"""
Thrown if user is not linked with a User model yet.
"""
def __init__(self, slack_user_mapping):
s... |
""" Author: Philipp Steinrötter (steinroe) """ |
"""
YUSS Class Band Creator
"""
from .cbcreator import *
|
# -*- coding:utf-8 -*-
from flask import redirect, url_for, render_template
from flask.globals import session
from flask_admin import BaseView, expose
from util import navigator, common
class Compare(BaseView):
@expose('/')
def index(self):
return redirect(url_for('.payment_compare_history_inq'))
... |
import unittest
import os
import itertools
import pandas as pd
import numpy as np
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
import gpflow
import TRANSPIRE.training
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class TestSVGP(unittest.TestCase):
def setUp(se... |
from __future__ import print_function
from base_action import BaseAction
import numpy as np
import rospy
from virtual_desert.msg import ActionData
from rolling_angular_velocity import RollingAngularVelocity
class PanelsAction(BaseAction):
index_to_patter_id = {}
#Possible virtual open loop implementation
... |
import time
import statistics
# A class to store all available runtime data on a website
# availability: tuple to store our main data, format: (UTC-Timestamp,availability)
# availability will be a number between 0 and 1 and the timestamp is the average availability from the
# previous timestamp to this one (in case of... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
The entry point for launching Meerschaum actions.
"""
from __future__ import annotations
from meerschaum.utils.typing import SuccessTuple, List, Optional
def _entry(sysargs : Optional[List[str]] = None) -> SuccessTuple:
"""
Parse arguments a... |
class DocumentPaginator(object):
""" Provides an abstract base class that supports creation of multiple-page elements from a single document. """
def CancelAsync(self,userState):
"""
CancelAsync(self: DocumentPaginator,userState: object)
Cancels a previous
erload:System.Windows.Documents.DocumentP... |
# Copyright 2019-2020 Faculty Science Limited
#
# 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... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
import sys... |
#program to create a new string with no duplicate consecutive letters from a given string.
def no_consecutive_letters (txt):
return txt[0] + ''.join(txt[i] for i in range(1,len(txt)) if txt[i] != txt[i-1])
print(no_consecutive_letters("PPYYYTTHON"))
print(no_consecutive_letters("PPyyythonnn"))
print(no_consecutive... |
import os
import sys
sys.path.append('../../common')
from env_indigo import *
import collections
indigo = Indigo()
indigo.setOption("ignore-noncritical-query-features", "true")
print("***** Aromaticity models *****")
def executeOperation (m, func, msg):
try:
func(m)
print(msg + m.smiles())
... |
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import generics
from .models import Post
from category.models import Category
from .serializer... |
## Directly From:
## https://gist.github.com/hchandad/b71ed0e977e6d345bcb8
from __future__ import print_function
from kivy.app import App
from kivy.uix.slider import Slider
from kivy.uix.boxlayout import BoxLayout
class ModifiedSlider(Slider):
def __init__(self, **kwargs):
self.register_event_type('on_re... |
from models import Visual, Category, Document
from django.core.files.uploadedfile import InMemoryUploadedFile
import StringIO
import pandas as pd
import datetime, time
def create_visual(corpus):
""" This function creates a visual model from a submitted corpus """
# Load data
cats = Category.objects.fi... |
from typing import List
from ConfigSpace import Configuration
from smac.initial_design.initial_design import InitialDesign
__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2016, ML4AAD"
__license__ = "3-clause BSD"
class DefaultConfiguration(InitialDesign):
"""Initial design that evaluates default c... |
# -*- coding: utf-8 -*-
from flask import Flask
from .extensions import api
from .extensions import filemanager
from .extensions import textExtractor
from . import config
from .extensions import views
def create_app():
app = Flask(__name__)
config.init_app(app)
filemanager.init_app(app)
textEx... |
import json
import os
import shutil
import signal
import sys
from io import open
import six
import yaml
from oslo_config import cfg
from oslo_log import log as logging
from fuel_agent import errors
from fuel_agent import manager as manager
from fuel_agent.utils import build as bu
from fuel_agent.utils import fs as f... |
"""
HttpCtrl library provides HTTP/HTTPS client and server API to Robot Framework to make REST API testing easy.
Authors: Andrei Novikov
Date: 2018-2021
Copyright: The 3-Clause BSD License
"""
class Response:
def __init__(self, status, reason, body, headers):
self.__status = status
... |
"""
Utility to combine individual JUnit XML files.
"""
import argparse
import logging
import os
import sys
from pbcommand.cli import (get_default_argparser_with_base_opts,
pacbio_args_runner)
from pbcommand.utils import setup_log
from pbsmrtpipe.testkit import xunit
log = logging.getLogg... |
import os
from lightgbm import LGBMClassifier
from sklearn.externals import joblib
def train_classifier(features, labels):
"""Trains a gradient boosting classifier on the input features and labels.
Classifiers are read from file if previously trained, or trained then cached otherwise.
Parameters
----... |
"""
A model made of pulses.
"""
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rng
reps = 100
t = np.linspace(-100.0, 100.0, 10001)
duration = t.max() - t.min()
for rep in range(reps):
while True:
num_pulses = rng.randint(100)
if rng.rand() <= 1.0/(1.0 + num_pulses):
... |
# import v2_0
# import _3_0
# from .v2_0.dto.AdditionalData import AdditionalData
# from .dto.AdditionalQueryParams import AdditionalQueryParams
# from .dto.Address import Address
# from .dto.AggregateInvoiceLineData import AggregateInvoiceLineData
# from .dto.Aircraft import Aircraft
# from .dto.AuditData import Audit... |
import csv
import sys
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
import pathlib
from config import *
double = []
rest = []
threshhold = 5
if len(sys.argv) < 2:
addon = ""
else:
addon = sys.argv[2]
def plot(bins=50):
pathlib.Path("plots"+addon+"/" + sys.argv[1]).parent.mkdi... |
import tensorflow as tf
from ..utils import nn
class JointCell(tf.contrib.rnn.RNNCell):
""" Run dual RNN cells (side by side). """
def __init__(self, cell1, cell2):
self.cell1 = cell1
self.cell2 = cell2
@property
def state_size(self):
return int(self.cell1.state_size) + int(s... |
# MIT License
#
# Copyright (c) 2019 Xilinx
#
# 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, modify, merge, publi... |
#!/usr/bin/python
# Copyright (C) Vladimir Prus 2003. Permission to copy, use, modify, sell and
# distribute this software is granted provided this copyright notice appears in
# all copies. This software is provided "as is" without express or implied
# warranty, and with no claim as to its suitability for any purp... |
from typing import Any, Dict
import logging
import os
import sys
from attr import asdict
from flask import g
from flask_wtf.csrf import CSRFProtect
from sentry_sdk.integrations.flask import FlaskIntegration
from social_flask.routes import social_auth
from social_flask_sqlalchemy.models import init_social
import sentry... |
import io
import gws
import gws.common.metadata
import gws.common.metadata.inspire
import gws.common.model
import gws.common.search.runner
import gws.common.template
import gws.gis.bounds
import gws.gis.extent
import gws.gis.render
import gws.gis.renderview
import gws.gis.gml
import gws.gis.proj
import gws.tools.units... |
from rest_framework import serializers
from recipe.models import Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ("user", "name",)
def create(self, validated_data):
return super().create(validated_data)
|
import os
import logging
import torch
logger = logging.getLogger(__name__)
def save_checkpoint(state, checkpoint_dir, checkpoint_prefix):
"""Saves model and training parameters at checkpoint: checkpoint_prefix.pth.tar'.
Args:
state: (dict) contains model's state_dict It may also contain other keys suc... |
# -*- coding: utf-8 -*-
"""API for collections."""
from typing import Optional
from .schema import Collection, Context
from .schema_utils import read_collections, read_contexts
__all__ = [
"get_collection",
"get_context",
]
def get_collection(identifier: str) -> Optional[Collection]:
"""Get the collec... |
import pytest
from flake8_plugin_utils import assert_error, assert_not_error
from flake8_pytest_style.config import DEFAULT_CONFIG
from flake8_pytest_style.errors import RaisesWithMultipleStatements
from flake8_pytest_style.visitors import RaisesVisitor
def test_ok():
code = """
def test_something():
... |
import os
from flask import Flask, render_template, request, jsonify, Response
from utils.yt_api_int import download_mp3
app = Flask(__name__, static_folder="./static", template_folder="./static")
# TODO https://developers.google.com/youtube/v3/getting-started
# you can find instructions here to get a developer ke... |
import aiohttp_apispec
from aiohttp import web
from app.api.v2.handlers.base_object_api import BaseObjectApi
from app.api.v2.managers.agent_api_manager import AgentApiManager
from app.api.v2.schemas.deploy_command_schemas import DeployCommandsSchema
from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, Ba... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Project'
db.create_table(u'core_project', (
(u'id', self.gf('django.db.models.fi... |
# ------------------------------------------------------------------------------
# Licence:
# Copyright (c) 2012-2020 Luzzi Valerio
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WA... |
#!/usr/bin/env python
# Copyright 2014 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.
"""Scans the Chromium source of UseCounter, formats the Feature enum for
histograms.xml and merges it. This script can also generate a ... |
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import os
import sys
from click.testing import CliRunner
sys.path.append('..')
from app import main
def config(tmpdir):
os.environ['JINA_WORKSPACE'] = os.path.join(tmpdir, 'workspace')
def test_wikipedia_sent... |
import unittest
# def test_import_dataformat_top():
# from larcv import dataformat
|
import hashlib
import json
import binascii
import base58
from bitcoin.wallet import P2PKHBitcoinAddress
from coincurve import PrivateKey, PublicKey
from mnemonic import Mnemonic
from bip32utils import BIP32Key
class Wallet(object):
def __init__(self, config):
self.seed = config.get('seed', '')
sel... |
#
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
... |
# -*- coding: utf-8 -*-
import zmq
from lucena.exceptions import IOTimeout
from lucena.io2.socket import Socket
class RemoteClient(object):
def __init__(self, default_timeout=None):
self.default_timeout = default_timeout
self.socket = Socket(zmq.Context.instance(), zmq.REQ)
self.socket.s... |
import os
import pathlib
import win32com.client
def all_files(directory):
for root, _, files in os.walk(directory):
for file in files:
yield os.path.join(root, file)
if __name__ == '__main__':
s = input("Dir: ")
root_dir = s.strip('\"')
app = win32com.client.Dispatch("Excel.Appl... |
import logging
import os
import re
import select
import signal
import subprocess
BUFSIZ = 4096
class XvfbView(object):
def __init__(self, xvfb_display, viewer_display):
"""
show an xvfb display using x11vnc
xvfb_display: display where xvfb is running
viewer_display: display t... |
import logging
from config.harvester_config import config_harvester
is_debug_level = config_harvester['is_level_debug']
if is_debug_level == 1:
LOGGER_LEVEL = logging.DEBUG
else:
LOGGER_LEVEL = logging.WARNING
|
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 import Features, EmotionOptions, EntitiesOptions, KeywordsOptions, CategoriesOptions, ConceptsOptions
from IBM_Auth import *
import matplotli... |
import subprocess
from scripts.test import shared
from . import utils
class ReduceTest(utils.BinaryenTestCase):
def test_warn_on_no_passes(self):
# run a reducer command that does nothing, and so ignores the input
open('do_nothing.py', 'w').close()
cmd = shared.WASM_REDUCE + [self.input_p... |
import numpy as np
with open("/sys/class/backlight/gmux_backlight/max_brightness") as f:
MAX_BRIGHTNESS = int(f.read())
def write_brightness(brightness, clip_min=1, clip_max=MAX_BRIGHTNESS):
brightness = np.clip(int(brightness), clip_min, clip_max)
with open("/sys/class/backlight/gmux_backlight/brightnes... |
# -*- coding: utf-8 -*-
"""
A module for translating "Actions" format to User API objects.
"""
from __future__ import absolute_import
from collections import OrderedDict
from psd_tools.debug import pretty_namedtuple
from psd_tools.decoder.decoders import new_registry
from psd_tools.decoder.actions import (
Descrip... |
"""
044) Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e
condição de pagamento:
- à vista dinheiro/cheque: 10% de desconto
- à vista no cartão: 5% de desconto
- em até 2x no cartão: preço normal
- 3x ou mais no cartão: 20% de juros
"""
preco = float(input('Qual o val... |
from .sdk_exception import ElectronicInstrumentAdapterException
DEFAULT_MESSAGE = "instrument not exists"
class InstrumentNotFoundException(ElectronicInstrumentAdapterException):
"""
Raised when the requested instrument not exists
"""
def __init__(self, message=DEFAULT_MESSAGE):
self.message =... |
from pyface.qt.QtTest import * # noqa
|
a = 2
b = 3
print("a is {}, b is {}".format(a, b))
a, b = 3, 2 # b, a
# temp = a
# a = b
# b = temp
print("a is {}, b is {}".format(a, b))
|
import unittest
from .common import monosaccharides, link, glycoct, load
from glypy.composition.composition_transform import derivatize
from glypy.composition import Composition
class LinkTests(unittest.TestCase):
def test_link_equality(self):
parent = monosaccharides['Hex']
child = monosaccharid... |
budget = float(input())
season = input()
spend = 0
if budget <= 100:
if season == "summer":
spend = budget * 0.3
print("Somewhere in Bulgaria")
print("Camp - " + f'{spend:.2f}')
elif season == "winter":
spend = budget * 0.7
print("Somewhere in Bulgaria")
print("H... |
#encoding=utf-8
import pandas as pd
import numpy as np
import cv2
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
from binary_perceptron import BinaryPerceptron
def main():
raw_data = pd.read_csv('../data/train_binary.csv', header=0)
data = raw_data.values
... |
"""
.. _serp:
Import Search Engine Results Pages (SERPs) for Google and YouTube
=================================================================
"""
__all__ = ['SERP_GOOG_VALID_VALS', 'YOUTUBE_TOPIC_IDS',
'YOUTUBE_VID_CATEGORY_IDS', 'serp_goog', 'serp_youtube',
'set_logging_level', 'youtube_cha... |
"""
This is a helper script to call from test_exec.py
It requires 2 arguments, the output directory and filename.
A file will be created in the output directory with the given filename.
If there are more arguments to the script, they will be written 1 per line to the file.
"""
import os
import sys
if __name__ == "__ma... |
# This module should hopefully remain **small**. Use other libraries and such
# if you can. There shouldn't be that much shared code among the different
# views.
from werkzeug.exceptions import NotFound, HTTPException
from flask import request
def is_url_on_site(app, url):
"""
Determines if *app* can handle *u... |
import os.path
import logging
import subprocess
import shutil
import json
from gii.core import *
from mock import _MOCK
from gii.qt.dialogs import requestString, alertMessage, requestConfirm
##----------------------------------------------------------------##
class EffectAssetManager( AssetManager ):
def getName(... |
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... |
# -*- python -*-
#
# Copyright (C) 2012, Pigeon Point Systems
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This
# file and program are licensed under a BSD style license.... |
import csv
import cx_Oracle
db = cx_Oracle.connect('books_admin/brekeke@192.168.56.111/xe')
cursor = db.cursor()
f = open("export.csv", "w")
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_NONNUMERIC)
r = cursor.execute("SELECT book_id, title, author_last_name, author_first_name, rating FROM books Vw")
#r... |
"""
Author: Nelson Gonzabato
Free Open Source Software, free and always will be.
"""
import re
from .helpers import remove_newlines, split_authors
from .pubmed import make_first_last
# Citation methods for NCBI based addresses
def ncbi_title(bs4_object):
title = bs4_object.find_all("h1", {"class": "content-title"... |
"""Parser for stupid game.
Python had problems with this file due to tabs/spaces indent mismatch.
Guess PIP8 is not entirely useless.
"""
class ParserError(Exception):
pass
class Sentence(object):
"""Lalalal."""
def __init__(self, subject, verb, obj):
self.subject = subject
self.ver... |
from MedWeb.clinical_database.dose_units import dose_unit_data
from MedWeb.clinical_database.entities import Medication, DoseUnit
from MedWeb.clinical_database.medication_data import medication_data
"""Build medication database from medication_data and dose_units files"""
medications = {}
dose_units = {}
for id, nam... |
# -*- coding: utf-8 -*-
from langml import TF_KERAS
if TF_KERAS:
import tensorflow.keras.backend as K
import tensorflow.keras.layers as L
else:
import keras.backend as K
import keras.layers as L
def test_transformer_encoder():
from langml.transformer.encoder import TransformerEncoder
X = L.I... |
import os.path
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='nyt-clerk',
version='0.1.21',
author='Jeremy Bowers',
author_email='jeremy.bowers@... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Detector de violencia de género en redes sociales. """
import csv
import io
import json
import logging
import numpy as np
import os
import pandas as pd
import re
import Stemmer
import sys
import time
from collections import Counter, OrderedDict
__author__ = "Miguel ... |
# -*- coding: utf-8 -*-
import datetime
from numbers import Number
from typing import Optional
class DataDogMetricPoint:
def __init__(self, value: Number, time: Optional[datetime.datetime] = None):
self.value = value
self.time = time
|
#Import basic stuff
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import linear_model
#import the custom analysis software
import scipy as sp
import plot_informationfootprint as pli
import seaborn as sns
import sys
def least_squares(raveledmat, batch):
'''Linear regression ... |
# @SciView sv
import net.imglib2.img.array.ArrayImgs as ArrayImgs
import bdv.util.BdvFunctions as BdvFunctions
import org.janelia.saalfeldlab.n5.imglib2.N5Utils as N5Utils
import org.janelia.saalfeldlab.n5.N5FSWriter as N5FSWriter
import org.janelia.saalfeldlab.n5.GzipCompression as GzipCompression
import random as ... |
# Copyright (c) 2018, Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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/lic... |
import pandas as pd
class PopularityRecommender:
MODEL_NAME = "Popularity"
def __init__(self, user_id, item_id, df_lookup=None):
self.user_id = user_id
self.item_id = item_id
self.df_lookup = df_lookup
@property
def name(self):
return self.MODEL_NAME
def fit(sel... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Arial']
dbColors = pd.Series({"Reactome": "#FFA52B",
"KEGG": "#C79D36",
"UniProt": "#F0F01F",
"GO_BP": "#2ECC71",
... |
import json
import pytest
import base64
import unittest
from src import app, db
from src.models import users
from pprint import pprint
def get_header(u):
email_pw = "%s:%s" % (u.email, u.api_token)
auth_pass = base64.b64encode(email_pw.encode('ascii'))
headers = { 'Authorization' : 'Basic %s' % auth_pass.... |
#!/usr/bin/env python
import getopt
import os
import sys
import sqlite3
import xml.etree.ElementTree as ET
import re
import httplib
import wikipedia
import amazonproduct
GUTENBERG_BASE_USL = 'http://www.gutenberg.org/ebooks/'
STARS_URL = '/gp/customer-reviews/widgets/average-customer-review/popover/ref=dpx_acr_pop_?... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
#Y configuration
coordinates=[(0, 1), (0.69802, 1.403), (1.60362, 1.92585), (2.60862, 2.50609), (3.68415, 3.12705), (4.81537, 3.78016), (5.99304, 4.46008), (-0.69802, 1.403), (-1.60362, 1.92585), (-2.60862, 2.50609), (-3.68415, 3.... |
"""
LinearMovementConstraintPython
is based on the scene
/Users/marco.magliulo/mySofaCodes/basicSofaExamples/LinearMovementConstraint.scn
but it uses the SofaPython plugin.
Further informations on the usage of the plugin can be found in
sofa/applications/plugins/SofaPython/doc/SofaPython.pdf
To launch the scene, typ... |
#escreva um programa para aprovar o emprestimo bancario para a compra de uma casa. O programa
#vai perguntar o valor da casa , o salario do comprador e em quantos anos ele vai pagar.
#Calcule o valor da prestacao mensal, sabendo que ela nao pode exceder 30% do salario ou entao
#o emprestimo será negado
#minha resposta... |
"""Data streams for processing with a pipeline."""
import warnings
import numpy as np
def segment(data, length, overlap=0):
"""Generate segments of an array.
Each segment is of a specified length and optional overlap with the
previous segment. Only segments of the specified length are retrieved (if
... |
"""
Do some raw fizzin and buzzin
"""
def fizzbuzz(num):
"""
A pretty vanilla actual fizzbuzz solution to build our raw dataset.
"""
if num % 3 == 0:
if num % 5 == 0:
return ('Fizz', 'Buzz')
else:
return('Fizz', '')
if num % 5 == 0:
return ('', 'Buzz... |
import matplotlib.pyplot as plt
import numpy as np
def display_data(x):
(m, n) = x.shape
# Set example_width automatically if not passed in
example_width = np.round(np.sqrt(n)).astype(int)
example_height = (n / example_width).astype(int)
# Compute the number of items to display
display_rows ... |
"""Example showing how one can implement a simple self-play training workflow.
Uses the open spiel adapter of RLlib with the "connect_four" game and
a multi-agent setup with a "main" policy and n "main_v[x]" policies
(x=version number), which are all at-some-point-frozen copies of
"main". At the very beginning, "main"... |
#!/usr/bin/env python
import argparse, grpc, sys, os, socket, random, struct, time
from time import sleep
import time
import Queue
import socket
import struct
from scapy.all import *
import matplotlib.pyplot as plt
import thread
import csv
from fcntl import ioctl
import IN
AVERAGE_NUM = 30
AVERAGE_NUM2 = 1
def main(... |
# -*- coding: utf-8 -*-
"""Constants for generating BLAST+6 files."""
from hypothesis.strategies import characters, floats, from_type
BLAST6_HEADERS = {
"qseqid": characters(min_codepoint=32, max_codepoint=126),
"qgi": from_type(int),
"qacc": characters(min_codepoint=32, max_codepoint=126),
"qaccver"... |
import subprocess
from ..common import write_file
def test_valid_file_no_config(tmp_path):
dummy_file = write_file(tmp_path, "script.gd", "tool")
assert subprocess.run(["gdlint", dummy_file], check=False).returncode == 0
def test_valid_file_w_config(tmp_path):
dummy_file = write_file(tmp_path, "script.... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
answer=0
for i in range(10001):
answer=answer+i
print("Hello the answer is ",answer)
|
import argparse
from pathlib import Path
import pandas as pd
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='The tool to generate tfrecords file by images and meta')
parser.add_argument('--base-image-path', required=True, help='base_img_path/an_img_name.jpg')
parser.add_argument(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.