content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""
@brief: fill queue with new tasks read from tasks file.
"""
import pika
import sys
from .ip_provider import get_valid_ip
def create_new_tasks(fn,broker):
tasks=[]
with open(fn,"r") as f:
for line in f:
tasks.append(line)
connection = pika.BlockingConnection(pika.ConnectionParamet... | python |
'''
@file: MPNCOV.py
@author: Jiangtao Xie
@author: Peihua Li
Copyright (C) 2018 Peihua Li and Jiangtao Xie
All rights reserved.
'''
import torch
import numpy as np
from torch.autograd import Function
class Covpool(Function):
@staticmethod
def forward(ctx, input):
x = input
batchSize = x.... | python |
# Copyright 2013 Nebula 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 to... | python |
import pytest
from constants.pipelines import OperationStatuses, PipelineStatuses
from factories.factory_pipelines import OperationRunFactory
from pipelines.celery_task import ClassBasedTask, OperationTask
from polyaxon.celery_api import app as celery_app
from tests.utils import BaseTest
@pytest.mark.pipelines_mark
... | python |
import os
import pygame
from game_defines import DIRECTIONS
ASSET_BASE = os.path.join(os.path.dirname(__file__), "assets")
class Actor(object):
@staticmethod
def asset(name):
return os.path.join(ASSET_BASE, name)
def __init__(self, name, image_path, actor_type, startx, starty):
self... | python |
"""
File: 240.py
Title: Search a 2D Matrix II
Difficulty: Medium
URL: https://leetcode.com/problems/search-a-2d-matrix-ii/
"""
import unittest
from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(mat... | python |
# -*- coding: utf-8 -*-
"""
safedun-server
Created on Sun Oct 13 00:00:00 2019
Author: Adil Rahman
GitHub: https://github.com/adildsw/safedun-server
"""
import argparse
import socket
from backend import safedun
from flask import Flask, render_template, request, send_file
app = Flask(__name__)
@app.route('/')
def ... | python |
"""The Policy can use these classes to communicate with Vizier."""
import abc
import collections
import dataclasses
import datetime
from typing import Dict, Iterable, List, Optional
from vizier import pyvizier as vz
@dataclasses.dataclass(frozen=True)
class MetadataDelta:
"""Carries cumulative delta for a batch m... | python |
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^sponsor/$', views.sponsor, name='sponsor'),
url(r'^hospitality/$', views.hospitality, name='hospitality'),
url(r'^transport/$', views.tran... | python |
import numpy as np
import math
import pandas as pd
#######################################################################
"""
These functions are applied to hierarchically classify the images.
level_n(x): determines the prediction at level n. If there is no prediction to be made at level n, the function returns nan.... | python |
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .models import Choice, Question
# Create your views here.
class IndexView(generic.ListView):
template_name =... | python |
#!/usr/bin/env python
import sys
from os import listdir
def proc_files(files):
fs = []
for f in files:
try:
fs.append(open(f, "r"))
except Exception as exct:
print("Failed to read file {:s}".format(f))
sys.exit(1)
done = False
result = []
whil... | python |
"""Define language independent properties at the module level"""
from adam.language.lexicon import LexiconEntry, LexiconProperty
from adam.language.dependency import MorphosyntacticProperty
# Define universal morphosyntactic properties
FIRST_PERSON = MorphosyntacticProperty("1p")
SECOND_PERSON = MorphosyntacticPropert... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 16:31:59 2021
@author: msantamaria
"""
# Redes Neuronales Artificiales
# Parte 1 - Pre procesado de datos
# Importar las librerías
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importar el data set
dataset = pd.read_csv("Churn_Modelling.... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-01-29 08:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('codenerix_products', '0008_auto_20180126_1711'),
('... | python |
# %%
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
import matplotlib.pyplot as pl
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# %%
# Other type of file could be used which contains tabular data
advertising = pd.read_csv("a... | python |
# -*- coding: utf-8 -*-
from collections import OrderedDict
import os
import re
from lxml import etree
from django.db.models import Count, Prefetch
from selections.models import PreProcessFragment
from stats.utils import get_label_properties_from_cache, prepare_label_cache
from .models import Corpus, Tense, Alignm... | python |
from math import exp
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
# from kornia.color import rgb_to_yuv
from torch.nn.modules.loss import _Loss
import numpy as np
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)*... | python |
from rvsml.align import dtw2, OPW_w
from rvsml.EvaluateRVSML import EvaluateRVSML_dtw
from rvsml.NNClassifier import NNClassifier_dtw
from rvsml.RVSML_OT_Learning import RVSML_OT_Learning_dtw | python |
import sys
class Foobar:
def __init__(self, foobar="foobar"):
self.foobar = foobar
def __repr__(self):
return(self.foobar)
| python |
import os
import json
import requests
import telegram
def custom_alert_slack(message):
text = ""
text = "%s" % message
requests.post(os.getenv('SLACK_WEBHOOK'), data=json.dumps({"text": text}), headers={'Content-type': 'application/json'})
def publish_on_telegram_channel(chat_id, message, token=None, image=None):
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author Eric Bullen <ebullen@linkedin.com>
@application jtune.py
@version 4.0.1
@abstract This tool will give detailed information about the running
JVM in real-time. It produces useful information that can
further assist the user ... | python |
import os
base_dir = os.getcwd()
project_name = '{{cookiecutter.project_name}}'
project_path = f'{project_name}'
# https://github.com/cookiecutter/cookiecutter/issues/955
for root, dirs, files in os.walk(base_dir):
for filename in files:
# read file content
with open(os.path.join(root, filename)) ... | python |
import unittest
from parameterized import parameterized as p
from solns.combinationSum3.combinationSum3 import *
class UnitTest_CombinationSum3(unittest.TestCase):
@p.expand([
[]
])
def test_naive(self):
pass
| python |
import pymongo
class Database(object): # Database class inherits all attributes from object class
URI = "mongodb://127.0.0.1:27017" # class attributes which defines a value for every class instance
DATABASE = None
@staticmethod
def initialize(): # method that creates path to desired mongodb database... | python |
from talon import Context, actions
ctx = Context()
ctx.matches = r"""
app: mintty
"""
ctx.tags = ['terminal', 'user.file_manager', 'user.generic_terminal', 'user.git', 'user.kubectl']
@ctx.action_class('user')
class UserActions:
def file_manager_open_parent():
actions.insert('cd ..')
actions.key('e... | python |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from django.conf.urls import url
from . import views
# The API URLs are now determined automatically by the router
urlpatterns = [
url(r"^$", views.index, name="index_page"),
url(r"^projects/create$", views.project_creat... | python |
from flask import Flask, render_template
from flask_cors import CORS
from prometheus_client import Summary, MetricsHandler, Counter
from agaveflask.utils import AgaveApi, handle_error
from controllers import MetricsResource, CronResource
from errors import errors
app = Flask(__name__)
CORS(app)
api = AgaveApi(app, ... | python |
#!/usr/local/bin/python
import SimpleHTTPServer, SocketServer, logging, subprocess, sys, glob, re, mimetypes
import argparse as argparse
# Stop traceback on ctrl-c
sys.tracebacklimit = 0
parser = argparse.ArgumentParser()
parser.add_argument("-p", nargs='?', default=8000)
parser.add_argument("-d", nargs='?', defaul... | python |
import os
import time
import numpy as np
import paddle.fluid as fluid
import config as cfg
from nets.attention_model import attention_train_net
from nets.crnn_ctc_model import ctc_train_net
from utils import data_reader
from utils.utility import get_ctc_feeder_data, get_attention_feeder_data
def main():
"""OCR tr... | python |
#Importing Libraries
import os
import cv2
import time
import struct
import socket
import pyaudio
import freenect
import wikipedia
import playsound
import numpy as np
from gtts import gTTS
from scripts.rhino.rhino import *
from scripts.porcupine.porcupine import *
#Fucntion to get images
def get_image(type, client): ... | python |
from .publish_measurement_handler import PublishMeasurementTransactionHandler
from .issue_ggo_transaction_handler import IssueGGOTransactionHandler
from .transfer_ggo_handler import TransferGGOTransactionHandler
from .split_ggo_handler import SplitGGOTransactionHandler
from .retire_ggo_handler import RetireGGOTrans... | python |
__author__ = 'guorongxu'
import sys
import re
import math
import logging
def parse_correlation(correlation_file):
correlation_list = {}
with open(correlation_file) as fp:
lines = fp.readlines()
for line in lines:
fields = re.split(r'\t+', line)
correlation_list.update({... | python |
"""Create grid-based spatial indexes.
Basic Usage
===========
Calculate the grid index or indices for a geometry provided in
well-known binary format at a given resolution:
Example:
>>> from shapely.geometry import Point
>>> pnt = Point(555000, 185000)
>>> bng_pnt = calculate_bng_index(
wkb = pn... | python |
from enum import IntEnum
class Finger(IntEnum):
Thumb = 0
Index = 1
Middle = 2
Ring = 3
Little = 4
@staticmethod
def get_array_of_points(finger):
finger_array = None
if finger == Finger.Thumb:
finger_array = [(0, 4), (4, 3), (3, 2), (2, 1)]
elif fing... | python |
import torch
import os
import sys
import re
import logging
from os.path import isfile
import copy
import threading
import time
import enum
from torch.multiprocessing import Pool, Process, set_start_method, Manager, Value, Lock
try:
set_start_method('spawn')
except RuntimeError:
pass
class CFMode(enum.Enum):
MANU... | python |
""" Expose PV data """
#
# import logging
# from datetime import datetime, timedelta
# from typing import List
#
# from fastapi import APIRouter, Depends
# from nowcasting_datamodel.models import PVYield
# from nowcasting_datamodel.read.read_pv import get_latest_pv_yield, get_pv_systems
# from sqlalchemy.orm.session im... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class HostManagementConfig(AppConfig):
name = 'host_management'
| python |
import numpy as np
from scipy.io import readsav
class fts:
ll = None
ii = None
cc = None
nu = None
datafile = './fts_disk_center.idlsave'
def __init__(self):
# watt / (cm2 ster AA) as emitted at solar surface
t = readsav(self.datafile)
# convert to ... | python |
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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 ag... | python |
import discord
from itertools import cycle
from discord.ext import commands, tasks
status = cycle(['Add ur text here','ur text here','ur text here','ur text here']) # you can add as much as you want EX: 'Stiizzy cat is hot','Name'
bot = commands.Bot(command_prefix="!") # prefix will not be used for changng status
@... | python |
import logging
from datetime import datetime
from pprint import pprint
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import text
from opennem.db import db_connect
from opennem.db.load_fixtures import update_existing_geos
from opennem.db.models.opennem import Fac... | python |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
# from http://stackoverflow.com/questions/15896217/django-loading-a-page-that-
# has-external-authentication-changes-the-session-key
class PersistentSessionMiddleware(object):
""" Injects the username into REMOTE_USER so that ... | python |
# -*- coding: UTF-8 -*-
from mpi4py import MPI
from sympy import pi, cos, sin
from sympy.abc import x, y
from sympy.utilities.lambdify import implemented_function
import pytest
from sympde.calculus import grad, dot
from sympde.calculus import laplace
from sympde.topology import ScalarFunctionSpace
from sympde.topolog... | python |
# Solution of;
# Project Euler Problem 226: A Scoop of Blancmange
# https://projecteuler.net/problem=226
#
# The blancmange curve is the set of points $(x, y)$ such that $0 \le x \le 1$
# and $y = \sum \limits_{n = 0}^{\infty} {\dfrac{s(2^n x)}{2^n}}$, where
# $s(x)$ is the distance from $x$ to the nearest integer. ... | python |
from aiohttp import ClientSession
from asyncio import get_event_loop
class ManagedHTTP:
def __init__(self):
self.session = ClientSession()
async def ensure_session(self):
if self.session.closed:
self.session = ClientSession()
async def request(self, method: str, url: str, *ar... | python |
"""Test the functions exposed at the top level of the module.
This isn't a full test of each method's capabilities,
just checking that the method is exposed at the top level namespace.
"""
import warnings
import pytest
import uk_politics
import uk_politics.exceptions
def test_color():
"""Check that... | python |
# Copyright 2018 Google 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 to in writing, ... | python |
# Generated by Django 3.1.2 on 2020-10-25 14:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | python |
name = 'membercount'
aliases = ['members']
async def run(message):
'Lists the number of people that are in this server'
true_member_count = message.guild.member_count
await message.channel.send(
f'There are **{true_member_count:,}** people in this server.'
)
| python |
import subprocess as sp
import os
import shutil
import tempfile
import logging
logger = logging.getLogger(__name__)
class AutoLoader(object):
"""Base class for automatic loaders (e.g. Git)"""
pass
class Git(AutoLoader):
def __init__(self, url, import_as=None, branch=None):
"Creates a temporary di... | python |
"""Filex."""
import random
from utils import timex
MIN_INT, MAX_INT = 10 ** 15, 10 ** 16 - 1
def read(file_name):
"""Read."""
with open(file_name, 'r') as fin:
content = fin.read()
fin.close()
return content
def write(file_name, content, mode='w'):
"""Write."""
with open(f... | python |
# -*- coding: utf-8 -*-
"""
fudcon.ui
------
fudcon ui application package
"""
| python |
from enigma import eRect, eServiceReference, iServiceInformation, iPlayableService
from Screens.Screen import Screen
from Screens.ServiceInfo import ServiceInfoList, ServiceInfoListEntry
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Pixmap import Pixmap
from Components.Label import Label
f... | python |
'''
Content under Creative Commons Attribution license CC-BY 4.0,
code under MIT license (c)2018 Sergio Rojas (srojas@usb.ve)
http://en.wikipedia.org/wiki/MIT_License
http://creativecommons.org/licenses/by/4.0/
Created on march, 2018
Last Modified on: may 15, 2018
'''
def myfuncPrimeFactors(n):
"""
This f... | python |
import hashlib
from settings import SIZE
class Address:
def __init__(self, ip, port):
self.ip = ip
self.port = port
def __key(self):
return f"{self.ip}{self.port}".encode()
def __hash__(self):
"""
Python uses a random hash seed to prevent attackers from tar-pitti... | python |
# -*- coding:utf-8 -*-
import logging
from time import sleep
import bigsuds
from networkapi.plugins import exceptions as base_exceptions
from networkapi.system.facade import get_value as get_variable
log = logging.getLogger(__name__)
class Lb(object):
def __init__(self, hostname, username, password, session=T... | python |
import image, touch, gc, time
from machine import I2C
from board import board_info
from fpioa_manager import fm
from Maix import GPIO
import time
from machine import SPI
from micropython import const
from sx127x import SX127x
board_info=board_info()
i2c = I2C(I2C.I2C3, freq=1000*1000, scl=24, sda=27) # amigo
devices =... | python |
#!/usr/bin/env python
import boto3
import botocore
import argparse
import sys
parser = argparse.ArgumentParser(description='Check if the given AWS VPC exists.')
parser.add_argument('--region_name', dest='region_name', action='store', required=True, help='AWS Region name, e.g. eu-west-1')
parser.add_argument('--vpc_nam... | python |
def arrays(arr):
# complete this function
# use numpy.array
return(numpy.array(arr,float))[::-1]
| python |
# Copyright 2004-2018 Tom Rothamel <pytom@bishoujo.us>
#
# 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, m... | python |
# # -*- coding: utf-8 -*-
from collections import Counter
from tests.testapp.tests.base_tests import BaseRedisTestCase
from tests.testapp.tests.multi_server_tests import MultiServerTests
from django.test import TestCase, override_settings
LOCATION = "unix://:yadayada@/tmp/redis0.sock?db=15"
LOCATIONS = [
"unix:/... | python |
import os
import logging
# (windows only for now)
if os.name == 'nt':
try:
logging.info('Looking for CUDA and adding it to path...')
# some python versions fail to load the path variables, so we're doing it manually here before importing tf
loaddir = "C:/Program Files/NVIDIA GPU Comput... | python |
import os
import getpass
import hashlib
os.system('cls')
print("Done...")
if 'MainDrive' in os.listdir('.'):
os.rmdir("MainDrive")
os.mkdir('MainDrive/')
os.mkdir('MainDrive/Users/')
username = input("Username: ")
password = getpass.getpass("Password (No echo): ")
encp = password.encode()
d = hash... | python |
# -*- encoding: utf-8 -*-
"""
@File : Surprise_SGD.py
@Time : 2020/11/21 14:41
@Author : biao chen
@Email : 1259319710@qq.com
@Software: PyCharm
"""
from surprise import Dataset
from surprise import Reader
from surprise import BaselineOnly, KNNBasic
from surprise import accuracy
from surprise.model... | python |
########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. 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... | python |
#########################################################################
# Copyright/License Notice (Modified BSD License) #
#########################################################################
#########################################################################
# Copyright (c) 2008, Da... | python |
from .test_helper import argv_kiwi_tests
import sys
import mock
from mock import patch
import azurectl
from pytest import raises
from azurectl.commands.storage_account import StorageAccountTask
from azurectl.azurectl_exceptions import AzureInvalidCommand
class TestStorageAccountTask:
def setup(self):
sy... | python |
def mySqrt(x):
r = x
precision = 10 ** (-10)
print(precision)
while abs(x - r * r) > precision:
r = (r + x / r) / 2
return r
print(mySqrt(25))
print(mySqrt(36))
| python |
from restkit.handlers.http_mrg_handlers import query_handler as chandler_0 # noqa
from restkit.handlers.http_mrg_handlers.http_report_handlers import report_csv_handler as chandler_1 # noqa
__all__ = [
'chandler_0',
'chandler_1',
]
| python |
from dart_fss.api import filings
def test_get_corp_code():
res = filings.get_corp_code()
actual = res[0].keys()
expected = ['corp_code', 'corp_name', 'stock_code', 'modify_date']
for act in actual:
assert act in expected
def test_get_corp_info():
se = filings.get_corp_info('00126380')
... | python |
from urllib.parse import urlencode
import requests
from module_pipedrive.pipedrive import exceptions
from module_pipedrive.pipedrive.activities import Activities
from module_pipedrive.pipedrive.deals import Deals
from module_pipedrive.pipedrive.filters import Filters
from module_pipedrive.pipedrive.leads import Leads... | python |
#!/usr/bin/python
"""
Copyright (C) International Business Machines Corp., 2005
Author: Dan Smith <danms@us.ibm.com>
This program 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 Foundation; under version 2 of the Licen... | python |
r"""Analyze Traffic Images
This executable is used to annotate traffic images to highlight vehicle types and to produce stats
and graphs for the amount of time bicycle lanes and bus stops are blocked by vehicles:
Example usage:
./analyzeimages \
-path_images ./data/rawimages/
-path_labels_map dat... | python |
import json
import random
from locoloco.models.db_orm import db
from locoloco.models.db_models import User
from locoloco.models.db_models import Country
from locoloco.models.db_models import DistributionCenter
from locoloco.models.db_models import StoreStatus
from locoloco.models.db_models import Store
from locoloco.... | python |
from pdfrw import PdfObject, PdfReader, PdfWriter
import os
defaultlang = 'en-US'
#read all files in the folder called 'files'
files = os.listdir('files')
for file in files:
print(file)
fixlist = []
trailer = PdfReader('files\\'+file)
print("Lang: ",trailer.Root.Lang)
if trailer.Root.Lang == None:
fixlist.appe... | python |
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2021, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import oci
import os
from ads.common import utils
def api_keys(
oci_config: str = os.path.join(os.path.... | python |
import sys
def print_line(to_file=None):
if to_file:
print("--------------------------------------------------",
file=to_file)
else:
print("--------------------------------------------------")
def print_header():
print_line()
print("NAS Parallel Benchmark v3.2")
print... | python |
import asyncio
import os
from telethon import TelegramClient
TELETHON_SESSION_FILE: os.path = input("Please insert path to telethon session file: ")
API_ID: int = int(input("Please insert session api id: "))
API_HASH: str = input("Please insert session api hash: ")
TG_USERNAME_RECIPIENT: str = input(
"Please inse... | python |
import logging
from sklearn.dummy import DummyClassifier, DummyRegressor
from amlb.benchmark import TaskConfig
from amlb.data import Dataset
from amlb.results import save_predictions
from amlb.utils import Timer, unsparsify
log = logging.getLogger(__name__)
def run(dataset: Dataset, config: TaskConfig):
log.in... | python |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | python |
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Persons import Person, Persons
from PLC.Auth import Auth
class DeletePerson(Method):
"""
Mark an existing account as deleted.
Users and techs can only delete themselves. PIs can only delete
thems... | python |
#-------------------------------------------------------------------------------
#
# An abstract base class implementation of the ITemplateDataNameItem interface
# that looks for all specified values in its input context or optionally any of
# its sub-contexts and outputs a context containing all such values found.
... | python |
import itertools
import math
def Solution():
N: int
T = int(input("테스트 수행횟수 입력:")) # 갯수
for i in range(0, T):
N = int(input("입력데이터: "))
sData = str(input("값 추가 \n"))
ans = math.trunc(sortMaxMin(sData, N))
print(ans)
def sortMaxMin(inputData: str, N: int):
maxNumber : ... | python |
#!/usr/bin/python3
"""
We want to use quad trees to store an N x N boolean grid. Each cell in the grid
can only be true or false. The root node represents the whole grid. For each
node, it will be subdivided into four children nodes until the values in the
region it represents are all the same.
Each node has another t... | python |
#!/usr/bin/env python
# Small web app to allow a user to top up their personal PaperCut balance
# Add a custom URL to the PaperCut user web page, which is used by end users
# when they want to add credit to their PaperCut personal account. The url
# should refer to this small web app When the user clicks on the URL l... | python |
#!/usr/bin/python
#-*- coding: utf-8 -*-
from distutils.core import setup, Extension
import os
import sys
prefix = os.environ.get("prefix", "/usr")
from distutils.core import setup, Extension
import subprocess as S
setup(name="polkit",
version="1.0.2",
description="Python bindings for polkit-1",
l... | python |
"""
Loading data and events submodule.
"""
from ..signal import find_events
#from .eeg_preprocessing import *
import numpy as np
import pandas as pd
import mne
import os
# ==============================================================================
# =================================================================... | python |
import json
your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(type(your_json))
print(type(parsed))
#print(json.dumps(parsed, indent=4, sort_keys=True)) | python |
# Time complexity: O(n)
# Approach: Implementation using 2 arrays.
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.minStack = []
def push(self, val: int) -> None:
if len(self.minStack)==0:
self.s... | python |
from celery.utils.log import get_task_logger
from flask.ext.celery import Celery
from datetime import datetime, timedelta
import time
from app import app, db
from models import Agency, Prediction
from nextbus import Nextbus
"""
Celery is a task queue for background task processing. We're using it
for scheduled tasks, ... | python |
"""
Контекстный процессор для меню.
"""
from .utils import get_menus
def menu_processor(request):
"""
Контекстный процессор для возможности отображения всех меню на сайте.
Меню обычно распологаются на нескольких страницах, поэтому вынесено сюда.
"""
current_path = request.path
context = {
... | python |
from typing import Union
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch import Tensor
from .functions import ActivationModule
from activations.utils.utils import _get_auto_axis_layout
def tent_activation(x, delta):
"""
Functional implementation of TentActivati... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import numpy as np
import operator as op
from NumPyNet.exception import LayerError
from NumPyNet.utils import check_is_fitted
from NumPyNet.layers.base import BaseLayer
__author__ = ['Mattia Ceccarelli... | python |
try:
from libs.layers import *
from libs.utils_ft import *
except:
from layers import *
from utils_ft import *
import copy
import os
import sys
from collections import defaultdict
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn import MultiheadAtte... | python |
from django.conf.urls import url
from authen import views
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
url(r'^api/user/(?P<pk>[0-9]+)/$', views.person_detail),
url(r'^api/add_group/(?P<pk>[0-9]+)/$', views.add_group),
url(r'^api/user/$', views.person_list),
url(r'^$', vi... | python |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | python |
# Copyright (c) 2021, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import os
import unittest
import numpy as np
import torch
from warp_drive.managers.data_manager im... | python |
# Copyright (c) 2017 OpenStack Foundation.
#
# 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... | python |
import re
from model.contact import Contact
def test_contact_info_from_home_page(app, db):
app.navigation.open_home_page()
contact_from_home_page = sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
def clean(contact):
return Contact(id=contact.id, firstname=contact.firstname.strip(), ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.