content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
from subprocess import Popen, DEVNULL
import os
import pandas
import time
import matplotlib.pyplot as plt
DSTAT_FNAME = "dstat.csv"
if os.path.exists(DSTAT_FNAME):
os.remove(DSTAT_FNAME) #dstat appends by default
dstat = Popen(["dstat", "--output="+DSTAT_FNAME], stdout=DEVNULL)
print("Dst... |
def solve(n, a):
total = 0
currA = a
for i in range(1, n + 1):
total += i * currA
currA *= a
return total
if __name__ == '__main__':
print solve(3, 3)
print solve(4, 4)
print solve(150, 15)
|
from flask import render_template, session, redirect, url_for, request, \
current_app, flash
from . import main
from .forms import PostForm, CommentForm
from .. import db
from ..models import User, Post, Comment
from ..decorators import admin_required
from flask_login import current_user
@main.route('/')
def inde... |
from ps.routes.api.v1.psone_router import endpoints
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Portforwarded'
db.create_table(u'portforwarding_portforwarded', (
(u'id', self.g... |
import asyncio
import fractions
import logging
import threading
import time
import av
from av import AudioFrame, VideoFrame
from ..mediastreams import AUDIO_PTIME, MediaStreamError, MediaStreamTrack
logger = logging.getLogger('media')
REAL_TIME_FORMATS = [
'alsa',
'android_camera',
'avfoundation',
... |
# Imports
import click
import numpy as np
from tqdm import tqdm
def encode(to_encode, unique_to_index, train_ord):
to_ret = np.zeros(len(to_encode), dtype=np.int64)
p_bar = tqdm(np.ndenumerate(to_encode), desc='Encoding', total=len(to_encode))
for idx, obj in p_bar:
try:
to_ret[idx] = train_ord[unique_... |
from __future__ import print_function
import sys, argparse, os.path, fnmatch
import xlrd
from openpyxl import Workbook
def create_csvs( filename ) :
workbook = xlrd.open_workbook( filename )
wb = Workbook()
worksheet_all = wb.create_sheet()
worksheet_all.title = "All"
sheet_count = 1
row_count_all = 1 # dif... |
login_query = \
"""
SELECT * FROM user_info
WHERE user_email=(%s) AND user_password=(%s)
"""
user_details_query = \
"""
SELECT * FROM user_info
WHERE user_id=(%s)
"""
admin_details = \
"""
SELECT * FROM admin
WHERE user_id=(%s)
"""
prof_details = \
"""
SELECT * FROM professor
WHERE user_id=(%s)
"""
student_deta... |
def fatorial(número, show=0):
"""
--> Calcula o fatorial de um número
:param número: O número a ser calculado
:param show: Mostra o cálculo do fatorial
"""
resultado = 1
if show == True:
if número == 0:
print("0! = 1",end='')
if número == 1:
print(... |
from abc import ABC, abstractmethod
import numpy as np
class StochasticProcess(ABC):
""" ABC for stochastic process generators """
def __init__(self, t_init, x_init, random_state):
self.rs = np.random.RandomState(random_state)
self.x = np.copy(x_init)
self.t = t_init
def sample... |
# This sample tests the alternative syntax for unions as
# documented in PEP 604.
from typing import Callable, Generic, TypeVar, Union
def foo2(a: int | str):
if isinstance(a, int):
return 1
else:
return 2
B = bytes | None | Callable[[], None]
A = int | str | B
def foo3(a: A) -> B:
if... |
from kivy.app import App
from controller.game import Game
from controller.actor import Local, AI
class GameApp(App):
def build(self):
game = Game()
game.actors = [
Local(game=game, name='player1'),
AI(game=game, name='player2'),
]
view = game.actors[0].vi... |
from sys import byteorder
class Datagram:
def __init__(self):
self.head = bytes(10)
self.payload = bytes(0)
self.EOP = bytes(4)
def set_head(
self,
message_type,
message_id,
num_payloads,
payload_index,
payload_size,
error_type,
restart_index
):
self.head = (
... |
from aoc2015.day15 import (Ingredient, parse, cookie_vals, partition,
highest_score)
def test_parse():
a = ('Butterscotch: capacity -1, durability -2, flavor 6, '
'texture 3, calories 8')
assert parse(a) == Ingredient('Butterscotch', -1, -2, 6, 3, 8)
def test_cookie_vals... |
from django.core.management.base import BaseCommand, CommandError
from udc.models import Concept
class Command(BaseCommand):
args = '<filename>'
help = 'Updates UDC concepts'
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError(u'Please specify udc.rdf file path'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-08-27 15:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0007_auto_20170825_2201'),
]
operations = [
migrations.AlterMode... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Milan Ondrašovič <[email protected]>
#
# MIT License
#
# 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 w... |
#!/usr/bin/env python
"""
This code holds the solution for part 1 of day 8 of the Advent of Code for 2017.
"""
import sys
def check_register(register):
if register not in registers:
registers[register] = 0
def perform_check(register, test, test_value):
register_value = registers[register]
if t... |
import sys
import typing
def action_sanitize():
''' Make action suitable for use as a Pose Library
'''
pass
def apply_pose(pose_index: int = -1):
''' Apply specified Pose Library pose to the rig
:param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib acti... |
"""
Implements the template loading functionality.
Loads template files and replaces all placeholders.
"""
from pathlib import Path
import logging
import typing
import re
import json
import yaml # type: ignore
import toml # type: ignore
LOGGER = logging.getLogger(__name__)
class BadFormatError(json.JSONDecodeErro... |
# Rotating Cube, by Al Sweigart [email protected]
import math, time, random, sys, os
if len(sys.argv) == 3:
# Set size based on command line arguments:
WIDTH = int(sys.argv[1])
HEIGHT = int(sys.argv[2])
else:
WIDTH, HEIGHT = 80, 50
DEFAULT_SCALEX = (WIDTH - 4) // 8
DEFAULT_SCALEY = (HEIGHT - 4) ... |
from pyvod.channel_collections import MovieTrailers, FeatureFilmsPicfixer, \
FeatureFilms
query = "grindhouse"
print("Searching Feature Films Picfixer for: ", query, "\n")
for movie, score in FeatureFilmsPicfixer.search(query):
print(movie, score)
print("\nSearching Feature Films for: ", query, "\n")
for mov... |
"""Test the Basic ICN Layer implementation"""
import multiprocessing
import time
import unittest
from PiCN.Layers.ICNLayer import BasicICNLayer
from PiCN.Layers.ICNLayer.ContentStore import ContentStoreMemoryExact
from PiCN.Layers.ICNLayer.ForwardingInformationBase import ForwardingInformationBaseMemoryPrefix
from Pi... |
from datetime import datetime
import hashlib
class ServerHelper(object):
def __init__(self):
pass
@staticmethod
def get_secret(args: list):
m = hashlib.md5()
message = "".join(args)
m.update(message.encode())
return m.hexdigest()
def check_secr... |
class AuthenticationFailed(Exception):
"""Custom exception for authentication errors on web API level (i.e. when
hitting a Flask server endpoint).
"""
def __init__(self, error, status_code):
self.error = error
self.status_code = status_code
# Custom exceptions to be raised in GraphQL ... |
import matplotlib.pyplot as plt
def plot_test_result(test):
sorted_x = sorted(test, key=lambda kv: kv[0])
x = list(range(50))
y = list(k[1] for k in sorted_x)
print(sorted_x)
sorted_k = sorted(test, key=lambda kv: kv[1])
print(sorted_k)
plt.plot(x, y)
plt.xlabel('epoch num')
plt.ylabel('domain mAP')
plt.tit... |
import torch
import numpy as np
def get_pad_mask(inputs):
"""Used to zero embeddings corresponding to [PAD] tokens before pooling BERT embeddings"""
inputs = inputs.tolist()
mask = np.ones_like(inputs)
for i in range(len(inputs)):
for j in range(len(inputs[i])):
if inputs[i][j] == ... |
from flask import Flask
app = Flask(__name__)
@app.route('/users/<string:username>')
def hello_world(username='MyName'):
return("Hello {}!".format(username))
if __name__ == '__main__':
app.run()
|
import os
__all__ = [
'list_all_py_files',
]
_excludes = [
'tensorlayer/db.py',
]
def _list_py_files(root):
for root, _dirs, files in os.walk(root):
if root.find('third_party') != -1:
continue
for file in files:
if file.endswith('.py'):
yield os.pa... |
from django.urls import path
from shiny_sheep.chat.api.views import RoomCreateView, RoomView
urlpatterns = [
path('', RoomCreateView.as_view()),
path('/<int:pk>/', RoomView.as_view()),
]
|
class Solution:
def makeLargestSpecial(self, S: str) -> str:
count = i = 0
res = []
for j, v in enumerate(S):
count = count + 1 if v=='1' else count - 1
if count == 0:
res.append('1' + self.makeLargestSpecial(S[i + 1:j]) + '0')
i = j + ... |
#############################################################
##### Simulates a pseudo-Premier League season
##### Scoring controlled by 3 ratings per team
##### Home team advantage not instituted
#############################################################
import sys
import numpy as np
import pandas as pd
import ran... |
#!/usr/bin/env python3
# Copyright (C) 2019 Canonical Ltd.
import nagios_plugin3
import yaml
from subprocess import check_output
snap_resources = ['kubectl', 'kubelet', 'kube-proxy']
def check_snaps_installed():
"""Confirm the snaps are installed, raise an error if not"""
for snap_name in snap_resources:
... |
#! /usr/bin/python
import sys
import common
def init_file(prefix):
if not prefix:
return
out_fd = open(prefix + ".h", "wt")
out_fd.write("#ifndef " + "_" + common.cmn_trans_underline(prefix).upper() + "_" + "\n")
out_fd.write("#define " + "_" + common.cmn_trans_underline(prefix).upper() + "_" + "\n")
out_fd.wr... |
import torch
from torch import nn, optim
import torchsolver as ts
class Discriminator(nn.Module):
def __init__(self, in_c=784, channels=(200,), leaky=0.02, layer_norm=nn.LayerNorm):
super(Discriminator, self).__init__()
layers = []
for out_c in channels:
layers.append(nn.Linea... |
'''
afhsb_csv.py creates CSV files filled_00to13.csv, filled_13to17.csv and simple_DMISID_FY2018.csv
which will be later used to create MYSQL data tables.
Several intermediate files will be created, including:
00to13.pickle 13to17.pickle 00to13.csv 13to17.csv
Required source files:
ili_1_2000_5_2013_new.sas7bdat a... |
import os
import numpy as np
import cv2
from Lane import Line
import parameter
import helper
import matplotlib.pyplot as plt
from moviepy.editor import VideoFileClip
def find_lane_pixels(binary_warped):
global LeftLane, RightLane
# Identify the x and y positions of all nonzero pixels in the image
nonzero =... |
import sys
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
try:
dataFileName = sys.argv[1]
except IndexError:
print("USAGE: python plotEnergies.py 'filename'")
sys.exit(0)
HFEnergy3 = 3.161921401722216
HFEnergy6 = 20.71924844033019
numPart... |
"""Test script for Time Predictor Network (TPN).
Once you have trained your model with train_time.py, you can use this script to test the model.
It will load a saved model from --checkpoints_dir and print out the results.
It first creates model and dataset given the option. It will hard-code some parameters.
It then ... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
tf.get_logger().setLevel('INFO')
tf.compat.v1.enable_eager_execution()
import argparse
import matplotlib.pyplot as plt
from ptfrenderer import utils
from ptfrenderer import camera
from ptfrenderer import uv
_shape = utils.... |
import itertools
import json
from unittest.mock import patch
from tornado import testing, web
from jsonrpcclient.clients.tornado_client import TornadoClient
from jsonrpcclient.request import Request
class EchoHandler(web.RequestHandler):
def data_received(self, chunk):
pass
def post(self):
... |
from csaf_f16.models.waypoint import *
def model_init(model):
"""load trained model"""
model.parameters['auto'] = None
def get_auto(model, f16_state):
if model.auto is None:
model.parameters['auto'] = WaypointAutopilot(model.waypoints, airspeed_callable=model.airspeed)
return model.auto
de... |
from typing import List
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
matrix = [[0 for i in range(m)] for i in range(n)]
for i in range(len(indices)):
for j in range(n):
matrix[j][indices[i][1]] += 1
for j in range(m):
... |
from django.urls import path
from . import views
urlpatterns = [
path('hands', views.HandListCreateApiView.as_view(), name='hands_view'),
] |
from pypinyin import pinyin as to_pinyin
from pypinyin import Style as style
tone_styles = [style.TONE, style.TONE2, style.TONE3]
def char_to_pinyin(char: str, tone_style: int) -> str:
"""Converts a single character to pinyin
# TODO support heteronyms?
Parameters
----------
char : String
... |
from netlds.models import *
from netlds.generative import *
from netlds.inference import *
from data.sim_data import build_model
import os
try:
# set simulation parameters
num_time_pts = 20
dim_obs = 50
dim_latent = 2
obs_noise = 'poisson'
results_dir = '/home/mattw/results/tmp/' # for storin... |
from trapcards import JustMathGenius
a = [1,2,3]
b = [1,1,1]
print(JustMathGenius.weightedAvg(a,b)) |
from collections import defaultdict
import sys
mapped = defaultdict(int)
with open(sys.argv[1], 'r') as samfile:
for line in samfile:
if (line[0] != '@') & (line.split('\t')[2] != '*'):
mapped[line.split('\t')[0]] = 1
print(len(mapped))
seqs = defaultdict(str)
outfile = open(sys.argv[3], 'w')
with open(sys.arg... |
# ------------------------------
# 497. Random Point in Non-overlapping Rectangles
#
# Description:
# Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which
# randomly and uniformily picks an integer point in the space covered by the rectangles.
#
# Note:
#
# An integer point is ... |
'''
Created on Mar 26, 2015
@author: jpenamar
'''
import unittest
from mytree import Tree
class TreeTestCase(unittest.TestCase):
"""Test the methods of the class Tree."""
def setUp(self):
self.tree = Tree('D', 'D data')
self.tree.insert('Q', 'Q data') # Insert in right node.
self.tree... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import imp
import os.path
import sys
import unittest
def _GetDirAbove(dirname):
"""Returns the directory "above" this file containing |dirname| (which mus... |
import numpy
import torch
def image_to_text(captions, images, npts=None, verbose=False):
"""
Images->Text (Image Annotation)
Images: (5N, K) matrix of images
Captions: (5N, K) matrix of captions
"""
if npts == None:
npts = images.size()[0] / 5
npts = int(npts)
ranks = numpy... |
num = int(input('Digite um número de 4 algarismos: '))
centena = num // 100
if centena % 4 == 0:
print(f'({centena}) é multiplo de 4')
else:
print(f'({centena}) não é multiplo de 4'') |
#
from pyclics.api import Clics # flake8: noqa
__version__ = "3.0.3.dev0"
|
def add_binary(a,b):
|
"""
Copyright 2021 Max-Planck-Gesellschaft
Code author: Jan Achterhold, [email protected]
Embodied Vision Group, Max Planck Institute for Intelligent Systems, Tübingen
This source code is licensed under the MIT license found in the
LICENSE.md file in the root directory of this source tree or at
https://o... |
# -*-coding:utf-8-*-
from random import random
import requests
import re
import time
import pandas as pd
import xlrd
from xlutils.copy import copy
from lxml import etree # xpath
user_agent = [
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import sys
import numpy as np
import argparse
import pprint
import pdb
import time
import cv2
import cPickle
import torch
from torch.autograd import Variable
import torch.nn as nn
i... |
from QCGym.hamiltonians.int_cross_resonance import InteractiveCrossResonance
from QCGym.fidelities.trace_fidelity import TraceFidelity
import gym
import numpy as np
from gym import spaces
from scipy.linalg import expm
import logging
logger = logging.getLogger(__name__)
CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0,... |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from symfit import Parameter, Variable, Fit, GradientModel
from symfit.distributions import Gaussian
palette = sns.color_palette()
x = Variable('x')
y = Variable('y')
A = Parameter('A')
sig = Parameter(name='sig', value=1.4, min=1.0, max=2.0)
... |
import argparse
from app import db
from app.models import Node, Post
all_posts = Post.query.all()
all_nodes = Node.query.all()
for i in all_posts:
db.session.delete(i)
db.session.commit()
for i in all_nodes:
db.session.delete(i)
db.session.commit()
# for u in users:
# if u.email == 'None':
# ... |
from pyneuroml.neuron import export_to_neuroml2
import sys
import os
os.chdir("../NEURON/test")
sys.path.append(".")
export_to_neuroml2("load_l23.hoc",
"../NeuroML2/L23_morph.cell.nml",
includeBiophysicalProperties=False,
known_rev_potentials={"na":60,"k":-9... |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .crf import CRF
class BiLSTMCRF(nn.Module):
def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim, pre_word_embed=None, num_rnn_layers=1):
super(BiLSTMCRF, self).__init__()
... |
import numpy as np
import logging
import torch
def seq_to_array(fp, max_len=15):
with open(fp) as f:
data = [x for x in f.read().split("\n") if x != ""]
new_list = []
for seq in data:
arr = seq.split(",")
new_list.append(np.array([int(w) for w in arr] + [0] * (max_le... |
import tensorflow as tf
class DCGAN2(object):
def __init__(self, name, data_shape,
noise_shape, discriminator, generator):
self.name = name
if self.name is not None:
with tf.variable_scope(self.name) as scope:
self._build_graph(data_shape, noise_shape,... |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
class ProcesssData(object):
def __init__(self, config):
self.batch_size = config["model"]["batch_size"]
self.data = input_data.read_data_sets(config[... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
from pprint import pprint
import logging
from .shared import get_model
from hubit import clear_hubit_cache
# logging.basicConfig(level=logging.INFO)
def model_0():
"""Send entire car object to worker"""
print(f"\n***MODEL 0***")
hmodel = get_model("model0.yml")
query = ["cars[0].price", "cars[1].pric... |
import tensorrt as trt
import torch
from torch2trt_dynamic.module_test import add_module_test
from torch2trt_dynamic.plugins import create_adaptivepool_plugin
from torch2trt_dynamic.torch2trt_dynamic import (get_arg, tensorrt_converter,
trt_)
@tensorrt_converter('torch... |
#!/usr/bin/env python3
# coding:utf-8
profit = int(input("Please enter current month profit: "))
bonus = 0
gear1 = 100000 * 0.1 # 第 1 档,10w 以内最高奖金
gear2 = gear1 + ( 200000-100000) * 0.075 # 第 2 档,20w 以内最高奖金
gear3 = gear2 + ( 400000-200000) * 0.05 # 第 3 档,40w 以内最高奖金
gear4 = gear3 + ( 600000-400000) * 0.03 # ... |
# Python - 3.6.0
Test.it('Basic tests')
Test.assert_equals(solve([3, 4, 4, 3, 6, 3]), [4, 6, 3])
Test.assert_equals(solve([1, 2, 1, 2, 1, 2, 3]), [1, 2, 3])
Test.assert_equals(solve([1, 2, 3, 4]), [1, 2, 3, 4])
Test.assert_equals(solve([1, 1, 4, 5, 1, 2, 1]), [4, 5, 2, 1])
|
from django.apps import AppConfig
class TractebelConfig(AppConfig):
name = 'tractebel'
|
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Implementation of the RNN based DrQA reader."""
import ipdb
import torch
import torch.nn as nn
from torch.n... |
from turtle import *
def turtle_controller(do, val):
do = do.upper()
if do == 'F':
forward(val)
elif do == 'B':
backward(val)
elif do == 'R':
right(val)
elif do == 'L':
left(val)
elif do == 'U':
penup()
elif do == 'D':
pendown()
elif do ==... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
(c) 2017 Brant Faircloth || http://faircloth-lab.org/
All rights reserved.
This code is distributed under a 3-clause BSD license. Please see
LICENSE.txt for more information.
Created on 17 March 2017 15:15 CDT (-0500)
"""
import pdb
import sys
import gzip
import arg... |
from datetime import timedelta
import logging
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import STATE_UNAVAILABLE
from .entity import PanasonicBaseEntity
from .const import (
DOMAIN,
DEVICE_TYPE_AC,
DATA_CLIENT,
DATA_COORDINATOR,
DEVICE_CLASS_SWITCH,
LABEL... |
'''
File name : rdf_FZUplace.py
Author : Jinwook Jung
Created on : Wed 14 Aug 2019 12:08:23 AM EDT
Last modified : 2020-03-30 22:54:26
Description :
'''
import subprocess, os, sys, random, yaml, time
from subprocess import Popen, PIPE, CalledProcessError
# FIXME
sys.path.inse... |
__doc__ = """
Main module for running BRISE configuration balancing."""
import itertools
import datetime
import socket
from sys import argv
from warnings import filterwarnings
filterwarnings("ignore") # disable warnings for demonstration.
from WSClient import WSClient
from model.model_selection import get_model
f... |
from . tga import * |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from profiles_api import views
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset')
router.register('profile', views.UserProfileViewSet)
router.register('feed', views.UserProfil... |
PAIRWISE_DRIVER_EXCEPTIONS = {
'verstappen': 'max_verstappen',
'magnussen': 'kevin_magnussen'
}
def initials_for_driver(name):
new_name = ''
if ((name) and (len(name) > 2)):
new_name = name[0:3].upper()
return new_name
def rename_drivers(name):
new_name = name.lower()
new_name =... |
from django.contrib.auth.models import AbstractUser
from social.invites.models import Invite
from . import constants
class User(AbstractUser):
"""A custom user for extension"""
@property
def remaining_connections(self):
"""Get the number of remaining available connections."""
return (
... |
r"""The real valued VGG model. Adapted from
https://github.com/kuangliu/pytorch-cifar/blob/master/models/vgg.py
https://github.com/anokland/local-loss/blob/master/train.py
"""
import torch
# var-dropout
from cplxmodule.nn.relevance import LinearVD
from cplxmodule.nn.relevance import Conv2dVD
# automatic relevance d... |
import sqlite3
conn = sqlite3.connect('ej.db')
c = conn.cursor()
f = open("data.txt","w") ##crear archivo de texto para el regresor logístico
for row in c.execute('SELECT ancho, alto, clase FROM features'): # mostrar base de datos
print(row)
f.write(' '.join(str(s) for s in row) + '\n') #escribimos el archivo... |
import numpy as np
import os
import skimage.io as io
import skimage.transform as trans
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as keras
def unet(pretrained_weights = None, input... |
import globals
from globals import get_soup, job_insert
from job import Job
# Upward Bound House
organization = "Upward Bound House"
url = 'https://upwardboundhouse.org/about-us/careers/'
organization_id= 60
def run(url):
soup = get_soup(url)
jobs_div = soup.find('h1', text='Careers').parent
job... |
# Copyright (C) 2020 Red Hat, Inc.
# SPDX-License-Identifier: MIT
#
# pylint: disable=invalid-name,missing-function-docstring
"""double-quote-strings-if-needed test cases.
"""
from . import common as C
class TestCase(C.YamlLintTestCase):
"""
double-quote-strings-if-needed test cases.
"""
tcase = "doub... |
import sys
import os
from Algorithmia.errors import AlgorithmException
import Algorithmia
# look in ../ BEFORE trying to import Algorithmia. If you append to the
# you will load the version installed on the computer.
sys.path = ['../'] + sys.path
import unittest
if sys.version_info.major >= 3:
class AlgoDummyT... |
#Report Memory
'''
Reset reason: RTC WDT reset
uPY stack: 19456 bytes
uPY heap: 512256/6240/506016 bytes (in SPIRAM using malloc)
'''
import gc
import micropython
#gc.collect()
micropython.mem_info()
print('-----------------------------')
print('Initial free: {} allocated: {}'.format(gc.mem_free(), gc.me... |
'''
DATASET'S AND DATALOADER'S
AUTHOR - shyamgupta196
PYTHON - 3.8.3
'''
ON HOLD
import torch
from torch.utils.data import DataLoader,Dataset
from torchvision import datasets
from torchvision.io import read_image
from torchvision.transforms import ToTensor, Lambda
import matplotlib.pyplot as plt
from p... |
from __future__ import unicode_literals
import re
def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compi... |
import logging
from pathlib import Path
from typing import Any, Dict, Mapping, Optional, cast
log = logging.getLogger(__name__)
try:
import message_data
except ImportError:
log.warning("message_data is not installed or cannot be imported")
MESSAGE_DATA_PATH: Optional[Path] = None
else: # pragma: no cover... |
# --------------------------------------------------------------------------
# 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 may cause incor... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-30 14:30
from __future__ import unicode_literals
import enum
from django.db import migrations
import enumfields.fields
class TrxType(enum.Enum):
FINALIZED = 0
PENDING = 1
CANCELLATION = 2
class TrxStatus(enum.Enum):
PENDING = 0
FIN... |
# Setup CA Firebase Project, and then create a mapping of the codes to their profile details.
# Ideally we should only need the users thingy
from firebase_admin import firestore
import json
from dateutil.parser import parse
from time import time
import firebase_admin
from firebase_admin import credentials
import pathl... |
#some code
codeChanged = True; |
def test_placeholder():
# Sample test added to make pytest happy :)
pass |
#
# wayne_django_rest copyright © 2020 - all rights reserved
# Created at: 26/10/2020
# By: mauromarini
# License: MIT
# Repository: https://github.com/marinimau/wayne_django_rest
# Credits: @marinimau (https://github.com/marinimau)
#
from django.contrib.auth.models import User
from django.db import models... |
import logging
import sys
from time import sleep
root = logging.getLogger(__name__)
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.DEBUG)
log_format = '%(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(log_format)
handler.setFormatter(f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.