text stringlengths 1 927k |
|---|
import os
import json
import redis
redis_connection = redis.Redis(decode_responses=True)
if not os.path.isdir('logs_json'):
os.mkdir('logs_json')
for key in redis_connection.scan_iter('*'):
file_name = 'logs_json/' + '_'.join(key.split(':')) + '.json'
print(key)
data = redis_connection.lrange(key, 0,... |
# MIT License
# This project is a software package to automate the performance tracking of the HPC algorithms
# Copyright (c) 2021. Victor Tuah Kumi, Ahmed Iqbal, Javier Vite, Aidan Forester
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 18 04:08:56 2017
@author: Mahmoud M. Abdelrahman
GHPL_contour
"""
import numpy as np
import matplotlib.pyplot as plt
data = "##input##"
cmap = '##cmap##'
levels = ##levels##
workingDir = "##workingDir##"
fileNameString = "##fileNameString##"
openData = open(data, 'r'... |
import astropy.constants as astroconst
from astropy import units as u
import numpy as np
# Defining Constants
# AU in cm
au = astroconst.au.decompose(u.cgs.bases).value
# Jupiter Radius in cm
# R_J = astroconst.R_jup.decompose(u.cgs.bases).value
R_J = astroconst.R_jup.decompose(u.cgs.bases).value
# Jupiter Radius sq... |
from __future__ import annotations
from time import sleep
from detect import DetectionSession, DetectPlugin
from typing import Any, List
import numpy as np
import cv2
import imutils
from gi.repository import GLib, Gst
from scrypted_sdk.types import ObjectDetectionModel, ObjectDetectionResult, ObjectsDetected
class Ope... |
# CloudFoundry (Heroku, IBM, etc.)
HOST = "0.0.0.0"
PORT = 8080
WEBHOOK_URI = None
# Telegram
PROXY = 'socks5://1.171.182.155:1080'
ENDPOINT = 'https://api.telegram.org'
# Text constants
MSG_GREETING = (f"Hi there, I am EchoBot. "
f"I am here to echo your kind words back to you. "
f"Ju... |
def sigma_days(days, daily_sigma):
return days*daily_sigma
sigma10 = sigma_days(10, 0.2)
print("The 10-day volatility is ${0:.2f}".format(sigma10)) |
"""
Created on 20 Jan 2021
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
https://realpython.com/python-logging/
"""
import logging
import sys
# --------------------------------------------------------------------------------------------------------------------
# noinspection PyPep8Naming
class Loggin... |
"""
Author : Robin Phoeng
Date : 24/06/2018
"""
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from Game import Game
import DiscordUtility
import BarFactory
from Bar import Box
Client = discord.Client()
bot = commands.Bot(command_prefix=... |
"""
WSGI config for parking project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTI... |
__copyright__ = "Copyright 2017-2018, http://radical.rutgers.edu"
__author__ = "Vivek Balasubramanian <vivek.balasubramaniana@rutgers.edu>"
__license__ = "MIT"
import radical.utils as ru
from radical.entk.exceptions import *
from radical.entk.pipeline.pipeline import Pipeline
from radical.entk.stage.stage import Stage... |
"""
AStar search
author: Ashwin Bose (@atb033)
"""
class AStar():
def __init__(self, env):
self.agent_dict = env.agent_dict
self.admissible_heuristic = env.admissible_heuristic
self.is_at_goal = env.is_at_goal
self.get_neighbors = env.get_neighbors
def reconstruct_path(self,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-22 19:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
# author: Paul Galatic github.com/pgalatic
#
# file handles downloading images
#
import os
import random
import logging
import datetime
import requests
from PIL import Image
from reddit import Reddit
from PIL import ImageChops
from imgur_album_downloader.imguralbum import ImgurAlbumDownloader
NO_ERROR = 0
ERR_NOT_IMA... |
def get_account(user):
from .models import Account
return Account.objects.for_user(user)
def get_data(request):
from .util import account_data
return account_data(request) |
# --------------
import pandas as pd
import scipy.stats as stats
import math
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#Sample_Size
sample_size=2000
#Z_Critical Score
z_critical = stats.norm.ppf(q = 0.95)
# path [File location variable]
data=pd.read_csv(path)
#Code starts here
d... |
from utils import *
from darknet import Darknet
import cv2
import pyrealsense2 as rs
def demo(cfgfile, weightfile):
m = Darknet(cfgfile)
m.print_network()
m.load_weights(weightfile)
print('Loading weights from %s... Done!' % (weightfile))
class_names = load_class_names(namesfile)
use_cuda = 1... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
import unittest
from unittest import mock
from algoliasearch.exceptions import AlgoliaException
from . import BaseWebTest
class RecordIndexing(BaseWebTest, unittest.TestCase):
def setUp(self):
self.app.put("/buckets/bid", headers=self.headers)
self.app.put("/buckets/bid/collections/cid", header... |
import os
import cv2
import numpy as np
import pandas as pd
from torchvision.transforms import transforms
from torch.utils.data import Dataset
from datasets.base_dataset import BaseDataset
from utils.augmenters.augment import seg
import xml.etree.ElementTree as ET
from PIL import Image
import matplotlib.pyplot as plt
... |
# The MIT License (MIT)
# Copyright (c) 2014 Microsoft Corporation
# 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... |
#!/usr/bin/env python
# Copyright (c) 2013 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 the default STRIP_STYLEs match between different generators.
"""
import TestGyp
import re
import subprocess
import sys
i... |
# -*- coding: UTF-8 -*-
import requests
import time
def html_parse(uid, html_content):
html_len = len(html_content)
uname = ""
duty = "user"
vip = "NA"
for i in range(0, html_len):
line_content = html_content[i].strip()
if line_content.find("bbsid") >= 1:
uname = line_co... |
import requests
import re
import time
import os
from datetime import datetime, timezone
from bs4 import BeautifulSoup
from sty import fg, bg, ef, rs
URL = "https://pid.cz/zastavkova-tabla/?stop=Hlavn%C3%AD&stanoviste=A"
def get_data():
try:
req = requests.get(URL)
soup = BeautifulSoup(req.conten... |
from pybind11_tests import iostream as m
import sys
from contextlib import contextmanager
try:
# Python 3
from io import StringIO
except ImportError:
# Python 2
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
# Python 3.4
from con... |
#!/usr/bin/env python
# encoding: utf-8
""" """
from web import Storage
from teslafaas.container.webpy.context_manager import ContextManager
from teslafaas.container.webpy.http_error_process import customize_http_error
import os
import sys
import web
import json
import pkgutil
import logging
import importlib
from cod... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pprint
from bs4 import BeautifulSoup
from astropy.extern.six.moves.urllib import parse as urlparse
from astropy.extern import six
from astropy import units as u
from . import conf
from ..query import BaseQuery
from ..utils import prepend_docstr_nor... |
import os
from datetime import datetime
def connect_notebook_to_post(name='Untitled', title='New post', tags='ipython', author='UEA'):
"""
Write a header to a markdown blog post and return an HTML string with links to the notebook.
Idea taken from http://ocefpaf.github.com/python4oceanographers
""... |
# -*- coding: utf-8 -*-
# Copyright 2015 Spotify AB. All rights reserved.
#
# The contents of this file are 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/LICE... |
from turtle import *
PART_OF_PATH = 'O'
TRIED = '.'
OBSTACLE = '+'
DEAD_END = '-'
# 假设or判断语句中有x个并列条件,只要第一个条件满足,就会直接进入下一步。
# 先沿着第一支一直往下算,算不通就返回上一级的第二支。。。上一级全部不通就返回上上一级的第二支。。。如此循环,确定第一个条件是T or F
class Maze(object):
def __init__(self, filename):
# 把txt文件转换成list。确认S的初始位置
rowsInMaze = 0
cols... |
"""CostCalculator that computes network cost or regularization loss."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
CONV2D_OPS = ('Conv2D', 'Conv2DBackpropInput', 'DepthwiseConv2dNative')
FLOP_OPS = CONV2D_OPS + ('MatMul',)
SUP... |
import abc
import builtins
import datetime
import enum
import typing
import jsii
import publication
import typing_extensions
import aws_cdk.core._jsii
import constructs._jsii
__jsii_assembly__ = jsii.JSIIAssembly.load(
"@aws-cdk/aws-kinesisfirehose",
"1.108.1",
__name__[0:-6],
"aws-kinesisfirehose@1.... |
import os
import pytest
from mikeio import Dfsu
##################################################
# these tests will not run if shapely is not installed
##################################################
pytest.importorskip("shapely")
def test_to_shapely():
filename = os.path.join("tests", "testdata", "oresund... |
# Copyright 2019 DeepMind Technologies Limited. 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 ... |
# Created by Pearu Peterson, September 2002
from __future__ import division, print_function, absolute_import
__usage__ = """
Build fftpack:
python setup_fftpack.py build
Run tests if scipy is installed:
python -c 'import scipy;scipy.fftpack.test()'
Run tests if fftpack is not installed:
python tests/test_basic.... |
from lib import *
audio2audio("test1.mp3","test1.wav") |
#20190212 count the number of cpu cores
import os
import sys
ncores = 0
lines = os.popen('cat /proc/cpuinfo | grep "cpu cores"').read().strip().split('\n')
for line in lines:
ncores += int(line.strip().split()[-1])
print "number of cpu cores", ncores |
"""Code for reading and writing scansion text-format protocol buffers."""
from google.protobuf import text_format # type: ignore
from . import scansion_pb2 # type: ignore
# TODO(kbg): Add read and write functions for Verse messages, if needed.
def read_document(path: str) -> scansion_pb2.Document:
"""Reads... |
# -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Authors: Jean-Emile DARTOIS <jean-emile.dartois@b-com.com>
#
# 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/... |
from testbook import testbook
from tests.conftest import REPO_ROOT
@testbook(REPO_ROOT / "examples/01-Getting-started.ipynb", execute=False)
def test_func(tb):
tb.inject(
"""
from unittest.mock import patch
from merlin.datasets.synthetic import generate_data
mock_train, mock_valid... |
from server.app import create_app
app = create_app()
app.run(host='127.0.0.1', port=5000, debug=True) |
#############################################################################
# Copyright (c) 2015-2016 Balabit
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation, or (at your option) an... |
#!/usr/bin/python
import render
import xmlrpclib
import json
from config import *
with open('secret.txt', 'r') as f:
secret = json.load(f)
passwd = secret['wordpress']['password']
x = xmlrpclib.ServerProxy(XMLRPC_ENDPOINT)
page = x.wp.getPage(BLOG_ID, PARTICIPANTS_PAGE_ID, USER, passwd)
text = render.rende... |
import flask
from flask import Flask
from .database import Database
app = Flask(__name__)
DATABASE = '/tmp/kittens.db'
def get_db():
db = getattr(flask.g, '_database', None)
if not db:
db = flask.g._database = Database(DATABASE)
return db
@app.teardown_appcontext
def close_db(exception):
db... |
import objects.Symbol as Symbol
import objects.Token as Token
import objects.Node as Node
import objects.Program as Program
import parser.ParseDFA as ParseDFA
import re
from anytree import Node as Node_any
from anytree import RenderTree
from anytree.exporter import DotExporter
class Irt:
def irt(self, main_program... |
import requests
import time
import json
# Dummy data to represent the statius of the neck application
current_neck_pan = 0
current_neck_tilt = 0
tactile_data = {'sensor0':1, 'sensor1':1, 'sensor2':1};
# Dummy data for LED
current_led_rgb = [255,255,255]
# Robot and database info
this_robot_id = 0
api_key = ""
URL = ... |
import re
import time
from pyquery import PyQuery as pq
from policy_crawl.common.fetch import get,post
from policy_crawl.common.save import save
from policy_crawl.common.logger import alllog,errorlog
def parse_detail(html,url):
alllog.logger.info("天津市教育厅: %s"%url)
doc=pq(html)
data={}
data["title"]=d... |
#!/usr/bin/env python
from boutiques.validator import validate_descriptor, ValidationError
from boutiques.logger import raise_error, print_info
from boutiques.zenodoHelper import ZenodoError, ZenodoHelper
from boutiques.util.utils import customSortDescriptorByKey
import simplejson as json
import requests
import os
c... |
import re
import pathlib
from typing import List, Union
from .resource_mgr import res_mgr
from .io import fopen
class FilterChain:
"""A sequential filter chain to post-process list of tokens. The **available
filters are:**
`c2w`: Stitches back space delimited characters to words.
Necessary for w... |
import _plotly_utils.basevalidators
class TextValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(self, plotly_name="text", parent_name="isosurface", **kwargs):
super(TextValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
arra... |
import logging
from flask import jsonify
from sqlalchemy import and_, func, or_
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm.exc import NoResultFound
from structlog import wrap_logger
from werkzeug.exceptions import InternalServerError, NotFound, Forbidden
from secure_message.constants import NON_SP... |
#!/usr/bin/python3
import json
from iot_message.message import Message
import iot_message.exception as ex
class MessageFactory(object):
"""Class MessageFactory"""
@classmethod
def create(cls, data=None):
if data is None:
return Message()
else:
return cls._decode(dat... |
# Copyright 2019 The Blueqat Developers
#
# 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 i... |
import pandas as pd
from data_pipeline.etl.base import ExtractTransformLoad
from data_pipeline.utils import get_module_logger
from data_pipeline.score import field_names
from data_pipeline.config import settings
logger = get_module_logger(__name__)
class MichiganEnviroScreenETL(ExtractTransformLoad):
"""Michiga... |
import os
import os.path as osp
import numpy as np
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
from torch.utils.data import DataLoader
from magnificat import drw_utils
from magnificat.cadence import LSSTCadence
class DRWDataset(Dataset):
bp_to_int = dict(zip(list('ugrizy'), range(6)))... |
import sasoptpy as so
import pandas as pd
def test(cas_conn):
m = so.Model(name='decentralization', session=cas_conn)
DEPTS = ['A', 'B', 'C', 'D', 'E']
CITIES = ['Bristol', 'Brighton', 'London']
benefit_data = pd.DataFrame([
['Bristol', 10, 15, 10, 20, 5],
['Brighton', 10, 20, 15, 1... |
# -*- coding: utf-8 -*-
import unittest
import sys
import oss2
from oss2 import to_bytes, to_string
from common import *
class TestChinese(OssTestCase):
def test_unicode_content(self):
key = self.random_key()
content = u'几天后,阿里巴巴为侄子和马尔佳娜举行了隆重的婚礼。'
self.bucket.put_object(key, content)
... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup
setup(name='lotube-crawler',
version='1.0',
description='LOTube video crawler',
author='lotube',
url='https://github.com/zurfyx',
packages=[
'lotube_crawler',
'lotube_crawler.base',
'lotube_crawler.extractor',
... |
import heapq
from operator import attrgetter
class Beam(object):
def __init__(self, maxsize, key=attrgetter("score")):
self.key = key
self.maxsize = maxsize
self.beam = []
def push(self, x):
key = self.key(x)
if len(self.beam) < self.maxsize:
heapq.heappush... |
from abc import ABC, abstractclassmethod
class DriverInterface(ABC):
@abstractclassmethod
def start(self) -> object:
raise NotImplementedError()
@abstractclassmethod
def getContent(self) -> str:
raise NotImplementedError()
@abstractclassmethod
def goTo(self) -> None:
... |
#!/usr/bin/env python
# Copyright 2016 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
"""Tries to evaluate global constructors, apply... |
def simple_cnn():
model = Sequential()
model.add(Convolution2D(32, 1, 4, 4, border_mode='full', activation='relu'))
model.add(Convolution2D(32, 32, 4, 4, activation='relu'))
model.add(MaxPooling2D(poolsize=(3, 3)))
model.add(Dropout(0.25))
model.add(Convolution2D(64, 32, 4, 4, border_mode='full'... |
from setuptools import find_packages, setup
setup(
name="share_rest_api",
package_dir={"": "src"},
packages=find_packages("src"),
package_data={},
include_package_data=True,
version="0.0.1",
long_description="...",
long_description_content_type="text/markdown",
keywords=["python"],
... |
# Copyright (C) [2021] by Cambricon, Inc.
#
# 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, merge, publish... |
# /usr/bin/python
# -*- coding: utf-8 -*-
"""
MongoDB logger module
"""
import datetime
import logging
import os
import json
import inspect
import random
from typing import Optional
from pymongo import MongoClient
class MongoLogger:
"""
MongoDB logger class.\n
"""
LEVELS = {'crit': 50, 'err': 40, 'wa... |
import math
import torch
import torch.nn as nn
import torch.nn.init as init
import torchvision
from . import block as B
from . import spectral_norm as SN
import functools
import numpy as np
import os
import models.modules.archs_util as arch_util
import torch.nn.functional as F
import re
####################
# Generato... |
#importando biblioteca de ano e pausa de apresentação
from datetime import date
from time import sleep
print('-*'*25)
print(' '*6,'CONFEDERAÇÃO NACIONAL DE NATAÇÃO')
print('-*'*25)
sleep(2)
print(''' As Categorias de Atletas são:
– Até 9 anos: MIRIM
– Até 14 anos: INFANTIL
– Até 19 anos: JÚNIOR
– Até 25 anos: SÊNIOR
–... |
"""
This files purpose is to the be one place of truth for the version of this
project.
The variable __version__ is a string following the guidelines of semantic
versioning. The general guidelines are as follows
Given a version number MAJOR.MINOR.PATCH, increment the:
1. MAJOR version when you make incompatible API ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from preggy import expect
from tornado.testing import gen_test
from... |
import tkinter as tk
import subprocess
import json
import os
import re
class PingAnalysis:
def __init__(self):
self.settings_file = open("settings.json", "r")
self.settings_json = json.load(self.settings_file)
self.settings_file.close()
self.FONT_SMALL = (f"{self.settings_json['FO... |
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRe... |
from collections import defaultdict
def condense_line(line):
necessary = line.replace(' bags', '').replace(' bag', '').replace('.', '')
segmented = necessary.replace(' contain ', ':').replace(', ', ':').split(':')
return segmented[0], segmented[1:]
def decode_bag_rules(rules):
bags = defaultdict(set... |
class WirelessSettings(object):
def __init__(self, session):
super(WirelessSettings, self).__init__()
self._session = session
def getNetworkWirelessSettings(self, networkId: str):
"""
**Return the wireless settings for a network**
https://developer.cisco.com/docs/mer... |
"""
Module implementing different samplers for the chipnexus data
"""
import pandas as pd
import numpy as np
from kipoi_utils.external.torch.sampler import Sampler
from kipoi_utils.data_utils import iterable_cycle
import warnings
import gin
def get_batch_sizes(p_vec, batch_size, verbose=True):
"""Compute the indi... |
from comet_ml import experiment
from data_loader.uts_classification_data_loader import UtsClassificationDataLoader
from models.uts_classification_model import UtsClassificationModel
from trainers.uts_classification_trainer import UtsClassificationTrainer
from evaluater.uts_classification_evaluater import UtsClassificat... |
from abc import ABCMeta, abstractmethod
from .chromosome import IChromosome
class IFitness(metaclass=ABCMeta):
"""
Description:
------------
適応度のinterface
"""
@abstractmethod
def evaluate(self, chromosome: IChromosome) -> None:
pass |
import os
import sys
from pathlib import Path
from typing import Optional, Union, Tuple
import sumo_rl
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)
else:
sys.exit("Please declare the environment variable 'SUMO_HOME'")
import traci
import sumolib... |
"""APBS interface for PDB2PQR
Authors: Todd Dolinsky, Jens Erik Nielsen
"""
import logging
import time
import string
from src import psize
from src import inputgen
from apbslib import *
_LOGGER = logging.getLogger(__name__)
Python_kb = 1.3806581e-23
Python_Na = 6.0221367e+23
NOSH_MAXMOL = 20
NOSH_MAXCALC = 20
... |
import os
import shutil
import subprocess
runinfo_fname = os.path.abspath('./example.runinfo')
output_directory = os.path.abspath('./runfiles/output/')
if os.path.isdir(output_directory):
shutil.rmtree(output_directory, ignore_errors=True)
print('making {}'.format(output_directory))
os.mkdir(output_directory)
pri... |
class Solution:
# def romanToInt(self, s):
# """
# :type s: str
# :rtype: int
# """
# roman = {'I': 1, 'V': 5, 'X': 10,
# 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# result = 0
# last = s[-1]
# for t in reversed(s):
# if t ==... |
name='Swaroop'
if name.startswith('Swa'):
print 'Yes,the string start with "Swa"'
if 'a' in name:
print 'Yes,it contains the string "a"'
if name.find("war")!=-1:
print 'Yes,it contains the string "war"'
delimiter='_*_'
mylist=['Brazil','Russia','India','China']
print delimiter.join(mylist) |
__author__ = "Benedict Thompson", "Hon Lam Lee"
__version__ = "0.1p"
import random
import re
from enum import Enum
import os
import csv
import requests
import time
import datetime
class MessageTone(Enum):
POSITIVE = 1
NEUTRAL = 0
NEGATIVE = -1
class WarningLevel(Enum):
WARNING = 0
MUTE = 1
... |
"""
remesh.py
-------------
Deal with re- triangulation of existing meshes.
"""
import numpy as np
import collections
from . import util
from . import grouping
def subdivide(vertices, faces, face_index=None):
"""
Subdivide a mesh into smaller triangles.
Parameters
----------
vertices: (n,3) f... |
from flask import request, Response # type: ignore
import json
import logging
import logging.config # type: ignore
from service import app, auditing, db_access, security
AUTH_FAILURE_RESPONSE_BODY = json.dumps({'error': 'Invalid credentials'})
INVALID_REQUEST_RESPONSE_BODY = json.dumps({'error': 'Invalid request'}... |
class Backend:
async def on_start(self, app):
pass
async def on_shutdown(self, app):
pass
def prepare_context(self, ctx):
pass
async def perform_updates_request(self, submit_update):
raise NotImplementedError
async def perform_send(self, target_id, message, attach... |
import nlu
from nlu.discovery import Discoverer
from nlu.pipe.utils.storage_ref_utils import StorageRefUtils
from typing import List, Tuple, Optional, Dict, Union
import streamlit as st
from nlu.utils.modelhub.modelhub_utils import ModelHubUtils
import numpy as np
import pandas as pd
from nlu.pipe.viz.streamlit_viz.st... |
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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... |
# imports
from .correlation import FunctionCorrelation |
# -*- coding: utf-8 -*-
from wtforms import Form, StringField, PasswordField, validators
class modificationForm(Form):
username = StringField('User Name', [
validators.Optional(),
validators.Length(min=2, max=20)
])
email = StringField('Email', [
validators.Optional(),
vali... |
import matplotlib.pyplot as plt
import argparse
import os
from collections import defaultdict
import habitat
import numpy as np
import quaternion
import torch
from evaluate_reality import load_model
from gym.spaces.dict_space import Dict as SpaceDict
from habitat.tasks.utils import cartesian_to_polar
from habitat.util... |
#!/usr/bin/env python
# -*- coding: latin-1; -*-
'''
Copyright 2018 University of Liège
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 req... |
#!/usr/bin/env python
#
# Copyright 2007 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 o... |
import torch
from torch_geometric.data import InMemoryDataset, Data, DataLoader
from torch_geometric.transforms import Compose
import numpy as np
from scipy.spatial.transform import Rotation
import math
import urllib.request
import tarfile
from pathlib import Path
import requests
from data_preprocessing.convert_pdb2npy... |
from interface.settings import *
SECRET_KEY = 'fake-key'
INSTALLED_APPS.append("tests") |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
DateType,
DataType,
)
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class EvidenceSchema:
"""
The Evidence... |
import sys
def get():
return sys.path |
p = str(input('EScreva uma frase: ')).lower() # vai ler e dizer se lido normal e de traz para frente é igaul
palavras = p.split()
sem = ''.join(palavras)
print(sem)
l = p.replace(" ", "") # reescreve trocando os espaços vazios por nada - uni as palavras
print(l)
n = len(l)
# print(n)
# print('++++++++')
for cnt in ra... |
# Copyright 2016 - Nokia Networks.
#
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.