content stringlengths 5 1.05M |
|---|
import pytest
from sivtools.data_structures import DotDict
def test_dotdict_get_item_by_key():
sample_dict = {}
sample_dict["item"] = "value"
my_dict = DotDict(sample_dict)
assert my_dict.item == "value"
def test_dotdict_nested():
inside_dict = {}
inside_dict["inner_item"] = "inner value"... |
# Copyright 2017 Alexandru Catrina
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import numpy as np
class ANN:
def __init__(self, type= None, optimizer = None, initial_W = 0):
self.layers = []
self.type = type
self.optimizer = optimizer
self.depth = 0
self.initial_W = initial_W
def add_layer(self, m, n, Activation):
self... |
# -*- coding: UTF-8 -*-
# Copyright 2014 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from __future__ import unicode_literals
def populate(p):
# Rapla (county)
p.county("Rapla", "")
p.municipality("Kehtna", "")
p.smallborough("Lelle", "")
p.smallborough("Eidapere", "")
p.sma... |
from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from bulletin_board_bot.dependencies import DIContainer
class DIContainerMiddleware(BaseMiddleware):
def __init__(self, container: DIContainer):
super().__init__()
self._container = container
async def on_pro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 1 19:02:42 2019
@author: zoescrewvala
"""
import os
import cartopy
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
import pandas as pd
import xarray as xr
#%% X-Y PLOT
#ds = Dataset(os.getcwd() + '/Output/si... |
# Generated by Django 3.0.6 on 2020-05-29 18:29
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('qualiCar_API', '0009_auto_20200529_1802'),
]
operations = [
migrations.AlterField(
... |
from django.shortcuts import render
from django.views import generic
# Create your views here or die
class MentorSettingsView(generic.TemplateView):
template_name = 'mentor/settings.html'
|
#!/usr/bin/env python
#
# NopSCADlib Copyright Chris Palmer 2018
# nop.head@gmail.com
# hydraraptor.blogspot.com
#
# This file is part of NopSCADlib.
#
# NopSCADlib is free software: you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundatio... |
import torch
import torch.nn as nn
from utils import transform_forward, transform_backward
def sqdist(X, Y):
assert X.size()[1] == Y.size()[1], 'dimensions do not match'
return ((X.reshape(X.size()[0], 1, X.size()[1])
- Y.reshape(1, Y.size()[0], Y.size()[1]))**2).sum(2)
class Constant(nn.Module... |
import numpy as np
import matplotlib.pyplot as plt
import msgpack
import os
from pathlib import Path
import argparse
plt.switch_backend('agg')
def file_load(indir, outdir, savefigbool, filename):
file_count = 0
current_path_name = Path().resolve()
Path('{}/output-figures'.format(current_path_name)).mkdi... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Official solution:
# https://leetcode.com/problems/sort-list/solution/
# Details on merge sort is inside
# Merge Sort
class Solution:
def sortList(self, head:... |
####################################
# File name: SiteScan_Image_Formatter_Source.py
# About: Embeds Drone Flight CSV GPS Info into Image Metadata/EXIF
# Version for Executable compilation
# Author: Geoff Taylor | Imagery & Remote Sensing Team | Esri
# Date created: 12/12/2019
# Date last modified: 1... |
import pygame
import random
import math
from userSession import userSession
"""
Pygame Pursuit-Evader Simulation
"""
"""
Stage 1: One human, one robot. Human is the pursuer and robot is the evader who aims to get a target from two possibilities.
Experiment set up: Record the EEG signals of the human pur... |
# ==============================================================================
# Copyright (c) 2018, Yamagishi Laboratory, National Institute of Informatics
# Author: Yusuke Yasuda (yasuda@nii.ac.jp)
# All rights reserved.
# ==============================================================================
""" """
imp... |
# Tutorial Kivy 002: Melhorando a aparência, personalizando widgets usando as
# Propriedades Kivy
# http://inclem.net/2019/12/18/kivy/kivy_tutorial_002_improving_appearance/
from kivy.app import App
from kivy.uix.label import Label
class YourApp(App):
def build(self):
# root_widget = Label()
# r... |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Tags: Math, Binary Search
分析:
不能用乘除、取模,剩下的只有加减和位运算。
(位运算中左移1位相当于"x2")
直观的方法是: 除数中不断减去被除数; 每次将被除数翻倍,以优化速度。(注意溢出判断)
'''
class Sol... |
import os
from collections import namedtuple
from subprocess import check_output
__all__ = ["Runtime", "get_runtimes"]
Runtime = namedtuple("Runtime", "name version path")
def get_runtimes(): # -> List[Runtime]
runtimes_l = check_output(["dotnet", "--list-runtimes"])
runtimes_l = runtimes_l.decode("utf8")... |
from threescale_api.utils import request2curl
def test_request2curl():
URL = "http://example.invalid"
HEADERS = {"X-Header": "this"}
HEADERS_STR = "-H 'X-Header: this'"
DATA = {'key': 'value'}
BODY_STR = "-d key=value"
request = _Request("GET", URL, None, None)
assert request2curl(request... |
# -*- coding: utf-8 -*-
import numpy as np
__all__ = ["get_latitude_lines", "get_longitude_lines"]
def get_latitude_lines(dlat=np.pi / 6, npts=1000, niter=100):
res = []
latlines = np.arange(-np.pi / 2, np.pi / 2, dlat)[1:]
for lat in latlines:
theta = lat
for n in range(niter):
... |
import time
import idiokit
from abusehelper.core import bot, utils
COLUMNS = ("first seen", "threat", "malware", "host", "url", "status", "registrar", "ip", "asn", "cc")
def _value_split(values):
results = set()
for value in values:
results = results | set([x for x in value.split("|") if x])
ret... |
import re
import datetime
from helpers.save_select_from_postgresql import save_pressure_to_postgresql
from helpers.analytics import analysis_result
from buttons import start_markup
from states import States
def pressure(update, context):
"""
take arm and pressure
prepare pressure data like ['180', '90']
... |
"""
Created on Mon Jul 26 17:23:16 2021
@author: Andile Jaden Mbele
"""
"""
1. first nested loop takes len(L1)*len(L2) steps
2. second loop takes at most len(L1) steps
3. Latter term overwhelmed by form term
4. O(len(L1)*len(L2))
"""
def intersect(L1, L2):
tmp = []
for e1 in L1:
for e2 in L2:
... |
import time
from datetime import date
from apscheduler.schedulers.background import BackgroundScheduler
import conf_keys
from job_conf_parser import job_conf_parser
from singleton import singleton
from loggingex import LOG_WARNING
@singleton
class job_center():
def __init__(self):
self._sched = None
... |
from probability_tree import BranchNode, LeafNode, parse_dict
def test_it_parses_leaf_node():
tree = parse_dict({"name": "leaf", "probability": 1.0, "conclusion": 1.0})
assert tree == LeafNode(name="leaf", probability=1.0, conclusion=1.0)
def test_it_parses_simple_tree():
tree = parse_dict(
{
... |
"""
To implement component value saving,
when component is created, the saved value should be loaded via `load_slicer_value`
and used as inital value for component's attr (e.g. `value`)
Then in each dashboard this component is used, a callback should be added
via `callback_slicer_state_saving` to save updates of the c... |
# Generated by Django 2.2.12 on 2021-03-28 08:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0002_auto_20210328_1538'),
]
operations = [
migrations.AddField(
model_name='siswa',
name='nama',... |
print('=' * 30)
print('\033[35m Simplex \033[m')
print('=' * 30)
totalCompra = produtosMais1000 = 0
nomeProdutoBarato = ''
precoProdutoBarato = 0
while True:
nomeProduto = str(input('\nNome do Produto: '))
preco = float(input('Preço: R$ '))
totalCompra += preco
if preco > 1000:
pro... |
# -*- coding: utf-8 -*-
from __future__ import division
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
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 restricti... |
from peewee import *
database = Proxy()
class UnknownField(object):
def __init__(self, *_, **__): pass
class BaseModel(Model):
class Meta:
database = database
class Example(BaseModel):
author_id = IntegerField(null=True)
message = TextField(null=True)
class Meta:
table_name =... |
""" Build tool that finds dependencies automatically for any language.
fabricate is a build tool that finds dependencies automatically for any
language. It's small and just works. No hidden stuff behind your back. It was
inspired by Bill McCloskey's make replacement, memoize, but fabricate works on
Windows as well as ... |
from collections import defaultdict
for _ in range(int(input())):
n = int(input())
ans = defaultdict(int)
j = 1
while j**2<=n:
ans[j**2]+=1
j+=1
i = 1
while i**3<=n:
ans[i**3]+=1
i+=1
print(len(ans)) |
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from mlbframe import db, models
import datetime
import os.path
db.drop_all()
db.create_all()
epoch = datetime.date(2017, 4, 1)
meta = models.Meta()
meta.last_updated = epoch
db.session.add(meta)
db.session.commit()
"""
if not os.p... |
# Not consistent with test passing
import numpy as np
import path_plan
from path_plan import compute_probability
from path_plan import model_polyfit
from numpy import interp
import sys
def main():
# Indian Road congress (INC)
V_lane_width = [2.0, 23.5]
# https://nptel.ac.in/content/storage2/courses/105101008/... |
"""Common definitions for GAN metrics."""
import hashlib
import os
import time
import numpy as np
import tensorflow as tf
import dnnlib
import dnnlib.tflib as tflib
from training import dataset, misc
# ----------------------------------------------------------------------------
# Base class for metrics.
class Met... |
import json
from ansiblemetrics.import_metrics import general_metrics, playbook_metrics, tasks_metrics
from flask import abort, jsonify
from api.defect_prediction import DefectPredictor
def list_all():
"""
This function responds to a request for /api/metrics/all (GET)
:return: a lists of metrics' names.
... |
import pickle
import json
import argparse
import cv2
import os
import numpy as np
import torch
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
import matplotlib.lines as lines
from tqdm import tqdm
import _init_paths
from datasets_rel.pytorch_misc import intersect... |
from flask import Flask, render_template, request
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
app = Flask(__name__)
def get_spreadsheet_data():
json_key = json.load(open('spreadsheet_credentials.json'))
scope = ['https://spreadsheets.google.com/feeds']
crede... |
from pydantic import BaseModel
class CodeBase(BaseModel):
key: str
code: str = None
class CodeCreate(CodeBase):
pass
class Code(CodeBase):
id: int
class Config:
orm_mode = True
class TransmitResponse(BaseModel):
success: bool
label: int = -1
|
import os
from behave import when, then, given
from helpers import aws_helper, emr_step_generator
@when("An emrfs '{step_type}' step is started on the ingest-hbase EMR cluster")
def step_impl(context, step_type):
s3_prefix = (
context.ingest_hbase_emrfs_prefix_override
if context.ingest_hbase_emrf... |
"""
This script will go through the commit logs for projects we dont have trace
links for [Moreno et al] and do our best to guess at them.
"""
import dulwich.repo
import re
import csv
from src.main import load_projects, load_repos, load_goldsets
import os.path
from src.utils import clone
projects = load_projects()
fo... |
from flask import json, jsonify
from datetime import datetime
laiks = datetime.now()
LOGFAILS = "chats.txt"
def lasi():
chata_rindas = []
with open(LOGFAILS, "r", encoding="utf-8") as f:
for rinda in f:
chata_rindas.append(json.loads(rinda))
return jsonify({"chats": chata_rindas})
... |
import allure
import pytest
from app import logger
from app.cli import pytestOption
from app.core.appium import AppiumService
from app.loader import Loader
procs = []
def pytest_addoption(parser):
op = pytestOption(parser)
# 配置文件
op.add_config_option()
# 运行设备:设备名,输入ios/android会选择默认的ios/android设备,未输入... |
from pytest import mark
from leetcode.uncommon_words_from_two_sentences import Solution
from . import read_csv
@mark.parametrize('a, b, expect', read_csv(__file__))
def test_two_sum(a, b, expect):
result = Solution().uncommonFromSentences(a, b)
assert set(result) == eval(expect)
|
# -*- coding: utf-8 -*-
# Copyright 2015 Donne Martin. 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. A copy of
# the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "lice... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE 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/lic... |
# Copyright (c) 2020 HAW Hamburg
#
# This file is subject to the terms and conditions of the MIT License. See the
# file LICENSE in the top level directory for more details.
# SPDX-License-Identifier: MIT
"""Simple helpers that can be useful with mm_pal."""
import serial.tools.list_ports
def serial_connect_wizard(... |
# Example:
# >>> nest(range(12),[2,2,3])
# [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
def nest(flat,levels):
'''Turn a flat list into a nested list, with a specified number of lists per nesting level.
Excess elements are silently ignored.'''
return _nest(flat,levels).next()
def _nest(flat,levels):... |
#Written by Owain using the proper OSRS quest dialogues
#13/08/18
from game.content.quest import Quest
from game.content.quest import QuestHandler
from game.content.quest import QuestReward
from game.item import ItemAssistant
from game.content.dialogueold import DialogueHandler
from game.content.skilling import Skilli... |
default_app_config = 'wshop.apps.dashboard.orders.config.OrdersDashboardConfig'
|
description = 'Tensile machine'
group = 'optional'
excludes = ['tensile']
tango_base = 'tango://dhcp02.ictrl.frm2.tum.de:10000/test/doli/'
devices = dict(
teload = device('nicos.devices.entangle.Actuator',
description = 'load value of the tensile machine',
tangodevice = tango_base + 'force',
... |
import cv2
import os
import numpy as np
# create a CLAHE with L channel(Contrast Limited Adaptive Histogram Equalization).
def pre_proc_CEH2(img):
img_lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
lab_planes = cv2.split(img_lab)
clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))
lab_planes[0] = c... |
__Author__ = "noduez"
'''Label控件演示'''
import tkinter as tk
top = tk.Tk()
label = tk.Label(top, text='Hello World')
label.pack()
tk.mainloop() |
#don't turn on display. It slow down the processing
import os
if 'DISPLAY' in os.environ:
del os.environ['DISPLAY']
import ROOT
import math
from tools.EventClassification import EventClassifier
from tools.KinematicsCalculator import KinematicsCalculator
from tools.SystematicsUniverse import GetAllSystematicsUniver... |
#
# Normalize YAML reports
#
from datetime import datetime
from itertools import groupby
import functools
import hashlib
import logging
import re
import string
import uuid
import yaml
log = logging.getLogger("normalize")
class UnsupportedTestError(Exception):
pass
test_name_mappings = {
"http_host": "ht... |
import collections
import random
import flowws
from flowws import Argument as Arg
import freud
import numpy as np
from .internal import ScaledMSE, ScaledMAE
CoarseSystem = collections.namedtuple('CoarseSystem',
['box', 'nlist', 'positions', 'types', 'type_names',
'child_positions', 'child_types', 'child_type_... |
import concurrent.futures
import argparse
import json
import sys
import os
from adb import adb_commands
from adb import sign_cryptography
from slugify import slugify
from functools import partial
def get_dirname_for_addr(addr):
return slugify(addr)
def get_device_info(args, signer, addr):
dirname = get_dirna... |
# Space: O(n)
# Time: O(n)
import collections
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
length1 = len(s1)
length2 = len(s2)
if length1 > length2: return False
if length2 == 0: return False
slow, fast = 0, 0
data = collections.Counter(s1)
... |
# -*- coding: utf-8
# Core
import pytest
# Models
from custom_auth_user.models import User
# Store
from custom_auth_user.user.store import UserStore
# Commands
from custom_auth_user.user.commands.register_command import register
@pytest.mark.django_db
class TestRegisterCommand():
@pytest.fixture
def user_... |
# -*- coding: utf-8 -*-
import scrapy
from kuan2.items import Kuan2Item
import re
import logging # 要先安装好
logging.basicConfig(filename='kuan.log', filemode='w', level=logging.WARNING,
format='%(asctime)s %(message)s', datefmt='%Y/%m/%d %I:%M:%S %p')
# https://juejin.im/post/5aee70105188256712786b7f... |
# DEPENDENCIES
import main
import functions
# LIBRARIES
import time
import winsound
import cv2 as cv
import numpy as np
from urllib.request import urlopen
import keyboard
from pynput.mouse import Button, Controller
import PySimpleGUI as sg
# VARIABLES
mouse = Controller()
delay = main.delay
image = f... |
import torch
from torch.nn import functional as F
def nll_loss(y_hat, y, reduce=True):
y_hat = y_hat.permute(0,2,1)
y = y.squeeze(-1)
loss = F.nll_loss(y_hat, y)
return loss
def test_loss():
yhat = torch.rand(16, 100, 54)
y = torch.rand(16, 100, 1)
loss = nll_loss(yhat, y.squeeze(-1)) |
# Generated by Django 3.2.7 on 2021-09-16 17:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('homepage', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='favorites',
name='name',
f... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-26 14:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webdike', '0011_auto_20171124_0641'),
]
operations = [
migrations.RemoveFie... |
import io
import json
from defang import defang
class MachinaeOutput:
@staticmethod
def get_formatter(format):
if format.upper() == "N":
return NormalOutput()
elif format.upper() == "J":
return JsonOutput()
elif format.upper() == "D":
return DotEscape... |
#!/usr/bin/python
import pyrfa
p = pyrfa.Pyrfa()
p.createConfigDb("./pyrfa.cfg")
p.setDebugMode(True)
p.acquireSession("Session1")
p.createOMMConsumer()
p.login()
print(p.directoryRequest())
|
x = input()
a= []
while x != '0':
a.append(x)
x = input()
print(a) |
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Imports
# ======================================================================================================================
from tempest_zigzag import cli
from click.t... |
from argparse import ArgumentParser
from path_helpers import path
from ._version import get_versions
#: ..versionadded:: 2.17
__version__ = get_versions()['version']
del get_versions
#: .. versionadded:: 2.13
MICRODROP_PARSER = ArgumentParser(description='MicroDrop: graphical user '
... |
#!/usr/bin/python -tt
# Project: Dropbox (Indigo Wire Networks)
# Filename: nornir_config_create
# claudia
# PyCharm
from __future__ import absolute_import, division, print_function
__author__ = "Claudia de Luna (claudia@indigowire.net)"
__version__ = ": 1.0 $"
__date__ = "7/30/18"
__copyright__ = "Copyright (c) 2018... |
import unittest
from logrec.dataprep.preprocessors.java import process_comments_and_str_literals
from logrec.dataprep.model.chars import OneLineCommentStart, NewLine, Quote, MultilineCommentStart, MultilineCommentEnd
# TODO write explanations with normal strings
from logrec.dataprep.model.containers import SplitCont... |
from django.urls import path
from . import views
urlpatterns = [
path("fileresponse/", views.file_response),
]
|
#!/usr/bin/env python3
"""
The goal of this module is to take the explicit qualified type information of
a set of functions as well as a call tree and to expand the type information
to include implicit type information. The following rules apply:
- A function with direct type X also has indirect type X
- A function... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 14:36:02 2021
@author: endocv2021@generalizationChallenge
"""
# import network
import os
import os.path as osp
import argparse
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
import skimage
from skimage import io
fro... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/result')
def result():
dict={'phy':50,'che':60,'maths':70,'OSAMA':6644}
return render_template('result.html', result=dict)
if __name__ == '__main__':
app.run(debug=True)
|
import re
discinfo = re.compile(r'Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).', re.ASCII)
def parse(s):
discs, npos, offset = zip(*[re.search(discinfo, line).groups() for line in s.split('\n')])
return [(n, d + o) for d, n, o in zip(map(int, discs), map(int, npos), map(int, offset))]... |
import re
with open('England.txt') as f:
data = f.read()
pat = re.compile(r"\{\{基礎情報 (.*?)\n\}\}", re.S)
baseInfo = '\n'.join(pat.findall(data))
print(baseInfo)
pat = re.compile(r"\|(.*?) = (.*)")
Info = pat.findall(baseInfo)
dic = {key: cont for key, cont in Info}
# print(dic)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .common import JsonObject
class TokenResponse(JsonObject):
def __init__(self, data):
super().__init__(data)
def __str__(self):
return f"TokenResponse(token={self.token}, renewToken={self.renewToken})"
|
from strategy.strategy import StrategyAbstract
from indicator.oscillator import Atr
class ESuperTrend(StrategyAbstract):
def apply_strategy(self) -> None:
self.data = self.data.copy()
atr = Atr(self.data, 'close')
self.data['e_atr'], _ = atr.compute(span=14, avg_type='ewm')
self.da... |
from flask import Blueprint
main = Blueprint('main', __name__)
import json
from engine import SentimentAnalysis
from flask import Flask, request
@main.route("/", methods = ['GET'])
def hello():
return "Hello World!"
@main.route('/predict/', methods = ['POST'])
def get_predict():
if request.method == 'POST':... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
"""
conn = MySQLdb.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd='',
db = 'test',
)
cursor = conn.cursor()
sql = "create table user(id int,name varchar(30),password varchar(30))"
cursor.execute(sql)
sql = "insert into user(id,name,p... |
import asyncio
import logging
async def safe_wrapper(c):
try:
return await c
except asyncio.CancelledError:
raise
except Exception as e:
logging.getLogger(__name__).error(f"Unhandled error in background task: {str(e)}", exc_info=True)
def safe_ensure_future(coro, *args, **kwargs)... |
# Generated by Django 2.0.7 on 2018-07-17 11:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_classified', '0002_auto_20180713_2158'),
]
operations = [
migrations.AlterField(
model_name='item',
name='is_a... |
import sys
sys.setrecursionlimit(10000000)
input=lambda : sys.stdin.readline().rstrip()
n,k,s=map(int,input().split())
ans=[10**9 if s!=10**9 else 10**9-1 for i in range(n)]
ans[:k]=[s for i in range(k)]
print(*ans)
|
# Merge Sort
# Like QuickSort, Merge Sort is a Divide and Conquer algorithm.
# It divides the input array into two halves, calls itself for the two halves,
# and then merges the two sorted halves. The merge() function is used for merging two halves.
# The merge(arr, l, m, r) is a key process that assumes that arr[l..m... |
from django.shortcuts import render, redirect, get_object_or_404, HttpResponse
from .models import Person, Documento
from .forms import PersonForm
from django.contrib.auth.decorators import login_required
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView, View
from django... |
# * Copyright (c) 2020-2021. Authors: see NOTICE file.
# *
# * Licensed under the GNU Lesser General Public License, Version 2.1 (the "License");
# * you may not use this file except in compliance with the License.
# * You may obtain a copy of the License at
# *
# * https://www.gnu.org/licenses/lgpl-2.1.txt... |
# -*- test-case-name: wokkel.test.test_delay -*-
#
# Copyright (c) Ralph Meijer.
# See LICENSE for details.
"""
Delayed Delivery.
Support for comunicating Delayed Delivery information as specified by
U{XEP-0203<http://xmpp.org/extensions/xep-0203.html>} and its predecessor
U{XEP-0091<http://xmpp.org/extensions/xep-00... |
# Generated by Django 2.1 on 2018-09-20 13:00
# Generated by Django 2.1 on 2018-09-20 12:41
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
def getData():
dataset = pd.read_csv('FUTURES MINUTE.txt', header = None)
dataset.columns = ['Date','time',"1. open","2. high",'3. low','4. close','5. volume']
dataset['date'] = dataset['Date'] +" "+ dataset['time']
dataset.drop('Date', axis=1, inplace=True)
dataset.drop('time', axis=1, inplace... |
"""
TODO
# Needs to connect to the DB to read
UserParameter=pgsql.get.pg.size[*-,-,hostname,-,dbname,schemaname, tablename],"$1"/pgsql_userdb_funcs.sh pg.size "$2" "$3" "$4" "$5"
# Needs to connect to the DB, and to get the table name
UserParameter=pgsql.get.pg.stat_table[*-,-,hostname,-,dbname,schemaname, tablename]... |
import threading
import time
from src.robot import Robot
import brickpi
#Initialize the interface
interface=brickpi.Interface()
interface.initialize()
NUMBER_OF_PARTICLES = None
OFFSET = 100
DISTANCE_TO_PIXEL = 15
#Draw the square
print "drawLine:" + str((OFFSET,OFFSET,40*DISTANCE_TO_PIXEL+OFFSET,OFFSET))
print "dr... |
"""
GMail! Woo!
"""
__title__ = 'gmail'
__version__ = '0.1'
__author__ = 'Charlie Guo'
__build__ = 0x0001
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2013 Charlie Guo'
from .gmail import Gmail
from .mailbox import Mailbox
from .message import Message
from .utils import login, authenticate
|
#!/usr/bin/env python3
import socket
import threading
import queue
import random
import time
# Config
HOST = "example.com"
PORT = 6667
NICK = "bot"
CHANS = ["#test"]
OPS = ["me"]
DEBUG = True
FORTUNES = open("fortunes.txt", "r").read().strip().split("\n")
DELAY = 0.1 # reading & sending new messages
# Handlers
def h... |
from common.tests.core import SimpleTestCase
from search.factories import SuggestionLogFactory
from search.models.suggestion import SuggestionLog
class QueryDataTestCase(SimpleTestCase):
def setUp(self):
self.login_user()
def tearDown(self):
SuggestionLog.objects.all().delete()
def call_... |
from decouple import config
from flask import Flask, render_template
from .models import DB, User, Tweet # imports our DB from models.py
# Make our "app factory" (app-creator) function:
def create_app():
"""
Create and configure an instance of the Flask application.
"""
app = Flask(__name__)
# A... |
import random
class Instances(object):
"""docstring for Instances"""
def __init__(self):
super(Instances, self).__init__()
self.clases = []
self.columnas = []
self.columnaTipo = {}
self.instances = []
def setClases(self, clasesPar):
self.clases = list(clasesPar)
def addClase(self, clase):
self.clase... |
from unittest import TestCase
from tests import get_data
from pytezos.michelson.micheline import michelson_to_micheline
from pytezos.michelson.formatter import micheline_to_michelson
class MichelsonCodingTestKT1G39(TestCase):
def setUp(self):
self.maxDiff = None
def test_michelson_parse_code_KT... |
from django.conf import settings
from django.core.files.storage import Storage
from meiduo_mall.settings.dev import FDFS_BASE_URL
class FastDFSStorage(Storage):
'''自定义文件存储类'''
def __init__(self, fdfs_base_url=None):
# if not fdfs_base_url:
# self.fdfs_base_url = settings.FDFS_BASE_URL
... |
# Copyright 2019 Google 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 law or a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.