content stringlengths 5 1.05M |
|---|
import json
import re
with open('armor_raw.json', 'r') as f:
armorjs = json.load(f)
newjson = {}
item_name = []
for armor in armorjs:
item_name.append(armor["name"].lower())
newjson.update(
{
armor["name"].lower() : {
'cost' : armor["cost"],
'weigh... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
from typing import Tuple, Callable
from stock_data_analysis_module.reinforcement_learning.deep_q.memory.agent_transitional_memory_abc import AgentTransitionMemoryABC
from stock_data_analysis_module.reinforcement_learning.deep_q.memory.circular_transitional_memory import CircularTransitionalMemory
from stock_data_ana... |
from hmmlearn import hmm
import numpy as np
from myPackage import kmeansSelection as kms
def train(num_clusters, labels):
# Make an HMM instance and execute fit
X = labels
# lengths = list(map(lambda x: len(x), X))
X = np.hstack(X)
X = X.reshape(len(X), 1)
n_iter = np.arange(10, 101... |
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
def get_profile():
# get the Firefox profile object
firefoxProfile = FirefoxProfile()
# Disable CSS
firefoxProfile.set_preference('permissions.default.stylesheet', 2)
# Disable images
firefoxPro... |
# Copyright 2020 Cloudbase Solutions Srl
# 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 r... |
from galaxy.managers.workflows import (
WorkflowSerializer,
WorkflowsManager,
)
from galaxy.webapps.galaxy.services.base import ServiceBase
from galaxy.webapps.galaxy.services.sharable import ShareableService
class WorkflowsService(ServiceBase):
def __init__(
self,
workflows_manager: Workf... |
# coding: utf-8
import tensorflow as tf
from concurrent.futures import ThreadPoolExecutor
from sgp4.io import twoline2rv
from sgp4.ext import jday
import datetime
from operator import attrgetter
import math
import numpy as np
import pandas as pd
import copy
class SpaceObjects(object):
"""Space objects to propaga... |
from pathlib import Path
from typing import *
from django.conf import settings
from django.utils.safestring import mark_safe
from PIL import Image
__all__ = [
"generate_image"
]
def generate_image(
url: str,
alt: str = "",
background_color: str = "rgba(0, 0, 0, 0)",
title: Option... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-10 22:10
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0002_auto_20160411_0049'),
]
operations = [
migra... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class DateRangePicker(Component):
"""A DateRangePicker component.
Capture date input from user. For more information, see: https://mantine.dev/dates/date-range-picker/
Keyword arguments:
- id (string; o... |
from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from posts.models import Post, Group
from django.urls import reverse
User = get_user_model()
class StaticURLTests(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.c... |
#All code in single file not cleaned
from mpi4py import MPI
import numpy as np
from numpy import zeros
import matplotlib.pyplot as plt
import time
start=time.time()
comm=MPI.COMM_WORLD
rank=comm.Get_rank()
nprocs=comm.Get_size()
size=nprocs
width=zeros(size,dtype=int)
N = 1000 #N and M are dimensions of 2D lattice... |
from param import *
import random
from Graph import MyQUEUE, BFS
import copy
task_allocation_record = {}
task_allocation = {}
each_agent_distance = {}
distance_total = 0
class InitStartGoal():
def __init__(self, agents, shelves, orderGoods, graph_nodes, graph):
self.agents = agents
self.shelves ... |
# 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
# Warning: do not change the path here. To use autodoc, you need to install the
# packa... |
#!/usr/bin/env python
# coding:utf-8
#################################################################################
# Copyright 2018 ROBOTIS CO., LTD.
#
# The robot moves in a straight line and stops when it encounters obstacles
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
# Python program to delete a node in a linked list at a position
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.... |
# this tells python we want to use the pyautogui library
import pyautogui
# **********************************************************************************************************************
# These are some global settings that pyautogui uses
# *********************************************************************... |
import requests
import configparser
import constants as c
import logging
log = logging.getLogger(__name__)
# parse configuration file
parser = configparser.ConfigParser()
parser.read(c.CONFIG_FILE_NAME)
options = parser["azure"]
ocr_url = options["ocr_url"]
subscription_key = options["subscription_key"]
def analyze(i... |
from server import server
server.port = 8521 # The default
server.launch() |
import feedparser
import re
from rasff_util import get_date
from rasff_util import get_notified
from rasff_util import get_packaged
from rasff_util import get_via
from rasff_util import get_origin
import pandas as pd
d = feedparser.parse("https://webgate.ec.europa.eu/rasff-window/consumers/?event=rss&country=all")
#pr... |
""" Pylint support. """
from os import path as op, environ
import logging
from pylama.lint import Linter as BaseLinter
CURDIR = op.abspath(op.dirname(__file__))
from astroid import MANAGER
from pylint.lint import Run
from pylint.reporters import BaseReporter
HOME_RCFILE = op.abspath(op.join(environ.get('HOME', ''),... |
import subprocess, gzip, datetime, glob, os, pickle, openpyxl, shutil
import pandas as pd
from pathlib import Path
from joblib import Parallel, delayed
## dereplication function to dereplicate a gzipped fasta file
def dereplication(file, project = None, comp_lvl = None, min_size = None):
"""Function to dereplicate... |
import pandas as pd
lego = pd.read_csv('data/lego_untidy.csv', index_col=0)
lego
# +
new = (lego.reset_index()
.melt(id_vars=['set_num'],
value_vars=['theme_id', 'num_parts'],
var_name="lego_info",
value_name="value")
.sort_values('set_num').set_index('set_num')
)
new... |
import numpy as np
import matplotlib.pyplot as plt
# var
L = 5
W = 5
# const var
pi = 3.1415926
# wave
A = 0.6
u = 343
v = 40000
_lambda = u / v
w = 2 * pi * v
k = 2 * pi / _lambda
T = 2 * pi / w
rho = 1.293
# translate into real distance
def r(x0, y0, x1=0, y1=0):
return np.sqrt((x0 - x1) ** 2 + (y0 - y1) ** ... |
"""
# Copyright 2022 Red Hat
#
# 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 agr... |
# Copyright 2019 Alibaba Cloud Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
# ----------------------------------------------------------------------
# Copyright (c) 2013-2016 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including... |
from hydraulics.elements import Element
from typing import List
class HSystem:
def __init__(self) -> None:
pass
def add_element(self, elm: Element) -> None:
pass
def get_elements(self) -> List[Element]:
pass
def simulate(self) -> List[str]:
pass
|
import torch.nn as nn
import torch.nn.functional as F
from pfrl.initializers import init_lecun_normal
class LinearBN(nn.Module):
"""Linear layer with BatchNormalization."""
def __init__(self, in_size, out_size):
super().__init__()
self.linear = nn.Linear(in_size, out_size)
self.bn = n... |
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
def flatten(nl):
integers = []
for i in nl:
if i.isInteger():
integers.append(i.getInteger())
else:
integers.extend(flatten(i.getList()))
... |
from .core import UnitedStates
from ..registry_tools import iso_register
@iso_register('US-DC')
class DistrictOfColumbia(UnitedStates):
"District of Columbia"
include_inauguration_day = True
FIXED_HOLIDAYS = UnitedStates.FIXED_HOLIDAYS + (
(4, 16, "Emancipation Day"),
)
|
"""Test terra wrapper."""
from anvil.util.reconciler import Reconciler
import logging
# logging.getLogger('anvil.test_terra').setLevel(logging.DEBUG)
logger = logging.getLogger('anvil.test_terra')
def test_reconciler_workspaces(user_project, namespaces, avro_path, terra_output_path, drs_output_path, project_pattern... |
import cv2
import ipywidgets as widgets
import warnings
from pypylon.genicam import LogicalErrorException
from pypylon import pylon
import numpy as np
import re
import os
import datetime
class BaslerOpenCVViewer:
"""Easy to use Jupyter notebook interface connecting Basler Pylon images grabbing with openCV image ... |
from . import views
from django.urls import path, include
urlpatterns = [
path('', views.browse, name="browse"),
path('<int:pk>/', views.trait_detail, name="trait_detail"),
path('<int:pk>/comment', views.comment, name="comment"),
path('<int:pk>/mapping', views.update_mapping, name='update_mapping'),
... |
#!/usr/bin/python
import pygame
from .spriteanimation import SpriteAnimation
class Characters(SpriteAnimation):
def __init__(self, initial_action, player_id):
"""Initiation of the player states"""
SpriteAnimation.__init__(self, initial_action)
self.pos = 1
self.pos2 = 1
sel... |
import random
from algorithm.Algorithm import Algorithm
def generate_test_data(length=200):
data = []
random_int = range(0, 2**12)
for i in (range(0, length)):
key = random.choice(random_int)
value = random.choice(['apple', 'banana', 'orange', 'apple', f'the number {i}'])
data.ap... |
import json
from datetime import datetime
from django.core.management.base import BaseCommand
from django.utils import timezone
from subscriptions.models import Subscription
from subscriptions.tasks import send_next_message
class Command(BaseCommand):
help = (
"This command is used when the subscription... |
#import gym
import numpy as np
from DDQNAgent import DDQNAgent
from puzzle import GameGrid
import matplotlib.pyplot as plt
import numpy as np
import json
def save_biggest_tiles(list, name):
unique, counts = np.unique(list, return_counts=True)
stats = str(dict(zip(unique, counts)))
with open(name, 'w') as ... |
n,k=input().split()
n=int(n)
k=int(k)
lista=[]
for i in range(n):
nome=input()
lista.append(nome)
lista.sort()
print(lista[k-1])
|
from .aggregatorConfig import RfaConfig
from .aggregatorUtils import RfaBackendUtils
import json
class RfaRackEnclosureChassisResources():
def __init__(self,rdr ):
self.rdr=rdr
self.rfaCfg=RfaConfig() # aggregatorConfig data
self.rfaUtils=RfaBackendUtils(rdr)
self.chassisResourc... |
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('',views.login,name='login'),
path('login/', views.login, name='login_success'),
path('login/check_vehicle_number', views.check_vehicle_number, name='check_vehic... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Cisco Systems, Inc. and others. 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... |
# -*- coding: utf-8 -*-
from raiden.transfer import channel
from raiden.transfer.architecture import TransitionResult
from raiden.transfer.mediated_transfer.state import TargetTransferState
from raiden.transfer.state_change import (
Block,
ReceiveUnlock,
)
from raiden.transfer.mediated_transfer.state_change imp... |
from fuzzy_asteroids.fuzzy_controller import *
from fuzzy_asteroids.fuzzy_asteroids import FuzzyAsteroidGame, Scenario
from src.controller import FuzzyController
if __name__ == "__main__":
# Available settings
settings = {
"frequency": 60,
"real_time_multiplier": 2,
"graphics_on": True... |
# coding: utf-8
# # Import Library and Load MNIST Data
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# # Define HyperParameters and Initialize them
learning_rate = 0.0001
epochs = 10
batch_size = 50
# # Declare t... |
similar_names_map = {
"start_date": "start_date",
"condition_start_date": "start_date",
"drug_exposure_start_date": "start_date",
"device_exposure_start_date": "start_date",
"measurement_date": "start_date",
"observation_date": "start_date",
"procedure_date": "start_date",
"specimen_date": "start_date",... |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url(r'^$',views.home,name='home'),
url(r'^new/post$', views.new_post, name='new-post'),
url(r'^profile/$',views.profile,name = 'NewProfile'),
url(r'^new_profile... |
from app.common.serializers import BaseModelSerializer
from ..models import News
class NewsSerializer(BaseModelSerializer):
class Meta:
model = News
fields = (
"id",
"created_at",
"updated_at",
"image",
"image_alt",
"title",
... |
from dearpygui.core import *
from dearpygui.simple import *
set_main_window_size(600, 600)
def callback(sender, data):
with window("Gerenciador de pagamento"):
valor = get_value("Preço das compras")
item = get_value("Opções")
parc = get_value("Parcelas")
if item == 0:
t... |
# Generates nth Fibonacci number (up to 10e9) given any f0 and f1, modulo (1e9 +7)
# firstly, initialise the 1,1,1,0 matrix to the power of 2^n for n up to 30, outside of the solve function
# this means we have the components needed to quickly (O(logn)) generate powers of the 1,1,1,0 matrix on the fly and don't have ... |
___assertIs(bool(10), True)
___assertIs(bool(1), True)
___assertIs(bool(-1), True)
___assertIs(bool(0), False)
___assertIs(bool("hello"), True)
___assertIs(bool(""), False)
___assertIs(bool(), False)
|
import cvarda.ext as cvarda
def test_mnv_common_end():
mnv_table = cvarda.MNVTable()
seq_table = cvarda.SequenceTable()
index = seq_table.insert("")
mnv_table.insert("chr1", 1, 4, 1, 1, index, 1)
mnv_table.insert("chr1", 2, 4, 1, 1, index, 2)
assert mnv_table.diagnostics() == \
{'ch... |
import json
import requests
DEFAULT_RESPONSE = {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps(
{
'message': 'success'
}
)
}
NOT_IMPLEMENTED_RESPONSE = {
'statusCode': 501,
'headers': {
'Content-Type':... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Modelisation of linear relations involved in the optimization problem
"""
import numpy as np
from numpy.polynomial import legendre
from numpy.linalg import multi_dot
from scipy.linalg import block_diag, null_space
from scipy.optimize import LinearConstraint
def get_... |
# -*- coding: utf-8 -*-
"""
file: wamp_services.py
WAMP service methods the module exposes.
"""
import os
import json
import logging
from twisted.internet import reactor
from autobahn.wamp.exception import ApplicationError
from graphit.graph_io.io_jsonschema_format import read_json_schema
from mdstudio.component.s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import random
import string
import sys
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.core.cache import cache
from django.test import RequestFactory
from django.urls import clear_url_cac... |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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... |
master = []
data = {}
ageSum = 0
while True:
print('-=-'*10)
data['Name'] = input('Name: ').strip().title()
data['Sex'] = input('Sex [M/F]: ').strip().upper()
while data['Sex'] != 'M' and data['Sex'] != 'F':
print('Invalid entry. Please type [M] or [F].')
data['Sex'] = input('Sex [M/F... |
__all__ = ['Parameters']
import six, re, json, copy
class ParametersArray(list):
def __init__(self):
pass
class ParametersKeys(object):
def __init__(self, key, Type='int', val=None,
enumItems=None, enumVals=None,
isArray=False, length=1,
default=None... |
# Listing_17-3.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Collision detection - bouncing beach balls off each other.
# Using a sprite group instead of a list
import sys, pygame
... |
from rtamt.operation.abstract_operation import AbstractOperation
class SinceOperation(AbstractOperation):
def __init__(self):
self.left = []
self.right = []
self.prev = -float("inf")
self.last = []
def update(self, *args, **kargs):
out = []
a = self.left + args[... |
import json
import logging
import nbformat
import cgi
from nbconvert.preprocessors import ExecutePreprocessor
from io import StringIO, BytesIO
import multipart as mp
from multipart import tob
import base64
import os
os.environ['PYTHONPATH'] = os.getcwd()
logger = logging.getLogger(__name__)
def execute_notebook(sour... |
import argparse
import os
from seldonite import embed, collect, nlp, run
from seldonite.sources import news
def main(args):
source = news.CSV(args.input)
collector = collect.Collector(source)
collector.limit_num_articles(10)
nl_processor = nlp.NLP(collector) \
.top_tfidf(20, load_path=args.tf... |
# Generated by Django 4.0.1 on 2022-06-10 23:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Sidebar',
fields=[
('id', models.BigAutoFie... |
# python3 theory/variadic_arguments.py
def example(a, b, *args, **kwargs):
print(args)
print(kwargs)
return a + b
print(example(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9,
money=True, pie="definitely", hello=3.3, SICKO=" mODe"))
def var_plus(*numbers):
result = 0
for number in numbers:
re... |
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from datetime import datetime, timezone, date, time, timedelta
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.views.generic.list import ListView
fr... |
"""Configurations export script for cli.
"""
import shutil
from .parse import parse
template = """# Pane Arrangement
{}
name: name
root: ~/
windows:
- panename:
layout: '{},{}'
panes:
{}
"""
def _generate_panes(layout_in, cols=None, lines=None):
if not (cols and lines):
cols, lines = shut... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import NamedTuple
class SquadMetrics(NamedTuple):
num_examples: int = 1
exact_matches: float = -1.0
f1_score: float = -1.0
def print_metrics(self) -> None:
print(f"Number of samples = {s... |
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
# x = -0.57860
def plot_func(y, start=-1, stop=0, steps=100):
func = sp.lambdify(_x, y)
xx = np.linspace(start, stop, steps)
yy = func(xx)
x_intersects = [float(r) for r in sp.solve(y, _x) if r.as_real_imag()[1] == 0]
x_inters... |
import time
from threading import *
from Crypto.NaCl import NaCl
from Protocol.LogicMessageFactory import packets
from Logic.Player import Player
class ClientConnection(Thread):
def __init__(self, client, addr):
super().__init__()
self.client = client
self.addr = addr
s... |
import json
import boto3
import inflect
def lambda_handler(event,context):
inflect_engine = inflect.engine()
number = inflect_engine.number_to_words(event['final_number'])
message = {"DelMeMessage": "The StepFunctions Result is %r" %number}
client = boto3.client('sns')
response = client.publish(
... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets,linear_model
from sklearn.metrics import mean_squared_error
diabetes= datasets.load_diabetes()
# print(diabetes.keys())
# dict_keys(['data', 'target', 'frame', 'DESCR', 'feature_names', 'data_filename', 'target_filename'])
# print(di... |
from django.conf import settings
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django import forms
from django.template import Context, Template
from django.dispatch import receiver
from django.db.models.signals import m2m_changed, post_save
from cabot3.plugins.models import ... |
import unittest
import numpy as np
from parameterized import parameterized
import relaxations.interval as iv
from relaxations.interval import Interval
from tests.RelaxationTestCase import RelaxationTestCase, sample_intervals
class TestIntervalSine(RelaxationTestCase):
@parameterized.expand([
[Interval(... |
from src.security.hash import generate
from colorama import Fore, Style
from dotenv import load_dotenv
import os
# This is the API initialization security
load_dotenv()
class Debug():
def Danger(self, message ):
self.message = message
print(Fore.RED + Style.BRIGHT + "[!]" + Fore.RESET , self.m... |
"""
stop_criteria_fn
custom_on_epoch_begin
custom_on_epoch_end
"""
import datetime, json5, os, pprint
from IPython import display
import pandas as pd
import gc, cv2
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LambdaCallback, ReduceLROnPlateau, Tensor... |
with open("ics.txt", "r") as file:
y=""
for line in file:
y+=line
print("y:"+y)
# xとyを比較して、差を表示する
# 一致した場合は、空文字
# 完全に違う場合は、y
def diff(x, y):
# 2文字以上で比較
# 比較対象の文字列のi-j
if(x in y):
y=y.replace(x, " "*len(x))
print("diff:" + y)
return y
x = "abc"
#y = "bbbaaab"
# 複数行に対応したい
# forで... |
# Generated by Django 2.1 on 2018-08-07 04:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('checkout', '0004_auto_20180807_0339'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='estimated_delivery',... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from registry import Registries
from .base_eval import BaseEval
@Registries.evaluation.register("mae")
class MAEEval(BaseEval):
def __init__(self, model:nn.modules):
super().__init__()
self.mode... |
from omnibus import Receiver
import config
from series import Series
from plot import Plotter
config.setup() # set up the series we want to plot
receiver = Receiver("") # subscribe to all channels
def update(): # gets called every frame
# read all the messages in the queue and no more (zero timeout)
whil... |
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis-python
#
# Most of this work is copyright (C) 2013-2018 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may ho... |
import tkinter as tk
infinity = 1000000000
class BinaryNode:
# Class-level drawing parameters.
node_radius = 10
x_spacing = 20
y_spacing = 20
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
# Drawing ... |
import io
from unittest import TestCase, mock
from header_printer import print_header
class TestPrinter(TestCase):
@mock.patch("sys.stdout", new_callable=io.StringIO)
def test_print_correct_header_text(self, mock_stdout):
# GIVEN the text to be displayed on the header.
header_text = "Some hea... |
import pandas
from decisionengine_modules.htcondor.sources import source
from decisionengine.framework.modules import Source
@Source.produces(startd_manifests=pandas.DataFrame)
class StartdManifests(source.ResourceManifests):
def acquire(self):
return {'startd_manifests': self.load()}
Source.describe(... |
"""
Author: Rayla Kurosaki
File: phase1_get_data.py
Description: This file contains the functionality to parse through and obtain
data from a Microsoft Excel Workbook.
"""
import __utils__ as utils
def get_talent_data(workbook):
"""
Creates a dictionary to store the number of type of talent dr... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import Autodesk
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
search_cats = UnwrapElement(IN[0])
search_ids = []
names = []
vag = []
for search_cat in search_cats:
search_ids.append(... |
from __future__ import unicode_literals
import json
import os
import shutil
import time
from random import randint
from requests_toolbelt import MultipartEncoder
from . import config
from .api_photo import get_image_size, stories_shaper
def download_story(self, filename, story_url, username):
path = "stories/{... |
"""
ado-ml-batch-train - machine_learning/utils.py
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
"""
import json
import os
from typing import Union
import azureml.core
import yaml
from azureml.core import Workspace
from azureml.core.authentication import (
InteractiveLo... |
from strategies.strategy_template import StrategyTemplate
import argparse
import numpy as np
import torch
import torch
import torch.nn as nn
class WeightedLoss(StrategyTemplate):
def get_parser(parser=None):
if parser is None: parser = argparse.ArgumentParser()
return parser
def __in... |
import numpy as np
class EpsilonGreedy:
"""
A behavior for managing exploration, using the epsilon-greedy algorithm.
"""
def __init__(self, epsilon_start, epsilon_min, epsilon_decay):
"""
Creates the behavior.
:param epsilon_start: The start value for epsilon.
:param ... |
# Copyright 2020 The Nod Team. 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... |
import constants
def get_item_with_lambda(sorted_seq, func):
first = 0
last = len(sorted_seq)-1
found = False
while first<=last:
midpoint = (first + last)//2
if func(sorted_seq[midpoint]) == 0:
return sorted_seq[midpoint]
else:
if func(sorted_seq[midpoi... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
import unittest
import numpy as np
from wyrm.types import Data
class TestData(unittest.TestCase):
def setUp(self):
self.data = np.arange(20).reshape(4, 5)
self.axes = [np.arange(4), np.arange(5)]
self.names = ['foo', 'bar']
self.units = ['u1', 'u2']
... |
import datetime
t = datetime.time(1, 2, 3, 4)
print(t)
print(t.replace(5, 6, 7, 8))
# インスタンスの操作ではなく、新しいインスタンスを返すらしい。インスタンスメソッドなのに。これはわかりづらい。
|
from flask import Flask, render_template, request, abort
import requests
import os
import json
app = Flask(__name__)
URL_BASE="https://api.pokemontcg.io/v1/"
URL_BASE2="https://api.clashroyale.com/v1/"
key="asdasd"
@app.route('/',methods=['GET'])
def inicio():
return render_template("index.html")
@app.route('/pokemo... |
import os
import signal
import sys
from builtins import id as identifier
from toga.command import CommandSet
from toga.handlers import wrapped_handler
from toga.platform import get_platform_factory
from toga.widgets.icon import Icon
from toga.window import Window
class MainWindow(Window):
_WINDOW_CLASS = 'MainWi... |
""".. include:: ../TUTORIAL.md""" # noqa: D400
import sys
from pathlib import Path
import toml
from typing_extensions import Final
# re-export
from .api import Repository # noqa: F401
# for pdoc to understand the include:: directive
__docformat__ = "restructuredtext"
__pkg_path__: Final[Path] = Path(sys.modules[_... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os.path
import re
import subprocess
from textwrap import dedent
import pytest
from pex.common import safe_open
from pex.pex import PEX
from pex.pex_bootstrapper import ensure_venv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.