text
stringlengths
8
6.05M
import numpy as np class DataScaler(): def __init__(self, nbytes = 2, signed=True): """ Initialize scaler for given byte-depth and signed data type Arguments: nbytes (int) : Number of bytes to scale data to signed (bool) : If set, signed integers are used, if False, unsigned """ s...
from api.resources import course_methods, question_methods, exam_methods, token_methods, token_validation, submission_methods, grade_methods from django.http import HttpResponseNotAllowed def course(request, course_id = None): if request.method == 'POST': return course_methods.create_course(request) el...
# -*- coding:utf-8 -*- from src.sentence_embedding.sentence_emb import UsableEncoder from sklearn.metrics.pairwise import cosine_similarity import numpy as np import jieba model_path = './saved_models/skip-best' dict_path = './data/wiki_clean_cn.txt.pkl' usable_encoder = UsableEncoder() stand_q_list = [] simi_q_lis...
from common.run_method import RunMethod import allure @allure.step("通用/消息通知/删除某则消息") def notices_noticeId_delete(noticeId, params=None, body=None, header=None, return_json=True, **kwargs): ''' :param: url地址后面的参数 :body: 请求体 :return_json: 是否返回json格式的响应(默认是) :header: 请求的header :host: 请求的环境 :...
"""Tests for the 'zero' plugin""" import unittest from test.helper import TestHelper, control_stdin from beets.library import Item from beetsplug.zero import ZeroPlugin from mediafile import MediaFile from beets.util import syspath class ZeroPluginTest(unittest.TestCase, TestHelper): def setUp(self): s...
# coding: utf-8 #CURRENCY CONVERTER #list of currency symbols s_currency=["0","XAF","ARS","AUD","BSD","BRL","BGN","CAD","CLP","CNY","COP","HRK","CYP","CZK","DKK","LTC","BTC","XCD","EEK","EUR","FJD","XPF","GHS","GTQ","HNL","HKD","HUF","ISK","INR","IDR","ILS","JMD","JPY","LVL","LTL","MYR","MXN","MAD","MMK","ANG","NZD",...
import numpy as np from scipy.linalg import expm, norm from skimage import color class RandomRotation: def __init__(self, axis=None, max_theta=180): self.axis = axis self.max_theta = max_theta def _M(self, axis, theta): return expm(np.cross(np.eye(3), axis / norm(axis) * theta)) ...
class LFSR(): def __init__(self, polyn): self.polyn = polyn[1:len(polyn)][::-1] def step(self): numb = 0 for _ in range(len(self.polyn)): if self.polyn[_] & self.state[_] == 1: numb ^= 1 self.state.append(numb) return self.state.pop(0) de...
"""miniportal URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home'...
""" These are search result related models. """ from dataclasses import dataclass, field from typing import Optional, List from .base import BaseModel from .common import BaseApiResponse, BaseResource, Thumbnails from .mixins import DatetimeTimeMixin @dataclass class SearchResultSnippet(BaseModel, DatetimeTimeMi...
# Generated by Django 2.2.4 on 2019-08-15 21:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('responses', '0003_auto_20190815_2113'), ] operations = [ migrations.RenameField( model_name='response', old_name='org_compar...
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("http://localhost:8081/ses/public/index.html") driver.find_element_by_xpath("//*[@id='login_form']/div[2]/div/input").send_keys("abc") driver.find_element_by_xpath("//*[@id='login_form']/div[3]/div/input").send_keys("123") driver.find_el...
#!/home/raymond/missing/bin/python # -*- coding: utf-8 -*- # # findDupes.py # # Copyright 2015 raymond import os import re import itertools import threading import time import guessit from operator import itemgetter from pytvdbapi import api import itertools import time import sys from pytvdbapi import api import...
"""ImageLocation class. ImageLocation is the pre-octree Image class's ChunkLocation. When we request that the ChunkLoader load a chunk, we use this ChunkLocation to identify the chunk we are requesting and once it's loaded. """ import numpy as np from napari.components.experimental.chunk import ChunkLocation, LayerRe...
import ast import socket import chatlib import random SERVER_IP = "127.0.0.1" SERVER_PORT = 5678 def build_and_send_message(conn, code, data): msg = chatlib.build_message(code, data) conn.send(msg.encode()) def recv_message_and_parse(conn): full_msg = conn.recv(1024).decode() cmd,...
import test13 from tornado.options import options, define def aaa(): print options.port print 12
#!/usr/bin/env python3 # -*- coding: utf-8 -*- x = abs(100) y = abs(-1e-7) print (x) print (y) print (x,y) summ = sum([1e-4,2,3]) print ('sum1,2,3=',summ)
from fnp.ml.token_classifier import TokenClassifier from fnp.ml.token_classifier_multihead import TokenClassifierMultiHead from argparse import ArgumentParser def classify_from_args(args): if args.classifier == "singlehead": classifier = TokenClassifier(args) else: classifier = TokenClassifie...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class UuidToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017615'...
from flask import Blueprint from flask import jsonify from shutil import copyfile, move from google.cloud import storage from google.cloud import bigquery from flask import request import dataflow_pipeline.ucc2.sms_beam as sms_beam import dataflow_pipeline.ucc2.sms_opc1_beam as sms_opc1_beam import dataflow_pipeline.u...
import numpy import argparse import patchbatch import glob import kittitool import pb_utils as utils def bench_kitti(images_path, GT_path, model_name, patch_size, batch_size): """ Used for easily benchmarking kitti, using kitti's file structure images_path - images path, with image pairs looking like: 0000...
class Hashtabell: def __init__(self, antalElement): self.h = {} def get(self, namn): return self.h[namn] def put(self, namn, nyAtom): self.h[namn] = nyAtom
from __future__ import division from __future__ import with_statement import json #or cjson import re from stemming.porter2 import stem from operator import itemgetter from math import log from collections import defaultdict import operator from Tkinter import * from PIL import Image, ImageTk from Tkinter import Tk, RI...
a = dict() #다음중 오류가 나는것은? a['name'] = 'python' #a[('a',)] = 'python' #a[[1]] = 'python' #a[250] = 'python' #a[[1]] 값은 변할수 있기때문에 사용 불가 print(a)
''' Created on Jul 10, 2013 @author: emma ''' from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0 from selenium.webdriver.common.action_chains import Action...
from django.db import models # Create your models here. class Event(models.Model): EVENT_TYPES = ( ("Race", "Race"), ("Training Session", "Training Session"), ) name = models.CharField(max_length=64) description = models.TextField() event_type = models.CharField(max_length=64, choic...
# @author: Bogdan Hlevca 2012 from numpy import zeros, array, prod, diagonal, dot from gaussElimin import * from gaussSeidel import * from thomas import * import timeit # Gauss Elimination test print "Gauss Elimination:" print "------------------" print "A = b = " print "8.0, 1.0, 6.0 1 " print "3.0...
from django.contrib.gis.db import models class WorldBorder(models.Model): # Regular Django fields corresponding to the attributes in the # world borders shapefile. name = models.CharField(max_length=50) area = models.IntegerField() pop2005 = models.IntegerField('Population 2005') fips = models.CharField('FIPS C...
""" Tests for thumbnails. """ import io from .base import BaseTestCase from pyyoutube.media import Media class TestThumbnailsResource(BaseTestCase): RESOURCE = "thumbnails" def test_set(self, authed_cli): video_id = "zxTVeyG1600" media = Media(fd=io.StringIO("jpeg content"), mimetype="im...
turmas = {} def adicionarTurma(): nome = str(input("Nome da turma: ")) alunos = {} turmas[nome] = alunos def adicionarAlunoNotas(): nomeTurma= str(input("Nome da turma:")) matricula=str(input("Matricula: ")) notas=[] mais = 'Sim' while (mais =='Sim'): nota = floa...
import tkinter from tkinter import filedialog import os from datetime import datetime today = datetime.now().date() print('today is ', today) directory = tkinter.filedialog.askdirectory() print(directory) os.chdir(directory) files = os.listdir(directory) for file in files: in_file = open(file, 'rb') image = ...
import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.graphics.api import qqplot import seaborn as sns %matplotlib df = sm.datasets.sunspots.load() dta = pd.DataFrame(df.data['SUNACTIVITY'], index = sm.tsa.datetools.dates_from_r...
#!/usr/bin/env python3 # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
from pymongo.cursor import Cursor from models import PostModel, UserModel import motor.motor_asyncio from dotenv import dotenv_values import os config = dotenv_values(".env") DATABASE_URI = config.get("DATABASE_URI") if os.getenv("DATABASE_URI"): DATABASE_URI = os.getenv("DATABASE_URI") client = motor.motor_asyncio.A...
from django.shortcuts import render from rest_framework.views import APIView from rest_framework import generics from .models import UserList, FileList from rest_framework.response import Response from .serailzers import UserListSerializer, UserListInfoSerializer, FileListInfoSerializer, FileListSerializer from django....
# Generated by Django 3.2.3 on 2021-06-02 05:03 import datetime import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
import contextlib import torch import torch.nn as nn import torch.nn.functional as F @contextlib.contextmanager def _disable_tracking_bn_stats(model): def switch_attr(m): if hasattr(m, "track_running_stats"): m.track_running_stats ^= True model.apply(switch_attr) yield model.appl...
import json # ToDO: Create users function # ToDo: Update user information function # class User(object): # User class created dynamically from JSON configuration def __init__(self, d): self.__dict__ = d class Config(object): def __init__(self): self._config = config # set it to conf ...
import translator from substitutiontranslator import * from .. import utils class VigenereTranslator(translator.Translator): """Adds perpetually key letters to text (Caesar with longer keys)""" def __init__(self, key="A", ignore_nonletters=True): self.key = key self.ignore_nonletters = ignore_nonletters def pa...
#only/just Monika from random import randint from time import sleep def main(): while True: x = randint(0, 1) if x == 1: writeLine("Just Monika") else: writeLine("Only Monika") def writeLine(string): for i in string: print(i, end='\r', flush=True) ...
from aws_cdk import ( core, aws_s3, aws_lambda, aws_apigateway, aws_iam ) class InfraStack(core.Stack): def __init__( self, scope: core.Construct, id: str, # env: core.Environment, **kwargs, ) -> None: super().__init__(scope, id, **kwargs) bucket = aws_s3.B...
# Name: Taidgh Murray # Student ID: 15315901 # File: triangle_area.py ############################################################################ import math def sides(): global a global b global c a=int(input("Please enter the first side: ")) b=int(input("Please enter the second side: ")) c=in...
# EXERCISE_9 WORK OF THE BOOK : for i in range(100): print(i,"Shivam")
# -*- coding: utf-8 -*- import sys import log from os import listdir from os.path import join, isfile, splitext JAVA_FILE_EXT = ".java" def get_root_path(): argv = sys.argv if len(argv) > 1: root_path = argv[1] else: root_path = argv[0] return root_path def is_java_file(file_pa...
import scapy.all as scapy import optparse def get_arg(): parser = optparse.OptionParser() parser.add_option("-t", "--target", dest="target", help="Target IP / IP range") (opt, arg) = parser.parse_args() return opt def scan(ip): arp_req = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:...
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from rabbitmq import RabbitMQ import time import sys def callback(ch, method, properties, body): print(" [x] Received %r" % body) def main(): queue = "vin" if len(sys.argv) >= 2: queue = sys.argv[1] mq = RabbitMQ(queue=queue) mq.start_consu...
# Generated by Django 3.1.7 on 2021-07-07 09:20 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AuthToken', fields=[ ('id', models.AutoFiel...
from fastapi import APIRouter from config.db import conn from models.user import users from schemas.user import User from cryptography.fernet import Fernet key = Fernet.generate_key() f = Fernet(key) user = APIRouter() @user.get("/users") def get_users(): return conn.execute(users.select()).fetchall() @user.p...
# Driver for microwave source HP_83650A # # Written by Bruno Buijtendorp (brunobuijtendorp@gmail.com) import logging from qcodes import VisaInstrument from qcodes import validators as vals log = logging.getLogger(__name__) def parsestr(v): return v.strip().strip('"') class HP_83650A(VisaInstrument): def...
# app/api.py from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework.views import APIView class ListUsers(APIView): # authentication_classes = [authentication.TokenAuthentication] # permission_classes = [permissions.IsAdminUser] def get(self, request, ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # in order to get table_2 from eurosport, first have to get the link list for all 380 matches during a year import urllib2 from bs4 import BeautifulSoup import re import sys reload(sys) sys.setdefaultencoding('utf-8') for j in range(5171,5209): url = "http://www.eurospor...
import datetime import random import sdl2.ext from sdl2 import * from sdl2.ext.compat import byteify from sdl2.sdlmixer import * import tetris.configuration.Colors from GameEntities import * class GameRenderer(sdl2.ext.SoftwareSpriteRenderSystem): def __init__(self, window): super(GameRenderer, self).__...
from django.db import models class ChatMessageManager(models.Manager): pass
""" publish ======= A tool to build and publish certain artifacts at certain times. `publish` was desgined specifically for the automatic publication of course materials, such as homeworks, lecture slides, etc. Terminology ----------- An **artifact** is a file -- usually one that is generated by some build process...
class punto: def __init__(self, valor,izq=None,der=None): self.valor=valor self.izq=izq self.der=der def inorden(arbol): if arbol != None: inorden(arbol.izq) print(arbol.valor) inorden(arbol.der) def buscar(arbol,valor): if arbol==None: return False if a...
from django.test import TestCase from django.test import Client from django.urls import reverse class CreatePostTestCase(TestCase): def test_blog_not_authenicated(self): client = Client() client.logout() url = reverse('post_new') response = self.client.get(url) #self.assert...
# Generated by Django 2.2.13 on 2020-07-10 06:30 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('shop', '0043_auto_20200710_1153'), ] operations = [ migrations.AddField( model_name='products_wome...
from Tkinter import * import random def draw_square(can, color, len, cent): '''Takes 4 arguments: can the canvas to draw on, color, len the height and width of the square, and cent the center of the square. Draws a square of the color specified centered at cent with dimensions len x len. ''' can....
from taiga.requestmaker import RequestMaker from taiga.models import Issue, Issues, IssueAttributes, IssueAttribute from taiga.exceptions import TaigaException import unittest from mock import patch from .tools import create_mock_json from .tools import MockResponse import six if six.PY2: import_open = '__builtin_...
import os work_sizes = [32, 64, 128, 256] elements = [1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216] if __name__ == '__main__': for s in work_sizes: for t in elements: cmd = f"g++ -DNUM_ELEMENTS={t} -DLOCAL_SIZE={s} -o third third.cpp /usr/local/apps/cuda/10.1/lib64/libOpenCL....
# while 循环求1000以内的质数 i = 2 while i < 1000: j = 2 count = 0 for j in range(1, i+1): if i % j == 0: count += 1 if count == 2: print(i, end=" ") i += 1
from track import Track from car import Car def lets_race(drivers=[Car("Rarri"), Car("Tesla")]) -> str: t = Track() done = False while not done: for d in drivers: print(d) d.accelerate() t.check_winner(d) if t.winner: done = True ...
# import the necessary packages from matplotlib import pyplot as plt import argparse import imutils import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the image") args = vars(ap.parse_args()) # ...
#!/usr/bin/env python """ :: ipython -i MockSensorAngularEfficiencyTable.py """ import os, numpy as np path = os.path.expandvars("/tmp/$USER/opticks/opticksgeo/tests/MockSensorAngularEfficiencyTableTest.npy") a = np.load(path) assert len(a.shape) == 3 ctx = dict(name=os.path.basename(path),shape=a.shape,num_c...
import random N = 10000 Q = 10000 with open('long.in', 'w') as fout: fout.write('{} {}\n'.format(N, Q)) # for i in range(N-1): # fout.write('{} {}\n'.format(i+1, i+2)) for i in range(Q): fout.write('{} {}\n'.format(random.randint(1, N), random.randint(1, N)))
affirm = ['y', 'yes', 'ok', 'ys', 'sure', 'fine', 'good', 'hella', 'aye', 'yea', 'yeah'] negate = ['n', 'no', 'nope', 'nah', 'naw', 'na', 'never', 'nay', 'bad'] topics = ['thoughts', 'gaym', 'dev', 'dead'] starter = 0 blogs = [] varies = [] obs = [] midz = [ '<table align=center id="navbar">\n', '<tr>\n', '...
from microbit import * from math import pi, sin scale = 50 max_dist = 70 maxx = 5 * scale def brightness(x, y, coords): grid_x = x * scale grid_y = y * scale x_distance = abs(coords[0] - grid_x) y_distance = abs(coords[1] - grid_y) if (x_distance > max_dist or y_distance > max_dist): ...
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "hola desde Argentina para todo el site de Chile" if __name__ == "__main__": app.run(host='0.0.0.0')
"""empty message Revision ID: 03c7857df4c3 Revises: 824c7c370d22 Create Date: 2021-09-17 23:58:55.838555 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '03c7857df4c3' down_revision = '824c7c370d22' branch_labels = None depends_on = None def upgrade(): # ...
from selenium import webdriver import time import logging PATH = "C:\Program Files (x86)\chromedriver.exe" logging.basicConfig(level=logging.INFO, filename="xboxStock.log") #patches will return availability def amazonPatch(link: str): logging.info("================>Checking AMAZON patch") driverAmazonPatch =...
# -*- coding: utf-8 -*- #============================================================================== # Name: pubsub # Purpose: Simple publish & subscribe in pure python # Author: Zhen Wang # Created: 23 Oct 2012 # Licence: MIT License #====================================================...
# genqueue.py # # Generate a sequence of items that put onto a queue def sendto_queue(source,thequeue): for item in source: thequeue.put(item) thequeue.put(StopIteration) def genfrom_queue(thequeue): while True: item = thequeue.get() if item is StopIteration: break yield it...
#!/usr/bin/env python # coding=utf-8 import subprocess import time class BrightnessScale: def __init__(self): # get active monitor and current brightness self.monitor = self.getActiveMonitor() self.currB = self.getCurrentBrightness() def initStatus(self): if(self.monitor == ""...
import numpy as np def calculate(lista): if len(lista) != 9: raise ValueError("List must contain nine numbers.") matrix = np.reshape(lista, (3,3)) #axis1 são colunas, axis2 são linhas #Mean mean_axis2 = [np.mean(matrix[0]), np.mean(matrix[1]), np.mean(matrix[2])] mean_axis1 = [np.mean(matrix[:,0]), np...
""" Bithumb Auto Trading Program with GUI Byunghyun Ban https://github.com/needleworm """ import sys from PyQt5 import QtGui from PyQt5 import QtWidgets as Q from PyQt5.QtCore import * import time from pybithumb import Bithumb as B doing_job = False from ui import Ui_Dialog ui_class = Ui_Dialog coin_list = ["-"] +...
num=int(input("Enter the value:")) if num>1: for i in range(2,num): if (num%i==0): print("It is not a prime number.") else: print("It is a prime number.") else: print(num,'is not a prime number')
import matplotlib.pyplot as plt import numpy as np import pandas as pd def list_productor(mean, dis, number): return np.random.normal(mean, dis*dis, number) list1 = list_productor(8531, 956, 100) list2 = list_productor(8631, 656, 100) list3 = list_productor(8731, 1056, 100) list4 = list_productor(8831, 756, 100) ...
import uuid class MessageTalk(): """ Object to make parsing talk messages easier, where talk messages are defined as custom messages published to a set of topics """ # pylint: disable=too-few-public-methods def __init__(self, from_id, origin_id, topics, data, message_id): # pylint: di...
from sqlalchemy.orm import Session from sqlalchemy.sql.expression import null from sqlalchemy.sql.sqltypes import Boolean from . import models from ..schemas import schemas def get_job(db: Session, job_id: int): return db.query(models.Job).filter(models.Job.id == job_id).first() def get_jobs(db: Session): ...
import json import os from django.conf import settings from django.template.loader import render_to_string URL_ATTR = 'urlName' CONFIG_ATTR = 'config' ROUTE_ATTR = 'route' JSON_TEMPLATE = getattr(settings, 'ROUTES_JSON_TEMPLATE', 'routes.js') JS_TEMPLATE = getattr(settings, 'ROUTES_FULL_TEMPLATE', 'full-routes.js') ...
num1 = int(input("Digite o Primeiro Numero: ")) num2 = int(input("Digite o Segundo Numero: ")) soma = num1+num2 print("A soma = ", soma)
""" DCC XML Generator Functions H3A MUX """ import os import dcc import dccxml import shutil wdr_mode = 0 def GenH3AMUXParams(handle, h3amux_params, cls_id): handle.write(' 1, //enable\n') handle.write(' 1, //number of LUTs\n') handle.write(' {\n') ...
# Common variables used in the scripts import os import datetime import sys import subprocess import shutil def get_parent_path(path): return os.path.abspath(os.path.join(path, os.pardir)) root = get_parent_path(get_parent_path(os.path.realpath(__file__))) def python(): return "python" def python3(): return ...
from Board.ActionPanel.ActionPanel import * from Board.Map.Map import * from Board.MenuRight.MenuRight import * from FinalScreen import FinalScreen from Menu.InGameMenu.InGameMenu import InGameMenu class Board: def __init__(self, game, actionPanel=None, menuright=None, map=None): self.Map = map if map is...
# Generated by Django 3.2.5 on 2021-07-31 04:59 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('master_file', '0015_auto_20210731_1157'), ] operations = [ migrations.AddField( model_name='pro...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 1 09:22:38 2020 @author: rajiv """ import numpy as np from skimage.filters import difference_of_gaussians from PIL import Image def DoG(image_name, Test= False, perceptron = False): train_path = "/home/rajiv/Documents/lectures/BIC/project_c...
#the function takes indefinite number of arguments (all must be numbers) def f1(*args): return sum(args) / len(args) print(f1(2,4,6,8))
import requests GITHUB_ROOT = "https://api.github.com" class Client: def __init__(self, user, password): self.user = user self.password = password def set_status(self, status, owner, repo, sha): # Valid status: pending, success, error, failure path = "/repos/%s/%s/statuses/%s" % (owner, repo, sha) payloa...
def push(l): l.append(1) def pop(l): if len(l) == 0: l.append(-1) elif l[0] == -1: l.append(-1) else: l.pop() T = int(input()) for i in range(T): stk = [] qus=input() for k in qus: if k == '(': push(stk) elif k == ')': pop(st...
import socket def send_message(message, host, port): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(message, (host, port)) chunks = [] while True: chunk, address = sock.recvfrom(1028) if chunk == '': break chunks.append(chunk) return ''.join(chunks) if __name__ == '__main__': impor...
# Generated by Django 2.1.3 on 2019-05-20 17:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('job', '0002_auto_20190520_2319'), ] operations = [ migrations.RenameField( model_name='job', old_name='imagef', ...
# ============LICENSE_START======================================================= # Copyright (c) 2019-2022 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
import tensorflow as tf import numpy as np xy = np.loadtxt('xor.txt', unpack=True) x_data = np.transpose(xy[0:-1]) y_data = np.reshape(xy[-1], (4,1)) X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) W1 = tf.Variable(tf.random_uniform([2, 4], -1.0,1.0 ), name='w1') b1 = tf.Variable(tf.zeros([4]), name='...
#!/usr/bin/python3 import os import sys remote = 'git@127.0.0.1:rk3229' if len(sys.argv) == 1: print('错误!请传入 xml 文件') elif len(sys.argv) > 2: print('错误!传入参数太多') else: print('传入的文件是 %s' % sys.argv[1]) with open(sys.argv[1], 'r') as fin: while True: linestr = fin.readline() if linestr ...
# ====== main code ====================================== # n, m = map(int, input().split()) a = [[0] * m for _ in range(n)] dr, dc, r, c = 0, 1, 0, 0 for cnt in range(1, n * m + 1): a[r][c] = cnt if a[(r + dr) % n][(c + dc) % m]: dr, dc = dc, -dr r += dr c += dc for row in a: ...
import keras.backend as K import tensorflow as tf def categorical_focal_loss(gamma=2.0, alpha=0.25): """ Implementation of Focal Loss from the paper in multiclass classification Formula: loss = -alpha*((1-p)^gamma)*log(p) Parameters: alpha -- the same as wighting factor in balanced cro...
from django.db import models from django.utils.translation import gettext_lazy as _ from delivery.validators import interval_validator, weight_validator class Region(models.Model): """Класс Region используется для описания модели районов доставки. Родительский класс -- models.Model. Атрибуты класса ...
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses import logging from dataclasses import dataclass from typing import Iterable, Mapping from packaging.utils import canonicalize_name ...
""" Module that calculates the number of developers that contributed to each modified file in the repo in a given time range. See https://dl.acm.org/doi/10.1145/2025113.2025119 """ from typing import Optional from pydriller import ModificationType from pydriller.metrics.process.process_metric import ProcessMetric cl...
dwarfDict = {} while True: command = input() if command == 'Once upon a time': break else: command_split = command.split(' <:> ') name, hat, physics = command_split[0], command_split[1], int(command_split[2]) if hat not in dwarfDict: dwarfDict[hat] = {name: physi...