text stringlengths 38 1.54M |
|---|
# Generated by Django 2.0 on 2017-12-20 06:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mainboard', '0020_receivingadvice'),
]
operations = [
migrations.CreateModel(
name='ReceivingAdvi... |
from models.GenericModel import GenericModel
from collections import OrderedDict
class TipoRenda(GenericModel):
def __init__(self, id = None, desc = None, auto = None):
self.id = id
self.desc = desc
self.auto = auto
def setMonth(self, month):
pass
def __str__(self):
... |
'''
考试题目1
题目内容:
输入一组不同食材的名字,用“,”分割,请输出它们可能组成的所有菜式名称。
输入格式:
食材1, 食材2, 食材3
输出格式:(注意:输出列表请按照用户输入食材顺序开始排列,例如:优先输出食材1开头的菜品)
食材1食材2
食材1食材3
食材2食材1
食材2食材3
食材3食材1
食材3食材2
输入样例:
西红柿, 花椰菜
输出样例:
西红柿花椰菜
花椰菜西红柿
'''
food = str(input())
food = food.replace(' ','')
foodlist = food.split(',')
for i in foodlist:
new_food_list ... |
from django.db import models
class Level(models.Model):
options = (
('I', 'Image'),
('NI', 'Not Image')
)
level = models.IntegerField(default=1)
answer = models.TextField()
source_hint = models.TextField(blank=True, null=True)
level_file = models.FileField(upload_to='level_ima... |
from collections import OrderedDict
import logging
import os
from subprocess import Popen, PIPE
import warnings
import parmed.unit as units
from intermol.utils import run_subprocess, which
from intermol.lammps.lammps_parser import load, save
# Python 2/3 compatibility.
try:
FileNotFoundError
except NameError:
... |
import torch
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
from Module.style_transfer_model import StyleTransferModel
from StyleTransferSample.style_transfer_dataset import StyleTransferSample
style_path = 'Data/Style_samples/cubic-picasso2.jpg'
content_path = 'Data/Content_samples/ayma... |
from sqlalchemy import Table
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Float
from sqlalchemy import String
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqla... |
#This file was created by Tate Hagan
def validateTle(tlefile):
valid = False
if(checktle(tlefile)):
valid = True
if(checkthreele(tlefile)):
valid = True
return valid
def checktle(tlefile):
valid = True
with open(tlefile) as file:
line = file.readline(... |
import pandas as pd
import csv
from PyQt5 import QtCore
from PyQt5.QtWidgets import QTableView, QFileDialog
from PyQt5.QtCore import Qt, QAbstractTableModel
class PandasModel(QAbstractTableModel):
def __init__(self, data, parent=None):
try:
QAbstractTableModel.__init__(self, parent)
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'E:\MHW-EPV-Editor\resources\SplashScreen.ui'
#
# Created by: PyQt5 UI code generator 5.7.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, D... |
import sys
n = int(sys.stdin.readline())
TB = 0
LR = 0
for _ in range(0, n):
T, B, L, R = list(map(int, list(sys.stdin.readline().split('\n')[0])))
TB += abs(T-1) + abs(B-1)
LR += abs(L-1) + abs(R-1)
swords = min(TB // 2, LR // 2)
v_left = TB - swords * 2
h_left = LR - swords * 2
print("{0} {1}... |
#!/usr/bin/env python3
import os
import sys
import subprocess
def run_cmd(cmd, stderr=None, stdout=None):
if cmd[0] == "git":
ret = subprocess.Popen(cmd, env=None, cwd=None, stderr=None, stdout=subprocess.PIPE)
else:
ret = subprocess.Popen(cmd, env=None, cwd=None, stderr=None, stdout=subprocess.PIPE)
ret.wait(... |
"""
owtf.models.email_confirmation
~~~~~~~~~~~~~~~~~~~~~~
"""
from sqlalchemy import Column, Integer, Unicode, ForeignKey, DateTime
from owtf.db.model_base import Model
class EmailConfirmation(Model):
__tablename__ = "email_confirmation"
id = Column(Integer, primary_key=True, autoincrement=True)
key_val... |
import random
import sys
import datetime
import itertools
import time
class MySensor:
def __iter__(self):
return self
def __next__(self):
return random.random()
sensor = MySensor()
dt = iter(datetime.datetime.now, None)
for s,d in itertools.islice(zip(dt, sensor), 10):
print(d,s)
... |
import primality
from itertools import *
N = 1000
primes = primality.primes(N)
nums = [False,]*N
nums[1] = 1,
for p in primes:
if p > N:
break
basket = [False,]*N
n = 1
while p**n < N:
for c in ifilter(lambda x: x, nums):
getvalue = lambda parts : reduce(lambda acc, part: a... |
"""Support for DD-WRT devices."""
from functools import partial
import logging
import voluptuous as vol
from datetime import (
datetime,
timedelta,
)
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_FRIENDLY_NAME,
ATTR_NAME,
CONF_HOST,
CONF_NAME,
CONF_SCAN_INTERVAL,
CONF_US... |
from pylab import *
#================================================================================
#================================================================================
def signif_nums(x,n,to, **kwargs):
""" find the n first significant number of x
inputs : x : number to work with
... |
"""
Zaimplementuj klasę Employee umożliwiającą rejestrowanie czasu pracy
oraz wypłacanie pensji na podstawie zadanej stawki godzinowej.
Jeżeli pracownik będzie pracował więcej niż 8 godzin
(podczas pojedynczej rejestracji czasu) to kolejne godziny
policz jako nadgodziny (z podwójną stawką godzinową).
Przykład użycia:
... |
#program to find average of two numbers.
a=int(input('enter first number'))
b=int(input('enter second number'))
c=int(input('enter third number'))
d=(a+b+c)/3
print('the average of three numbers is',format(d,'2f'))
|
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="mongodump-s3",
version="1.1.2",
description="Backup utility f... |
import pytest
from python_examples import *
my_list = [1, 3, 5, 7, 9]
unordered_list = [3, 4, 2, 1, 4, 7]
def test_binary_search_3():
assert binary_search(my_list, 3) == 1
def test_binary_search_9():
assert binary_search(my_list, 9) == 4
def test_find_smallest():
assert find_smallest(unordered_list) ... |
import wpilib
import wpilib.drive
import ctre
#Shriaynsh!
class Robot5511(wpilib.IterativeRobot):
def robotInit(self):
self.Tleft = ctre.WPI_TalonSRX(10)
self.Vleft1 = ctre.WPI_VictorSPX(11)
self.Vleft2 = ctre.WPI_VictorSPX(12)
self.Vleft1.set(ctre.WPI_VictorSPX.ControlMode.Follower... |
# Given an array of integers, every element appears twice except for one. Find
# that single one.
#
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement
# it without using extra memory?
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber0(sel... |
"""
File that defined all the serializer used in our API
See http://www.django-rest-framework.org/api-guide/serializers/
See http://www.django-rest-framework.org/api-guide/fields/
See http://www.django-rest-framework.org/api-guide/relations/
"""
from rest_framework import serializers
from project.models import *
from ... |
#!/usr/bin/env python
import sys
import os
import getopt
import re
import json
import pprint
import time
os.environ["BOTO_CONFIG"] = os.environ["HOME"] + "/.aws/config"
from boto import cloudformation
'''
Debug function
'''
DEBUG = 0
VERSION = '1.3.2'
NAME = 'query_stack'
def debug(str):
if DEBUG ==... |
import time
while True:
import random
print('\n1- Rock ')
time.sleep(0.5)
print('2- Paper')
time.sleep(0.5)
print('3- Scissors')
time.sleep(0.5)
random=random.randint(1,3)
player=int(input('choose rock(1),paper(2),scissors(3) :'))
Computer=(random)
while playe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-03 10:48
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
import mesa.models
class Migration(migrations.Migration):
initial = True
depen... |
from __future__ import print_function
from distutils.dir_util import copy_tree
from jinja2 import Template
import os
import subprocess
import json
import boto3
import logging
import jinja2
import urllib
def lambda_handler(event, context):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
... |
import time
import asyncio
def coroutine_example(name):
print("start ... name:", name)
x = yield name
# time.sleep(5)
print("send :", x)
coro1 = coroutine_example("GYH1")
next(coro1)
coro2 = coroutine_example("GYH2")
next(coro2)
print('send的返回值:', coro1.send(1))
print('send的返回值:', coro2.send(2)) |
from django import forms
from django.contrib.humanize.templatetags.humanize import ordinal
from smartsearch.manager import SearchManager
from bill.models import Bill, BillTerm, TermType, BillType, BillStatus, USCSection, RelatedBill
from person.models import Person
from us import get_congress_dates
from settings impo... |
#-*-coding:utf-8-*-
from lxml import etree
html = etree.parse("./text.html" , etree.HTMLParser())
result = html.xpath("//*")
print(result)
result = html.xpath("//li")
print(result) |
import matplotlib.pyplot as plt
workernum = [1,5,10,15,20]
time = [20.776124715805054, 8.15129017829895, 8.448184967041016, 10.523062467575073, 9.342151880264282 ]
plt.plot(workernum, time)
plt.xlabel('Worker numbers')
plt.ylabel('Time(s)')
plt.show() |
import json
from difflib import get_close_matches
def translate(word):
word=word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys())) > 0 :
yn=input("Did u mean %s instead? Enter Y for Yes and N for No" % get_close_matches(word,data.keys())[0])
... |
import socket
'''tcp套接字客户端程序
要求:客户端中端输入不断发送消息,不输入结束运行
'''
#1:创建套接字
sockfd =socket.socket(socket.AF_INET,socket.SOCK_STREAM) #参数可不写,为默认
#2:请求连接
sockfd.connect(('10.16.129.97',7777)) #需要注意Ipv4地址不同
#3:收发消息
while True:
message= input("comeClienMessage:")
if not message:
break
sockfd.send(m... |
from buildingblocks.rtl import uart
uart.convert.tx()
uart.convert.rx()
files = [
"uart_tx.v",
"uart_rx.v"
]
|
"""
LRU 缓存机制
链接:https://leetcode-cn.com/problems/lru-cache
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。
当缓存容量达到上限时,它应该在写入新数据之前删除最久未使... |
from django.core.mail import EmailMessage
import datetime
import threading
class EmailThread(threading.Thread):
def __init__(self, email):
self.email = email
threading.Thread.__init__(self)
def run(self):
self.email.send()
class Util:
@staticmethod
def send_email(data):
... |
import numpy as np
RUNS = 20
OUTPUTS = 10
def get_measures(csv_array, filename):
# Separate into two different lists according to the direction
dir_one_list = filter(lambda x: x[3] == 1, csv_array)
dir_minus_one_list = filter(lambda x: x[3] == -1, csv_array)
# Calculate the rate for each of the lists... |
from concurrent.futures import ThreadPoolExecutor, as_completed
import datetime
def make_parallel(single_func, THREAD_COUNT=5):
# This function will wrap another function
# (similar to a decorator, but we don't want to overwrite the original)
# e.g. parallel_func = make_parallel(singleton_func)
# sin... |
# Keyless
plain=input('Enter Plain text : ')
n=int(input('Enter no. of rows : '))
cipher=''
decipher=''
for i in range(n):
x=0
while (i+(x*n))<len(plain):
cipher+=(plain[i+(x*n)])
x+=1
print('Ciphered Text is : '+cipher)
for i in range(len(cipher)//n):
x=0
while (i+x*(... |
from collections import defaultdict , deque
from sys import stdin , stdout
import math , heapq
listin = lambda: list(map(int,input().split()))
mapin = lambda: map(int,input().split())
def getWaitTime(process,n,wt):
wt[0] = 0
for i in range(1,n):
wt[i] = process[i-1][1] + wt[i-1]
def getTAT(process,n,w... |
import pygame
from pygame.mixer import Sound
import random
import time
import sys
import os
pygame.init()
from pygame.mixer import Sound
clock = pygame.time.Clock()
WIDTH = 450
HEIGHT = 450
pygame.display.set_caption("jeu de tire")
screen = pygame.display.set_mode((WIDTH, HEIGHT))
bg = pygame.image.load("C:/Users/jea... |
import requests
import json
from collections import namedtuple
from recordtype import recordtype
from bs4 import BeautifulSoup
key = 'RGAPI-fbe2dda4-170d-48fe-8151-00002d5eb332'
champion = namedtuple("champion", 'name, id')
item = namedtuple("item", 'name, id, cost')
summoner = namedtuple("summoner", 'name,... |
import collections
class Solution(object):
def minSlidingWindow(self, nums, k):
if nums == None or len(nums)==0:
return []
size = len(nums)
queue = collections.deque()
res = []
for i in xrange(0, size):
if len(queue) and queue[0]==i-k:
queue.popleft()
while len(queue) and nums[queu... |
from base import JiraBaseAction
class JiraIncompletedissuesestimatesum(JiraBaseAction):
def _run(self, board_id, sprint_id):
return self.jira.incompletedIssuesEstimateSum(board_id, sprint_id)
|
n, m, q = map(int, input().split())
x = [[] for _ in range(n)]
p = [n for _ in range(m)]
for i in range(q):
s = list(map(int, input().split()))
if s[0] == 1:
ni = s[1]
ans = 0
for k in x[ni - 1]:
ans += p[k]
print(ans)
else:
_, ni, mi = s
... |
def writeTextToFile(file_path:str, text:str)->int:
file=None
try:
file=open(file_path,"w")
return file.write(text)
except OSError:
print(f"Error! the file can't write in this path {file_path}")
finally:
if file!= None:
file.close()
# Test program
fileName="m... |
# mtcli
# Copyright 2023 Valmir França da Silva
# http://github.com/vfranca
import csv
# Função para extrair os dados do arquivo CSV
def get_data(csv_file):
"""Importa dados do arquivo CSV."""
# Lista para armazenar as linhas do CSV
data = []
# Extrai os dados do CSV para popular a lista
with open... |
import unittest
from moytokenizer import Tokenizer
from search_engine import SearchEngine
class Test(unittest.TestCase):
def setUp(self):
self.Tokenizer = Tokenizer()
# unittest for method tokenize
def test_type_output(self):
result = self.Tokenizer.tokenize('text')
... |
import pytest
import tasks
from tasks import Task
def test_add_returns_valid_id(init_tasks_db):
"""tasks.add()(<valid task>) should return an integer. """
# GIVEN an initialized tasks db
# WHEN a new task is added
# THEN returned task_id is of type int
new_task = Task('do something')
task_id =... |
met_range = (0,2000, True)
# title, scale, rebin, usrrng
settings = {
# 'h_htcheck':('', 1,1, (0,2000)),
# 'h_htbprimemass':('', None, None, None),
# 'h_ht_presel' : ('H_{T} (GeV)', 10, 5, (1200,2000)),
# 'h_nfatjet_opt' : ("AK8 jets multiplicity", 10, 1, None),
# 'h_nGoodPV' ... |
# ¿En que se basan las sentencias de control de flujo?
# print ('¿Quieres acabar con el mundo?\n')
# .-Sentencias if
# if condicionante:
# sentencias
# .-Sentencias else
# .-Ejemplo donde se muestre un ejemplo y combinación con operadores lógicos
# inputUser = input()
# if inputUser == 'yes' or inputUser == 'y':
... |
import cv2
from matplotlib import pyplot as plt
airbus = cv2.imread('./images/cojinetes.bmp', cv2.IMREAD_GRAYSCALE)
airbus_th, airbus_bin = cv2.threshold(airbus, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
perritos = cv2.imread('./images/perritos.jpg', cv2.IMREAD_GRAYSCALE)
perritos_th, perritos_bin = cv2.threshold(pe... |
from typing import List
import collections
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
res = 0
while target:
tmp = min(target)
res += tmp
nxt_target = []
for t in target:
if t - tmp == 0: continue
... |
from operationscore.SmootCoreObject import *
import util.TimeOps as timeOps
import random
"""
Simulates a motion sensor:
DetectionRange
DetectionProbability
RefactoryTime
DataHook
Location
"""
class MotionSensorSimulator(SmootCoreObject):
def init(self):
#defaults:
if not self['R... |
#!/usr/bin/python2.7
# coding=utf-8
#
# Copyright 2011 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
# Vasallius
# Import necessary modules
import ezsheets
import os
# Load the spreadsheet
spreadsheet_id = input("Enter id of spreadsheet to be uploaded ex:(1SZq-wSN_iWuOZENRrNfD_YcbK95p2mHCcw9WBeLSbmQ): ")
ss = ezsheets.Spreadsheet(spreadsheet_id)
# Download files
print("Downloading as excel file...")
ss.downloadAsEx... |
from ch.systemsx.cisd.openbis.generic.shared.api.v1.dto import SearchCriteria
def process(tr, parameters, tableBuilder):
ids = parameters.get("identifiers")
search_service = tr.getSearchService()
expCodes = []
if "Experiment" in parameters:
print "preparing experiment update"
for exp in search_service.... |
import sys
from itertools import combinations
[N, P, E] = map(int, sys.stdin.readline().split())
peoples = [i for i in range(N)]
combs = []
for comb in list(combinations(peoples, P)):
combs.append(comb)
peopleDolls = []
for _ in range(N):
data = sys.stdin.readline().split()
peopleDolls.append({'min': in... |
from logging import getLogger
logger = getLogger('chime.publish.functions')
from urlparse import urlparse
from zipfile import ZipFile, ZIP_DEFLATED
from os.path import dirname, basename, join, exists, relpath
from tempfile import mkdtemp
from shutil import rmtree
from io import BytesIO
from os import walk
from reques... |
## Incomplete
def rob(nums):
if len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
elif len(nums) == 2:
return max(nums[0], nums[1])
else:
curr = 0
prev = 0
for i in range(len(nums)):
curr, prev = prev, max(curr + nums[i], prev)
... |
import time
import csv
import sys
import requests, json
def tell_joke(prompt, punchline):
""" A function that delivers jokes """
print(prompt)
#wait 2 seconds
time.sleep(2)
print(punchline)
def read_input():
""" A function that reads user input """
user_input = input("Type 'next' to hear a... |
API_key = "XlXK5MDAZTmll9dQlfICERhJG"
API_secret_key = "Ymv25hjsbJcZQmzXlA9FtLPes9yC1FmKesftuvxodGybTfx29m"
access_token = "1308059699141513216-070MAPs01OzvYM4y1uF5e7K5K65wp4"
access_token_secret = "gMB1oOEvjYMZYUM94qDmxYTMPdkpuM7z1nqzieGrZtfLR"
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 12:28:48 2018
@author: 612383249
"""
#Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10.
#
#
#makes10(9, 10) → True
#makes10(9, 9) → False
#makes10(1, 9) → True
def makes10 (a, b):
return sum_10(a, b) or is_10(a, b)
def sum_10 (a, b)... |
# importing libraries
import requests, logging
from time import sleep
from dbActions import dbSaver
from prettytable import PrettyTable
from bs4 import BeautifulSoup as bs
# class for parsing and generate table
class GenerateTable:
# A function that initially writes parameters to the self.table
# variable i... |
# coding: utf-8
from django.db import models
from django.contrib.auth.models import User
from jobs.models import Job
from feed.models import Feed
from Brick.App.my_resume.models import Resume
class Chat(models.Model):
CHAT_META = (
('job', '职位卡片'),
('feed', '定制'),
)
job_hunter = models.... |
import django
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from distutils.version import StrictVersion
class UserSetting(models.Model):
TYPE_STRING = "string"
TYPE_NUMBER = "number"
TYPE_BOOL = "bool"
TYPE_JSON = "json"
TYPE... |
# -*- coding: utf-8 -*-
from openerp import api, exceptions, fields, models, _
class VehicleConfig(models.Model):
_name = 'vehicle.config'
_description = 'Vehicle Configuration'
vehicle_id = fields.Many2one(
comodel_name='product.product', string='Vehicle Number',
help='Add Vehicle', dom... |
from .forms import FileUploadForm
from .models import BackgroundFile
from users.models import UserProfile
from . import background_utility
import os
from django.core.files import File
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_requi... |
from contexteval.contextualizers import * # noqa: F401,F403
from contexteval.data import * # noqa: F401,F403
from contexteval.models import * # noqa: F401,F403
from contexteval.predictors import * # noqa: F401,F403
from contexteval.training import * # noqa: F401,F403
|
class FARule(object):
def __init__(s,state,char,next_state):
s.state=state
s.char=char
s.next_state=next_state
def is_applies(s,state,char):
return s.state==state and s.char==char
def follow(s):
return s.next_state
def __str__(s):
return str(s.state)+"--"+s.char+"-->"+str(s.next_state)
cla... |
#!/usr/env/bin python
import argparse
import functools
import logging
import multiprocessing
import os
import time
import types
import typing
from bert import \
utils as bert_utils, \
constants as bert_constants, \
encoders as bert_encoders, \
datasource as bert_datasource, \
aws as bert_aws
from... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: Nicholas Elia
# @date: Thu May 27 16:00:00 BST 2014
import bob
import os
from facereclib import utils
class Extractor:
"""This is the base class for all feature extractors.
It defines the minimum requirements that a derived feature extractor class... |
# Import the socket library
from struct import *
import socket
import binascii
# Host IP to listen to. If '' then all IPs in this interface
serverIP = '127.0.0.1'
# Port to listen to
serverPort = 1000
close = False
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serverSocket:
# Bind the socket
serv... |
# TCP Client (simple echo code in Python)
# Import socket module and system module
import socket
import sys
from PyQt5.QtCore import QThread, pyqtSignal
class Client(socket.socket):
def __init__(self):
super().__init__(socket.AF_INET, socket.SOCK_STREAM)
self.connect(('localhost', 8001))
... |
"""
License
Simplified BSD License
Copyright (c) 2016, Iro Laina
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of cond... |
from django.shortcuts import render
def welcome(request):
page = 'welcome.html'
args = {}
return render(request, page, args)
|
import numpy as np
def func_j(x):
return np.sin(x) / x
def dfunc_j(x):
return np.cos(x)/x - np.sin(x) / (x*x)
T = 50
x = 1
for t in range(T):
x -= func_j(x) / dfunc_j(x)
print(x)
print("final x")
print(x) |
def parse_input(input_):
result = input_.split(" ")
return result
def prompt_correct():
yes = set(['yes','y', 'ye', ''])
no = set(['no','n'])
while(1):
choice = input("Is this correct? [y]/n: ").lower()
if choice in yes:
return True
elif choice in no:
return False
else:
print("Please respond... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
import json
import zabbix_mysql
import conn_oracle
# Create your views here.
@login_r... |
# -*- coding: utf-8 -*-
use_redislite = False
try:
import redislite
use_redislite = True
except ImportError:
import redis
import unittest
class RedisTestCase(unittest.TestCase):
db = 15
dbfilename = None
@classmethod
def setUpClass(cls):
# If we're using redislite spin up a redi... |
class Casa:
num_banos = 0
num_abitaciones = 0
def __init__(self, direccion):
self.direccion = direccion
def __repr__(self):
return f'Casa ubicada en {self.direccion}'
def __eq__(self, other):
return self.num_banos == other.num_banos and self.num_abitaciones == other.n... |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import pickle
import argparse
from torch.autograd import Variable
import torch.utils.data as data
from data import VOCroot, COCOroot, VOC, C... |
import requests
from env import DB_INFO
from django.utils.crypto import get_random_string
import uuid
def request_consumer_list():
# ret = requests.get(DB_INFO['host'] + ":" + str(DB_INFO['port']))
ret = requests.get(DB_INFO['host'])
if ret.status_code >= 500:
print(ret.text, ret.status_co... |
from collections import namedtuple
from numpy import array_equal
import numpy as np
from m260b.align.ukkonen import full_sw, banded_sw, _full_sw_matrix, _banded_sw_matrix
def test_full_and_banded_sw():
"""\
Test that full smith-waterman produces alignments that we would want.
If anything this has helped... |
import config
import json
from exceptions import InvalidMessageException
from received_messge import ReceivedMessage
class Callback(object):
def __init__(self, logger, pubsub_client, bigquery_client):
self._logger = logger
self._pubsub_client = pubsub_client
self._bigquery_client = bigque... |
import re
import string
import operation
import streetlib
import graph
re_cmd = r'^[acr][\ ]+'
re_street_name = r'"[a-zA-Z\ ]+"'
re_graph = r'^\ *g\ *$'
re_remove = r'^\ *r\ +"[a-zA-Z\ ]+"\ *$'
re_add_change = r'^\ *[ac]\ +"[a-zA-Z\ ]+"\ +(\(\ *\-?[0-9]+\ *,\ *\-?[0-9]+\ *\)\ *)+$'
re_point = r'\(\ *\-?[0-9]+\ *,\ *\... |
'''
최적화한 다익스트라
- 가장 크게 최적화된 부분: gates, summits를 set로 바꾼거... ㄷㄷ 엄청나게 최적화됨
- 그 다음은 1,2,3 번 조건문
'''
from collections import defaultdict
import heapq
def solution(n, paths, gates, summits):
INF = 987654321
answer = [INF, INF]
graph = defaultdict(lambda: defaultdict(int))
#list -> set
gates = set(gate... |
import sys
import os
def main():
i=1
diccionario={}
while(i<1000):
if(i<10):
archivo=open("mv_000000"+str(i)+".txt")
elif(i<100):
archivo=open("mv_00000"+str(i)+".txt")
elif(i<1000):
archivo=open("mv_0000"+str(i)+".txt")
lineas=archivo.readlines()
for linea in lineas:
datos=linea.split(",... |
import numpy as np
import matplotlib.pyplot as plt
def uniform_histogram_powers(sz, pow_1, pow_2):
lower_bound = 0.
upper_bound = 1.
sample = np.random.uniform(lower_bound, upper_bound, sz)
num_bins = 50
sample_1 = range(sz)
sample_2 = range(sz)
for k in range(sz):
sample_1[k] ... |
import tensorflow as tf
import os
from tensorflow.python.client import device_lib
from load.MainLoader import MainLoader
# os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
print(device_lib.list_local_devices())
size = 32
loader = MainLoader(size ,0.05)
base_dir ... |
# Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import subprocess
import re
import os
import errno
from distutils.version import LooseVersion
from chroma_agent.lib.shell import AgentShell
from chroma_agent.device_plug... |
import pymongo
import sys
import json
conn = pymongo.MongoClient("mongodb://localhost")
db = conn.students
col = db.grades
col.drop()
filepath = 'handouts/homework_2_1/grades.json'
with open(filepath,'rb') as f:
for line in f:
jsondoc = json.loads(line.replace('$oid','_id'))
col.insert(jsondoc)
... |
class Output:
_outFile = ["a_out.txt", "b_out.txt", "c_out.txt", "d_out.txt", "e_out.txt", "f_out.txt"]
_file = ""
def __init__(self, fileNbr):
self._file = "output/" + self._outFile[fileNbr]
with open(self._file, "w+") as file:
file.write('0\n')
def setIntersection(self, ... |
import csv
# s find algorithm
with open('data.csv','r') as f:
reader = csv.reader(f)
dlist = list(reader)
h = [['0','0','0','0','0','0']]
print("Data input is:")
for l in dlist:
print(l)
print("Training Data:")
for i in dlist:
if i[-1] == "True":
print(i)
j = 0
for x in i:
... |
from gcmd.components.options import OptionGroup
from gcmd.components.targets import TargetGroup
class Hook:
def __init__(self, name=None, config=None):
self.name = name
self.targets = TargetGroup(config=config)
self.options = OptionGroup(config=config)
|
from enum import Enum
from facebook_business.adobjects.campaign import Campaign
from Core.facebook.sdk_adapter.ad_objects.ad_set import DestinationType
from Core.facebook.sdk_adapter.catalog_models import Cat, cat_enum, Contexts
# TODO: add documentation link(s)
_special_ad_category = Campaign.SpecialAdCategories
... |
# Copyright 2020 Soil, Inc.
from soil.openstack.base import SourceBase
class Port(SourceBase):
"""A class for openstack port"""
def __init__(self, plugin, source_id):
super(Port, self).__init__(plugin, source_id)
def get_security_groups(self):
from soil.openstack.security_group impor... |
### Unique Paths III - Solution
class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
self.path_count, zero_count = 0, 1
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
x, y = i, j
if grid... |
# Generated by Django 2.1.7 on 2020-04-02 18:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.