content
stringlengths
5
1.05M
from django.shortcuts import render from django.http import HttpResponse def contact(request): return render(request, 'contact.html', {})
from django.conf import settings # permitted attributes to reveal REVEAL_INFO_ATTRS = getattr(settings, 'REVEAL_INFO_ATTRS', ['phone', 'phone2', 'website', 'email']) REVEAL_PROTOCOL_MAP = getattr(settings, 'REVEAL_PROTOCOL_MAP', { 'phone': 'tel:', 'phone2': 'tel:', 'email': 'mailto:', 'website': '...
import iris import iris.plot as iplt import matplotlib.pyplot as plt def generate_image(file_name): d = iris.load_cube(file_name) iplt.pcolormesh(d) plt.gca().coastlines() plt.gca().margins(x=0, y=0) plt.gca().set_axis_off() plt.savefig("./data.png", bbox_inches="tight", dpi=500, pad_inches=0)...
import os from invoke import * os.environ['FLASK_APP'] = "maintainer.py" @task def build(ctx): ctx.run("python3 -m flask run")
from typing import Optional from django.conf import settings from requests import Response, post def gen_api_request(): return { "device_id": settings.APP_SITE, "device_type": settings.APP_NAME, "device_model": settings.APP_NAME, "system_version": settings.APP_VERSION, "app_version": settings.A...
from string import ascii_lowercase, ascii_uppercase import sys from automata import Automata def get_validation(automata, words, primitives, identifiers): print '\nValidating words: ' + ', '.join(filter(None, words)) + '\n' symbols_table = {} error_list = [] for i, word in enumerate(words): ...
#from __future__ import division, absolute_import, print_function import sys import os import platform version = {} with open("timml/version.py") as fp: exec(fp.read(), version) l_d = "" try: import pypandoc l_d = pypandoc.convert("README.md", "rst") except: pass try: from numpy.distutils.core i...
import httplib, urllib, requests, os, json from base64 import b64encode class AEMTools: _protocol = "http" _server = "" _user = "" _passwd = "" _testPath = "/system/console/bundles" _isconnected = False _authHeader = "" def __init__(self, server,user, passwd): if server[:4] ...
import numpy as np def softmax(a): c = np.max(a) exp_a = np.exp(a - c) sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return y a = np.array([0.3, 2.9, 4.0]) y = softmax(a) print(y) print(np.sum(y))
from django import forms from django.core.exceptions import ValidationError # 校验错误 from post.models import Topic class TopicSearchForm(forms.Form): title = forms.CharField( label='话题标题', initial='Django BBS', help_text='帮助信息') class TopicField(forms.Field): default_error_messages = { 'inva...
import numpy as np import scipy.optimize import functools from scipy.spatial import distance def atom_coordinates(atoms): return np.array([x.get_coord() for x in atoms]) def ob_atom_coordinates(ob_atoms): return np.array([(a.GetX(), a.GetY(), a.GetZ()) for a in ob_atoms]) def axis_sum(arr, decimals=3): ...
# Functions - take an input(s) and return an output # Uses # The main purpose of a function is to do something that # needs to be done multiple times. This saves you the # need to code the same statements over and over in your # programs. my_age = 30 his_age = 35 def print_ages(): print "Ag...
# -*- coding: utf-8 -*- from . import app_version from phanterweb.helpers import ( DIV, IMG, SCRIPTMINIFY, CONCATENATE ) html = CONCATENATE( DIV( DIV( DIV(_id="titulo-warning"), _class='warnings-title' ), DIV( DIV( IMG( ...
import pytest import os, shutil from click.testing import CliRunner from luna_core.common.config import ConfigSet from luna_core.common.sparksession import SparkConfig from luna_pathology.point_annotation.refined_table.generate import cli import luna_core.common.constants as const point_geojson_table_path = "tests/l...
from .grid_cluster import grid_cluster from .matrix import from_matrix from .utils import sort_clusters, cluster_ranges, cluster_centroids, cluster_ranges_centroids, swap_axes # N.B.: the order is important for the autodoc in sphinx! __all__ = sorted(["grid_cluster", "from_matrix", "sort_clusters", "...
from bs4 import BeautifulSoup import requests url = input('Enter the name of site to check (format google.com): ') res = requests.get('https://isitup.org/' + url) soup = BeautifulSoup(res.text, 'lxml') container = soup.find('div', {'id': 'container'}) status = container.find('p') print(status.text)
import io import os import time import cv2 import numpy as np from flask import Flask, Response, json, request, g, send_from_directory from flask_cors import CORS from detector import Detector from recoer import Recoer detector = Detector('./data/models/ctpn.pb') recoer = Recoer('./tf_crnn/data/chars/chn.txt', './da...
#!/usr/bin/env python # ============================================================================ # Copyright (C) Microsoft Corporation, All rights reserved. # ============================================================================ import os import sys import time import inspect import codecs import imp scri...
""" The error parameters type definition. """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Union from sarpy.io.xml.base import Serializable, ParametersCollection from sarpy.io.xml.descriptors import FloatDescriptor, SerializableDescriptor, \ ParametersDescriptor from sa...
from django.core.exceptions import ValidationError from django.forms import ModelForm, CharField, Textarea from markdown2 import Markdown from common.utils import split_tags from posts.models import Post, Tag class PostForm(ModelForm): content = CharField(widget=Textarea( attrs={ ':value': 'i...
"""Tutorial 2. Creating a plot in window. Using a traitsui view, a plot can be placed as a configurable item that is viewed when configure_traits is called. """ from enable.api import ComponentEditor from traits.api import HasTraits from traitsui.api import Item, View from tutorial1 import myplot class PlotExample...
def get_divisor(num): divisor_list = [] ind = 1 while ind <= num: rem = num % ind if rem == 0: divisor_list.append(ind) ind += 1 return divisor_list len_of_g_list = len(get_divisor(10)) len_list = 0 div_list = [] i = 1 while i <= 100: if not i > 10: p...
n=int(input('Digite um número para ver sua tabuada:')) print('_______________\n{}x1 = {}\n{}x2 = {}\n{}x3 = {}\n' '{}x4 = {}\n{}x5 = {}\n{}x6 = {}\n{}x7 = {}\n{}x8 = {}\n{}x9 = {}\n{}x10 = {}\n_______________' .format(n,(n*1),n,(n*2),n,(n*3),n,(n*4),n,(n*5),n,(n*6),n,(n*7),n,(n*8),n,(n*9)...
from output.models.nist_data.list_pkg.normalized_string.schema_instance.nistschema_sv_iv_list_normalized_string_max_length_3_xsd.nistschema_sv_iv_list_normalized_string_max_length_3 import NistschemaSvIvListNormalizedStringMaxLength3 __all__ = [ "NistschemaSvIvListNormalizedStringMaxLength3", ]
# -*- coding: utf-8 -*- """Lempel-Ziv complexity for a binary sequence, in naive Python code. - How to use it? From Python, it's easy: >>> from lempel_ziv_complexity import lempel_ziv_complexity >>> s = '1001111011000010' >>> lempel_ziv_complexity(s) # 1 / 0 / 01 / 11 / 10 / 110 / 00 / 010 8 - Note: there is also a...
from abc import ABCMeta class BlockIds(): __metaclass__ = ABCMeta AIR = 0 STONE = 1 GRASS = 2 DIRT = 3 COBBLESTONE = 4 PLANKS, WOODEN_PLANKS = 5, 5 SAPLING = 6 BEDROCK = 7 FLOWING_WATER = 8 STILL_WATER, WATER = 9, 9 FLOWING_LAVA = 10 LAVA, STILL_LAVA = 11, 11 SA...
#Created by: Nathan T. Johnson #Edited: 09.24.2019 #Purpose: Supply error checking, O2 slurm job handling, and sbatch scripts for each image #Input: Full Path to the Project directory with assumption it fits certain organization as defined by documentation #Output: 1) sbatch scripts for each image 2) slurm submissi...
#!/usr/bin/python3 import base64 from Crypto.Cipher import AES import glob import sys import time key = "besthacker@@@@@@" def ranso(arq,key): f = open(arq, "rb").read() cript64 = base64.b64encode(f) e_c = (16 - len(cript64)) % 16 new_crip = cript64.decode() + "@" * e_c aes = AES.new(key, AES.MODE_...
OGG_DIR = '/home/brodul/Music'
from .main import denoise_mri from . import cli as _
#!/usr/bin/python3 # Temporary test runner, until kantanc has commandline arguments and this # can be properly integrated into kantan-test import subprocess from os import listdir, remove from os.path import splitext, join, isdir, exists kantan_path = '/home/felix/Documents/programming/kantan/compiler/' test_path = ...
#!/usr/bin/python3 # Copyright: University of Queensland, 2018 # Contributors: Ben Foley def foo(): pass
''' Created on April 20, 2017 @author: Subhasis ''' import argparse import ConfigParser import time import logging from SpellingCorrectService import SpellingCorrectService if __name__ == '__main__': logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) spelling_correction = Spelli...
from itertools import combinations, islice from functools import reduce from math import comb as C import math from typing import Generator, Iterator from prompts import p_choice, p_int, p_bool import operator import os import time # Make a charset of A-Za-Z0-9 CHARSET = '' for i in range(65, 91): CHARSET += chr(i...
from minicps.devices import PLC from utils import * import random import time import logging SENSOR_ADDR = IP['lit101'] LIT101 = ('LIT101', 1) class Lit101(PLC): def pre_loop(self, sleep=0.1): time.sleep(sleep) def main_loop(self): #print 'DEBUG: sensor enters main_loop' logging.basicConfig(format='%(asct...
from datetime import datetime class Base(object): def load(self, data): for name, value in list(data.items()): if hasattr(self, name) and not callable(getattr(self,name)): setattr(self, name, value) return self @staticmethod def strip_nanoseconds_from_date(value): if str(value).find...
""" A set of utilities for setting up property estimation workflows. """ from dataclasses import astuple, dataclass from typing import Generic, Optional, Tuple, TypeVar from openff.evaluator import unit from openff.evaluator.attributes import PlaceholderValue from openff.evaluator.datasets import PropertyPhase from op...
from pystiche import data __all__ = ["images"] def images() -> data.DownloadableImageCollection: images_ = { "neckarfront": data.DownloadableImage( "https://upload.wikimedia.org/wikipedia/commons/0/00/Tuebingen_Neckarfront.jpg", title="Tübingen Neckarfront", author="An...
colors = { "C": ["C", "B", "G", "C"], "M": ["B", "M", "R", "M"], "Y": ["G", "R", "Y", "Y"], "W": ["C", "M", "Y", "W"] } results = { "CC": "C", "CM": "B", "CY": "G", "CW": "C", "MC": "B", "MM": "M", "MY": "R", "MW": "M", "YC": "G", "YM": "R", "YY": "Y", ...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.water_heaters_and_thermal_storage import ThermalStorageIceDetailed log = logging.getLogger(__name__) class TestThermalStorageIceDetailed(unittest.TestCase): def setUp(self)...
def gp(marks): if marks>=90: return 4.0 if marks>=85: return 3.7 if marks>=80: return 3.3 if marks>=75: return 3.0 if marks>=70: return 2.7 if marks>=65: return 2.3 if marks>=60: return 2.0 if marks>=57: return 1.7 if ma...
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name='psroi_align_cuda', ext_modules=[ CUDAExtension('psroi_align_cuda', [ 'src/psroi_align_cuda.cpp', 'src/psroi_align_kernel.cu', ]), ], cmdclass={'build_ext...
''' Created on 16 Jun 2018 @author: Marcel Dunaiski ''' from __future__ import division from _collections import defaultdict from EvaluationMeasures import isNegativeMethod from multiprocessing import Pool from HelperTools import StreamReader, Experiment, Results from SwapRate import swapRate from ErrorTieRate import...
# -*- coding: utf-8 -*- # # Copyright (c) 2018~2999 - Cologler <skyoflw@gmail.com> # ---------- # lquery for tinydb # ---------- from ..queryable import AbstractQueryable from ..funcs import LinqQuery from ..iterable import IterableQueryProvider from ..expr import Make, ExprType from ..expr.builder import to_func_expr...
from celery import shared_task from django.conf import settings from django.core.mail import send_mail @shared_task def async_send_email(subject, message, email_list): send_mail(subject, message, settings.EMAIL_HOST_USER, email_list)
#!/usr/bin/env python3 """ Correct bed file to be compatible with bedToBigBed tool. 1.) restrict all scores to the maximal value of 1000, 2.) in strand column replace '?' with '.'. """ import argparse import pandas as pd from pandas.errors import EmptyDataError from resolwe_runtime_utils import error parser...
import iraf no = iraf.no yes = iraf.yes from axe import axesrc #import axesrc # Point to default parameter file for task _parfile = 'axe$stamps.par' _taskname = 'stamps' ###### # Set up Python IRAF interface here ###### def stamps_iraf(grism, config, sampling, drzpath...
""" Tests for checking that the plotting extension works. """ from textwrap import dedent from tests.execution_helper import Execution, ExecutionTestCase, SUCCESS_MESSAGE from pedal.extensions.plotting import * code_hist_and_plot = (''' import matplotlib.pyplot as plt plt.hist([1,2,3]) plt.title("My line plot") plt....
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ # pylint: disable=protected-access # pylint: disable=too-many-lines from typing import ( Any, List, Union, cast, TYPE_CHECKING ) imp...
#!/usr/bin/env python """Explore classification metrics for validated true positives and negatives. This identifies useful classification metrics to distinguish true and false variants. """ import os import sys import math import shutil import itertools import subprocess import yaml import vcf import numpy as np impo...
# 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) AutoRest Code Generator. # Changes ...
# ---------------------------------------------------------------------------- # cocos2d # Copyright (c) 2008-2012 Daniel Moisset, Ricardo Quesada, Rayentray Tappa, # Lucio Torre # Copyright (c) 2009-2019 Richard Jones, Claudio Canepa # All rights reserved. # # Redistribution and use in source and binary forms, with o...
from typing import List def split_multipart_field(field: str) -> List[str]: """ Splits a multi-part field into its component parts. :param field: The multi-part field's value. :return: The parts. """ return field.split("|", maxsplit=2)
from typing import Any, Dict from utils.request_utils import request_get def get_user_info(user: str) -> Dict[str, Any]: return request_get("https://api.github.com/users/{user}".format(user=user))
import shutil import os import unittest from Common.Config.ConfigHolder import ConfigHolder from glob import glob from Tests.errors import get_error, get_error_txt from Tools.datasets import get_dataset, split_samples from Tools.IOData import IOData from os.path import isdir, join, isfile # # Ignore warning TF # os....
import math from pysat.formula import IDPool from pysat.card import CardEnc, EncType from pysat.solvers import MinisatGH encs = ['seqcounter', 'sortnetwrk', 'cardnetwrk', 'totalizer', 'mtotalizer', 'kmtotalizer'] def bincoeff(n, k): n_fac = math.factorial(n) k_fac = math.factorial(k) n_minus_k_fa...
# Generated by Django 3.2 on 2021-12-16 19:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('courier', '0001_initial'), ] operations = [ migrations.CreateModel( name='Wee...
import argparse import os import sys import pathlib curr_dir=pathlib.Path(__file__).parent.resolve() root_dir=pathlib.Path(curr_dir).parent.resolve() info=sys.version_info sys.path.insert(0,str(root_dir)) sys.path.insert(0,str(root_dir)+"/PyDeps/lib/python{}.{}/site-packages".format(info[0],info[1])) import yaml from c...
import argparse import cv2 import gc import matplotlib.pyplot as plt import numpy as np import os import time import torch import torch.nn as nn import torch.nn.functional as F import torchvision from copy import deepcopy from pdb import set_trace from torch.utils.data import Dataset, DataLoader, Subset from torchinfo ...
""" Author: Kyle J. LaFollette Department of Psychiatry, University of Arizona Correspondance: kjlafoll@psychiatry.arizona.edu This script runs Chiu et al.'s 2015 experiment investigating the effect of peer influence, or 'other-conferred utility', on lottery choice decision-making. Code has been adapted from that u...
#!/usr/bin/env python # -*- coding: utf-8 -*- from telegram.ext import Updater, CommandHandler, MessageHandler, \ Filters from telegram import User from dotenv import load_dotenv import logging import shlex import subprocess import random import os load_dotenv() TOKEN = os.getenv("CITADOR_TO...
import pytz import unittest from airflow.models import DAG, TaskInstance, XCom, DagRun, DagTag, DagModel from airflow.models.xcom import XCOM_RETURN_KEY from airflow.operators.dummy import DummyOperator from airflow.utils.session import create_session, provide_session from airflow.utils.state import State from datetime...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import unittest from textwrap import dedent from typing import Dict, List, Union from pants.option.custom_types import DictValueComponent, ListValueComponent, UnsetBool from pants.option....
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. import cohesity_management_sdk.models.sql_update_restore_task_options import cohesity_management_sdk.models.files_to_directory_mapping class RestoreSqlAppObjectParams(object): """Implementation of the 'RestoreSqlAppObjectParams' model. TODO: type model ...
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
#! /usr/bin/env python from deep_morphology.data.seq2seq_data import Seq2seqDataset from deep_morphology.data.seq2seq_data import InflectionDataset from deep_morphology.data.seq2seq_data import NoSpaceSeq2seqDataset, UnlabeledNoSpaceSeq2seqDataset from deep_morphology.data.seq2seq_data import GlobalPaddingInflectionDa...
import os import time import secrets from flask import render_template, url_for, flash, redirect, request, abort from app import app from app.forms import VideoUploadForm from api.tritonAPI import Triton triton = Triton(DEBUG = True) def save_video(form_video): random_hex = secrets.token_hex(8) _, f_ext = o...
#!/usr/bin/python #-*- coding: UTF-8 -*- # chordgenerator.py: Generating tables of chords associated with scales. # # Copyright (c) 2008-2020 Peter Murphy <peterkmurphy@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that t...
from keras.datasets import imdb from keras import preprocessing # Number of words to consider as features max_features = 10000 # Cuts off the text after this number of words # (among the max_features most common words) maxlen = 20 # Loads the data as lists of integers (x_train, y_train), (x_test, y_test) = imdb.load_...
import os import math from datasources.stac.query import STACQuery from datasources.sources.base import Datasource class SRTM(Datasource): tags = ['Raster', 'Elevation'] def __init__(self, manifest): super().__init__(manifest) self.endpoint = 'https://s3.amazonaws.com/elevation-tiles-prod/s...
import wx class MainFrame(wx.Frame): def __init__(self): super().__init__(None, -1, "My app", size=(1024, 768)) self._panel = wx.Panel(self) hbox = wx.BoxSizer(wx.HORIZONTAL) self.list = wx.ListCtrl(self._panel, wx.ID_ANY, style=wx.LC_REPORT...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- from typing import Union from azure.ml._artifacts._default_storage_helper import DefaultStorageClient from azure.ml._artifacts._fileshare_...
from os.path import join from app.util.conf.base_config_loader import BaseConfigLoader class SlaveConfigLoader(BaseConfigLoader): CONFIG_FILE_SECTION = 'slave' def configure_defaults(self, conf): """ These are the slave configuration defaults. These values can override values in BaseConfigL...
import torch import torchvision from models.backbone.resnet_PR import * from models.backbone.csp_darknet import CSPDarknet from collections import OrderedDict def copyStateDict(state_dict): if list(state_dict.keys())[0].startswith('module'): start_idx = 1 else: start_idx = 0 ...
import json import jsonschema from aqt.qt import QDialog from aqt.utils import showWarning, showInfo from ..sr_setting_update_ui import Ui_SRSettingUpdate class SRSettingUpdate(QDialog): def __init__(self, parent): super().__init__(parent=parent) self.ui = Ui_SRSettingUpdate() self.ui.se...
#!/usr/bin/env python # coding: utf-8 import cgi from datetime import datetime html_body = u""" <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> </head> <body> <form action = "/cgi-bin/f13form.py" method="POST"> 西暦を選んでください: <select name="year" /> %s </select> <input type="submit" /> </...
import gzip import random pseq = {} dseq = {} prox = 400 dist = 2000 size = 50 with gzip.open('../project_imeter/at_ime_master.txt.gz', 'rt') as fp: for line in fp.readlines(): f = line.split() beg = int(f[1]) end = f[2] strand = f[3] intron = f[-1] seq = intron[5:-10] if beg < prox: for i in range(...
import datetime from drc_cmis.browser.drc_document import Folder def create_json_request_body(target_folder: Folder, properties: dict) -> dict: """Create the body of the JSON request from the target folder and the document properties The target properties are already converted to CMIS names. """ dat...
#Import modules import csv a = [] print("\n The Given Training Data Set \n") #Read dataset file with open('Candidate.csv', 'r') as csvFile: reader = csv.reader(csvFile) for row in reader: a.append (row) print(row) num_attributes = len(a[0])-1 print("\n The initial value of hypothesis: ") S = [...
import click import json @click.command() @click.option("--input_file", required=True, type=click.File("rb"), nargs=1) @click.option("--fields_to_track", type=click.STRING, multiple=True) @click.option("--fields_to_exclude", type=click.STRING, multiple=True) def cli(input_file, fields_to_track, fields_to_exclude): ...
""" common.py Common routines run throughout ARTView. """ # Load the needed packages from .core import QtGui, QtCore import numpy as np ######################## # Dialog methods # ######################## def ShowWarning(msg): ''' Show a warning message. Parameters:: ---------- msg - string ...
# # Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
from flask import Flask from .config import config_by_name from .services.auth import jwt from app.init.db import db, flask_bcrypt from app.init.api import api from .services.user import * from .services.serial_port_services import * def create_app(config_name): app = Flask(__name__) app.config.from_object(c...
#!/usr/bin/env python """Tests for `xepmts_server` package.""" # pylint: disable=redefined-outer-name import pytest from click.testing import CliRunner from xepmts_server import cli @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ ...
import os from datetime import datetime import re import pytz from apscheduler.schedulers.asyncio import AsyncIOScheduler from dotenv import load_dotenv import discord from discord.ext import commands import asyncio load_dotenv() pytz.timezone('America/Toronto').localize(datetime.now()) bot = commands.Bot(command_pr...
""" :Created: 6 May 2015 :Author: Lucas Connors """ from django import forms from menu.models import MenuItem from restaurant.models import Table class MenuForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Create a field for each menu item for m...
# -*- coding: UTF-8 -*- # **********************************************************************************# # File: # **********************************************************************************# import os def get_temp_path(file_name): """ Get path for saving temporary files. Args: fi...
import sys import datetime from django.core.management.base import BaseCommand from django_stormpath.models import APPLICATION, StormpathUserManager class Command(BaseCommand): help = 'Syncs remote accounts to the local database.' def handle(self, **options): try: user_manager = Stormpa...
# -------------- # import the libraries import numpy as np import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings('ignore') # Code starts here df=pd.read_csv(path) print(df.head()) X=df.iloc[:,:7] y=df['insuranceclaim'] X_train,X_test,y_tr...
# Copyright 2010-2011 OpenStack Foundation # Copyright 2011 Piston Cloud Computing, Inc. # 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...
from django.apps import AppConfig class AlgoConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'algo'
from django.shortcuts import render from establishment.webapp.state import State from establishment.webapp.base_views import single_page_app, global_renderer def render_single_page_app(request): return render(request, "{{project_main_app}}/app.html", {}) global_renderer.render_single_page_app = render_single_pa...
#!/usr/bin/env python3 # Part of CLRS solutions by SweetPalma, 2019. See LICENSE for details. import unittest import math # Solution: def lookup(): n = 1 while abs(8 * math.log2(n) - n) >= 1: n = n + 1 return n # Runner: if __name__ == '__main__': print(lookup())
import collections import json import math import sys def split_coco_labels(json_string, max_byte_size, current_task): """ Splitting input json string into smaller json strings :param current_task: object of current task in annotator :param json_string: JSON string (decoded) :param max_byte_size: ...
from wrappers import OSMClient from pytest import fixture from .osm_fixture import * from .config import * import json import time from .helpers import Helpers from .test_nsd import * def test_post_ns_instances_nsinstanceid_instantiate(post_ns_instances_nsinstanceid_instantiate_keys): """Tests API call to create...
import torch import torch.nn.functional as F import jax import jax.numpy as jnp import haiku as hk import numpy as np from icecream import ic ic.configureOutput(includeContext=True) # copy and edit to be worked with pytorh from https://github.com/tensorflow/models/blob/master/official/transformer/utils/me...
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404, JsonResponse from django.views.generic import DetailView, CreateView, UpdateView, ListView, View from django.shortcuts import render, redirect, reverse from .forms import...
def reverse_mapping(old_dict): new_dict = {} for key, value in old_dict.items(): if value in new_dict: new_dict[value].append(key) else: new_dict[value] = [key] return new_dict def dict_print(my_dict): for key, values in my_dict.items(): counter = 1 ...
import sys input = sys.stdin.readline T = int(input()) for _ in range(T): N = int(input()) S = input().rstrip() E = input().rstrip() score = 0 mismatch = 0 diff = abs(S.count('W')-E.count('W')) for s,e in zip(S,E): if s!=e: mismatch+=1 print(int((mismatch+diff)/2))
from parameterized import parameterized from queue import LifoQueue import unittest class Test(unittest.TestCase): @parameterized.expand([ ("provided example", [3, 34, 4, 12, 5, 2], 9, True), ("single value true", [1], 1, True), ("single value false", [1], 2, False), ("three values...