content
stringlengths
0
894k
type
stringclasses
2 values
# coding:utf-8 from django.contrib.auth import authenticate,login,logout from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required, permission_required,user_passes_test from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404 fro...
python
import random import numpy as np a = [5, -1, 0, -1, 2] b=-9 if sum(a) > 3 and b < -1: print(True)
python
from keras.callbacks import TensorBoard import tensorflow as tf from keras.callbacks import EarlyStopping, ModelCheckpoint from exercise_performance_scorer.data_creator import ExercisePerformanceDataCreator from exercise_performance_scorer.model import ExercisePerformanceModel class ExercisePerformanceTrainer: de...
python
from urllib.parse import urlparse from app import logger import requests class ControllerService: def init_app(self, app): return def send_command(self, gate, command='open', conditional=False): try: if gate.type == 'gatekeeper': if command == 'open' and not conditional: requests....
python
from quart import Blueprint home = Blueprint("home", __name__) @home.route("/") def index(): """Home view. This view will return an empty JSON mapping. """ return {}
python
from django.contrib import admin from froide.helper.admin_utils import ForeignKeyFilter class FollowerAdmin(admin.ModelAdmin): raw_id_fields = ( "user", "content_object", ) date_hierarchy = "timestamp" list_display = ("user", "email", "content_object", "timestamp", "confirmed") li...
python
""" @author: Viet Nguyen <nhviet1009@gmail.com> """ import cv2 import numpy as np from collections import OrderedDict # https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/image_classification/quickdraw_labels.txt # Rule: key of category = index -1, with index from the link above CLASS_IDS = Ordere...
python
import json import os TEST_FILE_BASE_PATH = 'tests' def __test_pages(app): testapp = app.test_client() pages = ('/') for page in pages: resp = testapp.get(page) assert resp.status_code == 200 def test_nearest_stations_mapper(): from transporter.utils import NearestStationsMapper ...
python
import unittest from pyalink.alink import * import numpy as np import pandas as pd class TestPrintStreamOp(unittest.TestCase): def test_printstreamop(self): df = pd.DataFrame([ [0, "abcde", "aabce"], [1, "aacedw", "aabbed"], [2, "cdefa", "bbcefa"], [3, "bdefh...
python
from sqlalchemy import * from sqlalchemy.orm import relationship, validates from db import db class ConfigTemplate(db.Model): __tablename__ = "config_template" id = Column(String, primary_key=True) doc = Column(Text, nullable=False) language_id = Column(String, ForeignKey('language.id')) ser...
python
import random import logging from . import scheme __all__ = ('MTProtoSessionData',) log = logging.getLogger(__package__) class MTProtoSessionData: def __init__(self, id): if id is None: id = random.SystemRandom().getrandbits(64) log.debug('no session_id provided,...
python
import argparse import torch import os from tqdm import tqdm from datetime import datetime import torch.nn as nn import torch.utils.data as data from torch.utils.tensorboard import SummaryWriter import deepab from deepab.models.PairedSeqLSTM import PairedSeqLSTM from deepab.util.util import RawTextArgumentDefaultsHelp...
python
from flask_wtf import FlaskForm as Form from wtforms import StringField from wtforms.validators import DataRequired class LoginForm(Form): username = StringField('username', validators=[DataRequired()]) password = StringField('password', validators=[DataRequired()])
python
import os import json import numpy as np import matplotlib.pyplot as plt def compute_iou(box_1, box_2): ''' This function takes a pair of bounding boxes and returns intersection-over- union (IoU) of two bounding boxes. ''' iou = np.random.random() width = min(box_1[2], box_2[2]) - max(box_1[0],...
python
# # Project: # glideinWMS # # File Version: # # Description: # This module implements functions and classes # to handle forking of processes # and the collection of results # # Author: # Burt Holzman and Igor Sfiligoi # import cPickle import os import time import select from pidSupport import register_sighan...
python
from click import Option from preacher.app.cli.executor import PROCESS_POOL_FACTORY, THREAD_POOL_FACTORY from preacher.app.cli.option import LevelType, ExecutorFactoryType from preacher.core.status import Status def test_level_type(): tp = LevelType() param = Option(["--level"]) assert tp.get_metavar(pa...
python
# Represents smallest unit of a list with value, reference to succeding Node and referenece previous Node class Node(object): def __init__(self, value, succeeding=None, previous=None): pass class LinkedList(object): def __init__(self): pass
python
## @package csnListener # Definition of observer pattern related classes. class Event: """ Generic event class. """ def __init__(self, code, source): self.__code = code self.__source = source def GetCode(self): return self.__code def GetSource(self): return self._...
python
#code for feature1
python
import unittest import pytest from botocore.exceptions import ClientError from localstack import config from localstack.utils.aws import aws_stack from localstack.utils.common import short_uid from .lambdas import lambda_integration from .test_integration import PARTITION_KEY, TEST_TABLE_NAME TEST_STREAM_NAME = lam...
python
import json import os import tkinter as tk def cancelclick(): exit(0) class GUI: def okclick(self): data = {"url": self.urlentry.get(), "telegramAPIKEY": self.apikeyentry.get(), "telegramCHATID": self.chatidentry.get(), "databaseFile": self.databaseent...
python
import io from collections import deque from concurrent.futures import ThreadPoolExecutor import numba from bampy.mt import CACHE_JIT, THREAD_NAME, DEFAULT_THREADS from . import zlib from ...bgzf import Block from ...bgzf.reader import BufferReader, EmptyBlock, StreamReader, _Reader as __Reader @numba.jit(nopython=...
python
"""test format Revision ID: b45b1bf02a80 Revises: a980b74a499f Create Date: 2022-05-11 22:31:19.613893 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b45b1bf02a80' down_revision = 'a980b74a499f' branch_labels = None depends_on = None def upgrade(): # ##...
python
from myhdl import * import random from random import randrange from .alu import def_alu from .ctrl import def_ctrl random.seed(4) def test_ctrl(): """Test bench for the ALU control. """ clk = Signal(bool(0)) reset = ResetSignal(0, active=1, async=True) alu_op = Signal(intbv(0)[2:]) func...
python
import asyncio import logging from datetime import datetime, timedelta from .login import BiliUser from .api import WebApi, medals, get_info, WebApiRequestError logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger("dailyclockin") cla...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016-2017 China Telecommunication 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/lice...
python
import os from awacs.aws import Policy, Allow, Statement, Principal, Action from cfn_encrypt import Encrypt, EncryptionContext, SecureParameter, GetSsmValue from troposphere import (Template, iam, GetAtt, Join, Ref, logs, Output, Sub, Parameter, awslambda, Base64, Export) from sys import argv...
python
# Copyright 2016 - Nokia # # 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 writing, sof...
python
import os import pandas as pd import glob import random import shutil INDEX = { 'Shift_png':0, 'Random_png':1, 'Original_png':2, 'Expand_png':3, 'Contract_png':4 } def make_label_csv(input_path,csv_path,mid_dir=None): info = [] for subdir in os.scandir(input_path): index = INDEX...
python
# coding=utf-8 import numpy as np from time import time from aux import * ''' Obre un fitxer a partir del seu nom i guarda cada una de les seves línies en cada posició d'una llista Paràmetres: - fileName: Nom del fitxer que es vol obrir. Return: - llista amb les paraules que conformen la llista Swadesh d'un id...
python
def swap_case(s): swapped_s = '' for letter in s: swapped_s += letter.lower() if letter.isupper() else letter.upper() return swapped_s if __name__ == '__main__': s = input() result = swap_case(s) print(result)
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
python
from os.path import join import matplotlib.pylab as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages from sklearn.metrics import roc_curve, auc import src.utils from src.methods.methods import good_methods as methods from src.methods.methods import mutliple_time_series_combiner from src.rea...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Defines functionality for pipelined execution of interfaces The `EngineBase` class implements the more general view of a task. .. testsetup:: # Chan...
python
from netCDF4 import Dataset #------------------------------------------------------------------------------- def set_difference_fields(): files = {"./output_hex_wachspress_0082x0094_120/output.2000.nc": ["./output_hex_pwl_0082x0094_120/output.2000.nc", "./output_hex_weak_0082x0094_120/...
python
import imp import librosa import numpy as np from keras.models import load_model genres = {0: "metal", 1: "disco", 2: "classical", 3: "hiphop", 4: "jazz", 5: "country", 6: "pop", 7: "blues", 8: "reggae", 9: "rock"} song_samples = 660000 def load_song(filepath): y, sr = librosa.load(filepath...
python
""" Tests for the StarCluster Job """ import sure from mock import Mock from .fixtures import * from metapipe.models import sge_job def test_qstat_queued(): j = sge_job.SGEJob('', None) sge_job.call = Mock(return_value=sge_job_qstat_queued) j.is_queued().should.equal(True) def test_qstat_running(): ...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def initial_log_action(apps, schema_editor): LogAction = apps.get_model('logs', 'LogAction') action, created = LogAction.objects.get_or_create( name='USER_CREATE', ) action.template = 'Use...
python
__author__ = 'Neil Butcher' from Institution import InstitutionSavingObject
python
import sys import os.path def main(): sys.argv[:] = sys.argv[1:] # Must rewrite the command line arguments progname = sys.argv[0] sys.path.insert(0, os.path.dirname(progname)) with open(progname, 'rb') as fp: code = compile(fp.read(), progname, 'exec') globs = { '__file__' : progna...
python
from __future__ import unicode_literals import os import shutil import subprocess import sys import optparse import datetime import time sys.path[:0] = ['.'] from yt_dlp.utils import check_executable try: iterations = str(int(os.environ['ZOPFLI_ITERATIONS'])) except BaseException: iterations = '30' parser ...
python
import json from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from django.urls.base import reverse from lykops.views import Base class Report(Base): def summary(self,request): result = self._is_login(request) if result[0] : ...
python
## # 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 writing, software # distributed under the...
python
""" Loader for Maya api sub-package """ from __future__ import absolute_import from __future__ import print_function from __future__ import division # this can be imported without having maya fully initialized from .allapi import *
python
#!/usr/bin/python # # Copyright (c) 2012 Mikkel Schubert <MSchubert@snm.ku.dk> # # 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 #...
python
import sys import srvdb db = srvdb.SrvDb("./pdb-aggregator.db") file = sys.argv[1] print(file) with open(file) as f: content = f.read().splitlines() print(content) ips = [] for ip in content: if ip not in ips: print("Adding node {}".format(ip)) db.add_node(ip, False, 0, "") ips.ap...
python
# Copyright (c) 2020 PaddlePaddle 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...
python
from output.models.nist_data.list_pkg.qname.schema_instance.nistschema_sv_iv_list_qname_pattern_2_xsd.nistschema_sv_iv_list_qname_pattern_2 import NistschemaSvIvListQnamePattern2 __all__ = [ "NistschemaSvIvListQnamePattern2", ]
python
#!/usr/bin/env python3 from datetime import datetime, timedelta from math import floor import sys from time import perf_counter from betterprint.betterprint import bp, bp_dict from modules.notations import byte_notation from modules.createfolder import folder_logic, folder_stat_reset from betterprint.colortext import...
python
# https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem # Enter your code here. Read input from STDIN. Print output to STDOUT x,y = map(int, input().split()) p = x/y n = int(input()) answer = 0 for z in range(1,n+1): temp = (1-p)**(z-1) * p answer = answer + temp print(round(answer,3))
python
# Generated by Django 3.0 on 2021-07-21 11:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wwwrate', '0007_auto_20210720_1450'), ] operations = [ migrations.AlterModelOptions( name='project', options={'orderin...
python
import subprocess from vendor.addressfetcher.addressfetcher import fetcher # constant ADDRESS_PATH = '' def input_number(prompt): while True: try: num = float(input(prompt)) break except ValueError: pass return num def display_menu(option...
python
import os import shutil import tarfile import urllib import zipfile from .constants import RU_VOWELS, DEFAULT_DATA_DIR from pathlib import Path from typing import Union def count_syllables(word: str) -> int: """ Вычисление количества слогов в слове Аргументы: word (str): Строка слова Вывод: ...
python
# -*- coding: utf-8 -*- ''' Copyright © 2014 by Virginia Polytechnic Institute and State University All rights reserved Virginia Polytechnic Institute and State University (Virginia Tech) owns the copyright for the BEMOSS software and its associated documentation (“Software”) and retains rights to grant research right...
python
import webbrowser import cv2 import numpy as np import pyautogui import PIL import time def init(): # TODO: Add more example websites with recaptcha webbrowser.open( '''https://jsso.indiatimes.com/sso/identity/register?channel=businessinsider&identifier=r@g.c''' ) # Move to a temporary location and wait for w...
python
""" A class/method/function should have only 1 reason to change!!! It should have single responsibility eg. book movie for a theatre """ class BookMovie(object): """ Bad code """ def book_movie_seat(self, movie, seat): if self.is_seat_available(seat): return False self.book_...
python
import unittest from Credentials import Credentials class TestCredentials(unittest.TestCase): """ Test class that defines test cases for the Credentials class behaviours """ def setUp(self): """ Set up method to run befor each test case """ self.new_credentials = Creden...
python
"""Module for handling buses.""" from sinfactory.component import Component from sinfactory.load import Load from sinfactory.generator import Generator class Bus(Component): """Node class""" def __init__(self, pf_object): """Constructor for the Bus class. Args: pf_object: The po...
python
#!/usr/bin/python # coding:utf-8 # ServerSan - ss-agent.py # 2018/3/14 15:03 # __author__ = 'Benny <benny@bennythink.com>' __version__ = '1.0.0' import os import platform import socket import sys import time import cpuinfo import psutil import requests # API = 'http://127.0.0.1:5000/' API = 'https://api.serversan...
python
import pyautogui import time # time to change tabs from editor to paint; time.sleep(10) # it will remain clicked till program ends; pyautogui.click() # can be varied according to convininence distance = 250 while distance > 0: # right pyautogui.dragRel(distance, 0, duration = 0.1) distance -= 5 ...
python
from flask import ( Flask, render_template, send_from_directory, redirect, url_for, request) from . import settings as st from .persistency import PersistencyManager import markdown from pygments.formatters import HtmlFormatter from flask_wtf import FlaskForm from flask_pagedown.fields import PageDownField from wtf...
python
from pwn import * # NOQA flag = b"flag{AAAAAAAAAAA}" flag = bytes(bin(int(binascii.hexlify(flag), 16)), 'utf8') class GuessIterator: def __init__(self): self.known_part = b"" self.first_block = True self.i = -1 def know_guess(self): self.known_part = self.current_guess() ...
python
from setuptools import setup from os import path from io import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='SimpleHTTPSAuthServer', version='1.1.0', description='HTTPS server with Basic authe...
python
""" A simple example which prints out parsed streaming responses. Python version: 3.6+ Dependencies (use `pip install X` to install a dependency): - websockets Usage: python deepgram_streaming.py -k 'YOUR_DEEPGRAM_API_KEY' /path/to/audio.wav Limitations: - Only parses signed, 16-bit li...
python
# This file is part of pure-dispatch. # https://github.com/SeedyROM/pure-dispatch # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT-license # Copyright (c) 2017, Zack Kollar <zackkollar@gmail.com> '''Test our database module. ''' from tests.base import TestCase from pure_dispatch.database imp...
python
# By Justin Walgran # Copyright (c) 2012 Azavea, 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, ...
python
# Copyright (c) 2017 Midokura SARL # 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 require...
python
from django.shortcuts import render_to_response, render from django.template.response import TemplateResponse from django.template import RequestContext from django.contrib.sites.models import Site from django.urls import reverse from django.views.decorators.clickjacking import xframe_options_exempt from django.views.d...
python
from rdflib.graph import Graph from rdflib.namespace import Namespace, RDFS, RDF from owmeta_core.rdf_query_modifiers import (ZeroOrMoreTQLayer, rdfs_subclassof_subclassof_zom_creator as mod, rdfs_subclassof_zom, ...
python
#!/usr/bin/env python '''This script will compile 1D spectra into cubes, and visualize them.''' # create (and save!) a cube, and visualize it from mosasaurus.Cube import Cube import sys try: c = Cube(sys.argv[1]) c.populate(remake=False, visualize=False) c.movieCube(stride=1) except IndexError: print...
python
# requires: # - phantomjs or geckodriver installed # - selenium from pip import sys import unittest import json import argparse from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditi...
python
#102 # Time: O(n) # Space: O(n) # Given a binary tree, return the level order traversal # of its nodes' values. (ie, from left to right, level by level). # # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its level order traversal as: # [ # [3], #...
python
"""Some useful data structures and functions""" import datetime espa_env = { "dev": "https://espa-dev.cr.usgs.gov", "tst": "https://espa-tst.cr.usgs.gov", "ops": "https://espa.cr.usgs.gov" } api_urls = { "status": "/api/v1/item-status/", "order": "/api/v1/order/" } def timestamp() -> str: "...
python
import os import glob import shutil # dictionary mapping each extension with its corresponding folder # For example, 'jpg', 'png', 'ico', 'gif', 'svg' files will be moved to 'images' folder # feel free to change based on your needs extensions = { "jpg": "images", "png": "images", "ico": "images", "gif"...
python
#! /usr/bin/env python3 from sklearn import svm import numpy as np import json import random import sys import os import argparse def estimate(data, target, trainingsubset, testingsubset, gamma='auto', C=1): if(len(set(target)) < 2): # only one class return 0; clf = svm.SVC(gamma=gamma, C=C) clf.fit(data[trainin...
python
# Initializes the datastore with sample data. # # Possibilities to execute the code in this file: # # * GAE SDK 1.5 or compatible: Paste the code in the interactive console and # execute it. # # * GAE (production): # # a) Enter the directory of the Reality Builder. # # b) Connect to the remote API sh...
python
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ lvmmodel.io ============ I/O utility functions for files in lvmmodel. """ import os from astropy.io import fits import yaml import numpy as np import warnings from lvmutil.log import get_logger log = get_logger() _thru = dic...
python
import glob import bz2 with open('all_data.ndjson','w') as out: for div in glob.glob('./OpenAccess-master/metadata/objects/*'): print('Working on: ',div) for file in glob.glob(f'{div}/*'): with bz2.open(file, "rb") as f: out.write(f.read().decode())
python
# Copyright 1999-2020 Alibaba Group Holding 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 a...
python
from django.urls import path,include from . import views urlpatterns = [ path('api/projects/', views.ProjectList.as_view()), path('api/projects/profile', views.ProfileList.as_view()), path('api/projects/ratings', views.RatingList.as_view()), ]
python
from output.models.ms_data.attribute.att_j004_xsd.att_j004 import Test __all__ = [ "Test", ]
python
import param from . import API1TestCase # TODO: I copied the tests from testobjectselector, although I # struggled to understand some of them. Both files should be reviewed # and cleaned up together. # TODO: tests copied from testobjectselector could use assertRaises # context manager (and could be updated in testobje...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from django.conf.urls import url from .views import create_view from .views import update_view from .views import delete_view from .views import list_view stagesetting_create = url(regex=r'^add/$', ...
python
# # Copyright (c) 2013-2020 Contributors to the Eclipse Foundation # # See the NOTICE file distributed with this work for additional information regarding copyright # ownership. All rights reserved. This program and the accompanying materials are made available # under the terms of the Apache License, Version 2.0 whic...
python
from insights.parsers.route import Route from insights.tests import context_wrap ROUTE = ''' Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 10.66.208.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 169.254.0.0 0.0.0.0 255.255.0.0 ...
python
#!/usr/bin/env python3.7 # Copyright: Ismael Narváez Berenjeno from datetime import datetime def get_time_isoformat(): """ Get timestamp with ISO format. :return: ISO timestamp :rtype: str """ return datetime.now().isoformat()
python
""" 面试题21:包含min函数的栈 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。 https://leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack...
python
#!/usr/bin/python3 from PyQt5 import QtCore, QtGui from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QFrame, QPushButton, QLabel class LaunchScreen(QFrame): def __init__(self, parent): # constructor super().__init__(parent) self.windowClass = parent # allows calling of parent class methods ...
python
"""Conditional Grammar.""" from sqlfluff.core.parser.segments import Indent from sqlfluff.core.parser.match_result import MatchResult from sqlfluff.core.parser.match_wrapper import match_wrapper from sqlfluff.core.parser.grammar.base import ( BaseGrammar, ) class Conditional(BaseGrammar): """A g...
python
from textformer.models import Seq2Seq # Creating the Seq2Seq model seq2seq = Seq2Seq(n_input=1, n_output=1, n_hidden=512, n_embedding=256, n_layers=2, ignore_token=None, init_weights=None, device='cpu')
python
from django.conf.urls import include, url import django.contrib.auth.views from work_evid import views urlpatterns = [ url(r'^overviews/$', views.overviews, name='overviews'), url(r'^delete_work/$', views.delete_work, name='delete_work'), url(r'^work/$', views.WorkList.as_view(), name='work_list'), ur...
python
#!/usr/bin/env python3 import tensorflow as tf import pickle import cv2 import os import os.path as path from utils import predict, predict_no_tiles from model import dilation_model_pretrained from datasets import CONFIG if __name__ == '__main__': test = True # Choose between 'cityscapes' and 'camvid' dat...
python
# -*- coding: utf-8 -*- """Unit test package for tatortot."""
python
import requests import re from bs4 import BeautifulSoup import logging import os import json base_url = "https://vulncat.fortify.com/en/weakness?q=" logpath=f'{os.getcwd()}/log' def scrape_url(url): soup:BeautifulSoup=None try: r=requests.get(url) soup=BeautifulSoup(r.text, 'html.parser') ...
python
from fastai.vision.all import * import fastai from fastai.tabular.all import * from fastai.data.load import _FakeLoader, _loaders import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import random # CUSTOM VIS DATABLOCK FUNCTIONS def get_npy(dataframe): "Get the images (.npy) that will...
python
from __future__ import absolute_import import re from cStringIO import StringIO from datetime import date, datetime, timedelta from psycopg2.extensions import AsIs, Binary, QuotedString from pytz import timezone class PostgresWriter(object): """Base class for :py:class:`mysql2pgsql.lib.postgres_file_writer.Post...
python
from app import server as user if __name__ == "__main__": user.run()
python
""" Faça um programa que possua um vetor denominado 'A' que armazene 6 números inteiros. O programa deve executar os seguintes passos. (a) Atribua os seguintes valores a esse vetor: 1, 0, 5, -2, -5, 7. (b) Armezene em uma variável inteira (simples) a soma entre os valores das posições A[0], A[1], e A[5] do vetor e mos...
python
""" Django settings for coralcity project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os ...
python
# https://jsonapi.org/format/#document-resource-identifier-objects def build_resource_identifier(type, id): return {"type": type, "id": id} #https://jsonapi.org/format/#document-meta def build_meta(meta): return meta # https://jsonapi.org/format/#document-links def build_links_object(links): links_objec...
python