content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import gym
import shutil
import tempfile
import ray
from ray.rllib.a3c import DEFAULT_CONFIG
from ray.rllib.a3c.a3c_evaluator import A3CEvaluator
from ray.rllib.dqn.dqn_evaluator import adjust_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Management of Redis server
==========================
.. versionadded:: 2014.7.0
:depends: - redis Python module
:configuration: See :py:mod:`salt.modules.redis` for setup instructions.
.. code-block:: yaml
key_in_redis:
redis.string:
- value: string data
The redis s... | nilq/baby-python | python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('canyon.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
values = []
for i in range(256):
n = np.where(gray_img == i, 1., 0.).sum()
values.append(n)
plt.bar(range(256), height=values, width=1.)
plt.xlabel('intensity')
plt.yl... | nilq/baby-python | python |
"""
Profile ../profile-datasets-py/div83/023.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/023.py"
self["Q"] = numpy.array([ 2.79844200e+00, 3.21561000e+00, 4.08284300e+00,
4.76402700e+00, 4.58551900e+00, 4.69499800e+00,
5.2297... | nilq/baby-python | python |
"""
Outpost URL Configuration
"""
import django
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
from django.views.i18n import JavaScriptCatalog
from rest_framework.authtoken import views as authtoken
js_info_dict = {
... | nilq/baby-python | python |
import argparse
from flatdb import flatdb_app
from flatdb.app import define_urls
def get_options():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', default=False)
parser.add_argument('-p', '--port', type=int, default=7532)
parser.add_argument('-b', '--data... | nilq/baby-python | python |
'''
the following import is only necessary because eip is not in this directory
'''
import sys
sys.path.append('..')
'''
The simplest example of reading a tag from a PLC
NOTE: You only need to call .Close() after you are done exchanging
data with the PLC. If you were going to read in a loop or read
more tags, you w... | nilq/baby-python | python |
from __future__ import unicode_literals
import frappe
from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
try:
rename_field("Pricing Rule", "price_or_discount", "rate_or_discount")
rename_field("Pricing Rule", "price", "rate")
except... | nilq/baby-python | python |
import logging
import os
import requests
import pickle
import json
from configparser import ConfigParser
logger = logging.getLogger(__name__)
project_dir = os.path.abspath(os.path.dirname(__file__)) + '/'
config = ConfigParser()
config.read(project_dir + '/config.cfg')
def get_or_download_file(filename, k, value, c... | nilq/baby-python | python |
from collections import namedtuple
Point = namedtuple('point', 'x, y')
mouse_pos = Point(100, 200)
print("X Position of Mouse:", mouse_pos.x) | nilq/baby-python | python |
import json
from graphql_relay import to_global_id
from tracker.api.services.auth import (
generate_auth_token,
)
from tracker.api.status_codes import StatusEnum
async def test_create_role_mutation(
client,
setup_project_list_test_retrun_auth_token
):
pm_auth_token = setup_project_list_test_retrun_a... | nilq/baby-python | python |
import pandas as pd
from .taxa_tree import NCBITaxaTree
from ..constants import MICROBE_DIR
MICROBE_DIR_COLS = [
'gram_stain',
'microbiome_location',
'antimicrobial_susceptibility',
'optimal_temperature',
'extreme_environment',
'biofilm_forming',
'optimal_ph',
'animal_pathogen',
's... | nilq/baby-python | python |
import json
import os
from django.apps import apps
DJANGO_TAILWIND_APP_DIR = os.path.dirname(__file__)
def get_app_path(app_name):
app_label = app_name.split(".")[-1]
return apps.get_app_config(app_label).path
def get_tailwind_src_path(app_name):
return os.path.join(get_app_path(app_name), "static_src... | nilq/baby-python | python |
from model_defs import *
from utils import *
from tensorflow.models.rnn.rnn_cell import *
###################################
# Building blocks #
###################################
# takes features and outputs potentials
def potentials_layer(in_layer, mask, config, params, reuse=False, name='Potentia... | nilq/baby-python | python |
import networkx as nx
import numpy as np
import torch
from gym_ds3.envs.core.node import Node
from gym_ds3.envs.utils.helper_dict import OrderedSet
class JobDAG(object):
def __init__(self, job):
self.job = job
self.jobID = self.job.task_list[0].jobID
self.commvol = self.job.comm_vol
... | nilq/baby-python | python |
from typing import List
import torch
from torch.nn import ParameterList, Parameter
from allennlp.common.checks import ConfigurationError
class ScalarMix(torch.nn.Module):
"""
Computes a parameterised scalar mixture of N tensors, `mixture = gamma * sum(s_k * tensor_k)`
where `s = softmax(w)`, with `w` an... | nilq/baby-python | python |
import bpy,bmesh
import time,copy,mathutils,math
from mathutils import noise
Context={
"lasttick":0,
"running":False,
"store":{},
"starttime":-1
}
def timeNow():
t=time.time()
return t
def calcFrameTime():
fps = max(1.0, float(bpy.context.scene.render.fps))
return 1.0/f... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
from .. import StorageTests, get_server_mixin
dav_server = os.environ.get('DAV_SERVER', 'skip')
ServerMixin = get_server_mixin(dav_server)
class DAVStorageTests(ServerMixin, StorageTests):
dav_server = dav_server
| nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
import os
import time
import numpy as np
import seaborn as sns
import tensorflow as tf
import tensorflow_probability as tfp
from matplotlib import pyplot as plt
from tensorflow import keras
from odin import visual as vs
from odin.bay import kl_divergen... | nilq/baby-python | python |
"""Script to convert MultiWOZ 2.2 from SGD format to MultiWOZ format."""
import glob
import json
import os
from absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
flags.DEFINE_string("multiwoz21_data_dir", None,
"Path of the MultiWOZ 2.1 dataset.")
flags.DEFINE_st... | nilq/baby-python | python |
#SENSOR_DATA_TRANSFER
import socket
import serial
host = "192.168.137.54"
port = 50007
import time
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
aD=serial.Serial('/dev/ttyACM0',9600)
while True:
while ... | nilq/baby-python | python |
import time
from typing import Any, Union
from copy import deepcopy
import biorbd_casadi as biorbd
import numpy as np
from scipy import interpolate as sci_interp
from scipy.integrate import solve_ivp
from casadi import vertcat, DM, Function
from matplotlib import pyplot as plt
from ..dynamics.ode_solver import OdeSol... | nilq/baby-python | python |
from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
import views
urlpatterns = patterns('',
(r'^$', views.home),
# would like to avoid hardcoding mibbinator here
(r'^(o/\.|\.?)(?P<oid>[0-9.]*)$', redirect_to, { 'url': '/mibbinator/o/%(oid)s' }),
(r'^o/(?P<oid>[0-... | nilq/baby-python | python |
# coding=utf-8
# Copyright 2021 The OneFlow 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 require... | nilq/baby-python | python |
# Generated by Django 3.1 on 2020-10-19 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0013_auto_20201020_0122'),
]
operations = [
migrations.AlterField(
model_name='restaurant',
name='business_num... | nilq/baby-python | python |
from jax import numpy as jnp
from typing import Callable
def weighted_dot(sigma_i: float, sigma_r: float, sigma_b: float) -> Callable:
"""Defines weighed dot product, i.e. <u, v> with u = [i, j]
Returns function which calculates the product given the weights.
"""
def dot(gram: jnp.ndarray, kernel: jn... | nilq/baby-python | python |
import requests,json
from HelperTools import Debug
import os
sourceStreamInfoListUrl = os.getenv('SourceStream')
GetNotFixedStreamAPIUrl = os.getenv("NotFixedStreamAPI")
# 需要做代理的源流信息
sourceStreamInfoList = {}
def GetSourceStreamInfoList():
if sourceStreamInfoListUrl == None or sourceStreamInfoListUrl == "defa... | nilq/baby-python | python |
import pygame as p
import dartboard
import buttonPanel
import statPanel
from dartboard import PERCENTAGES, LASTBULLSEYE
WIDTH = 800
HEIGHT = 700
BACKGROUND = p.Color("red")
MAX_FPS = 30
def main():
global throwing
p.init()
screen = p.display.set_mode((WIDTH, HEIGHT))
screen.fill(BACKGROUND)
p.dis... | nilq/baby-python | python |
import copy
import inspect
import math
import numpy as np
import random
def create_new_children_through_cppn_mutation(pop, print_log, new_children=None, mutate_network_probs=None,
max_mutation_attempts=1500):
"""Create copies, with modification, of existing individuals in t... | nilq/baby-python | python |
import sys
def solution(A):
difference = sys.maxsize
left = 0
right = sum(A)
for i in range(0, len(A)-1):
left += A[i]
right -= A[i]
if abs(right - left) < difference:
difference = abs(right - left)
return difference
def test_solution():
assert solutio... | nilq/baby-python | python |
import json
def readJsonFromFile(filename):
file = open(filename, 'r')
arr = json.loads(file.read())
file.close()
return arr | nilq/baby-python | python |
from enum import Enum
class TaskState(Enum):
# static states:
# a task can either succeed or fail
VALID = 0x0
INVALID = 0x1
# actionable states
DROP = 0x10
DONE = 0x99
class TaskConfigState(Enum):
VALID = 0x0
INVALID = 0x1
| nilq/baby-python | python |
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/data', one_hot=True)
# Path to Computation graphs
LOGDIR = './graphs'
# Start session
sess = tf.Session()
# Hyper parameters
LEARNING_RATE = 0.01
BATCH_SIZE = 1000
EPOCHS = 10
# Hid... | nilq/baby-python | python |
#:::::::::::::::::::::::::
#::
#:: ProjectDependencies/check.py
#::_______________________
#::
#:: Author: Clement BERTHAUD
#::
#:: MIT License
#:: Copyright (c) 2018 ProjectDependencies - Clément BERTHAUD
#::
#:: Permission is hereby granted, free of charge, to any person obtaining a copy
#:: of this software and asso... | nilq/baby-python | python |
"""
We presume that Channels is operating over a Redis channel_layer here, and use it
explicitly.
"""
from base64 import b64encode
from json import dumps
def message_to_hash(message):
message_hash = b64encode(dumps(message).encode("utf-8"))
return b"semaphore:" + message_hash
async def get_set_message_sema... | nilq/baby-python | python |
"""
Configuration for the integration issues tests
"""
import pytest
@pytest.fixture(scope="package", autouse=True)
def xfail():
pytest.xfail("Issues tests need refactored")
| nilq/baby-python | python |
import argparse
import json
import logging
import os
import subprocess
import tqdm
import wget
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import numpy as np
import torch
import random
def extracting_log_info(log_files, experiment, logging):
metrics_t2v = defaultdict... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function
"""
test_split_regex_and_collate.py
"""
JOBS_PER_TASK = 5
import os
tempdir = os.path.relpath(os.path.abspath(os.path.splitext(__file__)[0])) + "/"
import sys
import re
# add grandparent to search path for testing
grandparent_dir = os.path.abspath(os.p... | nilq/baby-python | python |
from django.views.generic import View
from core.models import Cardapio
from django.shortcuts import render
from core.outros.categoriasCardapio import categoriasCardapio
import json
class CardapioView(View):
def get(self, request, *args, **kwargs):
categoria = request.GET.get('categoria')
item_adi... | nilq/baby-python | python |
import argparse
import logging
import os
from sentiment_analysis.src.managers.survey_replies_manager import SurveyRepliesManager
from utils.data_connection.api_data_manager import APISourcesFetcher
from utils.data_connection.source_manager import Connector
from utils.gcloud.nlp_client import NLPGoogleClient
from utils... | nilq/baby-python | python |
import numpy as np
import os
forcing_filename = os.path.join(os.path.dirname(__file__), 'cmip6_solar.csv')
class Forcing:
forcing = np.loadtxt(forcing_filename, skiprows=7, delimiter=',')
year = forcing[:,0]
solar = forcing[:,1]
| nilq/baby-python | python |
import os
import numpy as np
from play_model import PlayModel
class PlayAgent:
def __init__(self, params):
self.parameters = params
os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(self.parameters['tf_log_level']) #reduce log out for tensorflow
self.model = PlayModel(self.parameters)
... | nilq/baby-python | python |
import pytest
import asyncio
from async_v20.client import OandaClient
@pytest.yield_fixture
@pytest.mark.asyncio
async def client():
oanda_client = OandaClient(rest_host='127.0.0.1', rest_port=8080, rest_scheme='http',
stream_host='127.0.0.1', stream_port=8080, stream_scheme='http',... | nilq/baby-python | python |
"""
Defines the blueprint for the auth
"""
import uuid
import datetime
from flasgger import swag_from
from flask import Blueprint, request
from flask.json import jsonify
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_jwt_extended import (create_access_token, get_jwt_identity)
from rep... | nilq/baby-python | python |
import numpy as np
def main():
nx = 2
ny = 3
nz = 4
def do_it(i):
return [i % nx, (i / nx) % ny, i / (nx * ny)]
def undo_it(x, y, z):
# return z + ny * (y + nx * x)
# return x + nx * (x + ny * y)
# return (x * nx * ny) + (y * ny) + z
# return (z * nx * ny... | nilq/baby-python | python |
import utils
import euclides
def esCarmichael(p):
# p > 0
# Retorna cert si p és un nombre de carmichael, fals altrament
i = 1
while i < p:
if euclides.sonCoprimers(i, p):
if utils.potencia_modular_eficient(i, p-1, p) != 1:
return False
i += 1
if i == p:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 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... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf8
from __future__ import print_function, division
from pyksc import dist
import glob
import numpy as np
import os
import plac
import sys
def main(tseries_fpath, in_folder):
ids = []
with open(tseries_fpath) as tseries_file:
for l in tseries_file:
id... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Processor for CRGA models"""
import otbApplication
from decloud.core import system
import pyotb
import unittest
from decloud.production import crga_processor
from decloud.production.inference import inference
from .decloud_unittest import DecloudTest
import datetime
d... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (c) 2018 Harold Wang, Ryan L. Collins, and the Talkowski Lab
# Distributed under terms of the MIT License (see LICENSE)
# Contact: Ryan L. Collins <rlcollins@g.harvard.edu>
# gnomAD credits: http://gnomad.broadinstitute.org/
"""
Helper script for workflow to calculates B-allele frequ... | nilq/baby-python | python |
"""Lib module for daq sub units"""
pass
| nilq/baby-python | python |
#!/usr/bin/env python
r"""Aggregate, create, and save 1D and 2D histograms and binned plots.
"""
from . import agg_plot
from . import hist1d
from . import hist2d
AggPlot = agg_plot.AggPlot
Hist1D = hist1d.Hist1D
Hist2D = hist2d.Hist2D
# import pdb # noqa: F401
# import logging
# import numpy as np
# import pandas ... | nilq/baby-python | python |
#-- GAUDI jobOptions generated on Mon Oct 12 10:07:37 2020
#-- Contains event types :
#-- 90000000 - 3737 files - 56787251 events - 2862.54 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass: '/Real Data/Reco14/Stripping21r1'
#-- StepId : 127013
#-- StepName : Stripping21r1-M... | nilq/baby-python | python |
"""
Customized Django model field subclasses
"""
from django.db import models
from django.db.models import fields
from django.db.models.fields.related import ManyToManyField
class CopyFromFieldMixin(fields.Field):
"""
Mixin to add attrs related to COPY FROM command to model fields.
"""
def __init__(se... | nilq/baby-python | python |
# Aula de estrutura de repetição com variavel de controle
for c in range(0, 6):
print('oi')
print('fim')
for a in range(0, 10, 2): # o primeiro argumento e o segundo é o range de contagem, o terceiro é o metodo da contagem
print(a)
print('fim')
# Outro exemplo
for a in range(10, 0, -1): # Com uma condição d... | nilq/baby-python | python |
from __future__ import print_function
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
#rc('text', usetex=True)
# generate data
# list of points
from matplotlib.backends.backend_pd... | nilq/baby-python | python |
import sys
import serial
import pprint
import time
import enum
import queue
from queue import Queue
from os.path import join, dirname, abspath
from qtpy.QtCore import Slot, QTimer, QThread, Signal, QObject, Qt, QMutex
class GcodeStates(enum.Enum):
WAIT_FOR_TIMEOUT = 1
GCODE_SENT = 2
READY_TO_SEND = 3
clas... | nilq/baby-python | python |
from urllib.parse import unquote
from flask import Flask
from flask import Response
from flask import abort
from flask import jsonify
from flask import render_template
from flask import request
from flask import send_file
from werkzeug.exceptions import BadRequest
from bootstrapper.lib import archive_utils
from boots... | nilq/baby-python | python |
# stream.models
# Database models for the Activity Stream Items
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Wed Feb 04 10:24:36 2015 -0500
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: models.py [70aac9d] benjamin@bengfort.com $
"""
Databa... | nilq/baby-python | python |
# files.py — Debexpo files handling functions
#
# This file is part of debexpo -
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
class BIT:
def __init__(self, size: int) -> None:
self.size = size
self._bit = [0 for _ in range(self.size + 1)]
def add(self, index: int, value: int) -> None:
while index <= self.size:
self._bit[index] += value
index += index & -index
... | nilq/baby-python | python |
"""Mock input data for unit tests."""
from copy import deepcopy
import uuid
# no dependencies
MOCK_BASE_PATH = "a/b/c"
MOCK_DRS_URI = "drs://fakehost.com/SOME_OBJECT"
MOCK_DRS_URI_INVALID = "dr://fakehost.com/SOME_OBJECT"
MOCK_DRS_URI_LONG = (
"drs://aaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa"
"aaaaa... | nilq/baby-python | python |
from sikuli import *
import sys
sys.path.insert(0, '/home/vagrant/Integration-Testing-Framework/sikuli/examples')
from test_helper import TestHelper
import open_flex_from_backup, check_change
helper = TestHelper("run_tests_from_backups")
folder = "/home/vagrant/Integration-Testing-Framework/sikuli/examples/images_for_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""File service tests."""
from io import BytesIO
def test_file_flow(
file_service, location... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from future.builtins import object
from contextlib import contextmanager
import sys
import unittest
from redis import Redis
from limpyd.database import (RedisDatabase, DEFAULT_CONNECTION_SETTINGS)
TEST_CONNECTION_SETTINGS = DEFAULT_CONNECTION_SETTINGS.... | nilq/baby-python | python |
from .newton_divided_differences import NewtonDifDiv
from .larange import Larange
from .linear_spline import LinearSpline
from .quadratic_spline import QuadraticSpline
from .cubic_spline import CubicSpline
| nilq/baby-python | python |
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ... | nilq/baby-python | python |
from setuptools import setup, find_packages
setup(
name='arranger',
version='1.1.2',
description="moves each file to its appropriate directory based on the file's extension.",
author='j0eTheRipper',
author_email='j0eTheRipper0010@gmail.com',
url='https://github.com/j0eT... | nilq/baby-python | python |
"""
Copyright 2018 Duo Security
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistribut... | nilq/baby-python | python |
from django.apps import AppConfig
class ProntuariomedicoConfig(AppConfig):
name = 'prontuarioMedico'
| nilq/baby-python | python |
"""
Enables the user to add an "Image" plugin that displays an image
using the HTML <img> tag.
"""
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from cm... | nilq/baby-python | python |
import lark
import copy
import torch
class LogicParser:
""" This class defines the grammar of the STL according to
the EBNF syntax and builds the AST accordingly.
"""
_grammar = """
start: prop
prop: VAR CMP (CONST | VAR) -> atom
| _NOT "(" prop ")" -> op_not
| (prop _... | nilq/baby-python | python |
from dash import Input, Output, callback
from dash import dcc
import dash.html as html
import dash_bootstrap_components as dbc
from pages.constants import TITLE_STYLE, PARAGRAPH_STYLE, IMG_STYLE
from utils.topic_crud import TopicCRUD
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = ... | nilq/baby-python | python |
#!/usr/bin/python
class race:
def __init__(self, t):
self.title = t
#ACCESSORS
def titleReturn(self):
return(self.title) | nilq/baby-python | python |
import glob
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setuptools.setup(
name="mldiag",
version="0.0.1",
author="Aymen SHABOU",
author_email="aymen.shabou@gmail.com",
descript... | nilq/baby-python | python |
#!/usr/bin/env python
import roslib
import rospy
import tf
from geometry_msgs.msg import TransformStamped
from posedetection_msgs.msg import ObjectDetection
def handle_pose(msg):
br = tf.TransformBroadcaster()
if len(msg.objects)==0:
return
p = msg.objects[0].pose
br.sendTransform((p.position.... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# Author: Jeremy Compostella <jeremy.compostella@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notic... | nilq/baby-python | python |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
... | nilq/baby-python | python |
"""
Merged String Checker
http://www.codewars.com/kata/54c9fcad28ec4c6e680011aa/train/python
"""
def is_merge(s, part1, part2):
result = list(s)
def findall(part):
pointer = 0
for c in part:
found = False
for i in range(pointer, len(result)):
if result... | nilq/baby-python | python |
import os
import docker.errors
import pandas as pd
import pytest
from ebonite.build.docker import create_docker_client, is_docker_running
from ebonite.core.objects.core import Model
from sklearn.linear_model import LinearRegression
from tests.client.test_func import func
def has_docker():
if os.environ.get('SKI... | nilq/baby-python | python |
from ..value_set import ValueSet
class BmiRatio(ValueSet):
"""
**Clinical Focus:** This value set contains concepts that represent a body mass index (BMI) ratio.
**Data Element Scope:** This value set may use the Quality Data Model (QDM) category or attribute related to Procedure.
**Inclusion Criter... | nilq/baby-python | python |
import os
import json
import tempfile
from model import VepException, VepResult
from bgcore import tsv
from bgcore.request import Request
def _ctype(value):
return value.split(",")
class VepService(object):
HOST = "beta.rest.ensembl.org"
VEP_STRAND = { "+" : "1", "-" : "-1", "1" : "1", "-1" : "-1" }
def __ini... | nilq/baby-python | python |
from ._PlaceBox import *
from ._RemoveBox import *
| nilq/baby-python | python |
"""Implements logic to render and validate web forms for login and user registration."""
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
"""Form for new users to log-in to... | nilq/baby-python | python |
spanish_columns = {
"oer": "oer",
"games": "partidos",
"points_made": "puntos_a_favor",
"total_possessions": "posesiones_totales",
"minutes": "minutos",
"assists": "asistencias",
"steals": "robos",
"turnovers": "perdidas",
"2_point_percentage": "porcentaje_2_puntos",
"2_point_mad... | nilq/baby-python | python |
import decimal
import numbers
import itertools
__all__ = [
'TRUNCATE',
'ROUND',
'DECIMAL_PLACES',
'SIGNIFICANT_DIGITS',
'NO_PADDING',
'PAD_WITH_ZERO',
'decimal_to_precision',
]
# rounding mode
TRUNCATE = 0
ROUND = 1
# digits counting mode
DECIMAL_PLACES = 2
SIGNIFICANT_DIGITS = 3
# padd... | nilq/baby-python | python |
import os
from setuptools import setup
README = """
See the README on `GitHub
<https://github.com/uw-it-aca/uw-restclients-coda>`_.
"""
version_path = 'uw_coda/VERSION'
VERSION = open(os.path.join(os.path.dirname(__file__), version_path)).read()
VERSION = VERSION.replace("\n", "")
# allow setup.py to be run from any... | nilq/baby-python | python |
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
################################################################################
# Project: OGR NextGIS Web Driver
# Purpose: Tests OGR NGW Driver capabilities
# Author: Dmitry Baryshnikov, polimax@mail.ru
# Language: Python
#############################################... | nilq/baby-python | python |
# Copyright (c) 2016 Rackspace Hosting Inc.
#
# 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 t... | nilq/baby-python | python |
# coding: utf-8
# pylint: disable=W0201,C0111
from __future__ import division, unicode_literals, print_function
# standard library
import sys
import os.path
import time
import datetime
import traceback
from copy import deepcopy
from collections import OrderedDict
from itertools import cycle
from math import ceil
impor... | nilq/baby-python | python |
#
# Copyright (c) 2010 Testrepository Contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two lic... | nilq/baby-python | python |
import re
import h5py
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from os.path import join,exists
from os import listdir
from paper import paper
def html_reader(input_dir):
"""
read the html file at input_dir, ... | nilq/baby-python | python |
from .experiment import Experiment # noqa: F401
from .trial import Trial # noqa: F401
| nilq/baby-python | python |
import os
import argparse
import imageio
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True, type=str)
args = parser.parse_args()
for file in sorted(os.listdir(os.path.join('outputs', args.name, 'particles'))):
i = int(file.replace('.bin', ''))
print('frame %d' % i, flush=True)
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-20 14:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0014_add_indices'),
]
operations = [
migrations.AddIndex(
... | nilq/baby-python | python |
###########################################################
# compare.py -Script that compares any two painting's hex
# hex values for similarity or rank in the
# frequency list and quantifies it with a
# percentage
# Author: Shaedil Dider
###########################################... | nilq/baby-python | python |
from selenium import webdriver
from utils.logging import init_logger
from utils.s3_manager.manage import S3Manager
class SeleniumCrawler:
def __init__(self, base_url, bucket_name, key, head=False):
self.logger = init_logger()
self.bucket_name = bucket_name
self.s3_manager = S3Manager(buc... | nilq/baby-python | python |
from ._accuracy_per_cell_type import accuracy_per_cell_type
from ._cd_ratio import cd_ratio
from ._cumulative_node import cumulative_node
from ._cumulative_node_group import cumulative_node_group
from ._dists_distr import dists_distr
from ._mean_node_per_cell_type import mean_node_per_cell_type
from ._metric_heatmap im... | nilq/baby-python | python |
import socket
class Triton200:
"""
Create an instance of the Triton200 class.
Supported modes: IP
:param str ip_address: The IP address of the Triton 200.
:param int port_number: The associated port number of the Triton 200 (default: 33576)
:param int timeout: How long to wait for... | nilq/baby-python | python |
import random
import itertools
import json
import networkx as nx
import sys, getopt
import dcop_instance as dcop
def generate(G : nx.Graph, dsize = 2, p2=1.0, cost_range=(0, 10), def_cost = 0, int_cost=True, outfile='') :
assert (0.0 < p2 <= 1.0)
agts = {}
vars = {}
doms = {'0': list(range(0, dsize))}
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.