content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class MonolithicTest(unittest.TestCase):
def _steps(self):
for name in dir(self):
if name.startswith("step"):
yield name, getattr(self, name)
def assertBrowserTitle(... | nilq/baby-python | python |
import json
from .measurementGroup import MeasurementGroup
from .measurementItem import MeasurementItem
from .codeSequences import CodeSequence
class MeasurementReport(object):
"""
Data structure plus convenience methods to create measurment reports following
the required format to be processed by the DCMQI tid... | nilq/baby-python | python |
from setuptools import setup, find_packages
setup(
name='pyhindsight',
packages=find_packages(),
include_package_data=True,
scripts=['hindsight.py', 'hindsight_gui.py'],
version='2.0.4',
description='Internet history forensics for Google Chrome/Chromium',
url='https://github.com/obsidianforensics/hindsigh... | nilq/baby-python | python |
from bs4 import BeautifulSoup
import requests
import re
# function to get all the policy urls from a website
def collect_url_links(url_link) -> list:
url_list = []
pattern = re.compile(r'^http')
source = requests.get(url_link).text
soup = BeautifulSoup(source, 'lxml')
a_tag = soup.find_all("a") ... | nilq/baby-python | python |
def diamond(n):
"""Display a diamond made of *.
Args:
n: (int) Amount of *s in the middle row.
Returns:
Diamond shaped text. None if input n is invalid.
"""
if n <= 0 or n % 2 == 0:
return None
offset = int((n - 1)/2)
# for i in range(offset + 1):
# shap... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 04 20:05:13 2015
Translation of octave code for CSAPS.
@author: Kevin
"""
import numpy as np
import scipy as sp
from scipy import interpolate
from scipy.sparse import linalg
def csaps(x, y, p, xi=[], w=[]):
# sort the inputs by ordering of x
ii = np.argsort(x)... | nilq/baby-python | python |
__pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x09\x00\x61\x0d\x0d\x0a\x08\x2d\xa0\x01\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\x36\x1e\x00\x00\x00\x00\x00\x10\x12\xd8\xc1\xe3\xd7\xa8\xd7\xd4\xb7\xb9\xae\x4c\x5b\x3c\xd7\x05\x00\x00\x00\x00\x00\x00\x00\x00\x78\x44\x98\xc9\x9e\xe4\x19\x... | nilq/baby-python | python |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import types
from recipe_engine.config import (
config_item_context, ConfigGroup, Single, Static)
from recipe_engine.config_types import Path
from . imp... | nilq/baby-python | python |
"""Test entry point"""
import aiohttp
import pyoctoprintapi
import argparse
import asyncio
import logging
from types import MappingProxyType
LOGGER = logging.getLogger(__name__)
async def main(host, user, port, use_ssl):
"""Main function."""
LOGGER.info("Starting octoprint")
async with aiohttp.ClientSe... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of CERN Search.
# Copyright (C) 2018-2021 CERN.
#
# Citadel Search is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Signal Receivers."""
from flask import current_app
fro... | nilq/baby-python | python |
from pyrosetta import *
from roseasy.movers import constraint
def insert_alas(pose, position, length, insert_after=True, reset_fold_tree=True, fold_tree_root=1):
'''Insert a poly-ALA peptide before or after a given position.,
Set the fold tree to have a cutpoint before or after inserted residues.
Author: X... | nilq/baby-python | python |
#!/usr/bin/env python3
a, b, c, d = map(int, open(0).read().split())
print(abs(a-c) + abs(b-d) + 1) | nilq/baby-python | python |
"""
Generate matched synthetic lesions dataset
Authors: Chris Foulon & Michel Thiebaut de Scotten
"""
import os
import argparse
import random
import numpy as np
import json
import csv
import nibabel as nib
import nilearn
from nilearn.masking import compute_multi_background_mask, intersect_masks
from nilearn.image imp... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# !/usr/bin/python
"""
Created on Mar 18th 10:58:37 2016
train a continuous-time sequential model
@author: hongyuan
"""
import pickle
import time
import numpy
import theano
from theano import sandbox
import theano.tensor as tensor
import os
import sys
#import scipy.io
from collections import ... | nilq/baby-python | python |
from os import getenv
from rockset import Client, Q, F
rs = Client(api_key=getenv('ROCKSET_SECRET'), api_server='api.rs2.usw2.rockset.com')
def after_req(response):
cnt = rs.sql(
Q('NewsArchivesHits').where(F['_id']=='News').select('count')
)[0]['count']
rs.Collection.retrieve('NewsArchive... | nilq/baby-python | python |
from datetime import datetime
from pydantic import BaseModel
from pydantic import Field
class TodoCreate(BaseModel):
title: str = Field(..., min_length=4, max_length=50, example="My first task")
class Todo(TodoCreate):
id: int = Field(...)
is_done: bool = Field(default=False)
created_at: datetime =... | nilq/baby-python | python |
#!/usr/bin/env python3
'''
Copyright 2018, VDMS
Licensed under the terms of the BSD 2-clause license. See LICENSE file for terms.
/sapi/modify endpoint. Designed to initiate a sapi API user.
```swagger-yaml
/custdashboard/modify/{dash_id}/ :
get:
description: |
Modifies a custom audit by either adding, r... | nilq/baby-python | python |
import click
import os
from click.exceptions import ClickException
from .dashboard import read_har_json, plot_har
@click.command()
@click.argument('path', type=click.Path(exists=True))
def plot(path):
"""
Plot HTTP Archive format Timings
:param path: Path containing HAR specs in json files
... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
DQMStore = cms.Service("DQMStore",
enableMultiThread = cms.untracked.bool(True),
saveByLumi = cms.untracked.bool(False),
trackME = cms.untracked.string(''),
verbose = cms.untracked.int32(0)
)
| nilq/baby-python | python |
import sys
import math
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
class QFT:
"""
Class which generates the circuit to perform the Quantum Fourier
Transform (or its inverse) as described in Mike & Ike Chapter 5.
(Michael A Nielsen and Isaac L Chuang. Quant... | nilq/baby-python | python |
from breezycreate2 import _Create2
import time
# A simple melody that plays every time the bot is connected to.
MELODY = [('C4',11,0.3),
('C4',11,0.3),
('C4',11,0.3),
('C4',32,0.7),
('G4',32,0.7),
('F4',11,0.3),
('E4',11,0.3),
('D4',11... | nilq/baby-python | python |
"""
This network is build on top of SNGAN network implementation from: https://github.com/MingtaoGuo/sngan_projection_TensorFlow.git
"""
from explainer.ops import *
from tensorflow.contrib.layers import flatten
import pdb
def get_embedding_size():
return [64, 64, 4]
class Generator_Encoder_Decoder:
def __in... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from Speak import JLing_Speak
import sys
if __name__ == '__main__':
print('''
********************************************************
* JLing - 中文语音对话机器人 *
* (c) 2019 周定坤 <zhoudk@ccitrobot.com> *
*****************************************... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-17 16:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0020_image_name'),
]
operations = [
migrations.AlterUniqueTogether(
... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
# build_path is mandatory, build_all is optional.
if len(sys.argv) < 2:
print "usage: %s [build_path> [build_all]" % sys.argv[0]
sys.exit(1)
# Build all is by default False.
build_all = False
if len(sys.argv) == 3 and sys.argv[2] == 'build_all':
build_all = True
build... | nilq/baby-python | python |
from django.shortcuts import get_object_or_404
from rest_framework import generics
from mangacache.models import Chapter, Manga, Author
from mangacache.serializers import AuthorSerializer, MangaSerializer, ChapterSerializer
class AuthorList(generics.ListCreateAPIView):
queryset = Author.objects.all()
seriali... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Small utility script to simplify generating bindings"""
import argparse
import os
import subprocess
import sys
SCRIPT_DIR = os.pat... | nilq/baby-python | python |
import argparse
import logging
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import TCPServer
class LoggingHandler(SimpleHTTPRequestHandler):
def log_message(self, format, *args):
logging.info(format % args)
def webserve():
parser = argparse.ArgumentParser(
d... | nilq/baby-python | python |
#Based on paper Predicting Protein-Protein Interactions by Combing Various Sequence- Derived Features into the General Form of Chou’s Pseudo Amino Acid Composition by Zhao, Ma, and Yin
import os
import sys
#add parent and grandparent to path
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os... | nilq/baby-python | python |
load("//tools/base/bazel:bazel.bzl", "iml_module")
load("//tools/base/bazel:kotlin.bzl", "kotlin_test")
load("//tools/base/bazel:maven.bzl", "maven_java_library", "maven_pom")
load("//tools/base/bazel:utils.bzl", "fileset", "flat_archive")
load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
load("//tools/base... | nilq/baby-python | python |
import sncosmo
from astropy.cosmology import w0waCDM
import numpy as np
from lsst.sims.catUtils.dust import EBV
import os
from scipy.interpolate import griddata
from sn_tools.sn_telescope import Telescope
from lsst.sims.photUtils import Bandpass, Sed
from astropy import units as u
import pandas as pd
from sn_tools.sn_i... | nilq/baby-python | python |
from random import randint
from tools.population_creator import (ImpossibleToCompleteError, Individual,
create_individual)
def mutation(individual: Individual):
"""
:param individual: особь
:return: возвращает мутировавшую особь
Для мутации хромосомы сначала с ... | nilq/baby-python | python |
import os
from django.conf import settings
from pdf2image import convert_from_path
class PdfRasterizer:
def __init__(self):
self._dpi = settings.PDF_RASTERIZER["dpi"]
self._fmt = settings.PDF_RASTERIZER["format"]
self._thread_count = settings.PDF_RASTERIZER["thread_count"]
def raster... | nilq/baby-python | python |
'''
This downloads the data about which locations Twitter provide top the top 10
trending item lists from and stores the data in the database
'''
from TrendAnalyser import TrendAnalyser
TA = TrendAnalyser()
print TA._update_woeid_data()
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
tests - helper functions
~~~~~~~~~~~~~~~~~~~~~~~~
test cases for olaf helper function
:copyright: (c) 2015 by Vivek R.
:license: BSD, see LICENSE for more details.
"""
import os
import random
import string
import unittest
from click.testing import CliRunner
import olaf
class Test... | nilq/baby-python | python |
import random
from timeit import default_timer as timer
from clkhash.key_derivation import generate_key_lists
from clkhash.schema import get_schema_types
from clkhash.bloomfilter import calculate_bloom_filters
from clkhash.randomnames import NameList
from anonlink.entitymatch import *
from anonlink.util import popcou... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from conf.config import *
import ssl
import socket
import os
class Tool:
def __init__(self):
self.description = "Get the SSL certificate information"
self.options = {
'domain': {
"value": "",
"required": Tru... | nilq/baby-python | python |
"""This module is a wrapper for the PuLP library, which is capable of
solving LP/MILP instances by using different kinds of solvers (like Gurobi or CBC).
The wrapper defines custom MILP and LP classes in order to simplify the instantiation of
problems from coefficient vectors and matrices."""
from .solverresult impor... | nilq/baby-python | python |
# Copyright 2022 Masatoshi Suzuki (@singletongue)
#
# 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... | nilq/baby-python | python |
#!/usr/bin/python2
import sys
import math
import socket
import random
import time
import errno
# put-get flag to service success
def service_up():
print("[service is worked] - 101")
exit(101)
# service is available (available tcp connect) but protocol wrong could not put/get flag
def service_corrupt():
p... | nilq/baby-python | python |
from django.urls import path
from . import views
app_name = 'sqds_officers'
urlpatterns = [
path('<str:api_id>/geotb/', views.GeoTBPlayerView.as_view(), name='geo_tb'),
path('<str:api_id>/sepfarm/', views.SepFarmProgressView.as_view(), name='sep_farm')
]
| nilq/baby-python | python |
import cv2
def undistort_image(img, mtx, dist):
'''
Undistorts image given a camera matrix and distortion coefficients
'''
undist_img = cv2.undistort(img, mtx, dist, None, mtx)
return undist_img
| nilq/baby-python | python |
lista_inteiros = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[9, 1, 8, 9, 9, 7, 2, 1, 6, 8],
[1, 3, 2, 2, 8, 6, 5, 9,6, 7],
[3, 8, 2, 8, 6, 7, 7, 3, 1, 9],
[4, 8, 8, 8, 5, 1, 10, 3, 1, 7],
[1, 3, 7, 2, 2, 1, 5, 1, 9, 9],
[10, 2, 2, 1, 3, 5, 1, 9, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
]
def encont... | nilq/baby-python | python |
# Copyright 2015-2018 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from ..azure_common import BaseTest, arm_template, cassette_name
from c7n_azure.resources.key_vault import (KeyVaultUpdateAccessPolicyAction, WhiteListFilter,
... | nilq/baby-python | python |
from django.apps import AppConfig
class ScalprumConfig(AppConfig):
name = 'scalprum'
| nilq/baby-python | python |
from typing import cast
import pytest
from parse import compile
from json import dumps as jsondumps
from behave.model import Table, Row
from grizzly.context import GrizzlyContext
from grizzly.types import RequestMethod, RequestDirection
from grizzly.tasks import TransformerTask, LogMessage, WaitTask
from grizzly.tas... | nilq/baby-python | python |
from enum import Enum
from parse import parse
from datetime import datetime
import json
class CDFLogType(Enum):
NEW_COREHDF_INSTANCE = 1
PERSON_DETECTED = 2
NOTHING_DETECTED = 3
CANNOT_BE_INFERRED = 4
class CDFLog:
def __init__(self, logfile: str = 'log.txt'):
self.file_handler = open(lo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
NAME: github-reqs.py
AUTHOR: Ulyouth
VERSION: 1.0.0
DATE: 15.10.2020
DESC: A PyBullet-based script to check which GitHub logins are valid
using requests library.
"""
from chkutils import ChkUtils
def chkMain(ss, test, rst, captcha, data):
# Good pract... | nilq/baby-python | python |
def build_nn(params):
seq_length, vocabulary_size, layers, embedding_dim, upside_dim, downside_dim, lr, dropout = \
params['seq_length'], params['vocabulary_size'], params['layers'], params['embedding_dim'], params['upside_dim'], params['downside_dim'], params['lr'], params['dropout']
from tensorflow.k... | nilq/baby-python | python |
import numpy as np
from keras.datasets import cifar10
from keras.models import Sequential, Model
from keras.layers import Input, Dense, LeakyReLU, BatchNormalization, ReLU
from keras.layers import Conv2D, Conv2DTranspose, Reshape, Flatten
from keras.optimizers import Adam
from keras import initializers
from keras.utils... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
import glob
import hashlib
import itertools
sys.path.insert(0, os.pardir)
from testing_harness import PyAPITestHarness
import openmc
class TallySliceMergeTestHarness(PyAPITestHarness):
def _build_inputs(self):
# The summary.h5 file needs to be created to read i... | nilq/baby-python | python |
from onnxquantizer import Quantizer
import config as cfg
import os
import cv2
import numpy as np
def prehandle(img_path, dst_size):
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
resized = cv2.resize(img, dsize=(dst_size[1], dst_size[0]), interpolation=cv2.INTER_LINEAR)
return resized
def main():
#l... | nilq/baby-python | python |
import logging
import logging.config
def configure_logging(config, disable_existing=False):
"""
Set up (process-global!) loggers according to given app configuration.
Look for 'logging' key in [app] config section, which should be the path to
a logging config file in the format expected by logging.co... | nilq/baby-python | python |
# A simple demo of the mesh manager.
# Generates and renders a single tile with some ferns and trees
#
# INSTRUCTIONS:
#
# Launch from outside terrain, meaning launch with:
# python terrain/meshManager/main.py
import sys
sys.path.append(".")
from panda3d.core import *
from panda3d.core import Light,AmbientLight,Dire... | nilq/baby-python | python |
import os
import re
import discord
from discord import MessageType
from discord.commands import slash_command, Option, message_command
from discord.ext import commands
from sqlalchemy import desc
from . import XpSys
import PictureCreator
from PictureCreator.utils import ConvrterToCI
from models.Emojies import Emojie
f... | nilq/baby-python | python |
config = {
"--beam-delta":[0.5,float],
"--delta":[0.000976562,float],
"--determinize-lattice":['true',str],
"--hash-ratio":[2,float],
"--minimize":['false',str],
"--phone-determinize":['true',str],
"--prune-interval":[25,int],
... | nilq/baby-python | python |
import socket
from unittest import TestCase
from ..subprocess_server_manager import SubprocessServerManager, SubprocessServer
from ..exceptions import ImproperlyConfigured
class BaseSocketTestCase(TestCase):
@ staticmethod
def get(host: str, port: int) -> bytes:
with socket.socket(socket.AF_INET, sock... | nilq/baby-python | python |
from builtins import zip
from builtins import range
from builtins import object
import os
import numpy as np
import warnings
import matplotlib.pyplot as plt
import rubin_sim.maf.utils as utils
__all__ = ['applyZPNorm', 'PlotHandler', 'BasePlotter']
def applyZPNorm(metricValue, plotDict):
if 'zp' in plotDict:
... | nilq/baby-python | python |
'''
Created on Jan, 2017
@author: hugo
'''
from __future__ import absolute_import
import multiprocessing
from gensim.models import Doc2Vec
class MyDoc2Vec(object):
def __init__(self, dim, hs=0, window=5, negative=5, epoches=5, dm=1, dm_concat=1):
super(MyDoc2Vec, self).__init__()
self.dim = dim
... | nilq/baby-python | python |
# -*- coding: utf-8-*-
import random
import re
import sys
sys.path.append('/home/pi/Desktop/autoh/Lights')
from serial_led import serialControl
WORDS = ["TURN", "THE", "LIGHT", "ON"]
def lightno(mic):
text=mic.activeListen()
if text=="ONE" or text=="1":
mic.say("Turning light one on")
serialControl("2000")
e... | nilq/baby-python | python |
#!/usr/bin/python3
# Copyright 2022 Sam Steele
#
# 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... | nilq/baby-python | python |
import copy
import enum
import logging
from pathlib import Path
import re
__version__ = "0.0.9"
__author__ = "rigodron, algoflash, GGLinnk"
__license__ = "MIT"
__status__ = "developpement"
# raised when the action replay ini file contains a bad formated entry
class InvalidIniFileEntryError(Exception): pass
# raised... | nilq/baby-python | python |
# unittest for cal.py
import unittest
import cal
class TestCal(unittest.TestCase):
def test_add(self):
result = cal.add(10,5)
self.assertEqual(result, 15)
if __name__ == '__main__':
unittest.main()
# to avoid using this if statement below; run python -m unittest test_cal.py
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayEcapiprodDrawndnContractGetResponse(AlipayResponse):
def __init__(self):
super(AlipayEcapiprodDrawndnContractGetResponse, self).__init__()
self._contract_conten... | nilq/baby-python | python |
"""
# Data Structures and Algorithms - Part B
# Created by Reece Benson (16021424)
"""
from tennis import Round
from tennis.Colours import Colours
class Tournament():
# Variables
name = None
game = None
parent = None
json_data = None
rounds = None
gender = None
difficulty = None
p... | nilq/baby-python | python |
#-*- encoding: utf-8 -*-
"""
Ordered fractions
Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1... | nilq/baby-python | python |
from enum import Enum
ISO8601_FMT = "%Y-%m-%dT%H:%M:%S.%fZ"
DATE_FORMAT = "%Y-%m-%d"
ALL_CASES_QUEUE_ID = "00000000-0000-0000-0000-000000000001"
UPDATED_CASES_QUEUE_ID = "00000000-0000-0000-0000-000000000004"
ENFORCEMENT_XML_MAX_FILE_SIZE = 1000000 # 1 MB
class GoodSystemFlags:
CLC_FLAG = "00000000-0000-0000-0... | nilq/baby-python | python |
import pytest
import case_conversion.utils as utils
from case_conversion import Case, InvalidAcronymError
@pytest.mark.parametrize(
"string,expected",
(
("fooBarString", (["foo", "Bar", "String"], "", False)),
("FooBarString", (["Foo", "Bar", "String"], "", False)),
("foo_bar_string",... | nilq/baby-python | python |
from weibo import APIClient
import json
APP_KEY = "3722673574"
APP_SECRET = "3686fea0a65da883b6c2a7586f350425"
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
with open('token.json', 'r') as f:
r = json.load(f)
a... | nilq/baby-python | python |
#!/usr/bin/env python3
# -+- coding: utf-8 -*-
import re
import json
import hashlib
from os import path, makedirs, SEEK_CUR
from harvester import libDataBs
def getOrCreatePath(archive_base_path):
if not path.exists(archive_base_path):
makedirs(archive_base_path)
def setUpDir(site, archive_base_path):
... | nilq/baby-python | python |
from collections import OrderedDict
import itertools
import json
from scipy.sparse import coo_matrix, block_diag
import autograd.numpy as np
from .base_patterns import Pattern
####################
# JSON helpers.
# A dictionary of registered types for loading to and from JSON.
# This allows PatternDict and PatternA... | nilq/baby-python | python |
class Recall:
def __init__(self, max_count=10):
self.max_count = max_count
self.position = 0
self.buffer = []
def move_up(self):
if self.position < len(self.buffer) - 1:
self.position += 1
return self.buffer[self.position]
def move_down(self):
... | nilq/baby-python | python |
# https://leetcode.com/problems/3sum/
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = set()
nums = sorted(nums)
for k in range(0, len(nums)):
target = -(nums[k])
l, r = k+1, len(nums)-1
while(l<r):... | nilq/baby-python | python |
from django.apps import AppConfig
class GradedConfig(AppConfig):
name = 'graded'
| nilq/baby-python | python |
from .base import *
DEBUG = False
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-prod.json'),
}
} | nilq/baby-python | python |
from src.pybitbucket.bitbucket import Bitbucket
config = {
"secret-properties": "secretproperties.properties",
"properties": "properties.properties"}
bb = Bitbucket(settings=config)
# workspace = bb.workspace
prs_df = bb.df_prs
commits_df = bb.df_commits
prs_list = prs_df["pr_id"].unique().tolist().sort()
pr... | nilq/baby-python | python |
#!/usr/bin/env python
'''
Tiger
'''
import json
import os
import subprocess
from collections import OrderedDict
from tasks.util import (LoadPostgresFromURL, classpath, TempTableTask, grouper,
shell, TableTask, ColumnsTask, TagsTask,
Carto2TempTableTask)
from tasks.meta ... | nilq/baby-python | python |
from collections import OrderedDict
from algorithms.RNN import RNNModel
from algorithms.AR import AutoRegressive
from algorithms.LSTM import LSTMModel
from algorithms import LSTNet, Optim
import torch
p = 5
def get_models_optimizers(node_list, algs, cuda, lr, hidden_dim, layer_dim, nonlinearity, Data):
models, q... | nilq/baby-python | python |
#!/usr/bin/env python3
import logging
import sys
from .ToolChainExplorer import ToolChainExplorer
class ToolChainExplorerDFS(ToolChainExplorer):
def __init__(
self,
simgr,
max_length,
exp_dir,
nameFileShort,
worker,
):
super(ToolChainExplorerDFS, self)._... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: signer.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from googl... | nilq/baby-python | python |
import sym.models
import sym.trainer
import sym.datasets
import sym.config
| nilq/baby-python | python |
#!/usr/bin/python
#
# Copyright (C) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# SPDX-License-Identifier: GPL-2.0+
#
import os
import struct
import sys
import tempfile
import command
import tools
def fdt32_to_cpu(val):
"""Convert a device tree cell to an integer
Args:
Value ... | nilq/baby-python | python |
import inspect
import typing
try:
from contextlib import (
AsyncExitStack,
asynccontextmanager,
AbstractAsyncContextManager,
)
except ImportError: # pragma: no cover
AbstractAsyncContextManager = None # type: ignore
from async_generator import asynccontextmanager # type: igno... | nilq/baby-python | python |
from oeis import phi
def test_phi():
assert [phi(x) for x in range (1, 10)] == [1, 1, 2, 2, 4, 2, 6, 4, 6] | nilq/baby-python | python |
from datetime import datetime
import json
import glob
import os
from pathlib import Path
from multiprocessing.pool import ThreadPool
from typing import Dict
import numpy as np
import pandas as pd
from scipy.stats.mstats import gmean
import torch
from torch import nn
from torch.utils.data import DataLoader
ON_KAGGLE:... | nilq/baby-python | python |
# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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... | nilq/baby-python | python |
from ebonite.core.objects.requirements import InstallableRequirement, Requirements, resolve_requirements
def test_resolve_requirements_arg():
requirements = Requirements([InstallableRequirement('dumb', '0.4.1'), InstallableRequirement('art', '4.0')])
actual_reqs = resolve_requirements(requirements)
assert... | nilq/baby-python | python |
"""
==================
Find ECG artifacts
==================
Locate QRS component of ECG.
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
print(_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pytest
from unittest import mock
from pytube import YouTube
from pytube.exceptions import LiveStreamError
from pytube.exceptions import RecordingUnavailable
from pytube.exceptions import RegexMatchError
from pytube.exceptions import VideoUnavailable
from pytube.exceptions import VideoPri... | nilq/baby-python | python |
import sys
import numpy as np
raw = sys.stdin.read()
locs = np.fromstring(raw, dtype=np.int64, sep=',')
average = np.average(locs)
def forLocation(locs, dest):
absolute = np.abs(locs - dest)
return ((absolute + 1) * absolute // 2).sum()
print('Result:', min(
forLocation(locs, int(np.ceil(average))),
... | nilq/baby-python | python |
from pycantonese import stop_words
_DEFAULT_STOP_WORDS = stop_words()
def test_stop_words():
_stop_words = stop_words()
assert "唔" in _stop_words
def test_stop_words_add_one_word():
_stop_words = stop_words(add="foobar")
assert "foobar" in _stop_words
assert len(_stop_words) - len(_DEFAULT_STO... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function
import roslib
import rospy
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import sys
# sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2 as cv
print(... | nilq/baby-python | python |
import numpy as np
from whole_body_mpc_msgs.msg import StateFeedbackGain
import copy
class StateFeedbackGainInterface():
def __init__(self, nx, nu, frame_id="world"):
self._msg = StateFeedbackGain()
self._msg.header.frame_id = frame_id
self._msg.nx = nx
self._msg.nu = nu
se... | nilq/baby-python | python |
""" This script runs every 10 seconds and assigns users to a new batch of tasks filtered by the specified column.
Notes:
1. Don't forget to enable Manual mode in Annotation settings
2. Be careful when adding email users: users who are not members of the project or workspace will break Data Manager
Install:
... | nilq/baby-python | python |
import time
import requests
from requests.exceptions import HTTPError, Timeout
from bs4 import BeautifulSoup
from core.log_manager import logger
class Updates:
MAX_LENGTH = 25 # Maximum amount of numbers that a version can support
TIME_INTERVAL = 48 # In hours
def __init__(self, link, loca... | nilq/baby-python | python |
import numpy
from typing import List
from skipi.function import Function
class AverageFunction(Function):
@classmethod
def from_functions(cls, functions: List[Function], domain=None):
r"""
Returns the average function based on the functions given as a list F = [f_1, ..., f_n]
::math.... | nilq/baby-python | python |
import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
from phyllo.phyllo_logger import logger
def getBooks(soup):
siteURL = 'http://www.thelatinlibrary.com'
textsURL = []
# get links to books in the collection
for a in soup.find_all('a', href=True):
... | nilq/baby-python | python |
import scipy.integrate as scin
import numpy as np
import matplotlib.pyplot as pl
g=9.80665
Cd=0.2028
m=80
ics = ([0,0])
t = np.linspace(0,100,500) #creates an array t, integration range from 0 and inclusive of 100 since its linspace, increment of 500
def deriv(x,t):
F = np.zeros(2) #creates an array F, with length ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use the ~/.wakatime.cfg file to set custom project names by
recursively matching folder paths.
Project maps go under the [projectmap] config section.
For example:
[projectmap]
/home/user/proj... | nilq/baby-python | python |
__all__ = ['features','graph_layers'] | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.