content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import os
from my_lib import Object, Object2, Object3
def is_unique(s):
s = list(s)
s.sort()
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
return 0
else:
return 1
if __name__ == "__main__":
print(is_unique(input()))
| nilq/baby-python | python |
def get_names():
names = []
while True:
name = input("Enter players name: ")
if name != 'done':
print(f'{name} added to the list of players')
names.append(name)
continue
else:
break
return names
def get_player_scores(players):
for... | nilq/baby-python | python |
#! /usr/bin/env python
from eclib.elgamal import *
key_length = 20
params, pk, sk = keygen(key_length)
delta = 1e-2
print('========== ElGamal parameter ==========')
print(f'key length = {key_length} bit')
print(f'p = {params.p}')
print(f'q = {params.q}')
print(f'g = {params.g}')
print(f'h = {pk}')
print(f's = {sk}')... | nilq/baby-python | python |
import numpy as np
import cv2
import os
from src.types.parent_slide import SlideImage
class FluorescenceSlide(SlideImage):
def __init__(self, img, **kwargs):
"""
Arguments:
img (ndarray): uint16 array of shape (h,w,3)
"""
self.img = img
self.height, self.width, ... | nilq/baby-python | python |
from typing import List, Optional, Type
from ape.types import AddressType
from .base import abstractdataclass, abstractmethod
from .providers import ProviderAPI, ReceiptAPI, TransactionAPI
@abstractdataclass
class AddressAPI:
_provider: Optional[ProviderAPI] = None
@property
def provider(self) -> Provi... | nilq/baby-python | python |
""" capture_faces.py
Author: Gonçalo S. Martins
This script implements the basic face detection and extraction features
needed for this work. The main section of the script illustrates its usage
in extracting faces from pre-recorded videos.
This script was tested using Python 3.5 and OpenCV 3.1.
Video capture code i... | nilq/baby-python | python |
#!/usr/bin/python3
"""
Made by Facundo Diaz - Tomas De Castro - Tadeo Grach for Holberton School 2021 """
""" IMPORTS EXTERN MODULES """
import time
from datetime import datetime
import os
""" IMPORTS FILES """
import persistence
import entities
import mail
import info
import percent
""" In case url 1 is not worki... | nilq/baby-python | python |
#Based on https://github.com/alexandrebarachant/muse-lsl/blob/master/notebooks/N170%20with%20Muse.ipynb
import sys
from collections import OrderedDict
from mne import create_info, concatenate_raws
from mne.io import RawArray
from mne.channels import read_montage
import pandas as pd
import numpy as np
from glob impor... | nilq/baby-python | python |
#https://www.hackerrank.com/challenges/mark-and-toys/problem?isFullScreen=true
def maximumToys(prices, k):
# Write your code here
prices.sort()
count = 0
sum = 0
i = 0
while sum < k:
sum += prices[i]
i += 1
count += 1
return count - 1
| nilq/baby-python | python |
import hassapi as hass
import datetime
import re
"""
Class Phone_Manager handles sending call to voice notfyng service
"""
__NOTIFY__ = "notify/"
SUB_TTS = [("[\*\-\[\]_\(\)\{\~\|\}\s]+", " ")]
class Phone_Manager(hass.Hass):
def initialize(self):
self.dict_lingua = {
"it-IT": "it-IT-Standar... | nilq/baby-python | python |
"""
Export biomedical data from a relational database to an Avro file.
An Avro file stores the data schema as a JSON blob and the data in a
binary format
See https://avro.apache.org for details
In this case, the Avro file is called a PFB
(Portable Format for Bioinformatics) file because the data in the Avro file
con... | nilq/baby-python | python |
from urlparse import urljoin
from kivy.properties import StringProperty
from kivy.uix.screenmanager import Screen
from kivy.utils import platform
from pytt.tools import Tool, RectangleTool
from pytt.pasteimage import PasteImageScreen, get_png_from_clipboard
class DMScreen(Screen):
mapfile = StringProperty('')
... | nilq/baby-python | python |
import adv.adv_test
from core.advbase import *
import marth
def module():
return Marth
class Marth(marth.Marth):
comment = 'dodge*2 to miss s2p3 then dodge*2 back to attack'
def s2_proc(self, e):
if self.stance == 0:
self.stance = 1
Selfbuff('s21',0.1,10).on()
... | nilq/baby-python | python |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\fame\fame_commands.py
# Compiled at: 2020-06-01 23:01:55
# Size of source mod 2**32: 8751 bytes
from... | nilq/baby-python | python |
from django.apps import AppConfig
class ReportConfig(AppConfig):
name = "reports"
verbose_name = "Django Model Reports"
def ready(self):
from .base import reports
reports.discover()
| nilq/baby-python | python |
#!/usr/bin/env python
import rospy
import numpy as np
import cv2
from subprocess import call
import sys
from std_msgs.msg import String
import cv2.cv as cv
import os
class martin_aimas_interface:
def __init__(self):
self.speechRecognitionFlag = True
self.subSpeech = rospy.Subscriber('/recognizer/output', String,... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 00:29:48 2018
@author: Hiba Lubbad
"""
animals = { 'a': ['horse'], 'b': ['baboon'], 'c': ['giraffe']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
def howmany(di):
count = 0
for i in di.values():
... | nilq/baby-python | python |
# Get the data from:
# https://archive.ics.uci.edu/ml/datasets/Airfoil+Self-Noise
from __future__ import print_function, division
from future.utils import iteritems
from builtins import range, input
import os
# Note: you may need to update your version of future
# sudo pip install -U future
# just in case we need it... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import inspect
from abc import ABC, abstractmethod
from typing import Dict, Generator, List, Type, TypeVar
from libcst impor... | nilq/baby-python | python |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
from itl.layers.core import Layer
from itl import logging
# from itl.decorators import deprecated_alias
__all__ = [
'UpSampling2dLayer',
'DownSampling2dLayer',
]
class UpSampling2dLayer(Layer):
"""The :class:`UpSampling2dLayer` class ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Author : xuqiang
@License : (C) Copyright 2020-, H3C
@Contact : xu.qiang@h3c.com
@Software: f8s
@File : config.py
@Time : 20200211
@Desc :
'''
#k8s cfg
K8S_CFG = "/root/f8s/kubeconfig.yaml"
FISCO_HOME = '/root/fisco_network'
NFS = "1... | nilq/baby-python | python |
import cfm_api_utils
token = get_token()
print token
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Project Contributors
#
# Distributed under the terms of the MIT License
# (see spyder/__init__.py for details)
# --------------------------------------------------------------------------... | nilq/baby-python | python |
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName #initialization of first number ,last number as done in the constructor
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)# #printout stat... | nilq/baby-python | 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 torch
# from transformers import MT5ForConditionalGeneration, MT5Config, MT5EncoderModel, MT5Tok... | nilq/baby-python | python |
# 167. Two Sum II - Input array is sorted - LeetCode
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 1... | nilq/baby-python | python |
import logging
def column_headers(header_row):
logging.info(f"Validating header row, headers: {header_row}")
header_list = header_row.split(",")
try:
valid = True
if header_list[0] != "code":
logging.info(f"got in code: {header_list[0]}")
valid = False
if ... | nilq/baby-python | python |
import json
from config import TEXT_LANGUAGE
from game.roles.villager import Villager
from game.roles.werewolf import Werewolf
from game.roles.guard import Guard
from game.roles.seer import Seer
from game.roles.lycan import Lycan
from game.roles.betrayer import Betrayer
from game.roles.superwolf import Superwolf
from ... | nilq/baby-python | python |
t = c = i= 0
menor = ''
while True:
n = str(input('Nome: ')).capitalize()
p = float(input('Preço: R$ '))
t += p
if i == 0:
m = p
menor = n
i += 1
if p > 1000:
c += 1
if p < m:
menor = n
op = ' '
while op not in 'sn':
op = str(input('Quer co... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Some generic laguage level utilities for internal use.
"""
import collections
import functools
import sys
import warnings
from typing import (
AbstractSet,
Any,
Callable,
Hashable,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Seque... | nilq/baby-python | python |
""" --- The Angles of a Triangle --- Elementary
You are given the lengths for each side on a triangle.
You need to find all three angles for this triangle. If the given side
lengths cannot form a triangle (or form a degenerated triangle),
then you must return all angles as 0 (zero). The angles should be
represented as... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" doScan.py
The core interface that takes minimal text description of scan and does IPC with hardware system
This is the common entry into the hardware interface and uses a minimal text desc file containing three
blocks: [Major], [Minor], [Interface]. This routine can be called independently... | nilq/baby-python | python |
import logging
from django.core.management.base import BaseCommand, CommandError
from plyara import Plyara
from rules.models import YaraRule
# Configure Logging
logging.basicConfig(level=logging.INFO)
class Command(BaseCommand):
help = 'Recalculate the logic hashes of the entire rule corpus'
def handle(se... | nilq/baby-python | python |
import pandas as pd
import numpy as np
class ExternalData():
def __init__(self, csv, mol_names, exclude=[]):
self.csv = csv
self.mol_names = mol_names
self.exclude = exclude
def fit(self, molecules):
return molecules
def fit_transform(self, molecules, labels):
... | nilq/baby-python | python |
import mailroom_stuff.Front_End
if __name__ == '__main__':
mailroom_stuff.Front_End.main()
| nilq/baby-python | python |
from flask_script import Manager,Shell,Server
from app import create_app ,db
from app.models import User
from flask_migrate import Migrate, MigrateCommand
app=create_app('production')
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
manager.add_command('Server',Server)
@mana... | nilq/baby-python | python |
#!/usr/bin/env python
import socket
import sys
import os
sys.path.append('./src')
from multi_detector import MultiDetector
libpath = "../lib/linux/libnyumaya.so"
hotword_graph="../models/Hotword/marvin_big_0.3.tflite"
hotword_labels="../models/Hotword/marvin_labels.txt"
action_graph="../models/Command/on_off_big_0... | nilq/baby-python | python |
#!/usr/bin/env python
""" This code implements a ceiling-marker based localization system.
The core of the code is filling out the marker_locators
which allow for the specification of the position and orientation
of the markers on the ceiling of the room """
import rospy
from ar_pose.msg import ARMarkers
... | nilq/baby-python | python |
import os
from typing import Any, Dict, Optional
import httpx
import pytest
from fastapi import status
from tortoise import Tortoise
from chapter6.tortoise_relationship.app import app
from chapter6.tortoise_relationship.models import (
CommentDB,
CommentTortoise,
PostDB,
PostTortoise,
)
DATABASE_FIL... | nilq/baby-python | python |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Test Project fro machine learning',
author='Vipin',
license='MIT',
)
| nilq/baby-python | python |
# Generated by Django 2.1 on 2020-01-10 00:07
from django.db import migrations
import pyuploadcare.dj.models
class Migration(migrations.Migration):
dependencies = [
('rate', '0002_auto_20200109_1306'),
]
operations = [
migrations.AddField(
model_name='profile',
n... | nilq/baby-python | python |
from .music import * | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import torbjorn as tbn
from .an2cn import An2Cn
from .cn2an import Cn2An
ac = An2Cn()
ca = Cn2An()
an = 9876543298765432
cn = "九千八百七十六万五千四百三十二亿九千八百七十六万五千四百三十二"
@tbn.run_time
def run_cn2an_ten_thousand_times():
for _ in range(10000):
result = ca.cn2an(cn)
assert result ==... | nilq/baby-python | python |
import warnings
from ..utility.strcmpi import *
from ..utility.debug_message import *
from .fileparts import *
def _open_file(filename, defaultExt, permission, fileDataFcn, verbose=False):
"""
Opens a given file and executes the specified function over its data
Parameters
---------... | nilq/baby-python | python |
numbers = ["886"]
def parse_phone_number(phone_number):
# 国内号码不按照国际号码方式处理,直接返回手机号,这样亿美才能发送成功
if phone_number.startswith("+86"):
return phone_number[3:]
real_phone_number = None
for number in numbers:
p = "+" + number
if phone_number.startswith(p + "0"):
real_phone... | nilq/baby-python | python |
# common conversion point stacking
# import modules
import sys
from geographiclib.geodesic import Geodesic as geo
import numpy as np
# from matplotlib.mlab import griddata
import scipy
import scipy.ndimage
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import num... | nilq/baby-python | python |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\aging\aging_data.py
# Compiled at: 2019-04-30 00:16:35
# Size of source mod 2**32: 7516 bytes
f... | nilq/baby-python | python |
"""Tests for web app requests"""
from unittest import TestCase
import sodar_taskflow
from apis.irods_utils import init_irods, cleanup_irods_data
class AppTestBase(TestCase):
"""Base test class for web app"""
def setUp(self):
# Init iRODS connection
self.irods = init_irods(test_mode=True)
... | nilq/baby-python | python |
from django.db import models
from django.urls import reverse
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('Date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = mode... | nilq/baby-python | python |
#!/usr/bin/env python2
"""
os_path_test.py: Tests for os_path.py
"""
from __future__ import print_function
import unittest
from pylib import os_path # module under test
class OsPathTest(unittest.TestCase):
def testBasename(self):
self.assertEqual('bar', os_path.basename('foo/bar'))
if __name__ == '__main_... | nilq/baby-python | python |
from abc import ABCMeta
class OgreMeshSerializerListener(metaclass=ABCMeta):
"""
This class allows users to hook into the mesh loading process and
modify references within the mesh as they are loading. Material and
skeletal references can be processed using this interface which allows
f... | nilq/baby-python | python |
import os
import dill
import numpy as np
from math import pi, exp, atan, sqrt, acos
def angle(x, y):
"""calculates the angle of (x,y) with respect to (0,0)
:param x: x choordinate
:param y: y choordinate
:returns: the angle"""
at = atan(y/x)
if(x < 0): return at+pi
elif(y < 0): return at+2*pi
return at
de... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Adrien Vergé
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# This pro... | nilq/baby-python | python |
# Copyright (C) 2014 Universidad Politecnica de Madrid
#
# 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... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/david/projects/luxcorerender/LuxCore/src/pyluxcoretools/pyluxcoretools/pyluxcoremenu/menuwindow.ui',
# licensing of '/home/david/projects/luxcorerender/LuxCore/src/pyluxcoretools/pyluxcoretools/pyluxcoremenu/menuwindow.ui' applies.
#
#... | nilq/baby-python | python |
from bflib.items.base import Item
from core import flags
from bfgame.factories.recipes import listing
from core.gameobject import GameObject
class ItemFactory(object):
name = "item"
type_map = Item
def __init__(self, game):
self.game = game
def create_new(self, base_item):
recipe = l... | nilq/baby-python | python |
num = [1,2,3,4]
evens = list(filter(lambda x: x % 2 == 0, num))
print(evens)
| nilq/baby-python | python |
from aclarknet.aclarknet.models import Client
from aclarknet.aclarknet.models import Service
from aclarknet.aclarknet.models import TeamMember
from aclarknet.aclarknet.models import Testimonial
from django.contrib import admin
class ClientAdmin(admin.ModelAdmin):
pass
class ServiceAdmin(admin.ModelAdmin):
p... | nilq/baby-python | python |
import unittest
from pydantic import ValidationError
from mobile_handset_price_model.prediction.model import MobileHandsetPriceModel
from mobile_handset_price_model.prediction.schemas import MobileHandsetPriceModelInput, \
MobileHandsetPriceModelOutput, PriceEnum
class ModelTests(unittest.TestCase):
def tes... | nilq/baby-python | python |
# stdlib
import itertools
from urllib import quote
from unittest import TestCase
import logging
import mock
import json
from utils.splunk.splunk import SplunkSavedSearch, SplunkInstanceConfig, SavedSearches
from utils.splunk.splunk_helper import SplunkHelper
class FakeInstanceConfig(object):
def __init__(self):... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import logging
import os
from logging.handlers import RotatingFileHandler
from platform import uname
from plexapi.config import PlexConfig, reset_base_headers
from plexapi.utils import SecretsFilter
from uuid import getnode
# Load User Defined Config
DEFAULT_CONFIG_PATH = os.path.expanduser('~/... | nilq/baby-python | python |
import sys
from cx_Freeze import setup, Executable
product_name = "Triangulation"
exe = Executable(
script = "main.py",
base = "Win32GUI",
targetName = "Triangulation.exe",
icon = "icon.ico",
shortcutName = "Triangulation",
shortcutDir = "ProgramMenuFolder"
)
build_exe_options = {"packag... | nilq/baby-python | python |
import sys
sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python')
from CodeJam.Y12R5P1.kelvinlau.A import *
def func_87caa8d11eaf4a20affa21f893f4cbfc(infile):
n = int(infile.readline())
l = map(int, infile.readline().split())
return l
def func_38404980cd9d4ebb8816600eb7513... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from app.api import HTTPStatus, Resource, api
from app.auth import auth
@api.response(code=HTTPStatus.UNAUTHORIZED.value, description="Unauthorized access")
class BaseController(Resource):
method_decorators = [auth.login_required]
| nilq/baby-python | python |
# https://www.youtube.com/watch?v=XNKeayZW4dY
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
from tensorflow import keras
from tensorflow.keras import layers
print('You ... | nilq/baby-python | python |
"""
Kaggle Challenge:
Modded version from
"http://www.kaggle.com/c/acquire-valued-shoppers-challenge/"
'Reduce the data and generate features' by Triskelion
"""
from datetime import datetime, date
from collections import defaultdict
data_dir = "../data/"
loc_offers = data_dir + "offers.csv"
loc_transactions = da... | nilq/baby-python | python |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import status, mixins, viewsets
from rest_framework.decorators import api_view
from rest_framework.decorators import action
#Serializers
from cride.maps.serializers import StopMo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import VERSION as DJANGO_VERSION
from django.db import migrations
def add_image_permissions_to_admin_groups(apps, schema_editor):
ContentType = apps.get_model('contenttypes.ContentType')
Permission = apps.get_model('auth.Permission')... | nilq/baby-python | python |
#!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# Curious numbers in Z3
#
# From Martin Henz' collection of puzzles
# http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/#curious
# """
# Curious Numbers from "Amusements in Mathematics, Dudeney", number 114.
#
# The number 48 has this peculiarity, that if you add... | nilq/baby-python | python |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class UserTestCase(IntegrationT... | nilq/baby-python | python |
#Curso #7 Templates tags
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app = Flask(__name__, template_folder = 'prueba_template')
#para darle una carpeta en especifico
@app.route('/')
def index():
name = 'Sergio'
return render_template('index.html', nombre = name)
@app.route('... | nilq/baby-python | python |
from output.models.ms_data.wildcards.wild_h003_xsd.wild_h003 import (
Bar,
Foo,
)
__all__ = [
"Bar",
"Foo",
]
| nilq/baby-python | python |
import torch.nn as nn
import functools
import torch.nn.functional as F
import torch
from core.dataset.architecture.mobilespace import *
class MBSpaceController(nn.Module):
def __init__(self, n_conditions=1, n_unit=N_UNITS,
depths=DEPTHS, kernel_sizes=KERNEL_SIZES, expand_ratios=EXPAND_RATIOS,
... | nilq/baby-python | python |
# Copyright (c) 2019 GalaxyLearning 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... | nilq/baby-python | python |
from django.apps import AppConfig
class TrantoolConfig(AppConfig):
name = 'transtool'
# todo check settings and show errors if there are any mistakes
| nilq/baby-python | python |
from layout import fonts
import pygame
from utils import gen_text_object
class Button:
def __init__(self, display, x, y, w, h,
color_active, color_inactive, border_w, border_color, pressed_down_color, text_color_norm,
text_color_pressed, text='', action=None, jump_inc=0):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了88.07% 的用户
内存消耗:13.4 MB, 在所有 Python3 提交中击败了42.98% 的用户
解题思路:
双指针
p指针用于记录位置,q指针寻找小于x的节点。
q指针找到<x的节点后,交换链表
"""
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
p, q = ListNode(0, next = head), head ... | nilq/baby-python | python |
import logging
from typing import Any, Dict
import requests
LOG = logging.getLogger(__name__)
class Client:
CROSSWALK_ENDPOINT = '/crosswalks'
STATISTICS_ENDPOTIN = '/statistics'
TOKEN_ENDPOINT = '/login/access-token'
def __init__(self, base_url: str, username: str, passwd: str) -> None:
se... | nilq/baby-python | python |
from tacred_enrichment.internal.ucca_enhancer import UccaEnhancer
from tacred_enrichment.internal.ucca_types import UccaParsedPassage
from tacred_enrichment.internal.dep_graph import Step, DepGraph
from tacred_enrichment.internal.ucca_types import is_terminal
class UccaEncoding(UccaEnhancer):
def enhance(self, t... | nilq/baby-python | python |
from flask import jsonify
class InvalidSearchException(ValueError): pass
class InvalidRequestException(Exception):
def __init__(self, error_message, code=None):
self.error_message = error_message
self.code = code or 400
def response(self):
return jsonify({'error': self.error_message... | nilq/baby-python | python |
from argparse import ArgumentParser
import pysam
def merge(input_path, output_path, custom_id='custom_id', line_length=80):
with open(output_path, 'w+') as out_f:
out_f.write(f'>{custom_id}\n')
data = ''
with pysam.FastxFile(input_path) as in_f:
for record in in_f:
... | nilq/baby-python | python |
n=input()
if(len(n)<4):
print("NO")
else:
count=0
for i in range(0,len(n)):
if(n[i]=='4' or n[i]=='7'):
count=count+1
dig=0
flag=0
if(count==0):
print("NO")
else:
while count>0:
dig=count%10
if(dig!=4 and dig!=7):
fl... | nilq/baby-python | python |
# Generated by Django 2.2.3 on 2019-07-12 14:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('TeamXapp', '0047_auto_20190712_1504'),
]
operations = [
migrations.AlterField(
model_name='allm... | nilq/baby-python | python |
import os
import numpy
import math
import cv2
from skimage import io
from skimage import color
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from random import randint
class ClusterDataset(Dataset):
"""Camera localization dataset."""
def __cluster__(self, root_dir, num_exp... | nilq/baby-python | python |
import pytest
from pretalx.common.forms.utils import get_help_text
@pytest.mark.parametrize('text,min_length,max_length,warning', (
('t', 1, 3, 't Please write between 1 and 3 characters.'),
('', 1, 3, 'Please write between 1 and 3 characters.'),
('t', 0, 3, 't Please write no more than 3 characters.'),
... | nilq/baby-python | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
Provides a set of I/O routines.
.. include common links, assuming primary doc root is up one directory
.. include:: ../links.rst
"""
import os
import sys
import warnings
import gzip
import shutil
from packaging import version
... | nilq/baby-python | python |
# stateio.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Supporting functions for accessing files from stateior via data commons.
https://github.com/USEPA/stateior
"""
import os
import pandas as pd
from esupy.processed_data_mgmt import download_from_remote, Paths,\
load_preprocessed_output
from flowsa.met... | nilq/baby-python | python |
from sys import argv
import json
finalOutput = {"result": ""}
outputFile = argv[3]
if_spark = argv[4]
reviewFile = argv[1]
businessFile = argv[2]
nCates = int(argv[5])
def no_spark():
def LOAD_FILE(filePath):
output = []
with open(filePath) as file:
for line in file:
... | nilq/baby-python | python |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import dj_database_url
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable f... | nilq/baby-python | python |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from PIL import Image
import scipy.misc
import pandas as pd
import numpy as np
import random
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from glob import glob
from torch.util... | nilq/baby-python | python |
"""
Define some reference aggregates based on *exact* site names
"""
import logging
import pandas as pd
from solarforecastarbiter import datamodel
from solarforecastarbiter.io import api
logger = logging.getLogger('reference_aggregates')
REF_AGGREGATES = [
{
'name': 'NOAA SURFRAD Average GHI',
... | nilq/baby-python | python |
import sys
import unittest
import dask.array as da
import dask.distributed as dd
import numpy as np
import xarray as xr
# Import from directory structure if coverage test, or from installed
# packages otherwise
if "--cov" in str(sys.argv):
from src.geocat.comp import heat_index
else:
from geocat.comp import h... | nilq/baby-python | python |
# INPUT
N = int(input())
A = [int(input()) for _ in range(N)]
# PROCESSES
"""
Critical observation:
To reach a value $V$, we must have come from a value SMALLER than $V$ AND that is before it.
Assuming that ALL values before $V$ have an optimal solution, we can find the optimal solution for $V$.
Define the DP ta... | nilq/baby-python | python |
""" Simple mutually-recursive coroutines with asyncio. Using asyncio.ensure_future
instead of yield from allows the coroutine to exit and merely schedules the next
call with the event loop, allowing infinite mutual recursion. """
import asyncio
@asyncio.coroutine
def a(n):
print("A: {}".format(n))
asyncio.asy... | nilq/baby-python | python |
from __future__ import unicode_literals
from collections import OrderedDict
from django import forms
from django.forms.widgets import Textarea
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
mark_safe_lazy = lazy(mark_safe... | nilq/baby-python | python |
"""
Just another Python API for Travis CI (API).
A module which provides the tests of our requester module.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Project link:
https://github.com/funilrys/PyTravisCI
Project documentation:
https://pytravisci.readthedocs.io/en/latest/
License
::... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function, division, absolute_import
import sys
from channelfinder import ChannelFinderClient, Channel, Property, Tag
import aphla as ap
#GET http://channelfinder.nsls2.bnl.gov:8080/ChannelFinder/resources/resources/channels?~name=SR*
cfsurl = 'http://web01.nsls2.bn... | nilq/baby-python | python |
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class PinCard(models.Model):
token = models.CharField(max_length=32, db_index=True, editable=False)
display_n... | nilq/baby-python | python |
#!/usr/bin/env python
"""The setup script."""
from setuptools import (
find_packages,
setup,
)
from authz import __version__
with open('README.md') as readme_file:
readme = readme_file.read()
requirements = ["casbin==1.9.3"]
test_requirements = ['pytest>=3', ]
setup(
author="Ezequiel Grondona",
... | nilq/baby-python | python |
real = float(input('Quanto você tem na Carteira? R$'))
dolar = real / 5.11
euro = real / 5.76
print('Com R${:.2f} você pode comprar U$${:.2f} e €{:.2f} '.format(real, dolar, euro))
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.