content
stringlengths
5
1.05M
from tempfile import NamedTemporaryFile import pytest from pytakeout import extract_code_lines, extract_code, code_to_file def func_to_extract(): line1 = '1' return line1 class SomeClass(object): def method_to_extract(self): return 0 def test_extract_func_lines(): func_lines = extract_...
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Examp...
# Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output # Imports from this application from app import app # 1 column layout # https://dash-bootstrap-components.opensource...
from django.contrib.auth.models import UserManager class CaseInsensitiveUserManager(UserManager): """Case-Insensitive Manager for User. By default, Django checks the username field (whatever it is defined) case-sensitive. This is has no sense, so this aproach avoids this problem, even if the username...
import logging import math from app.base_scalers import PaasBaseScaler from app.config import config class CpuScaler(PaasBaseScaler): def __init__(self, app_name, min_instances, max_instances, **kwargs): super().__init__(app_name, min_instances, max_instances) self.threshold = kwargs.get('thresho...
from itertools import combinations_with_replacement def generate_pairs(m: int, n: int) -> list: # First way # pairs: list = [] # for i in range(m, n+1): # for j in range(i, n+1): # pairs.append((i,j)) # return pairs # # Second way return [i for i in combinations_with_replac...
try: from PIL import Image except ImportError: import Image import pytesseract import netlist as ntl from netsolve import net_solve """ This program implements a prototype for the OCR feature of the Spyce program -assumes that text can be extracted from the image -potential solution : circuit be d...
from pathlib import Path from pytiled_parser import common_types, layer, tiled_map, tileset EXPECTED = tiled_map.TiledMap( hex_side_length=6, stagger_axis="y", stagger_index="odd", infinite=False, layers=[ layer.TileLayer( name="Tile Layer 1", opacity=1, ...
import numpy as np from astropy.io import fits base = fits.open("bias_2_MEF_2x2_slit.fits") base[0].header.pop('DATALAB', None) base[0].header.pop('CCDSUM', None) base[0].header['ARCBEFOR'] = True base[1].header['CCDSUM'] = 'a b' base[1].header['EXPTIME'] = -1 base.writeto("badheaders1.fits", overwrite=True) base[0].h...
#!/usr/bin/env python3 import os import sys import gevent.monkey sys.path.append(os.path.dirname(os.path.abspath(__file__))) gevent.monkey.patch_all() from diff_match_patch import diff_match_patch from collacode_lib import * class Checker(BaseChecker): def __init__(self, *args, **kwargs): super(Chec...
print("hello python") print("hello","python") print('hello' ,'python') print('hello', 'python') print(100+200) print("100+200=",100+200)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-07-07 17:31:59 # @Author : Wangmengcn (eclipse_sv@163.com) # @Link : https://eclipsesv.com # @Version : $Id$ from celery.schedules import crontab # BROKER_URL = 'amqp://guest:guest@localhost:5672//' BROKER_URL = 'redis://127.0.0.1:6379/7' CELERY_RESUL...
from data import params_a, params_b from model import EquilibriumModel flags = { 'PRINT_VARIABLES': True, # Whether to print values of decision variables 'PRINT_SOLUTION': True, # Whether to print solution details 'NETWORK_TYPE': "A", # One of: {"A", "B"} 'MARKET_TYPE': "C" # One...
from django.contrib.auth.models import User from authority import get_check class AuthorityPermissionBackend(object): supports_object_permissions = True supports_anonymous_user = False def authenticate(self, username, password): return None def has_perm(self, user_obj, perm, obj=None): ...
import os import logging import json import csv import upload from headers import create_header from validators import json_validator logger = logging.getLogger(name=__name__) class HumanGenesInteractingWithFileGenerator: def __init__(self, interactions, config_info, generated_files_folder): self.inter...
# AUTOGENERATED! DO NOT EDIT! File to edit: 02_Data_preparation.ipynb (unless otherwise specified). __all__ = ['dominicana', 'etp', 'get_independent_vars', 'independent_vars_to_targs', 'drop_last_value', 'get_target', 'get_clan_membership', 'merged_datasets', 'get_ETP_independent_vars', 'dblock_pretrain', '...
import tensorflow as tf from ocnn import * class AutoEncoderOcnn: def __init__(self, flags): self.flags = flags def octree_encoder(self, octree, training, reuse=False): flags = self.flags depth, nout = flags.depth, flags.nout channel = [4, nout, 128, 64, 32, 16, 8] with tf.variable_scope('ocn...
"""Methods for manipulating/formatting names. """ import enum class NameFormat(enum.Flag): """Names can be rendered in different formats, this enum defines different types of presentations that can also be combined with logical OR (``|``). """ SURNAME_FIRST = 0x1 """Bit flag for surname-first fo...
import numpy as np from copy import deepcopy class Molecule: def __init__(self, KE): self.structure = np.random.uniform(-10, 10, size=2) self.MinStruct = self.structure.copy() self.NHits = 0 self.MHits = 0 self.PE = self._potential_energy_function() self.KE = KE ...
import tensorflow as tf import keras from keras.models import Sequential from keras import Model from keras.layers import Dense, Conv2D, MaxPooling2D class AlexNet(): def __init__(self, num_classes): model = self.alexnet(num_classes) def alexnet(num_classes): model = Sequential() mode...
# coding: utf-8 import os import time import logging from flask import request, make_response, render_template, jsonify from flask.ext.restful import Resource, abort from werkzeug import secure_filename from werkzeug.exceptions import HTTPException from ..config import Config from ..utils import udefault from ..auth ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pruneTree(self, root: TreeNode) -> TreeNode: # 思路分析:当我们需要修剪root时,我们需要先修剪root->left、root->right, #然后再修剪root。这显然是一个递归定义,所以采用递归法处理。 if no...
from typing import Dict, Any from django.shortcuts import render, redirect from django.forms.models import model_to_dict from django.http import HttpRequest from ..middleware import authenticated from ..bl.groups import ( groups_objects, get_group, get_group_info_by_period, add_group, edit_group, ...
from model import * from utils import * from dataloader import * import argparse import tensorflow as tf import numpy as np import datetime ################################################################################### # Parsing all arguments parser = argparse.ArgumentParser() parser.add_argument('--dataset', ...
""" codebooks: automatic generation of codebooks from dataframes """ # Re-exported imports from codebooks import html from codebooks.variable import Variable # Hidden imports from htmlmin import minify as _minify from importlib import resources __version__ = resources.read_text(__name__, "VERSION").strip() def html...
import logging import random import string from contextlib import closing import yaml from psycopg2 import Error from sqlalchemy import create_engine from sqlalchemy.engine import url from csm_test_utils.rds_backup.generation.base import BaseDB, logging_configuration from .db_model import TestRdsTable from .session i...
from .Scan import SoftwareScan from ..environment import macro, MacroSyntaxError from ..motors import all_are_motors import numpy as np import time @macro class AScan(SoftwareScan): """ Software scan one or more motors in parallel. :: ascan <motor1> <start> <stop> ... <intervals> <exp_time> ...
# -*- coding: utf-8 -*- """ BaseTestCase for db testing """ from tornadotoolset.pymonorm import get_database_from_env import unittest class DBTestCase(unittest.TestCase): def setUp(self): self._db = get_database_from_env() self._db.client.drop_database(self._db.name)
import re from sqlalchemy import ( Column, TIMESTAMP, Boolean, func ) from sqlalchemy.ext.declarative import declarative_base, declared_attr class Base: @declared_attr def __tablename__(cls): """Takes in a class name, sets the table name according to the class name, with some manipulat...
#!/usr/bin/env python3 import math if __name__ == "__main__": NUMBER = 600_851_475_143 candidate_factor = 3 largest_prime_factor = 1 sqrt_n = math.sqrt(NUMBER) # handle common small primes if NUMBER % 2 == 0: largest_prime_factor = 2 while NUMBER % 2 == 0: NUMBER /...
# author: Drew Botwinick, Botwinick Innovations # license: 3-clause BSD import re from collections import Mapping from vpd import CaseInsensitiveDict as _ciDict mass = _ciDict({ "H": 1.00794, "He": 4.002602, "Li": 6.941, "Be": 9.012182, "B": 10.811, "C": 12.011, "N": 14.00674, "O": 15...
def hello_world(): return ["hello", "world", "!"] print("Incorrect formatting")
from __future__ import print_function import base64 import os import os.path import pickle from email.mime.text import MIMEText from dotenv import load_dotenv from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # If mod...
class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ result = [] for x in A: x.reverse() x = [1-i for i in x] result.append(x) return result if __name__ == '__main__':...
import sys from collections import defaultdict as d import re from optparse import OptionParser, OptionGroup import math import gzip #Author: Martin Kapun ######################################################### HELP ######################################################################### usage="""python %prog ...
from .pytorch import *
import sys, petsc4py petsc4py.init(sys.argv) from petsc4py import PETSc from xii.linalg.matrix_utils import as_petsc, diagonal_matrix from xii.linalg.convert import convert from block.algebraic.petsc import LU, SUPERLU_LU, AMG, Elasticity from block.algebraic.petsc.precond import precond from block import block_mat, b...
# coding: utf-8 from __future__ import unicode_literals from django.db.models import BooleanField from django.db.models.fields.related import OneToOneRel, RelatedField from django.core.urlresolvers import reverse from django.contrib.contenttypes.models import ContentType from django.contrib.auth import get_permission_c...
from wishlist.domain.product.ports import CreateProduct from wishlist.test.helpers import AsyncMock class TestCreateProduct: async def test_create_product_with_success( self, create_product_request, product_response ): create_product = CreateProduct( AsyncMock(retu...
def assign_context(name, context): if "bookmarks" in name: return "bookmarks", BookmarksContext(context) elif "googlesearch" in name: return "googlesearch", GoogleSearchContext(context) elif "form" in name: return "form", FormContext(context) elif "functionality" in name: ...
""" Implements a parser for the Bencoding format as described at https://wiki.theory.org/BitTorrentSpecification#Bencoding """ import re intNonRe = re.compile(rb'i(0|-?[1-9][0-9]*)e') bytesHeadRe = re.compile(rb'(0|[1-9][0-9]*):') def parseBencodingBytes(b): pos, bLen = 0, len(b) while pos < bLen: value, pos ...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that uldi can be disabled on a per-project-reference basis in vs2010. """ import TestGyp test = TestGyp.TestGyp(formats=['msv...
from pyeoskit import eosapi, wallet eosapi.set_node('https://api.eosn.com') #import your account private key here wallet.import_key('mywallet', '5K463ynhZoCDDa4RDcr63cUwWLTnKqmdcoTKTHBjqoKfv4u5V7p') account = 'testaccount1' args = { 'account': account, 'bytes': 100*1024 } r = eosapi.push_action('eosio', 'sell...
from google.api_core.exceptions import AlreadyExists, NotFound from google.cloud import pubsub_v1 from logger.log import Logger class PubSub: @staticmethod def create_topic(publisher_client, topic_path): try: publisher_client.create_topic(name=topic_path) except AlreadyExists: ...
""" @file @brief Implements a benchmark about performance. """ import pandas from pandas.api.types import is_numeric_dtype def enumerate_options(options, filter_fct=None): """ Enumerates all possible options. @param options dictionary ``{name: list of values}`` @param filter_fct filter...
from datetime import date from Stock import * s = date(2020,1,1) e = date(2021,1,1) tesla = Stock("tsla") tesla.load_data() #tesla.add_data_range(s,e,stockpath='pricedata/tsla.csv') #tesla.save_data() # adding individual days #tesla.add_data(s) #tesla.add_stock_data(s,stockpath='pricedata/tsla.csv')
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from __future__ import unicode_literals import sys sys.path.append("../") import Terry_toolkit as tkit # #-*- encoding:utf-8 -*- # from __future__ import print_function # #https://github.com...
from django.urls import path from book import views urlpatterns = [ path('', views.BookListView.as_view()), path('/detail/<int:book_id>', views.BookDetailView.as_view()), path('/<int:book_id>/review', views.ReviewView.as_view()), path('/reviewlike'...
#!/usr/bin/env python import json import math import matplotlib.pyplot as plt import numpy as np import sys Y, X = np.mgrid[1:10:50j,1:10:50j] U = np.ones_like(X) * 0 V = np.ones_like(Y) * 0 for line in sys.stdin: r = json.loads(line) i, j, theta = r['i'], r['j'], r['theta'] U[i][j] = math.cos(theta) ...
from fabric.api import run, put, env env.hosts = ['elsdoerfer.com:2211'] def publish_docs(): target = '/var/www/elsdoerfer/files/docs/flask-assets' run('rm -rf %s' % target) run('mkdir %s' % target) put('build/sphinx/html/*', '%s' % target)
# -*- coding: utf-8 -*- import argparse import random import os import cherrypy from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool from ws4py.websocket import WebSocket from ws4py.messaging import TextMessage class ChatWebSocketHandler(WebSocket): def received_message(self, m): cherry...
from logging import RootLogger from injector import singleton, inject from logging import Logger from core import CoreRedisClient, CorePikaModule import os @singleton class App: @inject def __init__(self, logger : Logger, redis_client : CoreRedisClient, pika_module : CorePikaModule) -> None: self.logg...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-01-25 20:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ecommerce', '0014_unique_coupon_code'), ] operations = [ migrations.AlterFi...
from django.contrib import admin from .models import Book, Publisher, Author, Genre # Register your models here. class BookAdmin(admin.ModelAdmin): pass class PublisherAdmin(admin.ModelAdmin): pass class AuthorAdmin(admin.ModelAdmin): pass class GenreAdmin(admin.ModelAdmin): pass admin.site....
#Work By APascoa #https://github.com/apascoa/ #-------------------------/ Import Py_Tools_AP by APascoa /-------------------------# import requests r = requests.get("https://raw.githubusercontent.com/apascoa/PY_Tools/main/main.py") Temp = open('Py_Tools_AP.py', 'wb') Temp.write(r.content) Temp.close() #---------------...
class Solution: def numSquares(self, n): squares = [i*i for i in range(int ((n**.5) + 1))] dp = [ float('inf') ] * (n +1) dp[0] = 0 for i in range(1, n+1): for square in squares: if i < square: break dp[i] = min(dp[i], ...
# """ # 请输入商品单价:5 # 请输入购买数量:3 # 请输入支付金额:20 # 应找回:5.0 # """ # price=float(input("请输入商品单价:")) # count=int(input("请输入商品数量:")) # amount=float(input("请输入商品支付金额:")) # result=amount-price*count # print("应找回:"+str(result)) # """ # 在终端中输入一个疫情确诊人数再录入一个治愈人数,打印治愈比例 # 格式:治愈比例为xx% # 效果: # 请输入确诊人数:500 # 请输入治愈人数:495 # 治愈比例为99.0% # "...
#!/usr/bin/env python3 # 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 logging import os import random import shutil import tempfile import time import warnings import crypten impor...
from itertools import groupby from django.http import HttpResponse from django.shortcuts import render, redirect from django.urls import reverse from django.views.decorators.http import require_POST from apps.administration.models import ActionLog from apps.pilots.models import Scenery from zhuartcc.decorators import...
""" pygments.lexers.web ~~~~~~~~~~~~~~~~~~~ Just export previously exported lexers. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexers.actionscript import ActionScript3Lexer from pygments.lexers.actionscript import A...
# -*- coding: utf-8 -*- import scrapy from douyu.items import DouyuItem import hashlib import re from douyu.MysqlHelper import MysqlHelper class MeiziSpider(scrapy.Spider): name = 'meizi' allowed_domains = ['mmjpg.com'] start_urls = ['http://mmjpg.com/'] # url = 'http://www.mmjpg.com/mm/1421/' de...
def count_types(categories): counts = {} for category, list_items in categories.items(): counts[category] = len(list_items) return counts
import discord from discord.ext import commands from bs4 import BeautifulSoup from random import randint from .utils import checks from .utils.dataIO import dataIO import os import aiohttp class MMR: """Gets MMR for users""" def __init__(self, bot): self.bot = bot self.players = dataIO.load_j...
''' ''' from unittest import TestCase from typing import List import heapq class Solution(): ''' Runtime: 60 ms, faster than 30.47% of Python3 online submissions for Top K Frequent Words. Memory Usage: 14.6 MB, less than 10.25% of Python3 online submissions for Top K Frequent Words. ''' def topKFre...
import os import re import uuid def gen_rand(): return str(uuid.uuid4()).replace('-', '') _up = os.path.dirname SAMPLE_PICTURE = os.path.join(_up(_up(_up(os.path.abspath(__file__)))), 'frontend', 'src', 'assets', 'about-logo.png') def build_data_for_query(verb, endpoint, ctx): ...
main=360 def check_full(value, main=360): ... from time import sleep import math def calcular_porcentos(maxim,comming): try: porcento=(100 *(maxim-comming))/maxim print(f'processing : {round(porcento)} % \t from {maxim} in {comming}') os.system('clear') if porcento>=99: ...
# Copyright 2015 The TensorFlow 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 applica...
#!/usr/bin/env python3 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2019 California Institute of Technology. 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 ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-03-08 18:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('local_groups', '0026_auto_20170308_0328'), ] operations = [ migrations.Alte...
"""A wrapper for engaging with the THOR environment.""" import random from PIL import Image import numpy as np from utils import game_util class Episode(object): """Manages an episode in the THOR env.""" def __init__(self): """Init function Inputs: """ # Start the enviro...
from aws_cdk.core import Construct import aws_cdk.aws_iam as iam import aws_cdk.aws_kms as kms import json from aws_cdk import ( aws_secretsmanager as sm, core ) class ElastiCacheSecret(Construct): """ Class for generate secrets. UserSecret extends from ElastiCacheSecret, it contains username an...
# Copyright © 2020 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
from test_plus.test import TestCase class TestUser(TestCase): def setUp(self): self.user = self.make_user() def test__str__(self): self.assertTrue( self.user.username in self.user.__str__() ) def test_get_absolute_url(self): self.assertEqual( self...
import json import os import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import f1_score from sklearn.utils import resample from sklearn.preprocessing import StandardScaler from sklearn.compose import Colu...
# This adds the derivative of g with respect to the state (x, y and heading) # to the class. # # slam_07_b_state_derivative # Claus Brenner, 11.12.2012 from lego_robot import * from math import sin, cos, pi from numpy import * class ExtendedKalmanFilter: @staticmethod def g(state, control, w): ...
import json import re class RTMMessageType(object): """RTM Message constants""" Unknown = 'unknown' Ping = 'ping' Pong = 'pong' Reply = 'reply' Ok = 'ok' P2PMessage = 'message' P2PTyping = 'typing' ChannelMessage = 'channel_message' ChannelTyping = 'channel_typing' UpdateU...
# -*- coding: utf-8 -*- """ """ import ctypes import pytest from cslug import ptr pytestmark = pytest.mark.order(-2) @pytest.mark.parametrize("binary", range(2)) def test_character_arrays_dont_need_null_termination(binary): """ Test that a C string converted to Python doesn't need to be null terminated. ...
# -*- coding: utf-8 -*- import datetime import io from openpyxl import load_workbook from ftc.management.commands._base_scraper import HTMLScraper from ftc.models import Organisation SCOT_LAS = { "Aberdeen City": "S12000033", "Aberdeenshire": "S12000034", "Angus": "S12000041", "Argyll & Bute": "S1200...
# Generated file, please do not change!!! import datetime import enum import typing from ._abstract import _BaseType from .common import ImportResource if typing.TYPE_CHECKING: from .common import ( Asset, CategoryKeyReference, ChannelKeyReference, CustomerGroupKeyReference, ...
# -*- coding: utf-8 -*- """MLforPP.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/13zHHnkZF8FVCj6he_9fMeMuJhTPpat__ Importing the libraries """ import numpy as np import matplotlib.pyplot as plt import pandas as pd """Importing the dataset""" ...
from dataclasses import dataclass from typing import Optional @dataclass class PlaceType: code: int name: str @dataclass class Location: country: str country_code: str name: str parent_id: int place_type: PlaceType url: str woeid: int @dataclass class Trend: name: str u...
# The MIT License # # Copyright (c) 2021 Luke Anderson (stuntguy3000) # # 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...
# -*- coding: utf-8 -*- """ Created on Thu Apr 18 14:19:23 2019 @author: QArif """ # import the good stuff import numpy as np import cv2 import pickle # haarcascade face_cascade2 = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml') face_cascade = cv2.CascadeClassifier('cascades/data/haarcascad...
from seedwork.application.modules import BusinessModule from seedwork.domain.events import EventPublisher from modules.bidding.domain.repositories import ListingRepository from modules.bidding.application.query.get_pastdue_listings import ( GetPastdueListingsQuery, get_past_due_listings, ) class BiddingModule...
import os from conans import ConanFile, CMake, tools class DecicmalTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" exports_sources = ("*", "!build") generators = "cmake_paths" def _configure_cmake(self): cmake = CMake(self) cmake.configure() return cmak...
import logging import os from datetime import datetime import altair import pandas as pd import streamlit as st from index_analyzer.index_data import IndexDataProvider def show_index_time_series(result): if result.empty: st.write('No data found.') return result = pd.melt( result, ...
import graphene from db.db import engine, my_session, get_json_by_sql class UserModel(graphene.ObjectType): TF = graphene.String() country = graphene.String() fullName = graphene.String() import graphene from db.db import engine, my_session, get_json_by_sql def get_users(): my_sql ='select * from tblUs...
#!/usr/bin/env python COPY_GOOGLE_DOC_KEY = '1YsDUk45YnKMoAIoiGMzaGLTMBeGoKfkNIfZ--qu3UU4'
import paho.mqtt.client as mqtt #import the client1 import time import sys import threading import unittest import Pub_Sub_client as pubsub class TestClient(unittest.TestCase): def setUp(self): pubsub.message="check_name;1;F;check_procedure" pass def test_subscriber(self): t1=...
s = input() print ("Your word is a palindrom" if s == s[::-1] else "Your word is not a palindrome")
import pytest from dvc.stage.utils import is_valid_name @pytest.mark.parametrize("name", ["copy_name", "copy-name", "copyName", "12"]) def test_valid_stage_names(name): assert is_valid_name(name) @pytest.mark.parametrize("name", ["copy$name", "copy-name?", "copy-name@v1"]) def test_invalid_stage_names(name): ...
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) # Get the long description from...
from cpeptools import generate_conformers_with_eccentricity from rdkit import Chem from rdkit.Chem import AllChem def test_confgen(): CsA_smiles = "CC[C@H]1C(=O)N(CC(=O)N([C@H](C(=O)N[C@H](C(=O)N([C@H](C(=O)N[C@H](C(=O)N[C@@H](C(=O)N([C@H](C(=O)N([C@H](C(=O)N([C@H](C(=O)N([C@H](C(=O)N1)[C@@H]([C@H](C)C/C=C/C)O)C)C...
from datetime import datetime class Screenshot(object): """This class formats the file name of the screenshot The current timestamp is added to the file prefix to create the filename The filename is passed to the get_screenshot method of the base class """ def __init__(self, base, take_screenshot...
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source ...
from marshmallow import Schema, ValidationError, validates, validates_schema from marshmallow.fields import Float, Int, List, Nested, Str from marshmallow.validate import Length, OneOf, Range from store.db.schema import CourierType from store.api.domain import TimeIntervalsConverter class CouriersNested(Nested): ...
# TODO(sonots): Implement in C++ def ravel(a): """Returns a flattened array. It tries to return a view if possible, otherwise returns a copy. Args: a (~chainerx.ndarray): Array to be flattened. Returns: ~chainerx.ndarray: A flattened view of ``a`` if possible, otherwise a copy...
import translator from substitutiontranslator import * from .. import utils class VigenereTranslator(translator.Translator): """Adds perpetually key letters to text (Caesar with longer keys)""" def __init__(self, key="A", ignore_nonletters=True): self.key = key self.ignore_nonletters = ignore_nonletters def pa...
#!/usr/bin/env python #--------Include modules--------------- from copy import copy import rospy from visualization_msgs.msg import Marker from std_msgs.msg import String from geometry_msgs.msg import Point from os import system from random import random from numpy import array from numpy import delete from numpy im...
#!/usr/bin/python3 import re syslog = open('syslog', 'r') syslogLine = syslog.readlines() syslog.close() dateTimestampIPport = re.compile(r'(^\w{3} {1,2}\d{1,2} \d\d:\d\d:\d\d) ' + \ r'.* SRC=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' + \ r'.* DPT=(\d{1,5})')...