content
stringlengths
0
894k
type
stringclasses
2 values
# test.py """ This file houses the suite of tests for main.py classes and functions THIS FILE IS A MESS AND TOTALLY BROKEN AT THIS POINT IT WILL NOT RUN IT IS HERE THAT IT MAY BE CANABALISED FOR FUTURE ITERATIONS OF THE PROJECT """ def test_variables(): """ variables needed for various tests """ ...
python
# Copyright 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
python
import os from leapp.models import FirewalldGlobalConfig def read_config(): default_conf = FirewalldGlobalConfig() path = '/etc/firewalld/firewalld.conf' if not os.path.exists(path): return default_conf conf_dict = {} with open(path) as conf_file: for line in conf_file: ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Ensure system commands and responses execute successfully.""" import pytest from stepseries import commands, responses, step400 from tests.conftest import HardwareIncremental @pytest.mark.skip_disconnected class TestSpeedProfileSettings(HardwareIncremental): de...
python
# -*- test-case-name: twisted.lore.test.test_slides -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Rudimentary slide support for Lore. TODO: - Complete mgp output target - syntax highlighting - saner font handling - probably lots more - Add HTML output ...
python
# -*- coding: utf-8 -*- """ ------------------------------------------------- @File : __init__.py Description : @Author : pchaos tradedate: 2018-4-7 ------------------------------------------------- Change Activity: 2018-4-7: @Contact : p19992003#gmail.com -----------------------------...
python
# Create a list of strings: mutants mutants = ['charles xavier', 'bobby drake', 'kurt wagner', 'max eisenhardt', 'kitty pryde'] # Create a list of tuples: mutant_list mutant_list = list(enumerate(mutants)) # Print the list of tuples print(mutant_list) # Unpack and ...
python
import abc import dataclasses import datetime from typing import Callable, List, Optional from xlab.base import time from xlab.data.proto import data_entry_pb2, data_type_pb2 class DataStore(abc.ABC): # Add a single data entry to the store. No exception is thrown if the # operation is successful. @abc.ab...
python
import subprocess; from Thesis.util.ycsbCommands.Commands import getLoadCommand; from Thesis.util.ycsbCommands.Commands import getRunCommand; from Thesis.util.util import checkExitCodeOfProcess; class Cluster(object): def __init__(self, normalBinding, consistencyBinding, nodesInCluster): self.__norma...
python
from .KickerSystem import KickerSystem
python
import pygame, sys from pygame.locals import * from camera import * def event_system(width, height): keys = pygame.key.get_pressed() is_fs = False for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if keys[pygame.K_ESCAPE]: ...
python
""" This file handles their access credentials and tokens for various APIs required to retrieve data for the website. The file that contains the credentials is called "vault.zip", and is referenced by a constant, `VAULT_FILE`. This file is accessed using a password stored in the config called `VAULT_PASSWORD`. Inside...
python
import streamlit as st container = st.container() container.write("This is inside the container") st.write("This is outside the container") # Now insert some more in the container container.write("This is inside too")
python
#!/usr/bin/env python # Usage: ./twitget.py twitget.ini import configparser import time import sys from pymongo import MongoClient import TwitterSearch import requests import logging logging.basicConfig(level=logging.DEBUG) DEFAULT_INTERVAL = 15 * 60 DEFAULT_LANGUAGE = 'en' def get_tweets(tweets_col, config): ...
python
from scrapers.memphis_council_calendar_scraper import MemphisCouncilCalScraper from . import utils def test_get_docs_from_page(): memphis_scraper = MemphisCouncilCalScraper() page_str = open(utils.get_abs_filename( 'memphis-city-council-calendar.html'), 'r').read() docs = memphis_scraper._get_docs...
python
from exquiro.parsers.package_diagram_parser import PackageDiagramParser from exquiro.models.package_diagram.package_node import PackageNode from exquiro.models.package_diagram.package_relation import PackageRelation from lxml import etree import uuid class OpenPonkPackageDiagramParser(PackageDiagramParser): def p...
python
import os import numpy as np import pandas as pd import rampwf as rw from rampwf.score_types.base import BaseScoreType class Mechanics(object): def __init__(self, workflow_element_names=[ 'feature_extractor', 'classifier', 'regressor']): self.element_names = workflow_element_names self...
python
# Copyright 2021 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...
python
""" Visdom server ------------- .. autosummary:: :toctree: toctree/monitor VisdomMighty """ import os import sys import time from collections import defaultdict import numpy as np import visdom from mighty.monitor.batch_timer import timer from mighty.utils.constants import VISDOM_LOGS_DIR class VisdomMig...
python
""" Gaze @author Anthony Liu <igliu@mit.edu> @version 1.1.0 """ from context import Rasta import numpy as np class Scene(object): x_range, y_range, z_range = 13.33333, 10., 10. num_viewer_params = 3 num_box_params = 3 @classmethod def sample(cls, num_boxes): # generate the boxes ...
python
v = int(input('Digite um valor')) print('o numero antecessor é {} e o numero sucessor é {}'.format((v-1),(v+1))) print('o numero somado a 10 é igual a {}'.format(v+10))
python
from .__version__ import __version__ from .util import environment_info from .wrapper import ( convert_into, convert_into_by_batch, read_pdf, read_pdf_with_template, )
python
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or module...
python
from sqlalchemy import Column, Integer, String, DECIMAL, ForeignKey, Date, Time, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class TimeEntry(Base): __tablename__ = "time_entries" time_entry_id = Column(Integer, primary_key...
python
import json import logging import re import sys import urllib.parse import requests logger = logging.getLogger(__name__) URL = sys.argv[1] NETLOC = urllib.parse.urlparse(URL)[1] ALLOWED_MAP = { # if any of these strings is in url, error is allowed 405: ["/xmlrpc.php", "wp-comments-post.php"], 400: ["?re...
python
import argparse import time from geopy.geocoders import Nominatim app = Nominatim(user_agent="pycoordinates") def get_location(latitude, longitude, verbose): '''Takes in a latitude and longitude and returns the commensurate location. :param latitude: the latitude :param longitude: the longitude :type...
python
""" This module consists of functions to calculate the [equivalent latitude](https://journals.ametsoc.org/doi/citedby/10.1175/1520-0469%282003%29060%3C0287%3ATELADT%3E2.0.CO%3B2) and edge of a polar vortex using [Nash criteria](https://agupubs.onlinelibrary.wiley.com/doi/10.1029/96JD00066). ### Installation ``` pip ...
python
''' Problem 9 25 January 2002 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ----------------------------------------...
python
# from django_filters import Filter # Add your filters here
python
import shap import numpy as np import cv2 class BetterImageMasker(shap.maskers.Image): def __call__(self, mask, x): if np.prod(x.shape) != np.prod(self.input_shape): raise Exception("The length of the image to be masked must match the shape given in the " + \ "ImageM...
python
# Generated by Django 2.1.5 on 2019-01-05 14:44 import django.contrib.postgres.fields import django.core.validators from django.db import migrations, models import reader.validators class Migration(migrations.Migration): dependencies = [ ('reader', '0011_auto_20181001_1853'), ] operations = [ ...
python
# -*- coding: utf-8 -*- import numpy as np from ipywidgets import interact from PIL import Image # [Preparation] # - check installation of jupyter and ipywidgets with # `pip list | grep ipywidgets` # - make the following jupyter extension enable # jupyter nbextension enable --py widgetsnbextension --sys-prefix de...
python
i = 0 classe = [] continuar = '' while True: nome = str(input('Nome: ').strip()) nota1 = float(input('Nota 1: ').strip()) nota2 = float(input('Nota 2: ').strip()) classe.append([i, nome, nota1, nota2, (nota1 + nota2) / 2]) while True: continuar = str(input('Quer continuar? [S/N] ').strip()[...
python
# Individual image generator import sys HW_NUMBER = int(sys.argv[1]) Q_NUMBER = int(sys.argv[2]) HW_PATH = sys.argv[3] + "/body.tex" f = open(HW_PATH, 'r') content = [n for n in f.readlines() if (not n.startswith('%') and not n.startswith('\sol') and n.strip())] def index_containing_substring(the_list, substring): ...
python
from typing import Sequence, Union, Optional from typing_extensions import Literal from .transforms import CriteriaFn from .deform import deform_image_random from ..transforms import transforms class TransformRandomDeformation(transforms.TransformBatchWithCriteria): """ Transform an image using a random defor...
python
import stk from .utilities import is_equivalent_atom def test_repr(atom): """ Test :meth:`.Atom.__repr__`. Parameters ---------- atom : :class:`.Atom` The atom, whose representation should be tested. Returns ------- None : :class:`NoneType` """ other = eval(repr(at...
python
##################################################################################### # Manager class of Meal which deals with Meal saving / loading / setting / deleting # ##################################################################################### from Manager import Manager from Models.Meal import Meal impor...
python
#!/usr/bin/env python # coding: utf-8 # In[1]: def gpa_cal(scores : str,base:int = 10) -> float: """Return float Grade Point Average for anyy base with default as 10 A- and B+ aree treated as similar, althouh functionality can be modified""" gpa_final = 0.0 scores = scores.upper() # To allow fo...
python
from docker import DockerClient from aavm.utils.progress_bar import ProgressBar from cpk.types import Machine, DockerImageName ALL_STATUSES = [ "created", "restarting", "running", "removing", "paused", "exited", "dead" ] STOPPED_STATUSES = [ "created", "exited", "dead" ] UNSTABLE_STATUSES = [ "restarting"...
python
"""Hyperopt templates for different models""" # forked from hyperopt/hyperopt-sklearn from functools import partial import numpy as np from hyperopt import hp from hyperopt.pyll import scope import sklearn.discriminant_analysis import sklearn.ensemble import sklearn.feature_extraction.text import sklearn.preprocess...
python
from unittest import TestCase from unittest.mock import patch from app.ingest.infrastructure.mq.publishers.process_ready_queue_publisher import ProcessReadyQueuePublisher from test.resources.ingest.ingest_factory import create_ingest class TestProcessReadyQueuePublisher(TestCase): @classmethod def setUpClass...
python
from aioredis import Redis, ConnectionPool from six.moves import xrange from ._util import to_string from .auto_complete import SuggestionParser class AioAutoCompleter(object): """ An asyncio client to RediSearch's AutoCompleter API It provides prefix searches with optionally fuzzy matching of prefixes ...
python
from .files import sppasFilesPanel __all__ = ( "sppasFilesPanel", )
python
from telebot import types from typing import List from datetime import datetime import logging from tengi.telegram.telegram_bot import TelegramBot logger = logging.getLogger(__file__) class TelegramCursor: def __init__(self, bot: TelegramBot, look_back_days: float, long_polling_timeout: float = 20): sel...
python
from willump.graph.willump_graph_node import WillumpGraphNode from willump.graph.willump_python_node import WillumpPythonNode from weld.types import * import ast from typing import List from willump.willump_utilities import strip_linenos_from_var class CascadeStackDenseNode(WillumpPythonNode): """ Willump S...
python
import os import sys import argparse from datetime import date from collections import defaultdict from egcg_core.app_logging import logging_default from egcg_core.config import cfg from egcg_core.util import query_dict from egcg_core import rest_communication from egcg_core.notifications.email import send_html_email ...
python
# -*- coding: utf-8 -*- import sys import gettext import Adventurer3.Controller gettext.install(__name__) class App: """UIアプリケーションクラス""" def __init__(self, ipaddress): self.adv3 = Adventurer3.Controller.Controller(ipaddress) def user_interface(self): while True: cmd = input("...
python
# coding: utf-8 import torch from torch.nn import functional as F import torch.utils.data import torch.utils.data.distributed from torch import autograd import numpy as np from gan_training.random_queue import Random_queue class Trainer(object): def __init__(self, generator, disc...
python
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
python
from apps import db from datetime import datetime #基础表 class BaseModel(object): create_time = db.Column(db.DateTime,default=datetime.now) update_time = db.Column(db.DateTime,default=datetime.now) #分类表 class Cate(BaseModel,db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String...
python
from decimal import Decimal from simfile.ssc import SSCSimfile import unittest from .helpers import testing_timing_data from .. import * from simfile.sm import SMSimfile class TestBeat(unittest.TestCase): def test_from_str(self): self.assertEqual(Beat(0, 1), Beat.from_str('0.000')) self.assertEqua...
python
# For compatibilty from ignite.utils import convert_tensor, apply_to_tensor, apply_to_type, to_onehot def _to_hours_mins_secs(time_taken): """Convert seconds to hours, mins, and seconds.""" mins, secs = divmod(time_taken, 60) hours, mins = divmod(mins, 60) return hours, mins, secs
python
class ScoreCard: def __init__(self, score_text: str): score_texts = score_text.split('|') self.normal_turns = [score_texts[i] for i in range(10)] if len(score_texts) == 12: self.additional_turns = [score_texts[11]] self.all_turns = self.normal_turns + self.additional_tur...
python
import os import cgi import requests import shutil def download_file(url, path, file_name=None): """Download file from url to directory URL is expected to have a Content-Disposition header telling us what filename to use. Returns filename of downloaded file. """ res = requests.get(url, stre...
python
from lib.getItensFromEntrance import getItens from lib.controllerImage import controllerImg import os import sys arguments = sys.argv pathDirect = os.getcwd() resizeImage = controllerImg(pathDirect, arguments) resizeImage.resizeImage()
python
from django.test import TestCase from .models import Location, Category, Photographer, Image # Create your tests here. class LocationTestClass(TestCase): def setUp(self): self.loc = Location(location_name = 'Mombasa, Kenya') # Testing instance def test_instance(self): self.assertTrue(isin...
python
#!/usr/bin/env python import sys field = int(sys.argv[1]) for i in sys.stdin: try: print(i.split()[field - 1], end=" ") print() except: pass
python
"""maillinter uses setuptools based setup script. For the easiest installation type the command: python3 setup.py install In case you do not have root privileges use the following command instead: python3 setup.py install --user This installs the library and automatically handle the dependencies. """ impor...
python
import logging import re import os import sys from flexget import plugin from flexget import validator log = logging.getLogger('rtorrent_magnet') pat = re.compile('xt=urn:btih:([^&/]+)') class PluginRtorrentMagnet(object): """ Process Magnet URI's into rtorrent compatible torrent files Magnet URI's wil...
python
from collections import OrderedDict from os.path import dirname, join from library.commands.nvidia import NvidiaSmiCommand from library.commands.sensors import SensorsCommand ROOT_DIR = dirname(__file__) DATA_FOLDER = join(ROOT_DIR, "data") COMMANDS = [ SensorsCommand, NvidiaSmiCommand ] # How far to look ...
python
n1 = float(input("Digite uma nota: ")) n2 = float(input("Digite a outra nota: ")) media = (n1 + n2)/2 print("A média das notas {:.1f} e {:.1f} é {:.1f}".format(n1, n2, media))
python
'''def do_twice(f): f() f() def print_spam(): print('spam') do_twice(print_spam) ''' s = input('input string: ') def do_twice(function, a): function(a) function(a) def print_twice(a): print(a) print(a) def do_four(function, a): do_twice(function, a) do_twice(function, a) do_twice(p...
python
"""Module with implementation of utility classess and functions.""" from WeOptPy.util.utility import ( full_array, objects2array, limit_repair, limit_invers_repair, wang_repair, rand_repair, reflect_repair, explore_package_for_classes ) from WeOptPy.util.argparser import ( make_arg_parser, get_args, get_dic...
python
from typing import Optional from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_tf, try_import_torch from ray.rllib.utils.schedules.schedule import Schedule from ray.rllib.utils.typing import TensorType tf1, tf, tfv = try_import_tf() torch, _ = try_import_torch() class ...
python
from carla_utils import carla import os from os.path import join import random import signal import subprocess import time import psutil, pynvml from carla_utils.basic import YamlConfig, Data from carla_utils.system import is_used class Core(object): ''' Inspired by https://github.com/carla-simulator/...
python
""" File Name : apiview.py Description : Author : mxm Created on : 2020/8/16 """ import tornado.web import tornado.ioloop import tornado.httpserver import tornado.options from abc import ABC from tornado.options import options, define from tornado.web import RequestHandler clas...
python
from rest_framework import serializers from .models import UserInfo class json(serializers.ModelSerializer): class Meta: model = UserInfo fields = ('UserName', 'UserBookLogo')
python
from django.contrib.auth.models import AbstractUser from django.core import mail from django.db.models.signals import post_save from django.dispatch import receiver class User(AbstractUser): pass @receiver(post_save, sender=User) def send_success_email(sender, **kwargs): """Sends a welcome email after user ...
python
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################### # Author: Mu yanru # Date : 2019.2 # Email : muyanru345@163.com ################################################################### from dayu_widgets.label import MLabel from dayu_widgets.tool_button impo...
python
input = "hello my name is sparta" def find_max_occurred_alphabet(string): alphabet_occurrence_array = [0] * 26 for char in string: if not char.isalpha(): continue arr_index = ord(char) - ord("a") alphabet_occurrence_array[arr_index] += 1 result = find_max_occurred_alphab...
python
import itertools import numpy as np from sklearn.preprocessing import scale import matplotlib.pyplot as plt from matplotlib import collections as mc # TODO: document it and wrap it as pip package, make ipynb example def get_cmap(n, name='hsv'): """ Returns a function that maps each index in 0, 1, ..., n-1 t...
python
import numpy as np import pandas as pd import time import os import sys from copy import copy from fastdtw import fastdtw from scipy import interpolate from scipy.stats import levy, zscore, mode from sklearn.metrics import silhouette_score from sklearn.metrics.pairwise import * from scipy.spatial.distance import * from...
python
import cv2 import math import time import numpy as np mmRatio = 0.1479406021 scale = 2 frameWidth = 2304 frameHeight = 1536 frameCroopY = [650,950] windowsName = 'Window Name' def playvideo(): vid = cv2.VideoCapture(0) vid.set(cv2.CAP_PROP_FRAME_WIDTH, frameWidth) vid.set(cv2.CAP_PROP_FRAME_HEIGHT, fram...
python
import os from setuptools import setup, find_packages import lendingblock def read(name): filename = os.path.join(os.path.dirname(__file__), name) with open(filename) as fp: return fp.read() meta = dict( version=lendingblock.__version__, description=lendingblock.__doc__, name='lb-py', ...
python
# pylint: disable=import-error from importlib import import_module from flask_restplus import Api # pylint: disable=no-name-in-module from utils.configmanager import ConfigManager from app import resources def make_api(api_config): api = Api( prefix=api_config["prefix"], title=api_config["title"]...
python
import os import sys import random import time import traceback import torch import torch.optim as optim from configs import g_conf, set_type_of_process, merge_with_yaml from network import CoILModel, Loss, adjust_learning_rate_auto from input import CoILDataset, Augmenter, select_balancing_strategy from logger import...
python
import json import urllib.request from urllib.error import URLError from django.shortcuts import render, get_object_or_404, redirect from django.core.cache import cache from django.http import HttpResponse, Http404 from django.template import Context, Template, RequestContext from django.db.models import Q, Prefetch, C...
python
""" After implementation of DIP (Dependency Inversion Principle). The dependency (Database or CSV) is now injected in the Products class via a repository of type Database or CSV. A factory is used to create a Database or CSV repository. """ class ProductRepository: @staticmethod def select_products(): ...
python
## import os from setuptools import setup, find_namespace_packages from pkg_resources import get_distribution, DistributionNotFound def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup ( name = "namespace.HeardBox", use_scm_version = True, setup_requ...
python
"""Regression.""" from ._linear_regression import LinearRegression from ._neighbors_regression import ( KNeighborsRegressor, RadiusNeighborsRegressor, )
python
#!/usr/bin/python #-*- coding: utf-8 -*- # >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>. # Licensed under the Apache License, Version 2.0 (the "License") # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # --- File Name: parser.py # --- Creation Date: 24-02-2020 # --- Last Modified: Tue 25 Feb...
python
# Generated by Django 3.2.6 on 2021-08-27 19:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('university', '0006_representative'), ] operations = [ migrations.AddField( model_name='course', name='slug_unimi', ...
python
from utils import hashable_boundaries, predicted_len from objects import Database from collections import defaultdict from math import ceil import gen_spectra def modified_sort_masses_in_sorted_keys_b(db_dict_b,mz,kmer_list_b): kmers = db_dict_b[mz] kmer_list_b += kmers def modified_sort_masses_in_sorted_key...
python
"""This module contains the support resources for the two_party_negotiation protocol."""
python
""" Manages updateing info-channels (Currently only `log` channel) """ from typing import Union import discord from discord.ext import commands class InfoChannels(commands.Cog): def __init__(self, bot: commands.Bot): print('Loading InfoChannels module...', end='') self.bot = bot self.gui...
python
print(""" 042) Refaça o DESAFIO 035 dois triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: - Equilátero: todos os lados iguais - Isósceles: dois lados iguais - Escaleno: todos os lados diferentes """) print(""" Este programa recebe o valor de três retas e verifica se, com elas, é possí...
python
import unittest import hcl2 from checkov.common.models.enums import CheckResult from checkov.terraform.checks.resource.aws.AppLoadBalancerTLS12 import check class TestAppLoadBalancerTLS12(unittest.TestCase): def test_failure(self): resource_conf = {'load_balancer_arn': ['${aws_lb.examplea.arn}'], 'port...
python
class Solution: def longestValidParenthesesSlow(self, s: str) -> int: stack, ans = [-1], 0 for i in range(len(s)): if s[i] == ")" and len(stack) > 1 and s[stack[-1]] == "(": stack.pop() ans = max(ans, i - stack[-1]) else: stack....
python
from flask import Flask, redirect from flask_fileupload import FlaskFileUpload from flask_login import LoginManager, UserMixin, login_user, logout_user app = Flask(__name__) app.config.from_object("config") lm = LoginManager(app) fue = FlaskFileUpload(app) class User(UserMixin): def __init__(self, user_id): ...
python
""" This module implements graph/sparse matrix partitioning inspired by Gluon. The goal of this module is to allow simple algorithms to be written against the current sequential implementation, and eventually scale (without changes) to parallel or even distributed partitioning. As such, many functions guarantee much le...
python
## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 ## PubNub Real-time Push APIs and Notifications Framework ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ ## ----------------------------------- ## PubNub 3.1 Real-time Push Cloud API ## ----------------------------------- imp...
python
# Configuration file for the Sphinx documentation builder. # # For a full list of configuration options, see the documentation: # http://www.sphinx-doc.org/en/master/usage/configuration.html # Project information # -------------------------------------------------- project = 'Apollo' version = '0.2.0' release = '' ...
python
from bson.objectid import ObjectId from pymongo import MongoClient def readValue(value): try: return float(value) except ValueError: pass try: return int(value) except ValueError: pass return value def run(host=None, db=None, coll=None, key=None, prop=None, valu...
python
from flask import Flask, render_template, Blueprint from modules.BBCScraper import BBCScraper from modules.MaanScraper import MaanHealthScraper from modules.MOHScraper import CovidPalestine from modules.MaanScraper import MaanNewsScraper import time import concurrent.futures from modules.CovidScraper import BBCCovi...
python
from fractions import Fraction def answer(pegs): arrLength = len(pegs) if ((not pegs) or arrLength == 1): return [-1,-1] even = True if (arrLength % 2 == 0) else False sum = (- pegs[0] + pegs[arrLength - 1]) if even else (- pegs[0] - pegs[arrLength -1]) # print sum if (arrLength...
python
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # In[2]: df=pd.read_csv('car_data.csv') # In[3]: df.head() # In[5]: df.shape # In[6]: print(df['Seller_Type'].unique()) # In[26]: print(df['Transmission'].unique()) print(df['Owner'].unique()) print(df['Fuel_Type'].unique()) # I...
python
from PIL import Image import numpy as np import time def renk_degisimi(): h=pic.shape[0] w=pic.shape[1] newpic=np.zeros((h ,w )) for i in range(h): for j in range(w): newpic[i][j]+=pic[i][j][0]*0.2989+pic[i][j][1]*0.5870+pic[i][j][2]*0.1140 matrix2=[] for i in ran...
python
from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate,logout from django.http import HttpResponse from account.forms import AccountAuthenticationForm, RegistrationForm,AccountUpdateForm from django.contrib import messages from django.conf import settings from django.contrib....
python
import numpy as np import cv2 from skimage import segmentation def runGrabCut(_image, boxes, indices): imgs = [] image = _image.copy() # ensure at least one detection exists indices = len(boxes) if indices > 0: # loop over the indices we are keeping for i in range(0,indices): ...
python