content stringlengths 5 1.05M |
|---|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module stores implememtation of deep Q-Network with experience replay.
"""
import logging
import numpy as np
import random
from collections import defaultdict, namedtuple
import tensorflow as tf
from keras.optimizers import Adam # noqa
from keras.models import... |
import smart_imports
smart_imports.all()
class RoadAdmin(django_admin.ModelAdmin):
list_display = ('id', 'exists', 'point_1', 'point_2', 'length')
list_filter = ('point_1', 'point_2')
class WaymarkAdmin(django_admin.ModelAdmin):
list_display = ('id', 'point_from', 'point_to', 'road', 'length')
l... |
## Standard libraries
import os
import random
import numpy as np
import time
import pandas as pd
## tqdm for loading bars
from tqdm import tqdm
## PyTorch
import torch
import torch.utils.data as data
import torch.optim as optim
# Losses
from pytorch_metric_learning import losses, distances
# Custom libraries
import... |
from UQpy.inference.inference_models.baseclass.InferenceModel import InferenceModel
|
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... |
n = input('Digite seu nome completo: ')
print(f'Seu nome com letras minúsculas é {n.lower()}')
print(f'Seu nome com letras maiúsculas é {n.upper()}')
#print(f'Total de letras que contem seu nome é {len(n.replace(" ", ""))}')
#Da para utilizar dessa formar também, no entanto o de baixo foi utilizado no vídeo
print(f'Tot... |
import sqlite3
import json
from collections import OrderedDict
import uuid as uuid
class Persistence:
def __init__(self, path, log):
self.path = path
self.log = log
def init_db(self):
db_conn, db_client = self.create_connection()
try:
db_client.execute('''CREATE T... |
import numpy as np
import cPickle
for filename in ('vectors',):
print 'Converting {}.txt'.format(filename)
word2id = dict()
embeddings = []
with open('../data/w2v/{}.txt'.format(filename)) as f:
n, k = map(int, f.readline().split())
i = 0
for line in f:
word, vect = ... |
"""
dbcentral.py
@author: Rob Newman <robertlnewman@gmail.com> 858.822.1333
@created: 2010-08-11
@modified: 2011-01-25
@notes: 1. Open up clusters table, create dictionary or list, return
2. Add unit testing
"""
import os
import sys
import time
import datascope as antdb
if '5.2' in os.environ['ANTELO... |
import os, sys, time
import numpy as np
import scipy.constants as sc
from scipy import integrate
from scipy.interpolate import interp1d
from scipy.special import ellipk, ellipe
from astropy.io import ascii
import matplotlib.pyplot as plt
import warnings
# constants (in cgs units)
_msun = 1.989e33
_AU = sc.au * 1e2
_mu... |
#!/usr/bin/env python
"""Harness for running benchmarks.
This module handles all aspects of running a series of benchmarks with
pre-built executables and emitting the results into a central location for
further processing.
It's currently very focused on HHVM and php-octane, but it could be generalized
because it uses... |
# Copyright (c) 2019. Partners HealthCare, Harvard Medical School’s
# Department of Biomedical Informatics, Sergey Trifonov
#
# Developed by Sergey Trifonov and Michael Bouzinier, based on contributions by:
# Anwoy Kumar Mohanty, Andrew Bjonnes,
# Ignat Leshchiner, Shamil Sunyaev and other members of Division of G... |
import os
from flask import Flask, render_template, request, session, redirect, flash, url_for
from flask_pyoidc.flask_pyoidc import OIDCAuthentication
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# pulling config settings
if os.path.exists(os.path.join(os.getcwd(), "config.env.py")):
app.confi... |
#!/usr/local/bin/python3.9
import argparse
import scapy.all as scapy
import subprocess
import time
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", dest="target", help="IP address target")
parser.add_argument("-r", "--router", dest="router", help="IP address r... |
##################################################################
# test T-splines mesh creation. The example is taken from Fig. 23,
# Isogeometric Analysis using T-splines
##################################################################
#importing Kratos modules
from KratosMultiphysics import *
from KratosMultiphys... |
# 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... |
"""
Licensed Materials - Property of IBM
Restricted Materials of IBM
20190891
© Copyright IBM Corp. 2021 All Rights Reserved.
"""
"""
Module to where data handler are implemented.
"""
import abc
from ibmfl.data.data_handler import DataHandler
from ibmfl.data.env_spec import EnvHandler
class EnvDataHandler(DataHandle... |
# BenchExec is a framework for reliable benchmarking.
# This file is part of BenchExec.
#
# Copyright (C) 2007-2019 Dirk Beyer
# 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 Lic... |
# Copyright 2020 MONAI Consortium
# 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, s... |
from caffe2.python import core, workspace
import unittest
core.GlobalInit(['python'])
class BlobDeallocationTest(unittest.TestCase):
def test(self):
net = core.Net('net')
x = net.GivenTensorStringFill([], ['x'], shape=[3], values=['a', 'b', 'c'])
y = net.GivenTensorStringFill([], ['y... |
# Generated by Django 3.1.3 on 2021-01-14 19:12
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('game', '0005_game_question'),
]
operations = [
migrations.AddField(
model_name='appuser',
... |
#!/usr/bin/python
from EFUMetrics import Metrics
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", metavar='ipaddr', help = "server ip address (default 127.0.0.1)",
type = str, default = "127.0.0.1")
parser.add_argument("-p", metavar='port', help = "server tcp port (defa... |
import shutil
from os import makedirs, rename
from pathlib import Path
from random import random
from typing import Optional
import pytest
import yaml
from superai.config import (
__env_switcher,
__local_settings_path,
__secrets_path,
__settings_path,
add_secret_settings,
ensure_path_exists,
... |
# -*- coding: utf-8 -*-
"""CircleCore."""
# community module
from six import PY2
if PY2:
class abstractclassmethod(classmethod):
__isabstractmethod__ = True
def __init__(self, callable):
callable.__isabstractmethod__ = True
super(abstractclassmethod, self).__init__(calla... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""""""
import tkinter as tk
from tkinter import font
import string
import pkinter as pk
class OptionBar(pk.Toolbar):
def __init__(self, parent):
pk.Toolbar.__init__(self, parent)
def change_tool(self):
for i in self.pack_slaves():
i... |
class NothingToDoError(Exception):
pass
|
# -*- coding: utf-8 -*-
from enchant.checker import SpellChecker
class Crypto:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".lower()
long_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ".lower()
cipher_text = ""
spell_check = None
language = "en_US"
... |
import InputOutput
files = ["a_example.txt",
"b_lovely_landscape.txt",
"c_memorable_moments.txt",
"d_pet_pictures.txt",
"e_shiny_selfies.txt"]
data = InputOutput.Data("input_data/" + files[0])
"""
data.photos[photo_id][0] - photo id
data.photos[photo_id][1] - 'h' or 'v'
data.photos[... |
#!/usr/bin/env python
# Copyright (c) 2022 SMHI, Swedish Meteorological and Hydrological Institute.
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
Created on 2020-04-14 12:20
@author: a002028
"""
import numpy as np
import pandas as pd
from profileqc.boolean_handler import BooleanBa... |
import mysql.connector
mydb = mysql.connector.connect(
host="192.38.56.161",
user="chp",
passwd="<password>",
database="ecpower_training"
)
cursor = mydb.cursor() |
from vk import VKAPI
class Search(VKAPI):
method_class = 'search'
def __init__(self, access_token=''):
super(Search, self).__init__(access_token=access_token)
def get_hints(self, **params):
self.set_method('getHints')
return self.send(params)
|
def cV(v):
return [ x[:] for x in v]
def move(m, v, i, j, steps, path, modified, check):
s1 = s2 = 99999
if m[i][j] == 0:
s1 = solve(m, cV(v), i, j, steps, path+[(i,j)], modified,check)
return s1
elif not modified:
s2 = solve(m, cV(v), i, j, steps, path+[(i,j,True)], True,check)... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, Q... |
# This file is part of OctoBot (https://github.com/Drakkar-Software/OctoBot)
# Copyright (c) 2021 Drakkar-Software, All rights reserved.
#
# OctoBot is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either
... |
from django.test import TestCase
from .test_forms import (ForeignFormAreaTestDefaultWidget,
ForeignFormTestDateTime, ForeignFormTestDefaultWidget,
ForeignFormTestInteger)
from .test_models import Target
class ForeignFieldTestCase(TestCase):
def setUp(self):
... |
from setuptools import setup
from sys import version_info
if version_info < (3, 0):
raise RuntimeError("""
Using python 2.x? 3.x required (modify setup.py to disable the
exception if the code has been ported)
""")
try:
import PyQt5
except ImportError:
print("""
PyQt5 is not a... |
"""Units for distance etc."""
from __future__ import division
from math import pi
M = METER = METERS = 1.
CM = 0.01
MM = 0.001
IN = INCH = INCHES = 0.0254
FT = FOOT = FEET = 12 * INCHES
DEG = DEGREES = 180.0 / pi
|
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are:
# 012 021 102 120 201 2... |
# import wikipedia
#
# print(wikipedia.page("List of Nobel laureates in Literature").html())
import wikipediaapi
wiki_wiki = wikipediaapi.Wikipedia('en')
page_py = wiki_wiki.page('List_of_Nobel_laureates_in_Literature')
# print(page_py.sections)
print(page_py.section_by_title('Laureates'))
# push... |
from builtins import object
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from future.utils import python_2_unicode_compatible
from parler.models import TranslatedFields
from bluebottle.utils.models import SortableTranslatableMod... |
#!/usr/bin/env python3
from high_templar.main import create_app
from high_templar.connection import header
api_url = 'http://localhost:8000/api/'
class Settings:
API_URL = api_url
FORWARD_IP = 'HTTP_X_REAL_IP'
CONNECTION_HEADERS = {
'foo': header.Param('foo').map(str.upper),
}
app = create_... |
import os
for root, dirs, files in os.walk("/Users/coco/Documents/GitHub/pingcap-upstream/docs-cn", topdown=True):
#for root, dirs, files in os.walk("/Users/coco/Documents/GitHub/python-side-projects/cofile", topdown=True):
for name in files:
if '.md' in name: # Check all markdown files
filep... |
def convex_combs(collection, n_terms):
base = len(collection)
for i in range(base ** (n_terms - 1), base ** n_terms):
current_combination = []
integer_rep = i
current_power = 1
while current_power <= n_terms:
current_combination.append(
collect... |
from Cryptodome.Cipher import AES
from flask import Flask, render_template, send_from_directory, request, jsonify, redirect
from flask.globals import session
from flask.helpers import url_for
from argon2 import PasswordHasher
import requests
import AESCipher
import cx_Oracle
import fingerprint
import random
import json... |
""" Tests the create limbo model unit used by pyMARS """
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import pytest
import cantera as ct
from sensitivity_analysis import create_limbo
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
... |
#!/usr/bin/python3
# Adapted from tdjson_example.py, which is copyright Aliaksei Levin (levlam@telegram.org),
# Arseny Smirnov (arseny30@gmail.com), Pellegrino Prevete (pellegrinoprevete@gmail.com)
# 2014-2021. Source: https://github.com/tdlib/td/blob/master/example/python/tdjson_example.py
#
# Distributed under the B... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep
from datetime import datetime
import pan... |
#This part of the tool is not yet implemented.
# IMPORTANT ITEMS FOR CLASSES:
# Barbarian:
# - WEAPON OPTIONS
# - ENHANCEMENT OPTIONS
# - Furious (BIS enchantment)
# - Courageous (after Furious)
# - Speed (self-haste, only if mage cannot apply)
# - Dancing (pricey but free extra hits)
# - Bardiche (reach, 1... |
from menu import main_menu
if __name__ == "__main__":
main_menu()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file was part of Flask-Bootstrap and was modified under the terms of
# its BSD License. Copyright (c) 2013, Marc Brinkmann. All rights reserved.
#
# This file was part of Bootstrap-Flask and was modified under the terms of
# its MIT License. Copyright (c) 2018 Grey ... |
from flask import request, jsonify, session,render_template
from application import app, logger, cache
from application import app
from application.models import *
from forms import *
from models import Customer
import stripeview
@app.before_first_request
def before_first_request():
logger.info("----------------... |
class Restaurant:
def __init__(self, restaurant_name, cuisine_type, maximum):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
self.maximum = maximum
def describe_restaurant(self):
print('The restaurant\'s name is ' + self.re... |
TOKEN_IDS = 'token_ids'
ATT_MASK = 'att_mask'
TOKEN_TYPE_IDS = 'token_type_ids'
# for single sentence tasks
SENTENCE_COLUMN = 'sentence_column'
# for pair of sentences tasks
FIRST_SENTENCE_COLUMN = 'first_sentence_column'
SECOND_SENTENCE_COLUMN = 'second_sentence_column'
TARGET_COLUMN = 'target_column'
DATA_FOLDER =... |
s = 'My name is {name} and I am a {job_title}'
my_dict = {'name': 'Pankaj', 'job_title': 'Software Engineer'}
print(s.format_map(my_dict))
print(s.format(**my_dict))
my_dict = {'name': 'Meghna', 'job_title': 'Editor', 'company': 'JournalDev'}
print(s.format_map(my_dict))
print(s.format(**my_dict))
# my_dict = {'na... |
'''Yppy algorithm facilities.
'''
# ....................{ IMPORTS }....................
from yppy import ui
# ....................{ CLASSES }....................
class YppyAlgorithmBase(object):
'''Base class for all Yppy algorithms.
Subclasses of thi... |
try:
import sys, os, logging
import webbrowser
except:
print("ExceptionERROR: cFish is missing fundamental packages (required: os, sys, logging, webbrowser).")
try:
import config
import cInputOutput as cIO
import fGlobal as fGl
except:
print("ExceptionERROR: Missing RiverArchit... |
import subprocess
import os
import turingarena as ta
# evaluator for TuringArena
# to launch this evaluator, use this command:
# turingarena-dev evaluate --store-files models/map_LP-model_gmpl.mod
def evaluate_solution(mod, dat):
# here I start a subprocess to evaluate the submission
# glpsol writes ... |
from requests_html import HTML, HTMLSession
from time import sleep
import csv
import datetime
file = open(f'data-{datetime.datetime.now()}', 'w', newline='')
writer = csv.writer(file)
writer.writerow(["name", "date", "content"])
session = HTMLSession()
url = 'https://www.ybtour.co.kr/promotion/incRepList.yb'
data =... |
import os
from pathlib import Path
import click
from click.testing import CliRunner
from ..command import download
from ...consts import dandiset_metadata_file
def test_download_defaults(mocker):
mock_download = mocker.patch("dandi.download.download")
r = CliRunner().invoke(download)
assert r.exit_code ... |
def display(p,**karg):
print(p)
print(karg)
return None
#display(4,5)
#display(b=5,a=4)
#display(a=4,b=5,c=6)
display(56,x=5,y="Hi",z=6.7,user="root") |
#! /usr/bin/env python
import sys
with open(sys.argv[1], 'r') as f_in:
with open(sys.argv[2], 'w') as f_out:
for line in f_in:
row = line.rstrip().split('\t')
# Header line
if line[0] == '@':
if line[1:3] == 'SQ' and len(row[1].split(':')) > 2:
... |
from gensim.models import word2vec
import pandas as pd
data_path = "E:\\ML_learning\\Daguan\\data\\train_set.csv"
train_data = pd.read_csv(data_path)
article = train_data["word_seg"]
f = lambda x: x.split(" ")
article_sentences = article.apply(f)
model = word2vec.Word2Vec(article_sentences, size=300, workers=8)
model... |
'''
A Derangement is a permutation of n elements, such that no element appears in its original position.
Problem statement: Given a number n, find total number of Derangements of a set of n elements.
Input format
Line1: Number of test cases
Line2: Give the value of n
Output format
The total number of derangement
Ba... |
a = 100
if a < 100:
print("조건이 참입니다")
print("실행을 종료합니다")
|
#!/usr/bin/env python
import tensorflow as tf
import argparse
import numpy as np
import cv2
import time
from extractor import extractor
from aligner import aligner
import os
import random
parser = argparse.ArgumentParser()
parser.add_argument('--devices', default='/gpu:0')
parser.add_argument('--extractor_batch_siz... |
# Copyright (c) 2020 Anastasiia Birillo, Elena Lyulina
import sys
import logging
from typing import List
from src.main.util import consts
from src.main.util.consts import LANGUAGE
from src.main.task_scoring.task_checker import ITaskChecker, check_call_safely, check_output_safely, SOURCE_OBJECT_NAME
log = logging.get... |
# pylint: disable=missing-module-docstring
__all__ = [
'dir_init_checker',
'trailing_commas',
]
|
#!/usr/bin/env python3
import subprocess
import re
import json
from pprint import pprint
from pathlib import Path
import os
import argparse
import sys
compiler_include_search_paths_s = "#include \"\\.\\.\\.\" search starts here:((.*\n)*)#include <\\.\\.\\.> search starts here:((.*\n)*)End of search list."
compiler_in... |
from abc import ABC, abstractmethod
class Strategy(ABC):
def __init__(self, task) -> None:
self.task = task
@abstractmethod
def run(self, model, config):
self.config = config
return
|
from ml_enabler.models.ml_model import MLModelVersion, Prediction, PredictionTile
from ml_enabler.models.dtos.ml_model_dto import PredictionDTO
from ml_enabler.models.utils import PredictionsNotFound
from ml_enabler.utils import bbox_str_to_list, bbox_to_quadkeys, tuple_to_dict, polygon_to_wkt, geojson_to_bbox
from ml_... |
import unittest
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree:
def __init__(self, arr):
self.root = self.genTree(arr)
@staticmethod
def genTree(arr)... |
import glob
import os
import gym
from gym import error, spaces
from gym import monitoring
from gym.monitoring import monitor
from gym.monitoring.tests import helpers
class FakeEnv(gym.Env):
def _render(self, close=True):
raise RuntimeError('Raising')
def test_monitor_filename():
with helpers.tempdir(... |
# Standard libs
import os, re, shutil, sys, time, datetime, logging, pickle, json, socket
import random, math, gc, copy
from collections import OrderedDict
from ctypes import c_bool
from multiprocessing import Process, Value
from multiprocessing.managers import BaseManager
import multiprocessing, threading
import numpy... |
#!/usr/bin/python3 -u
import argparse
import jenkinsapi
from jenkinsapi.utils.crumb_requester import CrumbRequester
import etcd
import time
import sys
import os
from concurrent.futures import ThreadPoolExecutor
import re
import urllib
import shlex
import random
random.seed()
supported_algorithms = ['ignore', 'decend... |
RS = ''
"""The record separator."""
US = ''
"""The unit separator."""
|
def matrix_form():
r = int(input("Enter the no of rows"))
c = int(input("Enter the no of columns"))
matrix=[]
print("Enter the enteries")
for i in range(r):
a = []
for j in range(c):
a.append(int(input()))
matrix.append(a)
return(matrix)
def check_matrix(fi... |
from MapMyNotesApplication import database
from MapMyNotesApplication.models.module_code import ModuleCode
from MapMyNotesApplication.models.note_meta_data import NoteMetaData
from MapMyNotesApplication.models.user import User
from sqlalchemy import Column, Integer, String, ForeignKey, and_
"""
Extends SQLAlchemy mode... |
import json
class MockResponse():
def __init__(self, status_code, text, headers={}):
self.status_code = status_code
self.text = text
self.headers = headers
def json(self):
return json.loads(self.text)
def create_mock_json(path):
with open(path) as f:
return f.rea... |
#!/usr/bin/python3
"""
Prepares, Validates and then starts the Server process(glusterfsd, shd)
"""
import os
import glusterfsd
import shd
from kadalulib import Monitor, Proc, logging_setup
def start_server_process():
"""
Start glusterfsd or glustershd process
"""
mon = Monitor()
curr_dir = os... |
"""
Support for Tellstick switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.tellstick/
"""
from homeassistant.components import tellstick
from homeassistant.components.tellstick import (ATTR_DISCOVER_DEVICES,
... |
import numpy as np
import re, pprint, scipy, scipy.linalg
from numpy import linalg as LA
from numpy.linalg import inv
from scipy.linalg import hilbert, lu
from scipy.interpolate import lagrange
from fractions import Fraction
# get the shape of the data e.g. [10][5]
def getShape(data_str):
count_semi = 0
fir... |
import sys
import os
import glob
import numpy as np
import skimage.io
files = glob.glob('*.jpg')
from PIL import Image
for num in range(int(len(files)/16)):
sub_img = [ img for img in files if img.split('.')[0][2:] == str(num+1)]
sub_img.sort()
print (sub_img)
temp = skimage.io.imread(sub_img[0]).shape
al... |
import netaddr
import requests
import openstack_dashboard.models as fogbow_models
import base64
from django.core.validators import RegexValidator
from django.core.urlresolvers import reverse
from django.core import validators
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
fro... |
from setuptools import setup
setup(
name='tztz',
version='0.1.0',
description='Toolz for Toolz',
author='Christopher Prohm',
author_email='mail@cprohm.de',
license='MIT',
packages=["tztz"],
tests_require=['pytest', 'dask', 'pytest-pep8'],
classifiers=[
'Development Status :... |
from pycparser import c_parser, c_ast
import ast, astunparse
from polyrec.ctopy import CtoPy
from polyrec.pyast import Analyze
def representation(file):
with open(file) as source:
# reading the c file
parser = c_parser.CParser()
astc = parser.parse(source.read())
# convert to python... |
class PodUnschedulableError(Exception):
pass
class PodTerminatedError(Exception):
pass
class ImagePullError(Exception):
pass
class PodConfigError(Exception):
pass
|
import matplotlib.pyplot as plt
log_fn = './models/training.log'
history = {'loss': [], 'acc': []}
with open(log_fn, "r") as f:
for line in f:
line = line.split(',')
loss = line[-2].split(':')[1].strip()
loss = float(loss)
acc = line[-1].split(':')[1].strip()
acc = float(a... |
#!/usr/bin/env python
# coding: utf-8
# ## **Trabalho final: Análise Exploratória de Dados**
#
# Grupo: Bianca Muniz, Meyrele Torres e Ricardo Grimbaun
# ## **Análise exploratória univariada**
# Variável escolhida: `idade`
# In[ ]:
# Importando as bibliotecas
import pandas as pd #para abrir e manipular as bases
i... |
"""
This module contains a function that can be used to generate an SQLite3 database from ascii files.
:author: Sami-Matias Niemi
:contact: niemi@stsci.edu
"""
import sqlite3
import glob as g
import SamPy.log.Logger as lg
import SamPy.db.sqlite
def generateSQLiteDBfromSAMTables(output='sams.db',
... |
import scrapy
from xiachufang.items import Recipe
class RecipesSpider(scrapy.Spider):
name = "recipes"
start_urls = [
"https://www.xiachufang.com/category/"
]
allowed_domains = ["xiachufang.com"]
def parse(self, response):
for category in response.css('div.cates-list-all'):
... |
n = int(raw_input())
data = [int(i) for i in raw_input().split()]
data = sorted(data)
for i in data:
print i,
|
n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
a.sort(reverse = True)
print sum(a[:m])
|
from google.appengine.ext.webapp import util
from protorpc.wsgi import service
import logging
import deliveryservice
logging.debug('Handling service...')
# Map the RPC service and path (/DeliverService)
delivery_service = service.service_mapping(deliveryservice.DeliveryService, '/DeliveryService.*')
def main():
uti... |
#!/usr/bin/env python3
# coding=utf-8
# Имеется массив в два столбца и 10 строк. Реализовать команду заполнить
# случайными числами, при которой заполняется первый столбец. Реализовать
# команду выполнить задание, при которой второй столбец заполняется значениями
# по формуле y(i) = (сумма(K нечетных до i) + произведе... |
for i in range(1,10):
for j in range(1,i+1):
print(f"{j}*{i}={i*j:2d}",end="")
print() |
import numpy as np
import cv2
import csv
import os
def create_dir(_dirpath):
try:
if not os.path.exists(_dirpath):
os.makedirs(_dirpath)
except OSError:
print("Error: creating directory."+_dirpath)
def csvWriter(_outputfilename, _data):
f = open(_outputfilename, 'w... |
import unittest
from pysapets.worm import Worm
from pysapets.animal import Animal
import pysapets.constants as constants
from unittest.mock import patch
from io import StringIO
from copy import deepcopy
class WormTest(unittest.TestCase):
def setUp(self):
self.worm = Worm()
self.friends = [self.worm, Animal... |
# Generated by Django 2.2.20 on 2021-07-06 19:22
# Third-party
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("licenses", "0001_initial"),
]
operations = [
migrations.RenameField(
model_name="translationbranch",
... |
import pandas as pd
def test_import():
import CellLayers |
# MIT License
#
# Copyright (c) 2015-2021 Iakiv Kramarenko
#
# 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, modif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.