text stringlengths 38 1.54M |
|---|
'''
Created on Jun 29, 2016
@author: mateusz
'''
from src.mvc.model.olx.offer_search_query import OfferSearchQuery
class ApartmentOfferSearchQuery(OfferSearchQuery):
'''
Build an OLX search query for apartments
'''
# OLX offer query url example:
# http://olx.pl/nieruchomosci/mieszkania/wynajem/kra... |
instructions = []
with open('6.in') as f:
lines = f.read().splitlines()
for line in lines:
i = line.split(' ')
if len(i) == 5: # turn on/off x,y through x',y'
instructions.append((i[1], i[2].split(','), i[4].split(',')))
elif len(i) == 4: # toggle x,y through x',y'
... |
import requests
import urllib3
import click
import json
from rich.console import Console
from rich.table import Table
# from rich.text import Text
from vmanage.api.authenticate import authentication
from vmanage.constants import vmanage
from vmanage.api.vpn import generate_dict_vpn_ip_nexthops
import ast
urllib3.disabl... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from desktopsite.apps.repository.models import *
from desktopsite.apps.repository.forms import *
from desktopsite.apps.repository.categories import REPOSITORY_CATEGORIES
from django.contrib.auth... |
import os, sys, argparse, stat, traceback, shutil, subprocess, logging, json
import glob
logging.basicConfig(level=logging.WARNING)
log = logging.getLogger(os.path.basename(__file__))
mapping = [
[ "backend/*.cpp" , None ],
[ "backend/*.d" , None ],... |
from time import ctime,sleep
import multiprocessing
def talk(content,loop):
for i in range(loop):
print("Talk:%s %s"%(content,ctime()))
sleep(2)
def write(content,loop):
for i in range(loop):
print("write:%s %s"%(content,ctime()))
sleep(3)
process=[]
p1=multiprocessing.Process... |
from bs4 import BeautifulSoup as bs
from requests import Session
s = Session()
f = open('opel.txt',mode='w',encoding='utf-8')
headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0'}
# url = 'https://www.autoscout24.com/lst/?sort=standard&desc=0&fuel=3&ustate=N%2CU&size=20... |
from bloghandler import BlogHandler
from models.user import User
from models.post import Post
from helper import *
from google.appengine.ext import db
class EditPost(BlogHandler):
def get(self):
if self.user:
self.render("editpost.html")
else:
self.redirect("/login")
... |
#!/usr/bin/env python
"""For AN
leptonjets efficiencies and resolutions
"""
import argparse
import awkward
import coffea.processor as processor
import numpy as np
import matplotlib.pyplot as plt
from coffea import hist
from coffea.analysis_objects import JaggedCandidateArray
from FireHydrant.Analysis.DatasetMapLoader ... |
mixed_token = "in99"
if mixed_token.isdigit:
eng_pron = 'in'
digit_pron = 'jiu4_jiu5'
spoken_form = eng_pron + '_' + digit_pron
print(spoken_form)
|
import socket
import asyncore
import uuid
import struct
import logging
log = logging.getLogger('slim')
SLIMPORT = 3483 # server listens on tcp, client on udp
WEBPORT = 9000 # webinterface
BUFFERSIZE = 1024 # reading messages in this blocksize
class SlimProto(object):
"""implements the logitech/slimdevic... |
# Sequence iteration
stairs = (1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 7)
from operator import getitem
def count_while(s, value, getitem=getitem, len=len):
"""Count the number of occurrences of value in sequence s.
>>> stairs.count(4)
3
>>> count_while(stairs, 4)
3
"""
total, index = 0, 0
whil... |
# Generated by Django 3.1.7 on 2021-06-05 11:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0007_auto_20210604_1337'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='numbe... |
#!/usr/bin/env python
## Controls the airship altitude
import rospy
import time
import sys
from geometry_msgs.msg import TransformStamped
from airshippi_vicon.msg import Rotor
#from airshippi_vicon import testmodule
# Global params
P = 90
I = 0.5
D = 0
RATE_HZ = 5 # Hz
VICON_TOPIC = '/vicon/gal_airship/gal_airship'
... |
"""Estos dos primeros métiodos van a permitir abrir un fichero de texto y extraer de él los casos test en forma de
matriz de 3 dimensiones [Primera dimensión: lista de los atributos del ítem. Segunda dimensión: lista de ítems de un día.
Tercera dimensión: lista de listas de cada día. Los casos test están escritos en la... |
# Generated by Django 3.0.6 on 2020-06-16 09:02
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('main', '0008_auto_20200616_0901'),
]
operations = [
migrations.AlterField(
... |
import numpy as np
import torch
import torch.nn as nn
from cvpods.utils import comm
from torch import distributed as dist
import swav_resnet as resnet_models
class SwAV(nn.Module):
def __init__(self, cfg):
super(SwAV, self).__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.... |
from bruteforce import Bruteforce
from sieve_of_eratosthenes import SieveOfEratosthenes
if __name__=='__main__':
while True:
print("""\nWhich program to run:
1) SieveOfEratosthenes
2) Brute-Force
3) Exit""")
run = input("\nPlease Enter your choice: ")
if run == "1" or run == "SieveOfErat... |
import numpy as np
def sigmoid(x):
return 1.0/(1.0 + np.exp(-x))
def sigmoid_derivative(value):
return value(1 - value)
def tanh_derivative(value):
return 1.- value**2
# create uniform random array w/ values in [a, b] and shape args
def rand_arr(a, b , *args):
# 设置相同的seed时,每次生成的随机数相等
np.random.s... |
#!/usr/bin/python2
import numpy as np
import os
import shutil
import sys
import h5py
#sys.path.insert(0,'/master/home/nishac/.local/lib/python2.7/site-packages')
sys.path.append("/master/home/nishac/fds/")
sys.path.append("/master/home/nishac/S3/")
#import map_sens
import fds
from adFVM.interface import SerialRunner
fr... |
#-*- coding: utf-8 -*-
# coding:utf-8
import jieba
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import math
import gensim
import numpy as np
def cos_dist(a, b):
if len(a) != len(b):
return None
part_up = 0.0
a_sq = 0.0
b_sq = 0.0
for a1, b1 in zip(a,b):
part_up += a1*b1
a_sq += a1**2
b_sq += b1*... |
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if test:
xua, yua, xla, yla, xub, yub, xlb, ylb = (int(i) for i in test.split(','))
range_x_a = set(xrange(xua, xla + 1))
range_y_a = set(xrange(yla, yua + 1))
range_x_b = set(xrange(xub, xlb + 1))
range_y... |
# prompt: https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem
import sys
def solve(arr, money):
costIdxDict = {}
for idx, amt in enumerate(arr):
if money - amt in costIdxDict:
print(costIdxDict[money - amt] + 1, idx + 1)
return
else:
costIdxD... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainv3.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import os
import sys
#this part enables ... |
from django.apps import AppConfig
class ContaCorrenteConfig(AppConfig):
name = 'conta_corrente'
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 2 10:55:54 2020
@author: Administrator
"""
import csv
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.dates as mdate
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.tick... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.stats import truncnorm
import pickle
import os
from sklearn import preprocessing
import scipy.io as sio
import matplotlib.gridspec as gridspec
import progressbar
from pprint import pprint
import copy
import time
FRA... |
#Each gesture correspond to a number showed by the hand
def oneFinger():
#i01.startedGesture()
rest()
i01.moveHead(64.00,94.00,76.93,58.72,0.00,129.00)
i01.moveArm("left",90.00,60.00,83.00,15.00)
i01.moveArm("right",5.20,90.20,30.20,12.20)
sleep(2.5)
i01.moveHand("left",0.00,180.00,180.00,180.00,180.00,90... |
# 3rd-party modules
from lxml.builder import E
# module packages
from ... import jxml as JXML
from .. import Resource
class SharedAddrBookSet( Resource ):
"""
[edit security address-book <ab_name> address-set <name>]
~! WARNING !~
This resource is managed only as a child of the :ZoneAddrBook:
resource. D... |
import json
import requests
from flask import request
from mattermostgithub import config, app
import hmac
import hashlib
SECRET = hmac.new(config.SECRET, digestmod=hashlib.sha1) if config.SECRET else None
def check_signature_githubsecret(signature, secret, payload):
sig2 = secret.copy()
sig2.update(payload)... |
import unittest
from selenium import webdriver
from test_project.pageObjects.Pages.main_page import MainPage
from test_project.pageObjects.Pages.login_page import LoginPage
from test_project.pageObjects.Pages.secure_area_page import SecurePage
class TestLogin(unittest.TestCase):
def setUp(self):
self.dri... |
import numpy as np
from math import acos, degrees
from util.graph import Graph
u = np.array([-5, -1])
v = np.array([4, 2])
n = u @ v
d = np.linalg.norm(u) * np.linalg.norm(v)
cos_angle = n / d
angle = acos(cos_angle)
print(f'{degrees(angle)} degrees')
g = Graph()
g.add_vector(u, color='b')
g.add_vector(v, color='g')... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Bookstore(models.Model):
name = models.CharField(max_length=100)
url = models.CharField(max_length=200)
def __str__(self):
return self.name
class Company(models.Model):
name = models.CharF... |
# 简单画布
import tkinter
baseFrame = tkinter.Tk()
cvs = tkinter.Canvas(baseFrame, width=300, height=200)
cvs.pack()
# 一条线需要两个点指明起始
# 参数数字的单位是pixel
cvs.create_line(23, 23, 190, 234)
cvs.create_text(56, 67, text="I LOVE PYTHON")
baseFrame.mainloop()
|
import csv
import os
import requests
from flask import Flask, render_template, request
from modal import *
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_M... |
from crummycm.validation.types.placeholders.placeholder import (
KeyPlaceholder,
ValuePlaceholder,
)
from crummycm.validation.types.dicts.foundation.unnamed_dict import UnnamedDict
from crummycm.validation.types.dicts.foundation.known_dict import KnownDict
from crummycm.validation.types.dicts.config_dict import... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-04 20:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('LedgerBoardApp', '0003_auto_20170704_1854'),
]
operations = [
migrations.Al... |
import unittest
import spelling
class TestNameSpace(unittest.TestCase):
def test_predict(self):
# As such because the built in model is not trained, only all words are added
self.assertIn(spelling.predict("bway"), ["way", "bay", "away", "sway", "tway", "bray"]) |
import time, datetime
import RPi.GPIO as GPIO
import telepot
from telepot.loop import MessageLoop
blue = 6
yellow = 13
red= 19
green= 26
now = datetime.datetime.now()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
##LED Blue
GPIO.setup(blue, GPIO.OUT)
GPIO.output(blue, 0) #Off initially
#LED Yellow
GPIO.setup(yellow, ... |
from binary_search import binary_search
list = [i for i in range(129)]
list2 = [i for i in range(259)]
# print list
# print binary_search(list,111)
# print binary_search(list,66)
# print binary_search(list,128)
print binary_search(list2,258) |
import theano
import theano.tensor as T
from collections import OrderedDict
import lasagne
from lasagne.layers import InputLayer,Conv2DLayer, ConcatLayer, Pool2DLayer, Deconv2DLayer
from lasagne.layers import ReshapeLayer, DimshuffleLayer, NonlinearityLayer, SliceLayer, DropoutLayer
from lasagne.layers import batch_n... |
# ### Summary of testing debuggin packaging distribuıting
# * unittest is a framework for developing reliable automated tests
# * You define test cases by subclassing from unittest.TestCase
# * unittest.main() is useful for running all of the tests in a module
# * setUp() and tearDown() run code before and after each t... |
from rover.settings import *
DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
# Disable Authentication for Tests
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100
} |
# coding=utf-8
import sublime_plugin, datetime
class insertDatetimeCommand(sublime_plugin.TextCommand):
def run(self, edit, format):
timestamp = datetime.datetime.now()
if format == "ymd":
# yyyy-mm-dd
timestamp = timestamp.strftime("%Y-%m-%d")
elif format == "ymdhms":
# %X = %H:%... |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from pydrive.auth import GoogleAuth
... |
import numpy as np
from ..utils import read_hdf5_array
from ..sampling import eFAST_omega
def eFAST_first_order(Y, M, omega):
"""Sobol first order index estimator."""
N = Y.shape[0]
f = np.fft.fft(Y)
Sp = np.power(np.absolute(f[np.arange(1, int((N + 1) / 2))]) / N, 2)
V = 2 * np.sum(Sp)
D1 = ... |
#!/usr/bin/env python3
import sys
import psycopg2
import scraper
import database
""" Loads and processes all data related to block with given number """
def process_block(block_number):
b = scraper.load_block(block_number)
try:
database.save_block(b)
except psycopg2.IntegrityError:
print("... |
# Create your views here.
from pprint import pprint
from django.shortcuts import render
from lab2 import GetWeather_Data
from lab2.GetWeather_Data import CitySearchError
def index(request):
return render(request, "lab2/lab2.html")
def weather(request):
latitude = request.GET['latitude']
longitude = re... |
N = int(input())
S = []
T = []
for i in range(N):
si, ti = tuple(input().split())
S.append(si)
T.append(int(ti))
X = input()
i = S.index(X)
print(sum(T[i + 1:]))
|
import numpy as np
from os import fstat
from .utils import *
def ReadIndex(f, fileSize):
nBytes = fileSize - f.tell()
if nBytes <= 0:
return True
nRows = int(nBytes / 64)
table = f.read(nBytes)
print(" ")
print("-----------------------------------------------------------------"
... |
import requests
from threading import Thread
import sys
import queue
import urllib.parse
import pickle
from sample.parse import get_selected_course
class select_course(object):
def __init__(self,username,MAX,TIMEOUT,index1='',index2=''):
'''
初始化一些参数
max为队列倍数
index1 index2分别为选课页数和在... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
d=int(input())
n=int(input())
r=0
for x in map(int,input().split()):r+=d-x
print(r-d+x)
|
# -*- coding:utf-8 -*-
# import pymysql as ps
# import pymssql as ps
import contextlib
import pandas as pd
from Common.Config.DBConfig import DBConfig
from Common.DB.EnumType import *
from Common.DB.DBCommon import DBCommon
dbType =DBConfig.getDBType()
if dbType == DBType.MYSQL:
import pymysql ... |
"""Add widgets onto URI contexts."""
from django.conf import settings
import www.common.context
from .models import WikiPage, WikiHome
from .page import OneColumnPage
def home_widget_context(context):
"""If it exists, add the home wiki to the context, otherwise set
it to None."""
if 'id' not in context... |
import random
file = open('allpsswrds.txt', 'a')
email = input("What email did you use?")
uname = input("What username did you use?")
account = input("What is this for?")
gen_psswrd = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
list_of_char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', ... |
from tkinter import *
from PIL import Image,ImageTk
from tkinter import messagebox
import sqlite3
class Register:
def __init__(self, master):
#Toplevel.__init__(self)
global master_root
#master_root = master
self.root=master
#self.root.state('zoomed')
... |
import utils
import speech
LARGE_NUMBER_DAYS = 3650
def ensure_date_and_service_slots_filled(intent):
if ("value" not in intent["slots"]["Date"]) or ("value" not in intent["slots"]["Service"]):
speechlet_response = {
"shouldEndSession": False,
"directives": [{"type": "Dialog.Deleg... |
#!/usr/bin/env python
#CVE-2012-2982 translated from ruby metasploit module (/webmin_show_cgi_exec.rb)
#program outline:
# - POST request with compromised creds to get the cookie
# - exploit using invalid characters to get system shell
# - fetches system shell as root
# - sends shell through socket to listening a... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.http import Http404
from django.template import loader
from .models import File
from django.views.generic.edit import CreateView
from django.views import generic
# Create your views here.
def index(request):
all_fi... |
import pygame
from pygame import mixer
import screeninfo
from screeninfo import get_monitors
pygame.init()
mixer.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
for m in get_monitors():
screen_width = m.width
screen_height = m.height
block_width = 8
block_height = ... |
from gpiozero import MotionSensor
pir = MotionSensor(17)
if pir.wait_for_motion(4):
print("Motion detected!")
else:
print("no motion")
|
from deeds.jobs import import_data_async
from deeds.models import (
Data, Deed, DeedType, Gender, Origin, OriginType, Party, Person, Profession,
Role, Source
)
from django.contrib import admin, messages
from django_rq import job
from rq import get_current_job
class BaseALAdmin(admin.ModelAdmin):
list_disp... |
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
class AES_OBJECT:
BLOCK_SIZE_AES = 16 # AES: Bloque de 128 bits
def __init__(self, key, mode, IV):
"""Inicializa las variables locales"""
self.key = key
self.mode = mode
... |
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.core.mail import send_mail
@shared_task
def send_tmp_password(email, username, new_pwd):
send_mail(
"Worka Service Team",
f"안녕하세요 {username}님 :)\n\nWorka에서 임시 비밀번호를 발급해드렸습니다."
f"\n\n임시 비밀번호는... |
# Ask user: "What's my favorite food?"
# If user guesses my favorite food, output: "Yep! So amazing!"
# If not, output: "Yuck! That's not it!"
# End with "Thanks for playing!"
favoriteFood = "Enchiladas"
userGuess = input("What's my favorite food? ")
if userGuess == favoriteFood:
print("Yep! So amazing!")
else:
... |
import copy
import pickle
import numpy as np
from . import Agent
from reaver.envs.base import Env, MultiProcEnv
class RunningAgent(Agent):
"""
Generic abstract class, defines API for interacting with an environment
"""
def __init__(self):
self.next_obs = None
self.start_step = 0
... |
from misinfo.server_oneoff import server
# if you want to run a batch run
#from misinfo.server_batch import server
server.launch() |
##########################################################################
##
## This is a modification of the original WndProcHookMixin by Kevin Moore,
## modified to use ctypes only instead of pywin32, so it can be used
## with no additional dependencies in Python 2.5
##
###########################################... |
import os
import logging
class AssertConditionConstants:
languages = ["eng", "kor"]
available_models = ["transformer", "bert", "poly-encoder", "gpt2"]
available_optimizers = ["adam", "adam_w"]
preprocess_approaches = ["stop", "ignore", "truncate"]
aggregation_methods = ["first", "last", "sum", "ave... |
#
# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <brunato@... |
from typing import List
class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
hashmap = {}
s = 0
hashmap[s] = 1
res = 0
for i in range(len(nums)):
if nums[i] & 1 == 1:
s += 1
if s - k >= 0:
res +=... |
import astropy.units as u
import astropy.coordinates as coord
from astroquery.gaia import Gaia
from astropy.io import ascii
import numpy as np
import pandas as pd
import math
import struct
from functools import partial
import sys
import os
from os import listdir
import warnings
warnings.filterwarnings("ignore")
pd.se... |
"""
PARSER
--------------------
Class responsible for parsing the desired site
"""
from bs4 import BeautifulSoup
import requests
from urlparse import urlsplit
import utilities
class BookParser(object):
def __init__(self, url, selector, tag_name):
self.url = url
self.selector = utilities.class_or... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pickle
import scipy
from scipy import signal
from collections import deque
def loadDistMatrix():
# load distortion matrix
with open('camera_dist_pickle.p', mode='rb') as f:
dist_pickle = pickle.load(f)
mtx = dist... |
from django.contrib import admin
from django.urls import path, re_path
from leads import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/leads/$', views.leads_list),
re_path(r'^api/leads/([0-9])$', views.leads_detail),
]
|
class Buffer:
# Конструктор без аргументов.
def __init__(self):
# Список, в который будет добавляться последовательность целых чисел.
self.current_part = []
# Добавляет следующую часть последовательности.
def add(self, *a):
# Расширяем список, добавляя в него элементы.
... |
from tornado import gen
from tornado.ioloop import IOLoop
from bokeh.server.server import Server
from bokeh.application.handlers import FunctionHandler
from bokeh.application import Application
import numpy as np
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
import fire
class BokehSco... |
import PeruDB
import PeruConstants, CommonFunctions
def PersonInsertFromList(people):
resultString = ""
for person in people:
result = PersonInsertStatement(person)
if result == -1:
return result
resultString += result
return resultString
def... |
import sajilo
import sys
import os.path
if len(sys.argv) == 1:
#ask for the file if no file is provided
print("Usage: %s filename" % __file__)
else:
#get the file extension if file is provided.
ext = str(os.path.splitext(sys.argv[1])[1])
if ext == ".sajilo":
#execute the file if extension m... |
print('''Aprimore o Desafio 093 para que funcione com varios jogadores,
incluindo um sistema de visualização de detalhes do aproveitamento de
cada jogador.
''')
#captação de dados.txt
jogador = dict()
time = list()
print('{:=^50}'.format(' Gerenciamento de Aproveitamento '))
while True:
keep = '0'
jogador['No... |
import eng
class Yamazaki:
name = 'Yamazaki'
#type = 'Item'
visible = True
aliases = ['yamazaki', 'Mr. Yamazaki', 'Genzo Yamazaki', 'Japanese businessman']
descriptions = {'desc': "You see an Japanese businessman dressed in formal attire. ",
'intro':'Hajimemashite, I am Genzo Yamazaki. I am COO at M... |
# ディクショナリ
scores = {
"山田" : 90,
"高橋" : 100,
"山本" : 70,
"田中" : 85,
"坂本" : 55
}
# 変数初期化
total = 0
# 計算
for score in scores.values():
total += score
ave = total / len(scores)
# 1回目の表示
print("合計:" + str(total) + "点")
print("平均:" + str(ave)+ "点")
# 辞書に"中田"を追加
scores["中田"] = 95
# 計算
total += sco... |
# coding=utf-8
import json
from decimal import Decimal
import sys
from django.core import serializers
from datetime import datetime
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from laboratorio import views_nivel_insumos
from laboratorio... |
from segmentation_models.base import Loss
from segmentation_models.base import functional as F
import segmentation_models as sm
import keras.backend as K
import tensorflow as tf
class L1Loss(Loss):
def __init__(self):
super().__init__(name='l1')
def __call__(self, gt, pr):
return l1(gt, pr, *... |
from tkinter import *
from functools import partial
import Mainwindow
import class_gallons
class SeauWindow:
def __init__(self, nbrSeau, tailles, final, initial):
self._contenu = []
self._first = True
self._select = -1
self._tailles = tailles
self.Seau_w = ""
self.... |
import shapely
import pandas as pd
from shapely.geometry import Point, GeometryCollection
import pytest
from h3ronpy.pandas import change_resolution
from h3ronpy.pandas.vector import (
cells_to_points,
cells_to_polygons,
cells_dataframe_to_geodataframe,
geodataframe_to_cells,
geoseries_to_cells,
)
... |
import string
import random
import sys
import time
import re
import pdb
def DrawIPFile(inputfile):
dipfile = {}
with open(inputfile) as res:
for line in res:
templine=line.decode('string_escape').strip("\"").strip()
line_split=line.split('\t')#line_split[0]=dip_sip,line_split[1... |
from typing import List
from trainer_v2.keras_server.name_short_cuts import NLIPredictorSig
def get_em_base_nli() -> NLIPredictorSig:
def tokenize_normalize(chunk):
tokens = chunk.lower().split()
return tokens
def em_based_nli(t1: str, t2: str) -> List[float]:
tokens1 = tokenize_norm... |
# BaekJoon18870.py
N = int(input())
arr = list(map(int, input().split()))
sorted_arr = sorted(list(set(arr)))
dic = {sorted_arr[i] : i for i in range(len(sorted_arr))}
for i in arr:
print(dic[i], end = " ") |
#!/usr/bin/env python3
"""
This file generates a single html page. When run multiple times, is can
generate all html files. When no input csv in defined, input is read from
stdin. When no output file is defined, output is written to stdout.
Usage:
soc_generator.py -o output_filename -t socs_topics_filename
-g soc... |
# encoding: utf-8
import pytest
from mastermind_code import mastermind
def test_should_return_list():
response = mastermind(['red'], ['red'])
assert isinstance(response, list)
def test_should_return_list_with_2_components():
response = mastermind(['red'], ['red'])
assert len(response) > 0
def t... |
#'''
def amount_people(PP) :
result = 0
cResult = 0
PPR = PP[::-1]
PPR = list(map(int,PPR))
#printDebug("PPR : ",PPR)
M2 = len(PP) - 1
#printDebug("M2 : ",M2)
for i in range (len(PP)-1) :
#PPR[i]
#printDebug("len of less lev",len(PPR[i+1::]))
lev = len(PPR[i+1::])
SPPI = sum(PPR[i+1... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 1 15:38:43 2019
@author: 10670
"""
import sys; sys.path
from tkinter import*
import GUI_CeShi
def main():
root = Tk()
root.title("手写数字识别系统")
#生成标签
main_label = Label(root, text = "欢迎来到手写数字识别系统")
main_label.grid(row = 0, column = ... |
# Generated by Django 3.1.4 on 2021-01-04 07:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='product',
... |
from __future__ import annotations
import json
from datetime import datetime
from typing import TypeVar, Generic, Callable, Any
import util
MessageContent = TypeVar("MessageContent")
class _Keys:
SENDER: str = "sender"
CONTENT: str = "content"
TOPIC: str = "topic"
DATE: str = "date"
class Message... |
import os
from datetime import datetime
from zipfile import ZipFile, ZIP_DEFLATED
import pandas as pd
from flask import Flask, jsonify, send_from_directory, request, send_file
from flask_cors import CORS
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
... |
from django.db import models
# Create your models here.
class passengers(models.Model):
From=models.CharField(max_length=50)
To=models.CharField(max_length=50)
Date=models.DateField()
no_of_people=models.CharField(max_length=20)
class flit(models.Model):
name=models.CharField(max_length=50)
... |
from src.common import database
from src.models.alerts import alert
database.Database.initialize()
alert.check_alerts()
|
from sklearn.naive_bayes import GaussianNB
import numpy as np
from scipy import stats
from sklearn.metrics import jaccard_similarity_score
from numpy import array
from sklearn.metrics import accuracy_score
#assigning predictor and target variables
import csv
reader = csv.DictReader(open('presidential_polls.csv', 'rU')... |
from __future__ import print_function
import argparse
import numpy as np
import os
import time
import airsim
from airsim.types import Pose, Vector3r, Quaternionr
from airsim import utils as sim_util
from airsim.utils import to_quaternion
AS_CAM_ID = 1
def handle_arguments(parser):
parser.add_argument("--pose", ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.