text stringlengths 8 6.05M |
|---|
n,m = map(int,input().split())
start = list(map(int,input().strip().split()))[:2]
end = list(map(int,input().strip().split()))[:2]
arr = []
for k in range(n):
a = list(map(int,input().split()))[:m]
arr.append(a)
mat = [[0 for i in range(n)] for j in range(m)]
mat[start[0]][start[1]] = 1
def m... |
from headline_generator.config import Config1, Config2, Choose_config
from headline_generator.model import model1
import numpy as np
from keras.preprocessing import sequence
from keras.utils import np_utils
import random, sys
from sklearn.cross_validation import train_test_split
import pickle
# from keras.utils.visuali... |
from copy import deepcopy
import numpy as np
from clients.base import BaseClient
class FedProxClient(BaseClient):
def __init__(self, model, optimizer, criterion, dataloader, scheduler=None):
super().__init__(model, optimizer, criterion, dataloader, scheduler)
def local_update(self, epoch):
glo... |
# -*- coding:utf-8 -*-
import os
import sys
sys.path.append('utils/')
from preprocess import *
from sentianalysis import *
main_path = os.path.abspath('.')
dict_path = main_path + '/dict/'
#修改各词库的路径
stopword_path = dict_path + 'stop_words.txt'
degreeword_path = dict_path + 'degreewords.txt'
sentimentword_path = d... |
from __future__ import print_function
import numpy as np
import tensorflow as tf
import tensorflow.contrib.rnn as rnn
from constants import constants
def normalized_columns_initializer(std=1.0):
def _initializer(shape, dtype=None, partition_info=None):
out = np.random.randn(*shape).astype(np.float32)
... |
from django.contrib import admin
# Register your models here.
from .models import Profile
from django.utils.html import format_html
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ('ph_no', 'company', 'designation')
def image_tag(self, profile):
return format_html('<img s... |
DEBUG = True
"""邮件配置"""
MAIL_SERVER = 'smtp.163.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = 'melondean@163.com'
MAIL_PASSWORD = 'admin123'
MAIL_DEFAULT_SENDER = ('CZAOAO', 'melondean@163.com')
|
import turtle
def drawSq(the_turtle):
for x in range(1,5):
the_turtle.forward(100)
the_turtle.right(90)
def draw_square():
window = turtle.Screen()
window.bgcolor("yellow") #turns the shell's window yellow
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("blue")
... |
from django.shortcuts import render
from django.http import HttpResponse
def openhomepage(request):
type="home"
return render(request, "home.html", {"type": type})
def UserLogin(request):
type = request.GET.get("type")
return render(request,"home.html",{"type":type})
def booking(request):
type = r... |
from flask import Flask, request, g, render_template, logging, Response
from functools import reduce
from os import getenv
import uuid
import time
import structlog
from pymongo import MongoClient
import traceback
import prometheus_client
CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')
COUNTER_PAG... |
from typing import Dict
from variables import district
for k,v in district.items():
for l,u in district[k].items():
district[k][l].pop('name')
for m,w in district[k][l].items():
district[k][l][m]['name']=m
district[k][l][m]['lat']=1
district[k][l][m]['lo... |
from shared import read_input_lines, exec_cl_function
from collections import Counter
def letter_repeats(strings, recurrences=(2, 3)):
counts = {r: [] for r in recurrences}
for string in strings:
for n in recurrences:
counts[n].append(contains_letter_repeated_n(n, string))
return coun... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 8/16/2017 10:55 AM
# @Author : Winnichen
# @File : excel_reader.py
from openpyxl import Workbook
from openpyxl import load_workbook
from config import settings
class Common_ExcelReader(object):
def __init__(self,sheet):
self.wb=load_workbook(se... |
def indent(text, by=4, first_line=True):
r"""
>>> indent("a\nb\nc", by=1) == ' a\n b\n c'
True
"""
spaces = " " * by
lines = text.splitlines(True)
prefix = lines.pop(0) if (lines and not first_line) else ""
return prefix + "".join(spaces + line for line in lines)
|
#!/usr/bin/python
import sys
import os
import logging
activate_this = '/home/http/medlemsregistrering/venv/bin/activate_this.py'
exec(open(activate_this).read())
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/home/http/medlemsregistrering")
os.chdir("/home/http/medlemsregistrering")
from medlemsregistreri... |
import datetime
from django.db import models
# Create your models here.
class Course(models.Model):
name = models.CharField(max_length=64, verbose_name='课程名称')
desc = models.CharField(max_length=512, verbose_name='课程描述')
detail = models.TextField(verbose_name='课程详情')
level = models.CharField(
... |
#coding=utf8
from django.http import HttpResponse
from usr.models import Accounts
import json
# 注册行为返回值类型
class LoginReturnType:
def __init__(self):
self.result = 'FAILED'
self.reason = ''
def deal_login(request):
# 取得注册数据
ac = Accounts()
ac.usr_name = request.REQUEST.get('usr_name','... |
ab = {'Swaroop': 'swaroopch@byteofpython.info',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'}
print 'Swaroop\'s address is %s'%ab['Swaroop']
ab['Guido'] = 'guido@python.org'
del ab['Spammer']
print 'There are %d contacts in the address book.'%len(ab)
for na... |
from __future__ import print_function
from __future__ import division
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, mode... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import threading
import time
def receive_message():
while not stopThread:
indata = s.recv(4096).decode("utf-8")
if len(indata) == 0: # connection closed
s.close()
print('server closed connection.')
brea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import configparser
import logging
import logging.handlers
import json
from threading import Lock
import sys
import traceback
import platform
import threading
import src.common.constant as constant
from getpass import getuser
import time
import da... |
import pyfaidx
import argparse
from tqdm import tqdm
import pandas as pd
def parse_args():
parser=argparse.ArgumentParser(description="get gc content from a foreground bed file")
parser.add_argument("-i","--input_bed", help="bed file in narrow peak format - we will find gc content of these regions centered on... |
import pytest
@pytest.mark.asyncio
async def test_llen(redis):
length = await redis.llen('foo')
assert 0 == length
redis._redis.lpush('foo', 'bar')
length = await redis.llen('foo')
assert 1 == length
@pytest.mark.asyncio
async def test_lpush(redis):
ret = await redis.lpush('foo', 'bar')
... |
"""
-------------------------------------------------------------------------------
| Copyright 2016 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/... |
import sys
import os
import shutil
sys.path.insert(0, 'scripts')
sys.path.insert(0, 'tools/families')
sys.path.insert(0, 'tools/trees')
sys.path.insert(0, 'tools/mappings')
import experiments as exp
import fam
from ete3 import Tree
from ete3 import SeqGroup
import get_dico
from read_tree import read_tree
from read_tree... |
import pandas as pd
import numpy as np
import os
import sys
def hotencode_train(data):
train = pd.DataFrame()
parents = pd.get_dummies(data[0], prefix="parents")
has_nurs = pd.get_dummies(data[1], prefix="has_nurs")
form = pd.get_dummies(data[2], prefix="form")
children = pd.get_dummies(data[3], pre... |
a = input().upper()
D = {}
for i in a:
try:
D[i] += 1
except KeyError:
D[i] = 1
d2 = list(D.items())
d2.sort(key=lambda x: x[1], reverse=True)
if len(d2) != 1:
if d2[0][1] != d2[1][1]:
print(d2[0][0])
else:
print("?")
else:
print(d2[0][0])
# Done |
import numpy as np
import torch
from torch.autograd import Variable
class DataLoaderS(object):
# train and valid is the ratio of training set and validation set. test = 1 - train - valid
def __init__(self, cmip5, soda, godas, device, horizon, window, valid_split=0.1,
transfer=True, concat_cmi... |
def multiply(solid_number):
x = None
res = 1
for i in str(solid_number):
if not x:
x = int(i)
res = int(i)
else:
res *= int(i)
return res
def persistence(n):
steps = 0
b = str(n)
while len(b) != 1:
y = multiply(b)
steps +=... |
from value_objects.util.compat import izip, unicode
from value_objects.util.once import once
class ObjectHelper( object ):
def __init__( self, object_class, field_names, field_values ):
self.object_class = object_class
self.field_names = field_names
self.field_values = field_values
@property
def f... |
text = input("Digite seu texto: ")
print(len(text))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 06:59:02 2019
@author: Sneha
"""
import numpy as np
import vrep
import sys
text_file = open("FinalPath.txt", "r")
lines = (text_file.read()).split(' ')
text_file.close()
final_path=[]
for i in lines:
if(i!=''):
k=i.split(',')
for j in range(5):
... |
import os
PREFIX = 'data/'
path = '{{ .VARIABLE }}'
data_path = os.path.join(PREFIX, path)
full_path = os.path.abspath(data_path)
data = ''
with open(full_path, 'r') as f:
data = f.read()
print(data)
|
#!/usr/bin/env python
import netfilterqueue
#the purpose of this program is to drop or accept packets being sent from a victims computer to the internet. it is intended
#to be used after already being the Man in the middle from our arp_spoof program. To be able to access these packets,
#we must first put them in a qu... |
import sys
import os
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QMainWindow, QPushButton, QFileDialog, QWidget, QCheckBox, QHBoxLayout
# User defined imports
from OCR_reader import OCRReader
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
... |
"""
Entrada: Um texto qualquer
Saida: No lugar de nomes (com letras maiúsculas), retorna M, se for preposição, retorna p,
se for numeral, retorna N, se for conjunção, retorna c ...
"""
import libplnbsi
#Codifica recebe um texto tokenizado
def codifica(pTexto):
preposicoes = ['a', 'ante', 'após', 'com', 'contra','de'... |
__author__ = 'Ben'
from helper import greeting
greeting("new file says hi")
greeting() |
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# fmt: off
# isort: skip_file
import builtins as _builtins, sys, typing as _typing
from google.protobuf.field_mask_pb2 import FieldMask
from google.protobuf.internal.containers ... |
#coding:utf8
import pandas as pd
df=pd.read_excel("./corrDataSet.xlsx")
print df.corr()
|
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 13:17:37 2019
@author: quiath
"""
import time
from collections import namedtuple
from PIL import Image, ImageEnhance
from net_image_cache import ImageCache
from config_util import read_config_json
"""
contents of config.json enabling a 128x128 LCD display
if "lc... |
from fabric.api import sudo
from fabtools import require
from appconfig import APPS
from appconfig.config import App
def require_certbot():
require.deb.package('software-properties-common')
require.deb.ppa('ppa:certbot/certbot')
require.deb.package('python-certbot-nginx')
def require_cert(domain):
... |
import numpy as np
import scipy as sp
import matplotlib.pyplot as py
import random as rd
import math as m
ylim = 200
xlim = 200
def create_instance(n):
inst = [(0, 0)]
route = [0]
for i in range(n):
x = rd.randint(-xlim, xlim)
y = rd.randint(-ylim, ylim)
inst.append((x, y))
... |
from flask_wtf import Form
from flask_wtf.file import FileRequired, FileAllowed
from wtforms import StringField, TextAreaField, FileField, SelectField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length, Optional
from app import photos
class NewAlbumForm(Form):
title = StringField(u'标题... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from setuptools import setup, find_packages
from codecs import open
#get the readme file for the long description below--optional
with open('README.md', 'rb', encoding='utf-8') as f:
readme = f.read()
# see https://github.com/pypa/samplepro... |
from .fetal_net import fetal_envelope_model
from .fetal_net_skip import fetal_origin_model
from .fetal_net_skip2 import fetal_origin2_model
from .fetal_net_skip3 import fetal_origin3_model
from .unet.unet import unet_model_2d
from .unet.isensee import isensee2017_model
from .unet3d.unet import unet_model_3d
from .une... |
import configparser
import os.path
class CurtisConfig:
CONFIG_PATHS = [
'./curtis.ini',
'~/.curtis.ini',
]
DEFAULT_TIMEOUT = 10
SITE_PREFIX = 'site:'
def __init__(self, config_file=None, site=None):
self.parser = configparser.ConfigParser()
self.parser.add_section(... |
ee=int(input())
fl=0
if ee>2:
for i in range(3,int(ee/2)):
if ee%i==0:
fl=1
print("no")
break
if fl==0 or ee==2:
print("yes")
|
from gensim.models import word2vec
import csv
#import pandas as pd
import os
# word2vec_kadai.pyにより作成されたモデルを読み込み
model = word2vec.Word2Vec.load("./training.model")
# [テスト用]指定単語の類似度Top10を表示
# results = model.wv.most_similar(positive=['AI'])
# for result in results:
# print(result)
# 課題で指定された50単語及びターゲットの5単語をリストに格納
... |
t = int(input())
while t:
t -= 1
a, b, n = [int(x) for x in input().split()]
if(a>=0 and b>= 0):
if(a>b):
print(1)
elif(b>a):
print(2)
else:
print(0)
else:
if(n%2 == 0):
if(abs(a)>abs(b)):
print(1)
elif(abs(a)<abs(b)):
print(2)
else:
print(0)
else:
if(a... |
"""Create the input data pipeline using `tf.data`"""
import tensorflow as tf
import numpy as np
#
def _parse_function(data_index, label, alldata):
"""Obtain the image from the filename (for both training and validation).
The following operations are applied:
- Decode the image from jpeg format
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
p1 = head
p2 = head
# ... |
import pandas as pd
import numpy as np
# Classe ReadData
# Recebe o caminho do arquivo csv já agrupado
# Retorna a base de dados discretizada, as informações da discretização e um frame de cada grupo
def read_csv(path):
bd = pd.read_csv(path,sep=',',parse_dates=True)
return bd
# separador_grupos - Método para divi... |
from django.conf.urls import url
from django.urls import path
from apicontent import views
from django.conf.urls.static import static
from django.conf import settings
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('login', obtain_auth_token, name = "login"),
url(r'^file/savefile$'... |
import numpy as np
import matplotlib.pyplot as plt
def getvals(zmin):
folder = 'distributions'
name1 = 'KiDS_2017-05-26_deepspecz_photoz_10th_BLIND_specweight_1000_4_ZB'
name2 = '_rlim_percentile'
name3 = '_blindB_Nz.asc'
zmin = np.round(zmin,1)
zmax = zmin+0.2
if(zmin==0.9):
zmax =... |
import os
import json
import falcon
class HelloResource(object):
def on_get(self, req, res):
res.status = falcon.HTTP_200
res.body = json.dumps({
'message': "hello!"
})
class TestVariableResource(object):
def on_get(self, req, res):
res.status = falcon.HTTP_20... |
#! / usr / bin / python
print ( "Hola, buen dia hace")
|
#from flask_login import UserMixin
from db import get_db
#class Friend(UserMixin):
class Friend():
def __init__(self, id_, user_id, friend_user_id):
self.friend_id = id_
self.user_id = user_id
self.friend_user_id = friend_user_id
@staticmethod
def get(friend_id):
db = get_... |
import sys
import json
scores = {}
'''
load sentiments file into dictionary
'''
def load_sentiment_file():
sent_file = open(sys.argv[1])
#'AFINN-111.txt')
for line in sent_file:
term, score = line.split("\t")
scores[term] = int(score)
'''
Derive the sentiment score for each... |
import json
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
fro... |
n = 1
c = 0
for _ in range(5):
A = input()
if A.find('FBI') != -1:
c = 1
print(n, end=' ')
n += 1
if c == 0:
print("HE GOT AWAY!")
# Done
|
import sys
import os
import time
import datetime
import hashlib #import hashlib.md5() as md5()
import http.client
import urllib, urllib.request, time
from io import StringIO #真是改的心力交瘁啊哭哭。
#raise except print>> 的写法3里均有改变。
#unichr——chr
__version__ = '0.5.0'
__url__ = 'http://code.google.com/p/pydelicious/'... |
#!/usr/bin/env python
import gzip
from pipeline import *
import util
config = util.read_config('import')
log = util.config_logging(config)
table = 'area.area'
columns=('area', 'zip', 'po_name', 'geom')
filename = 'bayareadata.gz'
area = 'sfbayarea'
db = util.DB.from_config(config)
log.info('importing file %r to tab... |
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math
def Round(a):
return int(a+.5)
def init():
glClearColor(1.0,1.0,1.0,0.0)
glColor3f(1.0,0.0,0.0)
glPointSize(3.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0.0,600.0,0.0,600.0)
def readinput():
glo... |
from app.models.models import db
|
#!/usr/bin/env python
"""
This program finds the location of each HELIX in a PDB file.
(For each helix, it prints out the starting and ending residue
using a format which is recognized by the "select_interval.py" script.
That script is typically used for extracting excerpts of a PDB file.)
This script is not really ... |
#!/usr/bin/env python
import random
from typing import Any
RULES = {'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper'}
def relationship_builder(user_option: list, chosen_option: Any):
index_of_chosen = user_option.index(chosen_option)
if chosen_option != user_option[-1]:
new_l... |
from scipy.integrate import ode,odeint
import numpy as np
import matplotlib.pyplot as plt
import time
import sys
import inspect, os
#import progressbar
from progbar import *
pool_count=12
#params
Nrun1=2000 # total run count
stamp_versions() # stamps the versions of Scipy, Numpy, GCC, current file name and directory... |
# -*- coding: utf-8 -*-
"""
@author: Stephanie McCumsey
CIS 472 WINTER 2015
Naive Bayes
./nb <train> <test> <beta> <model>
the input I use to test : "run nb.py spambase-train.csv spambase-test.csv 1 nb.model"
"""
from __future__ import division
import sys
import pandas as pd
import numpy as np
import pdb
import m... |
"""
N-gram model
"""
class NGramTrie:
def __init__(self, n_gram_size: int, encoded_text: tuple):
self.size = n_gram_size
self.encoded_text = encoded_text
self.n_grams = ()
self.n_gram_frequencies = {}
self.uni_grams = {}
self._fill_n_grams()
self._calculate_... |
import logging
import json
import os
import paho.mqtt.subscribe as subscribe
import paho.mqtt.publish as publish
import RPi.GPIO as gpio
switch_name = os.getenv('SWITCH_NAME', 'test01')
host = os.getenv('MQTT_HOST', 'nas.home')
pin = int(os.getenv('GPIO_PIN', '40'))
invert_logic = False if os.getenv('INVERT_LOGIC', '... |
import os
from flask import Flask, request, jsonify, url_for, Blueprint, Response
# from flask_dotenv import DotEnv
# from flask_sqlalchemy import SQLAlchemy
# from flask_migrate import Migrate
from flask_swagger import swagger
from flask_cors import CORS
# from api.user.model import db,User
app = Flask(__name__)
# a... |
# -*- coding: utf-8 -*-
while True:
year=int(input())
if year==-9999:
break
elif (year%4==0)or (year%100!=0 and year%400==0):
print(year,"is a leap year.")
else:
print(year,"is not a leap year.")
|
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print("you have %d cheeses!" % cheese_count)
print("have %d boxes of bcrackers" % boxes_of_crackers)
print("aha!")
print("we can blabla:")
cheese_and_crackers(20,30)
print("\nwe can blabla:")
amount_of_cheese = 10
amount_of_crackers = 15
c... |
import re, datetime, json, tempfile
from pathlib import Path
class Settings:
filename = None
settings = {}
def __init__(self, json_file:str=None) -> None:
if json_file is not None:
Settings.filename = json_file
self.load(json_file)
def __str__(self) -> st... |
"""Demo 類別的範例。
這個模組示範文件字串的寫法。"""
#類別的註解。
class Demo:
"""類別的文件字串。"""
# __init__() 的註解。
def __init__(self, v1=11, v2=22):
""" __init__() 的文件字串。"""
self.__a = v1
self.__b = v2
# 方法的註解。
def do_something(self):
"""方法的文件字串。"""
return self.__a + self.__b
if __name__ == "__main__":
d = Demo... |
# Implementation of mergesort
# Divide and conquer ~ O(n log n)
def mergesort(array):
if len(array) == 1:
return array
# split array into left and right
split = int(len(array)/2)
left = array[:split]
right = array[split:]
return merge(
mergesort(left),
mergesor... |
#!/usr/bin/env python
import sys,os
from PIL import Image
image=Image.open(sys.argv[1])
if image.width&7: raise Exception("%s: Width must be multiple of 8 (have %d)"%(sys.argv[1],image.width))
data=image.getdata()
frames=[] # each is an array of bytes, byte is one 8-pixel row
def read_row(x,y):
"""Read 8 pixels st... |
# author:lyr time:2019-10-17
# from random import randint#随机数包
# print(randint(0,1))
class Tigter:
def rora(self):
print('父类t属性')
@staticmethod
def tell():
print('父类t静态属性')
class Tigter2:
def rora(self):
print('父类t2属性')
@staticmethod
def tell():
print('父类t2静态属性')
... |
# -*- coding: utf-8 -*-
from discord import Member
from .converters import add_converter
from .converters import ConverterError
from .utils import get_member
# some converters for base types
# noinspection PyUnusedLocal
@add_converter(str)
def convert_str(arg, ctx):
return arg
# noinspection PyUnusedLocal
@add... |
vv=input()
print(len(vv))
|
import os
import sys
import unittest
import test_configmgr
import test_pluginmgr
import test_baseimager
import test_msger
import test_runner
import test_chroot
if os.getuid() != 0:
raise SystemExit("Root permission is needed")
suite = unittest.TestSuite()
suite.addTests(test_pluginmgr.suite())
suite.addTests(test... |
fname = input("Enter the file name: ")
fhandle = open(fname)
# creating a dictionary to count sender
sender = dict()
for line in fhandle:
line = line.strip()
# count the second word if the line starts with 'From'
if line.startswith('From '):
words = line.split()
address = words(1)
s... |
string = 'Monty Python'
print(string[0:5])
print(string[6:12])
fruit = 'banana'
print(fruit[:3])
print(fruit[3:])
print(fruit[3:3])
print(fruit[:])
|
"""toc builder.
toc builder has business logic.
"""
import typing
class TOCBuilder:
"""TOC Builder class.
TOCBuilder is a class for main process.
"""
HEADER_CHAR = "#"
ITEM_CHAR = "* "
ITEM_INDENT = " "
SECTION_JOINT = "-"
SECTION_PREFIX = "sec"
CODE_BLOCK_CHAR = "```"
... |
import mysql.connector
import datos_db
conexion = mysql.connector.connect(**datos_db.dbConnect)
cursor = conexion.cursor()
sql = "update usuarios set clave = 'solgty780' where id = 27"
cursor.execute(sql)
'''n_id = int(input("Id: "))
clave = input("Clave usuario: ")
sql = "update usuarios set clave = %s where id = ... |
from .flow_interface import FlowInterface
from synonym_dict import SynonymSet
class Flow(FlowInterface):
"""
A partly-abstract class that implements the flow specification but not the entity specification.
"""
_context = ()
_context_set_level = 0
_filt = str.maketrans('\u00b4\u00a0\u2032', ... |
import curses
import random
import time
def update(win_col, k, player):
if k == ord("a") and player[2] >= 1:
player[2] -= 1
if k == ord("d") and player[2] <= win_col:
player[2] += 1
if k == ord("s"):
player[3] = True
return player
def draw_man(win, chances):
parts = [(3,2... |
import numpy as np
def to_class_lables(score_list,number_of_classes):
lables = ['A','B','C','D','E','F','G','H','I','J','K']
matching_scores_to_lables = [[], [], [], [], [], [], [], [], [], [], []]
rounded_score_list = [round(x) for x in score_list]
class_labels=[]
if number_of_classes == 11:
all_possible_sc... |
import numpy as np
import matplotlib.pyplot as plt
import sys
np.random.seed(42)
def init_config(m,init_type='zero',bc='nonperiodic'):
ret = np.zeros((m,m))
if init_type == 'zero':
pass
elif init_type == 'full':
if bc == 'nonperiodic':
ret[::2,::2] = np.ones((m/2,m/2))
ret[1::2,1::2] = np.ones((m/2,m/2))... |
from py4j.java_gateway import JavaGateway
class Token:
def __init__(self, conll):
# CoNLL-U Format
# https://universaldependencies.org/format.html
# id, form, lemma, uPOSTag, xPOSTag, feats, head, depRel, deps, misc
conll = conll.split("\t")
self.id = conll[0]
self.f... |
###############################################################################
######## Retrieval of candidate neologisms ending with -age from frWaC ########
###############################################################################
## Before running the script, we need a list extracted from NoSketchEngine ... |
'''Select files to be edited in Vim from Git repository data'''
# Copyright (c) 2013-2016 Benjamin Althues <benjamin@babab.nl>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice... |
from random import random, randint
from django.core.management import BaseCommand
from faker import Faker, providers
from blog.models import *
CATEGORIE = ['Art', 'Animals', 'Clothing', 'Dairy Products', 'Drinks', 'Emotions', 'Foods', 'Fruits','Furniture', 'Insects',
'Jobs', 'Kitchen', 'Tools', 'Meats',... |
import threading
import multiprocessing
import subprocess
import time
import inspect
from ha_engine import ha_parser
from ha_engine import ha_infra
import os
import signal
import sys
LOG = ha_infra.ha_logging(__name__)
class HAExecutor(object):
def __init__(self, parser):
"""
Get the resource for... |
def fib_digit(n):
if n <= 2:
return 1
else:
a = 1
b = 1
res = 0
for i in range(3, n + 1):
res = (a + b) % 10
a = b
b = res
return res
print(fib_digit(317457))
|
'''
Ошибки - это когда вы налажали.
Неправильное использование конструкций языка.
Исключение - это когда налажали НЕ вы.
Код написан правильно, но пользуются
ей неправильно.
if 2 + 3 = 5
print('DA') <- ошибка = вместо == и не стоит : в конце условия
a = int(input('Введите целое число: '))
5.6 <- исключение
'''
... |
import requests
try:
import simplejson as json
except ImportError:
import json
import sys
import logging
log = logging.getLogger(__name__)
class BzAPI(object):
def __init__(self, api,
username=None, password=None):
self.api = api
self.username = username
self.password =... |
from collections import defaultdict
junks = defaultdict(int)
key_materials = {
'shards': 0,
'fragments': 0,
'motes': 0
}
collected = ''
while collected == '':
data = input().lower().split()
for index in range(0, len(data), 2):
quantity = int(data[index])
material = data[index + 1]
... |
# Generated by Django 2.2 on 2020-11-21 20:50
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CoffeeShop',
fields=[
('id', models.AutoField... |
# 进程》线程〉协程
# 创建进程
'''
首先:导入创建进程的函数
from multiprocessing import Process
process = Process(target = 函数, name=进程的名字, agres(给函数传递的参数
process 对象
对象调用的方法
process.start() 启动进程并执行任务
process.run() 只执行了任务,没有启动进程
terminate()终止
'''
from multiprocessing import Process
from time import sleep
import os
m = 1
def task1(s):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.