content stringlengths 5 1.05M |
|---|
pessoas = []
dados = []
print('ENTRE DADOS DE TRÊS PESSOAS')
for i in range(3):
dados.append(str(input(f'\nNome {i + 1}...: ')))
dados.append(str(input(f'Idade {i + 1}..: ')))
pessoas.append(dados[:])
print('Dados.....:', dados)
print('Pessoas ..:', pessoas)
dados.clear()
print('\nUsar dados.cle... |
from enum import Enum
class InnovationType(Enum):
new_link = 1
new_node = 2
|
#for Python2.6 compatability.
import unittest2 as unittest
import mock
import logging
import datetime
import timex
from winchester import db, models
logging.basicConfig()
TEST_DATA = [
{'event_type': [
dict(id=1, desc='test.thing.begin'),
dict(id=2, desc='test.thing.end'),
dict(id=3, des... |
from django.urls import path
from layouts.views import BoxedView
from layouts.views import CollapsedSidebarView
from layouts.views import FixedView
from layouts.views import IndexView
from layouts.views import LoginView
from layouts.views import RegisterView
from layouts.views import TopNavigationView
app_name = 'lay... |
#!/usr/bin/env python
import setuptools
import sys
from setuptools.command.install import install
def install_win():
try:
import winreg
except ImportError:
import _winreg as winreg
SZ = winreg.REG_SZ
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\Classes\.ipynb") as k:
... |
#!/usr/bin/env python
import os
import logging
import argparse
import json
from itertools import islice
import numpy as np
try:
import cPickle as pickle
except:
import pickle
import features
MASK = set(['desc', 'meta'])
def read_dataset(filename):
X, y = [], []
points = list(features.filter(featur... |
from abc import ABC, abstractmethod
class State(ABC):
name = None
transitions = []
def __init__(self):
pass
@abstractmethod
def on_start(self, context: dict) -> dict:
pass
def is_final_state(self):
return not len(self.transitions)
def check_transitions(self, *ar... |
import sys
import unittest
from sklearn.preprocessing import LabelEncoder
from keras.utils import to_categorical
sys.path.append('../utils')
from utils import process_config
class TestCycleGANKerasArtAttrs(unittest.TestCase):
def test_encoder(self):
config, _, _ = process_config('../input_params.json')
... |
from urllib.parse import urlparse, parse_qs
import requests as req
import datetime
class MinerWithAuthentication:
def __init__(self, username = None, token = None):
if (username is None and token is None):
self.auth = None
elif(token is not None and username is None):
self.auth = token
else:
self.auth... |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.db import models
from django.conf import settings
from geoposition.fields import GeopositionField
class usersProfiles(models.Model):
username = models.CharField(max_length=100)
age = model... |
n = int(input())
univs = []
acnt = 0
for i in range(n):
ss = input()
univ,team = ss.split()
if univ in univs: continue
univs.append(univ)
print(univ, team)
acnt += 1
if acnt == 12: break
|
#! /usr/bin/python3
# -*- coding: utf-8 -*-
"""This `translator.py` provides the classes `BasicTranslator`, and `Translator`.
These two classes enable the functionality
to initialize a `DimQuant` with a string representation of a dimensional quantity,
e.g. '1 m.s',
instead of the more cumbersome `BaseDimQuant` init
wi... |
from .base import GnuRecipe
from ..version import extension_regex
class LibXkbCommonRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(LibXkbCommonRecipe, self).__init__(*args, **kwargs)
self.sha256 = '09351592312d67b438655f54da5b6785' \
'3026662c4a57e6be4d225f04a9... |
for i in range (0, 10, 1):
print ((" " * (10 - i)) + ("*" * (i * 2 + 1)))
for i in range (10, -1, -1):
print ((" " * (10 - i)) + ("*" * (i * 2 + 1)))
raw_input () |
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Bartosz Kruszczynski
# Copyright (c) 2015 Bartosz Kruszczynski
#
# License: MIT
#
"""This module exports the Reek plugin class."""
from SublimeLinter.lint import RubyLinter
import re
class Reek(RubyLinter):
""... |
from moviepy.editor import VideoFileClip, concatenate_videoclips
from core.video_audio_manager import add_background_audio
from misc import get_random_name
def merge_videos(file_paths):
clip_list = [VideoFileClip(file_path) for file_path in file_paths]
final_clip = concatenate_videoclips(clip_list)
file_... |
"""empty message
Revision ID: fc6ae578b07c
Revises: None
Create Date: 2016-04-02 21:01:59.399396
"""
# revision identifiers, used by Alembic.
revision = 'fc6ae578b07c'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... |
# Generated by Django 2.2.2 on 2019-06-17 20:25
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... |
from numpy import min
from probability.calculations.operators.array_operators.array_operator import \
ArrayOperator
class MinOperator(
ArrayOperator,
object
):
"""
Operator to take the minimum of a list of distributions.
"""
symbol = 'min'
operator = min
pandas_op_name = 'min'
|
import pygame
from .widgets.battery import Battery
from .widgets.clock import Clock
class Taskbar:
def __init__(self, ws, col, w, h):
self.ws = ws
self.col = col
self.w = w
self.h = h
self.clock = Clock(self.ws, self.w / 2 , self.h / 2)
self.battery_icon = Battery(s... |
from .data import train_problems, validation_problems, describe_task_group, train_data_dir, valid_data_dir
from .types import ArcIOPair, ArcProblem
from .consts import ArcColors, colors_rgb
from . import agents
from . import types
from .evaluation import ArcEvaluationResult, evaluate_agent
from .plot import plot_grid
... |
class Node():
def __init__(self, val):
self.val = val
self.right = None
self.left = None
def trim(root, L, R):
if not root:
return None
if root.val > R:
return trim(root.left, L, R)
if root.val < L:
return trim(root. right, L, R)
root.left = trim(ro... |
#!/usr/bin/env python
# Copyright 2022 Simon Lin - simon.lin(at)uwaterloo.ca
#
# License
# This file is part of Juliane Mai's personal code library.
#
# Juliane Mai's personal code library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 3 23:37:21 2021
@author: Rafhael de Oliveira Martins
"""
#%% Importando Bibliotecas
import psycopg2
from datetime import datetime
#%% Desenvolvimento
print("---------------------------------------")
print("\t \t Medidor de pressão \t \t")
print("---------... |
s = input()
t = []
for c in s:
if c != c.lower():
t.append(c.lower())
elif c != c.upper():
t.append(c.upper())
else:
t.append(c)
print(''.join(t))
|
a = float(input('Aqui vai o número 1: '))
b = float(input('Aqui vai o número 2: '))
c = float(input('Aqui vai o número 3: '))
maior = a
if b > a and b > c:
maior = b
if c > a and c > b:
maior = c
menor = a
if b < a and b < c:
menor = b
if c < a and c < b:
menor = c
print(f'O menor é: {menor :.0f}')
... |
import sys,os
import time
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
from mechatts import ttsObject as tts
speak = tts()
#Vague config class, will change asap
def checktrue(a):
if a=="True" or a==True:
return True
return False
class Config():
def __init__(self):
... |
import obd
from obd_gui import (
window,
new_speed,
new_rpm,
new_coolant_temp,
new_engine_load,
new_intake_temp,
new_throttle_pos,
new_timing_adv,
conn_lbl,
)
try:
# Start async connection to OBD adapter
# connection = obd.Async(baudrate=9600)
connection = obd.Async()
... |
# -*- coding: utf-8 -*-
import codecs
import errno
import os
import shutil
import sys
import tempfile
import unittest
from dirq import QueueBase
from dirq.QueueBase import QueueBase as QueueBaseClass
__all__ = ['TestQueueBase', 'TestQueueBaseModuleFunctions']
class TestDirQueue(unittest.TestCase):
def setUp(s... |
def is_polydivisible(s, b):
|
# motors
from joint import *
Box()
p = 100, 120
v = 60,10
arm = Segment(p, v)
PivotJoint(b0, arm.body, p)
p1 = 200, 120
arm = Segment(p1, v)
PivotJoint(b0, arm.body, p1)
SimpleMotor(b0, arm.body, 10)
p2 = 300, 120
arm = Segment(p2, v)
SimpleMotor(b0, arm.body, 10)
App().run() |
import ignite.distributed as idist
from ignite.engine import Engine, Events
from ignite.handlers import TerminateOnNan
from ...datasets import DataloaderCreator
from ...utils import common_functions as c_f
from .. import utils as f_utils
from . import utils as i_g
from .loggers import IgniteEmptyLogger
class Ignite:... |
"""
Sample 2d animation from a set of images
"""
import math
import os.path
import pygame
from pygame.locals import QUIT
import util
class Animation(object):
def __init__(self, screen):
self.screen = screen
directory = "./assets/images/nyan"
files = [
"nyan00.png",
... |
#
# This file is part of pyasn1-modules software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
import sys
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1_modules import pem
from pyasn1_m... |
import os
import unittest
import subprocess
from vmaf.config import VmafConfig
from vmaf.tools.misc import run_process
from vmaf import ExternalProgram
__copyright__ = "Copyright 2016-2019, Netflix, Inc."
__license__ = "Apache, Version 2.0"
class RunProcessTest(unittest.TestCase):
def test_run_process(self):
... |
import requests
from datetime import datetime
api_key = '87d845b0b6cf29baa1a73cc34b067a95'
location = input("Enter the city name: ")
complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+location+"&appid="+api_key
api_link = requests.get(complete_api_link)
api_data = api_link.json()
#cre... |
#!/usr/bin/env python3
import tensorflow as tf
from utils import tf_util
from utils.pointnet_util import pointnet_sa_module, pointnet_fp_module
def placeholder_inputs(batch_size, num_point):
pointclouds_pl = tf.placeholder(tf.float32, shape=(None, num_point, 3), name='pointclouds')
labels_pl = tf.placehold... |
import sys
sys.path.append('../')
from log.log import Log
from typing import *
log = Log.get_instance()
class Servo():
def __init__(self) -> None:
pass
# sets the servo to its neutral value
def set_neutral(self) -> None:
pass
def set_value(self, value: int) -> None:
pass
c... |
"""Jikan/AioJikan Exceptions
====================================
exceptions.py contains exceptions used in Jikan and AioJikan.
"""
from typing import Optional, Mapping, Any, Union
class JikanException(Exception):
"""Base exception class for JikanPy."""
class APIException(JikanException):
"""Exception due t... |
def is_leap(year):
# leap = False
# Write your logic here
if (year >= 1900 and year <= 1000000):
if (year%4 == 0) and (year%100 != 0) or (year%400 == 0):
return True
else:
return False
else:
print "Enter the Valid Year Between (1900-10^5)"
ret... |
# -*- coding: utf-8 -
#
# This file is part of restkit released under the MIT license.
# See the NOTICE for more information.
import base64
import errno
import logging
import os
import time
import socket
import ssl
import traceback
import types
import urlparse
try:
from http_parser.http import (
HttpSt... |
import time
import threading
class BlockingInputHelperThread(threading.Thread):
""" A helper thread inside which the blocking function will be run.
"""
def __init__(self, blocking_function):
self.blocking_function = blocking_function
threading.Thread.__init__(self)
self.exception... |
from .vanilla_gan import GAN
from .dcgan import DCGAN
from .wgan import WGAN
from .wgangp import WGANGP
from .sngan import SNGAN
from .sagan import SAGAN |
"""Message model tests."""
# run tests from terminal with:
#
# python -m unittest test_user_model.py
import os
from app import app
from unittest import TestCase
from models import db, User, Message, FollowersFollowee
os.environ['DATABASE_URL'] = "postgresql:///warbler-test"
db.create_all()
class MessageModel... |
from django.shortcuts import render
# Create your views here.
from errors.forms import ErrorForm
def error(request, error_dict=None): # TODO can we make it a POST redirect?
if error_dict is None:
error_dict = {}
error_form = ErrorForm(error_dict)
error_object = {}
if error_form.is_valid():
... |
class GUI:
"""Gets file parameters and AI parameters and new/retain/display settings from User and returns them to Main"""
def __init__(self):
self.ai_param = {'alpha':None}
self.settings = {'mode':None}
self.file_param = {'name':None}
def get_ai_param(self):
"""get AI param... |
def tokened(inp):
inp = inp.lower()
inpToken = inp.split()
return inpToken
def operatorChange(inp):
index = 0
toke = tokened(inp)
for i in toke:
if i == "plus":
toke[index] = '+'
index += 1
elif i == "power":
toke[index] = '**'
in... |
# -*- coding: utf-8 -*-
"""
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Thermodynamics-based Flux Analysis
.. moduleauthor:: pyTFA team
Tests the I/O functionalities of pytfa
"""
import os
from settings import cobra_model, tmodel
#############
# I/O #
#############
def test_read_write_mat()... |
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
|
''' Schemdraw base Element class '''
from collections import ChainMap
import numpy as np
from ..backends.mpl import Figure
from ..adddocs import adddocs
from ..segments import SegmentText, BBox
from ..transform import Transform, mirror_point, flip_point
gap = [np.nan, np.nan] # Put a gap in a path
def angle(a, b)... |
import os
import pickle
import numpy as np
def load_cifar10():
path = 'cifar-10-batches-py'
if not os.path.exists(path):
os.system("wget {}".format(path))
os.system("tar xvf {}".format(path))
load_cifar10()
|
import keyboard
import time
from user import Input,Print,press
from game import gen_rock,rock_gen
from game import move_lasers,move_rocks
from bordm import con,insert_rock,insert_ship
from moves import move_right,move_left,move_up,move_down
height = 20
width = 40
brd = []
ship = [(width-1)/2,(height-2)] #sh... |
##############################################################################
# Copyright (c) 2017 NEC Corporation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is avail... |
import json
from app import app
def test_post_to_tasks_fail_if_no_title_given():
req, res = app.test_client.post('/tasks', data='{}')
assert res.status == 400
def test_post_to_tasks_succeds_if_title_given():
req, res = app.test_client.post('/tasks', data='{"title":"Hola"}')
assert res.status == 201... |
"""
Helper functions and classes to do various thing in meroshare.
See `nepse_tools.platforms.meroshare.api` for all supported features.
"""
|
# -*- coding: utf-8 -*-
import os
import sys
import json
import jwt
import hmac
import requests
import responder
from time import time
import statsd as Statsd
from hashlib import sha1
from base64 import b64decode
from urllib.parse import urlencode
api = responder.API(debug=True)
class env:
user_agent = os.gete... |
import os
import cv2
import numpy as np
from PIL import Image
from .abstract_dataset import ReadingDataset
from transforms import CLAHE
class CarvanaDataset(ReadingDataset):
def __init__(self, root, rows, cols, channels=3, image_folder_name='train', apply_clahe=False):
super(CarvanaDataset, self).__init_... |
'''
Script to migrate all current users from role=user to role=contributor
'''
import os, sys, cog
path = os.path.dirname(cog.__file__)
sys.path.append( path )
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django import setup as django_setup
django_setup()
from django.contrib.auth.models import User, Permissi... |
import unittest
import dtk.metrics.image as img
import numpy as np
class Metrics(unittest.TestCase):
def test_iou(self):
a = np.zeros((100, 100))
b = 2 * np.ones((100, 100))
a[25:75, 25:75] = 2
ious = img.iou(a, b)
self.assertEqual(ious[2], 0.25, "The iou for the class sho... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os, sys, time, random, argparse
from .share_args import add_shared_args
def obtain_sbr_args_v2():
parser = argpa... |
import numpy as np
import copy
from naslib.predictors.predictor import Predictor
from naslib.predictors.feedforward import FeedforwardPredictor
class Ensemble(Predictor):
def __init__(self,
encoding_type=None,
num_ensemble=3,
predictor_type='feedforward',
... |
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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
#
# htt... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import nu... |
# ---
# jupyter:
# jupytext:
# cell_metadata_json: true
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
#... |
"""
1. Clarification
2. Possible solutions
- Horizontal scanning
- Vertical scanning
- Divide and Conquer
- Binary search
3. Coding
4. Tests
"""
# T=O(m*n), S=O(1), m=avg(map(len, strs)), n=len(strs)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return... |
def merge_sort(li):
# recursively split the lists
if len(li) <= 1:
return li
middle = len(li) / 2
left = li[:middle]
right = li[middle:]
return merge(merge_sort(left), merge_sort(right))
def merge(left, right):
# Merge the two lists back together
result = []
while left or r... |
#!/opt/djenv/bin/python
import json
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine(
'sqlite:////var/ftp/nsd2018/nsd1804/python/ansible_project/myansible/db.sqlite3',
... |
import maya.cmds as mc
import System.blueprint as bp
reload(bp)
import System.utils as utils
import os
CLASS_NAME = 'Finger'
TITLE = 'Finger'
DESCRIPTION = 'Creates 5 joints, defining a finger. Ideal use: finger'
ICON = os.environ['RIGGING_TOOL_ROOT'] + '/Icons/_finger.xpm'
class Finger(bp.Blueprint):
... |
from django.test import TestCase
from django.urls import reverse
from logs.models import Topic, Entry
from django.contrib.auth import get_user_model
class TestTopicModel(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username = 'testname',
email = 't... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#!/usr/bin/env python3
# args 1, 2, 3 are used for exit code, stdout, stderr.
import sys
print(sys.argv[2], file=sys.stdout)
print(sys.argv[3], file=sys.stderr)
sys.exit(int(sys.argv[1]))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class DoubleColonTranslations(PyxformTestCase):
def test_langs(self):
model_contains = """<bind nodeset="/translations/n1""" + \
"""" readonly="true()" type="string"/>"""
... |
REQUEST_BASE = "http://{ip}:{port}{url}"
RESPONSE_OK = 200
RESPONSE_OK_WITH_NO_CONTENT = 204
RESPONSE_GET_PARTIAL_OK = 206
RESPONSE_INVALID_INPUT = 400
RESPONSE_ALREADY_EXIST = 422
RESPONSE_INTERNAL_ERROR = 500
INDEX_ALREADY_EXIST = {
"error": "index already exist"
}
INDEX_NOT_EXIST = {
"error": "index not ex... |
from django.conf.urls import url
from django.views.generic import TemplateView
from wellbeing.views import ResultsView
urlpatterns = [
url(
r'^$',
TemplateView.as_view(template_name='wellbeing/home.html'),
name='fwb_home'
),
url(
r'^results/$', ResultsView.as_view(), name=... |
import xmlrpclib
import time
# Create an object to represent our server.
server_url = 'http://127.0.0.1:20738/RPC2'
server = xmlrpclib.Server(server_url)
G = server.ubigraph
G.clear()
# Set default edge style
G.set_edge_style_attribute(0, "oriented", "true")
G.set_edge_style_attribute(0, "color", "#C5892F")
# Defau... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from thecut.authorship.settings import AUTH_USER_MODEL
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.contenttypes.models import C... |
from __future__ import print_function
#
# Conducts bootstrap sampling on a u_kln Matrix using MBAR
#
# Copyright Michael R. Shirts, University of Virginia, 2014
#
import numpy as np # numerical array library
import pymbar # multistate Bennett acceptance ratio
from pymbar import timeseries # timeseries analysis
from o... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask import abort, redirect, url_for
from functools import wraps
from itsdangerous import URLSafeTimedSerializer
from flask.ext.login import LoginManager, current_user
from .. import app
ts = URLSafeTimedSerializer(app.config["SECRET_K... |
import numpy as np
import matplotlib.pyplot as plt
from myPSOVS import myPSOVS
# Setup
# Time
dt = 0.01
startTime = 0
endTime = 100
simulationTime = np.linspace(
startTime, endTime, 1 + int((endTime-startTime)/dt))
# Output
outputSetpoint = 30 # degree (angles), meter/second (velocity)
optimizeParameter = "psi"... |
#!/usr/bin/env python3
from collections import Counter
def read_digits():
return map(int, input().strip())
def index_of_nonzero(items):
return next(i for i, x in enumerate(items) if x != 0)
def with_leading_nonzero(items):
index = index_of_nonzero(items)
items.insert(0, items.pop(index))
return ... |
import asyncio
from concurrent.futures.thread import ThreadPoolExecutor
from typing import Callable
_executor = ThreadPoolExecutor()
async def cpu_bound_task(func: Callable, *args):
"""
Execute async function in a separate thread, without blocking the main event
loop.
:param func: async function tha... |
import bpy
class WreckfestWrapperNode(bpy.types.ShaderNodeCustomGroup):
"""Add wreckfest node"""
bl_name = "wreckfest_wrapper_node"
bl_label = "Wreckfest Wrapper"
# Manage the node sockets
def __nodeinterface_setup__(self):
# Clear inputs
self.node_tree.inputs.clear()
# F... |
from re import compile, fullmatch
import sys
from typing import Dict, List, Optional, Tuple
from icontract import require, ensure
_REQUIRED_KEYS = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}
@ensure(lambda: True)
def blank_line_split(text: str) -> List[str]:
# NOTE: I tried to do a lookahead for the 2nd n... |
import unittest
import logging
import asyncio
from goldstone.lib.core import ServerBase, ChangeHandler, NoOp
from goldstone.lib.connector.sysrepo import Connector
from goldstone.lib.errors import *
class Handler(ChangeHandler):
def apply(self, user):
self.server.handled_changes.append(self.change)
clas... |
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
count_r={}
for c in ransomNote:
if c not in count_r:
count_r[c]=1
else:
count_r[c]+=1
print(count_r)
for cr in magazine:
if cr n... |
"""
Author
-----------
Bongani Detilisi
Description
-----------
This python provides backend support to the software's GUI
components
Classes
--------
None.
Attributes
----------
None.
Methods
----------
None.
"""
#Dependencies
f... |
import logging
from datetime import datetime
import os
from collections import OrderedDict
import tempfile
import subprocess
import shutil
import hashlib
import base64
import email
import email.utils
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text i... |
import sys, os
from nlputils import *
from hw2utils import *
params = {} # parameters dictionary
params['debug_level'] = 0 # no debugging by default
params['progname'] = "runXXXX" # temporary
params['run_mode'] = 'test'
params['dump_text'] = False
params['classifier'] = 'weka.classifiers.trees.J48'
### function... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-02-06 09:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
'''
Mierzenie wydajnosci skryptu
'''
import time
def suma_1(a):
suma = 0
for liczba in range(1, a + 1):
suma = suma + liczba
return suma
def suma_2(a):
return (1 + a) / 2 * a
def suma_3(a):
return sum([liczba for liczba in range(1, a + 1)])
def suma_4(a):
return sum((liczba for... |
# Desenvolva um algoritmo em Python que exibia os números de 1 a 5
for num in range(0,5,1):
print(num +1) |
import os
import random
from enum import Enum
from .dictionary import Dictionary
from .wordentry import WordEntry, DefinitionEntry
class Category(Enum):
"""Enum class representing the categories for HSK3.0.
Attributes:
title: The string name of the category.
index: The integer representing t... |
from django.conf import settings
from django.db import transaction
from django.http import Http404
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.generic import FormView
from django.views.generic import View
from django.views.generic import UpdateView
from django.t... |
from .oauth import module as oauth
from .imports import module as imports
|
from .settings import secret, public, db_name
|
from PySide2.QtGui import QKeySequence
from PySide2.QtCore import Qt
from .menu import Menu, MenuEntry, MenuSeparator
class ViewMenu(Menu):
def __init__(self, main_window):
super(ViewMenu, self).__init__("&View", parent=main_window)
self.entries.extend([
MenuEntry('Next Tab', main_wi... |
import sys
sys.path.append("../../")
def press(btn):
print(btn)
if btn == "Cols":
print(app.colourBox())
if btn == "dir":
print(app.directoryBox())
if btn == "text":
print(app.textBox("a", "b"))
if btn == "save":
print(app.saveBox())
from appJar import gui
app=gui("... |
#!/usr/bin/python
import sys
import dns.resolver
from ipwhois import IPWhois
import pprint
if len(sys.argv) < 2:
print(sys.argv[0] + ": <ip_addr>")
sys.exit(1)
try:
rev_name = dns.reversename.from_address(sys.argv[1])
reversed_dns = str(dns.resolver.query(rev_name, "PTR")[0])
print(reversed_dns)
... |
def arr2bin(arr):
total = 0
for a in arr:
if not type(a) == int:
return False
total += a
return '{:b}'.format(total)
|
import pathlib
import os
import sys
check_name = "AM_I_IN_A_DOCKER"
if os.getenv(check_name, None) is None:
import dockrice.argparse as argparse
parser_kwargs = {
"script_name": __file__,
"container_name": "python",
"docker_kwargs": {"environment": {check_name: ""}},
}
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.