text stringlengths 8 6.05M |
|---|
#prime number
num=int(input("enter number:"))
for i in range(2,num//2+1):
if num%i==0:
print("Not prime")
break
else:
print("Prime")
|
#!/usr/bin/env python
import os
import sys
import Queue
import socket
import threading
import dnslib
from time import sleep
from abstractbackend import abstract_backend
QRTYPE = {
'A': 1, # a host address
'NS': 2, # an authoritative name server
'MD': ... |
from tkinter import Toplevel, Text, Button, Label, N, S, E, W
def confirm_pb (menu, timer):
if menu._layer1: # kind of a redundant check bc if menu is not None, then layer1 needs to be false anyway, but whatever
menu._root.bell()
return
menu._layer1 = True
##########
# other TODO: can ... |
#!/bin/env python2
#import multiprocessing
bind = "127.0.0.1:8000"
#workers = multiprocessing.cpu_count() * 2 + 1
workers = 30
worker_class ='egg:gunicorn#gevent'
graceful_timeout = 3000
user = "admin"
group = "admin"
daemon = True
timeout = 30
keepalive = 5
limit_request_line = 4094
max_requests = 102400
worker_conne... |
import io
import os
pid = os.fork()
try:
f = io.open('my_data', 'x')
except IOError:
print("Failed to create file; I'm the slave")
f = io.open('my_data', 'r')
while True:
s = f.read()
if s:
print("Received", s)
break
else:
print("Created file; I'm the master!... |
from django.contrib import messages
from django.db.models import Q
from django.shortcuts import get_object_or_404, render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import FormMixin
from books.models import Book, Category
from cart.forms import CartAddForm
class BookListView... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 11:34:57 2014
@author: atproofer - mbocamazo
"""
# you do not have to use these particular modules, but they may help
from random import randint
from math import * ## SS: I added this line - don't forget to add the math library dependency!
import Image
#need... |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.http import FileResponse
import sys
sys.path.append('./DB')
from login import *
from profile import *
def audio(request):
audio = open('./Sound/test.wav','rb')
return HttpResponse(audi... |
"""algumas funções possíveis com strings"""
A = "lucas "
B = "LIMA"
############################
""" concatenar (+) strings """
juntar = A + B
print(juntar, "\n")
""" len() -> numero de instens no (objeto) """
tamanho = len(R)
print(tamanho, "\n")
""" exebir posição de um caracter da string """
#funciona tipo como u... |
from onegov.ballot import ComplexVote
from onegov.ballot import Election
from onegov.ballot import ElectionCompound
from onegov.ballot import ElectionCompoundPart
from onegov.ballot import ProporzElection
from onegov.ballot import Vote
from onegov.core.utils import Bunch
from onegov.election_day.layouts.detail import D... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 30 21:17:26 2021
@author: arthur
"""
#解題關鍵 Backtracking
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
stack = [[]]
for i in nums:
new_stack = []
... |
from psycopg2 import Error, connect
def create_connection():
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
with open('connection_string', 'rt') as f:
connection_... |
from cgi import FieldStorage
from io import BytesIO
from wtforms import EmailField, TextAreaField
from onegov.agency import _
from onegov.agency.collections import ExtendedAgencyCollection
from onegov.agency.models import ExtendedAgency
from onegov.agency.utils import handle_empty_p_tags
from onegov.core.security imp... |
import os
from typing import Tuple
import numpy as np
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers ... |
# -*- coding: utf-8 -*-
#rnn from scratch by Yijun D.
import numpy as np
data = open('kafka.txt','r').read()
chars = list(set(data))
data_size,vocab_size = len(data), len(chars)
print ('data has %d chars, %d unique' % (data_size,vocab_size))
|
def add(p, q, r):
return p + q + r
def add1(q, p, r):
return p - q + r
# forwarding function
def add2(p, q, r):
return add1(p,q,r)
d1 = [1000, 20, 10]
s = add(*d1)
print(s)
|
def main():
x = float(input("Coordenada x: "))
y = float(input("Coordenada y: "))
if 1 <= y <= 2 and -3 <= x <= 3:
print("dentro")
elif (4 <= y <= 5 or 6 <= x <= 7) and ( -4 <= x <= -3 or -2 <= x <= -1 or 1 <= x <= 2 or 3 <= x <= 4):
print("dentro")
e... |
#import sys
#input = sys.stdin.readline
def main():
n, m = map( int, input().split())
n %= 12
m /= 60
n += m
n /= 12
n *= 360
m *= 360
ans = abs(n-m)
print(min(ans, 360-ans))
if __name__ == '__main__':
main()
|
def get_user_ip(request):
if request.headers.get('X-Forwarded-For'):
return request.headers['X-Forwarded-For']
elif request.headers.get('X-Real-IP'):
return request.headers.get('X-Real-IP')
else:
return request.remote_addr
|
class Copy:
def __init__(self, *args):
self.src = args[:-1]
self.dst = args[-1]
def init_build(self, script):
count = self.dst.count(':')
self.mode = None
self.owner = None
if count == 2:
self.dst, self.mode, self.owner = self.dst.split(':')
e... |
import cv2
from darkflow.net.build import TFNet
import numpy as np
import time
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
options = {
'model':'C:/Users/LENOVO/Anaconda3/darkflow-master/cfg/yolo.cfg',
... |
# -*-coding:utf-8-*-
# AUTHOR:tyltr
# TIME :2018/11/27
import time
def get_timestamp():
"""
时间戳,基于毫秒
:return:
"""
_time = int(time.time()*1000)
return _time
if __name__ == '__main__':
print(get_timestamp())
|
import sys,os,argparse,time
import copy
import numpy as np
import importlib
import torch
import easydict
import utils
sys.stdout.flush()
tstart=time.time()
tstart = time.time()
args = easydict.EasyDict({
"seed": 0,
# "experiment": 'auto_ML',
# "experiment": 'split_MNIST',
"experiment": 'cifar',
... |
#import serial
import urllib2
import json
'''
# Serial port connection with baud rate of 9600
try:
ser = serial.Serial(/dev/ttyACM0,9600,timeout=1)
except:
ser = serial.Serial(/dev/ttyACM1,9600,timeout=1)
'''
pulses = 0
liters = 581984
APIKEY="YrrR0K4MtS4gdEjXXGfRaNSnsWjCh" # Replace with your APIKEY
DEVICE = ... |
# This solution works for all scenarios
# 4 minutes first time
# currently takes 2 minutes to run
#!python
import time
from pprint import pprint
from hashtable import HashTable
# import glob
import os
def load_data():
"""
Returns a list of phone prefixes and prices from a file.
"""
# all_route_costs =... |
import datetime
import os
import random
import sys
import xbmc
import xbmcaddon
import xbmcplugin
import api
import constants
import utils
from exceptions import ApiError
ADDON = xbmcaddon.Addon()
APPID = xbmcaddon.Addon().getAddonInfo("id")
NAME = xbmcaddon.Addon().getAddonInfo("name")
VERSION = xbmcaddon.Addon().g... |
import matplotlib.pyplot as plot
def plot_graph(file, img_name):
precision_values = {}
recall_values = {}
query_values = {}
with open(file) as content:
data = content.read().splitlines()
data = [s.split() for s in data]
# print data
i = 0
for pid in data:
preci... |
"""Example on how to read mask version and properties from a KNX actor."""
import asyncio
import sys
from typing import List
from xknx import XKNX
from xknx.core import PayloadReader
from xknx.telegram import IndividualAddress
from xknx.telegram.apci import (
DeviceDescriptorRead,
DeviceDescriptorResponse,
... |
import pandas as pd
def add(data_string):
data_list = [k.split(",") for k in data_string.split("\n") if k != ""]
data_header, data_values = data_list[0], [list(map(float, k)) for k in data_list[1:]]
data = pd.DataFrame(data_values, columns=data_header)
data["x+y"] = data["x"]+data["y"]
# return dat... |
#created by ahmad on 02-10-2019
def fun():
steps =int(input("How many steps do you want? :"))
print()
k0="__"
k1=" |"
for i in range(steps):
print(k0," \--»",i+1)
print(k1,end='')
k1=" "+k1
print()
print('-----------------------------------------')
print()
c="y"
while True:
if c=="y" or c=="Y":
fu... |
# Generated by Django 2.2.3 on 2019-09-10 18:16
import datetime
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('DatosEmpresa', '0002_auto_20190910_1316'),
('estado_paros_deta3', '0001... |
import logging
log = logging.getLogger('onegov.gis') # noqa
log.addHandler(logging.NullHandler()) # noqa
from onegov.gis.forms import CoordinatesField
from onegov.gis.integration import MapboxApp
from onegov.gis.models import Coordinates, CoordinatesMixin
__all__ = ('Coordinates', 'CoordinatesMixin', 'CoordinatesFi... |
# -*- coding: UTF-8 -*-
import os
import Module
from MFile import MFile
def list_dir(path):
files = os.listdir(path)
list_libs = ['pro/AutoNews/Rexxar', 'pro/AutoNews/shauto-lintcheck', 'pro/AutoNews/shauto-comment']
list_modules = []
for file in files:
sub_path = path + "/" + file
if... |
#!/usr/bin/env python
# encoding: utf-8
"""
低レベルファイルIOを使って、標準入力から標準出力にファイルをコピーする
"""
import sys
import os
STDIN_FILENO = 0
STDOUT_FILENO = 1
BUFSIZE = 8192
while True:
try:
buf = os.read(STDIN_FILENO, BUFSIZE)
except Exception, e:
sys.exit("read error")
if not buf:
break
... |
# # 셀레늄 모듈 임포트
# from selenium import webdriver
# import time
# # 크롬 물리드라이버 가동 명령
# driver = webdriver.Chrome("C:\chrome/chromedriver.exe")
# # 물리 드라이버로 사이트 이동 명령
# driver.get("https://www.naver.com")
# time.sleep(1)
# # xpath를 이용하여 자동으로 클릭 제어하기
# login_btn = driver.find_element_by_xpath('//*[@id="account"]/a')
# #... |
import os
import sys
import datetime
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from utils import functions as c_functions
import utils.anchors as l_anchors
gpus = tf.config.experimental.list_physical_devices("GPU")
if gpus:
for gpu in gpus:
tf.config.experimental.set_mem... |
# Sequencia de Fibonacci
n = int(input('Digite quantos termos da sequencia de Fibonacci vc quer ver (digite um número maior que 1): '))
cont = 2
t1 = 0
t2 = 1
print('0 → 1 → ', end='')
while cont < n:
t3 = t1 + t2
print('{}'.format(t3), end=' → ')
t1 = t2
t2 = t3
cont += 1
print('Fim')
|
import os
import re
import sys
import time
import json
import logging
import traceback
import emoji
import random
import datetime
from arango import ArangoClient
from dotenv import load_dotenv
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
def update_guidance(guidance_data, db):
for entry in guidanc... |
# Generated by Django 3.0.7 on 2020-11-09 14:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cl_table', '0080_poshaud_cart_id'),
]
operations = [
migrations.AlterField(
model_name='depositaccount',
name='type'... |
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
from torchvision import transforms, models
# Get "features" from VGG19 ("classifier" portion isn't needed)
vgg = models.vgg19(pretrained=True).features
# Freeze all VGG params since we're onl optimizing ... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import os
import random
import numpy as np
from config import PROJECT_FOLDER
import causaldag as cd
# === FUNCTIONS DEFINING THE DIRECTORY STRUCTURE
# /data
# /nnodes=5,nlatent=3,exp_nbrs=2,ngraphs=100
# /graph0
# /... |
from django.contrib import admin
from django.urls import path
from .views import *
from .water_usage import *
from .friends import *
urlpatterns = [
path('', login_view),
path('login/', login_view, name="login"),
path('logout/', logout_view, name="logout"),
path('register/', register_view, name="regist... |
from django.urls import path
from . import views
app_name = "blog_app"
# Contails all urls for the blog app
urlpatterns = [
path('write/', views.CreateBlog.as_view(), name="write"),
path('blog_list/', views.BlogList.as_view(), name="blog_list"),
path('blog_details/<slug>', views.blog_details, n... |
from typing import Dict, Union, Tuple, Iterable
from pathlib import Path, WindowsPath
from os import sep, utime
import time
import logging
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import font as tkfont
import toml
import attr
from attr.validators import instance_of
from... |
# coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://github.com/")
# 获取cookie信息
cookie = driver.get_cookies()
print cookie
driver.add_cookie({'name':'key-aaaaaa','value':'value-bbbbbb'})
for cookie in driver.get_cookies():
print "%s --> %s" % (cookie['name'],c... |
from binary_search_tree import BST
def main():
pass
b = BST()
b.insert(12)
b.insert(9)
b.insert(13)
b.preorder()
if __name__ == '__main__':
main()
|
from __future__ import unicode_literals
from django.apps import AppConfig
class WvpnConfig(AppConfig):
name = 'wvpn'
|
""" Runs continuous prediction"""
import ContiniousPrediction as cp
if __name__ == "__main__":
contpred = cp.ContiniousPrediction()
contpred.on_folder() |
import tkinter as tk
from tkinter import ttk
from tkinter.font import BOLD
from tkinter import scrolledtext
from tkinter.ttk import Style
import pandas as pd
from sys import platform as _platform
def saveinfo():
valor1 = nameEntry.get()
valor2 = mobileEntry.get()
valor3 = emailEntry.get()
valor4... |
from django.urls import path
from . import views
app_name = 'staff'
urlpatterns = [
path('', views.LoginView, name='login'), #localhost:8000
path('register', views.RegisterView.as_view(), name='register'), #localhost:8000/register
path('users', views.ViewUsers.as_view(), name='users'), #localhost:8000/r... |
import ex_1
import ex_2
# проверка работы функций первого модуля
ex_1.create_dir()
ex_1.remove_dir()
# проверка работы функции второго модуля
print(ex_2.choise_list(ex_2.create_list())) |
name = []
password = []
def register():
name_of_user = input('Enter your NEW name : ')
if name_of_user in name:
print('Alredy exist plz try other username')
for i in range(500):
name_of_user = input('Enter your NEW name : ')
if name_of_user not in name:
... |
import csv
class IntCodeProgram:
class Instruction:
def __init__(self, instruction):
self.opcode = int(instruction[3:])
self.mode1 = int(instruction[2])
self.mode2 = int(instruction[1])
self.mode3 = int(instruction[0])
def __init__(self, input_string, s... |
# Generated by Django 2.2.3 on 2019-11-07 18:10
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('main', '0039_auto_20191108_0010'),
]
operations = [
migrations.CreateModel(
name='Wishlist',
fie... |
import cv2
import numpy as np
from datetime import datetime
cap = cv2.VideoCapture(0)
backgroundSubtracter = cv2.createBackgroundSubtractorMOG2()
kernel = np.ones( (25,25),np.float32 ) / 625
font = cv2.FONT_HERSHEY_SIMPLEX
while(1):
# Take each frame
_, frame = cap.read()
grayFrame = cv2.cvtColor(frame, ... |
# -*- coding: utf-8 -
import random
def read_polarity():
lines = []
for line in open('rt-polarity.pos', 'r'):
lines.append("+1 " + line)
for line in open('rt-polarity.neg', 'r'):
lines.append("-1 " + line)
random.shuffle(lines)
return lines
def write_sentiment(lines):
f = open('... |
from . import render_all
render_all()
|
# Generated by Django 2.2.2 on 2019-08-05 06:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('filemaster', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='docfile',
name='content',
... |
import simplejson, builder, pprint, os
f = open("suite.txt")
data_structure = simplejson.loads("\n".join(f.readlines()))
f.close()
f = open("results.txt")
bug = simplejson.loads("\n".join(f.readlines()))["bugs"][0]
f.close()
suite = builder.build(data_structure)
suite.evaluate(bug, True)
print suite
#print suite
#... |
import json
import os, errno
from xml.dom import minidom
from bs4 import BeautifulSoup
import json
import base64
import numpy as np
import cv2
from PIL import Image
import random
import argparse
import os.path as osp
import sys
import io
import PIL.Image
from augmentor import Augmentor
from config import config
import ... |
print("testchild)
|
'''
Utility to updated ACDD global attributes in NetCDF file using metadata sourced from GeoNetwork
Created on Apr 7, 2016
@author: Alex Ip, Geoscience Australia
'''
import sys
import subprocess
import re
import os
import netCDF4
from geophys2netcdf import ERS2NetCDF
def main():
assert len(
sys.argv) >= ... |
# -*- coding: utf-8 -*-
#========================================================================#
# CGLOPS LSWT L3U processing
#------------------------------------------------------------------------#
# Run from command line as:
# python2.7 run_lswt_l3u.py --rerun no --run_l3cdaily no &
#-----------------------------... |
"""Backend for a proteomics database."""
from flask import Flask, jsonify, make_response, render_template
from ctesi.ldap import LDAPUserDatastore, LDAPLoginForm
from http import HTTPStatus
from redis import StrictRedis
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security
from flask_migrate impor... |
a,b=input().split()
c=[]
c=input().split()
e=0
for i in range(1,int(a)+1):
if(int(c[i-1])==int(b)):
e+=1
if(e>0):
print("yes")
else:
print("no")
|
import sys
import os.path as op
import backslant
from flask import Flask, render_template
sys.meta_path.insert(0, backslant.PymlFinder(op.dirname(__file__), hook="bsviews"))
from bsviews.templates import index
app = Flask(__name__)
app.debug = True
@app.route('/')
def hello_world():
s = ''.join(index.render(tit... |
"""
The MIT License (MIT)
Copyright (c) 2017 Marvin Teichmann
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import scipy as scp
import warnings
import deepdish as dd
import logging
from tables.exceptions imp... |
bl_info = {
'name':'SaveIncOperator',
'category':'User',
'author':'miguel'
}
import bpy
import string
class SaveIncOperator(bpy.types.Operator):
bl_idname = "object.save_incremental"
bl_label = "Save scene incrementally"
@classmethod
def poll(cls, context):... |
#Ejercicio 04
def find_needle(needle, haystack):
posicion_needle = 0
posicion_haystack = 0
while posicion_haystack<len(haystack):
if needle[posicion_needle] == haystack[posicion_haystack]:
needle_encontrado = True
def encontrar(cadena, subcadena):
subcadena in cadena
encontrar("Tikto... |
from typing import Generator
import numpy as np
from keras.callbacks import Callback
from keras.utils import GeneratorEnqueuer
from sklearn.metrics import precision_score, roc_auc_score
# TODO: Add extra metrics to history so that they are saved in the file
class PrecisionCallback(Callback):
def on_train_begin(s... |
"""
Usage: python dealer_socket_functions.py
This script is used to intake dealerSocket data in csv format and save it to a simple json format after differential data is merged with the full data set provided via ftp in the morning.
The script expects there to be a "../data/3213_ctc_activities_update.csv" file contain... |
import os
import requests
import numpy as np
import json
import pandas as pd
import glob
import subprocess
import math
from pathlib import Path
from hashlib import md5
import shutil
PHOTO_FOLDER = "./photos/"
# Adapted directly from Andrew Wheeler:
# https://andrewpwheeler.wordpress.com/2015/12/28/using-python-to-gr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.RemoveField(
... |
#ex002.py:使用readline()读文件
f=open("story.txt")
while True:
line = f.readline()
if line:
print(line)
else:
break
f.close
|
class FileFormatException(Exception):
"""
An exception thrown when workflow file has incorrect format.
"""
pass
|
__author__ = 'leah'
from data_import_tools import import_arcadia_archived_data
from matplotlib import pyplot as plt
detector_dict, detector_list = import_arcadia_archived_data()
huntington_baldwin = detector_dict[3092]
for det in huntington_baldwin:
plt.figure()
df = det.data
# df.volume.plot()
plt.plo... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
##########################################################################################
# si_2mode.py
#
# scipy implementation of two mode SI shapers, both positive and Unity Magnitude (UM)
#
# NOTE: UM case is still *very* sensitive to initial guess. Optimization will... |
import warnings
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def Visualize_4DTensor(tensor, channels, threshold=1E-6, savefile="Visualize_4DTensor.png"):
Channel_Titles = ["Energy Grid","H","O", "N", "C", "P", "Cu","Co","Ag","Zn","Cd", "Fe"]
if (len(tensor.shape) != 4... |
### RUN THIS TO MAKE ALL USED DIRECTORIES FOR PROGRAM ###
import os
directories = [
'ColorMaps',
'DifferenceMaps',
'ImageSets',
'InputImages',
'Photomosaics'
]
for d in directories:
try:
os.mkdir(d)
except:
print "Failed to create directory ... |
# sample_two.py
import sys
import os
import platform
import wx
# class My_Printout
# class My_Frame
# class My_App
#-------------------------------------------------------------------------------
if os.name == "posix":
print("\nPlatform : UNIX - Linux")
elif os.name in ['nt', 'dos', 'ce']:
print("\nPlatform... |
#!/usr/bin/python
'''
Authors : Goerges, Wahn
Description : Methods to predict the secondary structure based on RNA
sequences
Requirements: * http://www.tbi.univie.ac.at/RNA/
- Download and extract source code package
- Navigate into the package with terminal
... |
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
import re
import time
import os
# main
from method import *
from PreProcess import NormalEstimate
from ransac import RANSAC
from Projection import Plane2DProjection, Plane3DProjection
# zenrin
import figure2d as F
#from IoUtest import CalcIoU, C... |
"""
2. Написать программу, которая запрашивает у пользователя ввод числа.
На введенное число она отвечает сообщением, целое оно или дробное.
Если дробное — необходимо далее выполнить сравнение чисел до и после запятой.
Если они совпадают, программа должна возвращать значение True, иначе False.
"""
def check_number(st... |
import os
import sys
from .communication import CommunicationManager, ProcessDiedException
class FileNoComs(CommunicationManager):
"""
IPC via fileno i.e. pipes.
"""
def __init__(self, is_child, read_fileno=-1, write_fileno=-1):
super().__init__(is_child)
if read_fileno == -1:
read_fileno = sys.stdin.f... |
"Auto-complete selection widgets using Django and jQuery UI."
__version__ = '0.6.2'
|
# Generated by Django 2.1.7 on 2019-04-01 01:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0010_prof_suffix'),
]
operations = [
migrations.AddField(
model_name='prof',
name='middle_initial',
... |
import pandas as pd
import json
import sys
from casos import casos_positivos, casos_fallecidos
poblacion_pasco = 270575
positivos_pasco = list(casos_positivos[casos_positivos['DEPARTAMENTO'] == "PASCO"].shape)[0]
positivos_hombres_pasco = list(casos_positivos[(casos_positivos['DEPARTAMENTO'] == "PASCO") &(casos_posit... |
import argparse
import numpy as np
# usage: python3 gender_projection.py '/Users/boyuliu/Dropbox (MIT)/nlp_project/data/topic_embeddings/trump_embeddings.npy'
gender_vector = '/Users/boyuliu/Dropbox (MIT)/nlp_project/data/gender_bias/trump_tweets_gender_pca_vector.npy'
def project_embed(embed, vec, onto=False):
... |
#!/usr/bin/env python
import rospy
import numpy as np
from detection_filter import Filter, Hypothesis
from linemod_detector.msg import NamedPoint
class SampleDetectionFilter(object):
def __init__(self):
self.current_sequence = None
# node parameters
self.sample_name = rospy.get_param("~sa... |
#!/usr/bin/env python3
import argparse
import binascii
from pyfiglet import Figlet
from getpass import getpass
import os
import pyudev
import subprocess
import sys
import xxtea
def intro():
f = Figlet(font='graffiti')
print(f.renderText("NoRKSEC"))
print('usbWatchdog.py - (c) 2017 NoRKSEC - no rights reserved\n')... |
# coding: utf-8
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import concurrent.futures
import os
def datagen(filename, destination):
datagen = ImageDataGenerator(
rotation_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,... |
from __future__ import print_function
import datetime
import hashlib
import json
import os
import sqlite3
import time
import uuid
from functools import wraps
import numpy as np
import optuna
import pandas as pd
import torch
import yaml
from box import Box
from clearml import Task
from ludos.models import common
from ... |
# Generated by Django 3.0.6 on 2020-06-10 18:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Home', '0008_auto_20200610_1323'),
]
operations = [
migrations.CreateModel(
name='Promotions',
... |
'''
Crie uma lista, inicialmente vazia, para armazenar uma listagem de nomes.
Criar uma função para inserir um nome na lista
Criar uma função que recebe como parâmetro a lista e uma posição (índice) dessa lista e retornar o nome que está nessa posição.
Essa função deve gerar e tratar uma exceção do tipo IndexError cas... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
#!/usr/bin/python3
# vim:fileencoding=utf-8:ts=2:sw=2:expandtab
# Setup the path
import os, os.path, sys; sys.path.insert(1, os.path.abspath(sys.path[0] + "/../Python"))
import json
from base64 import b64encode
try:
from DocStruct import Setup
from DocStruct.Config import EnvironmentConfig
except ImportError:
... |
print ("questao 2")
mes = print ("Mes de Fevereiro")
ano = int(input("Digite o ano "))
if ano % 4 == 0 or 100!= 0 and 400 == 0:
print ("fevereiro tem 29 dias", ano)
else:
print ("fevereiro tem 28 dias", ano)
|
import sqlite3
def changePassword(user_id, new_password):
conn = sqlite3.connect('Database.db3')
conn.execute("UPDATE User SET password = '" + new_password + "' WHERE user_id = '" + user_id + "'")
conn.commit()
conn.close()
return True
|
# ¿Acaso hubo buhos aca?
# Definir una función que detecte si
# una palabra es un palíndromo y devuelve True o False.
# Ejemplos:
# palindromo( "python" ) => False
# palindromo( "reconocer" ) => True
# palindromo( "Neuquén" ) => False
# ★★ Challenge: Modificar la función para
# ignorar espacios, signos de punt... |
# kullanıcıdan okunan sayının kaç basamaklı olduğunu bulan algoritma
n = int(input("Bir sayı giriniz: "))
bs = 0
while(n!=0):
n = n//10
bs += 1
print(bs)
# n = input("Bir sayı giriniz: ")
# print(len(n)) fonkla kısaca bulabiliriz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.