text
stringlengths
38
1.54M
from django.contrib.auth.models import AnonymousUser from rest_framework.authtoken.models import Token from channels.db import database_sync_to_async from channels.middleware import BaseMiddleware @database_sync_to_async def get_user(token_key): # If you are using normal token based authentication try: ...
from django import forms post = ( ('-','---SELECT---'), ('President','President'), ('Vice President','Vice President'), ('Sports secretary','Sports secretary'), ('Environment secretary','Environment secretary'), ('Cultural secretary','Cultural secretary'), ) class S...
from rest_framework import serializers from .models import Book class BookListSerializer(serializers.ModelSerializer): """Books list serializer""" class Meta: model = Book fields = ('id', 'title', 'author') class BookDetailSerializer(serializers.ModelSerializer): """Books detail and cr...
import numpy as np import matplotlib.pyplot as plt import config import pandas as pd import seaborn as sns ''' Heatmap --------------------------- Plot ''' __all__ = [ 'Heatmap' ] class Heatmap(): def __init__(self, bandwidth, csi): self.bandwidth = bandwidth self.csi = csi self.n...
#! /usr/bin/python3 import sys def sum_rec(num): if num == 0: return 0 else: return (num + sum_rec(num-1)) def main(): if len(sys.argv) <= 1: print("No Command line arguments. Please enter the number") exit() else: print("Name of the script is {}".format(sys.arg...
import sys sys.path.append("..") import urllib.request as urllib from bs4 import BeautifulSoup import datetime import numpy as np import re from harvest_utils.fetch_utils import get_opendapp_netcdf def get_gfs_forecast_info(gfs_url): """ get_gfs_forecast_info(gfs_url) This function assembles an array t...
#!/usr/bin/python3 from nbt import nbt from sys import argv items = [] for filename in argv[1:]: f = nbt(file=filename).contents scale = int(f["data"]["data"]["scale"]) items.append([scale, filename]) items.sort(key=lambda x: x[0], reverse=True) for i in items: print(i[1])
# -*- coding: utf-8 -*- """ Created on Tue May 30 09:43:22 2017 @author: Fabian """ import numpy as np import cv2 from line_merge import line_interpreter #from movement_handling import movement from connection_handling import connection class VisionAlgorithm(object): def __init__(self,con):...
import sys import hashlib import json from os import environ import threading from flask_restful import reqparse from flask import request import requests import grequests import schedule import time import math from vector_clock import VectorClock, VectorClockEncoder, VectorClockDecoder from history import History, Hi...
from multiprocessing import Process, Queue import os, sys, time, errno import json, subprocess, re from shutil import copy, rmtree from glob import glob from parallelmgmt import ParallelMgmt import pathlib def get_file_time(path): print("Last modified: %s" % time.ctime(os.path.getmtime(path))) print("Created: ...
def send_request(url): pass def visit_utack(): return send_request('http://www.ustack.com')
# import pickle # # shoplistfile = 'shoplist.data' # # print(type(shoplistfile), shoplistfile) # shoplist = ['apple', 'mango', 'carrot'] # # f = open(shoplistfile, 'wb') # pickle.dump(shoplist, f) # print(type(shoplistfile), shoplistfile) # f.close() # # del shoplist # # f = open(shoplistfile, 'rb') # comment = pickle....
import csv, os import numpy as np from scipy import stats debug = True home = os.getcwd() acc_path = os.path.join(home, "level1-CV-acc-LS") os.chdir(acc_path) algo_list = ["DT", "KNN", "NB"] acc = [[None for j in range(200)] for i in range(3)] acc_ave = [[None for j in range(200)] for i in range(3)] naming_l...
"""Read from and write to S3 buckets.""" import numpy as np import numpy.ma as ma import os import rasterio import six import warnings import boto3 from mapchete.config import validate_values from mapchete.formats import base from mapchete.formats.default import gtiff from mapchete.io.raster import RasterWindowMemory...
import time import queue import os, signal from web import app from waitress import serve from multiprocessing import Process, Queue from control.control import Control, shutdown PID_FILE = os.path.join(os.path.dirname(__file__), 'seedling.pid') def clear_queue(q): while True: try: q.get_nowa...
import numpy as np def stride_sliding_window(np_array,window_length,window_stride): x_list = [] y_list = [] n_records = np_array.shape[0] remainder = (n_records-window_length) % window_stride num_windows = 1 + int((n_records-window_length-remainder)/window_stride) for i in range (num_windows):...
import numpy as np import matplotlib.pyplot as pl d = np.loadtxt('results.dat') c = ['k','b','r','g'] fig=pl.figure() for ii,dv in enumerate(2**(np.arange(4)+16)): ind = d[:,1]==dv pl.plot(d[ind,0],d[ind,2],'o',color=c[ii],alpha=0.5,label='%1.3e'%dv) pl.legend() pl.xlabel('Number of Components') pl.ylabel('...
from flask import Blueprint from . import views from . import models engine = Blueprint("engine", __name__, template_folder = "templates", static_folder='static')
import os import unittest import requests class TestCase(unittest.TestCase): def setUp(self): '''app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db') self.app = app.test_client() ...
name = raw_input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) address = {} for line in handle: if not line.startswith("From:"): continue name = line.split()[1] address[name] = address.get(name,0) + 1 """ bigcount = None bigname = None for i in address: if bigc...
#画图,学用line画直线 import turtle import time draw=turtle.Pen() draw.color(0.3,0.8,0.6) draw.begin_fill() for i in range(5):#range内的数字是几就是几边形,为1是直线 draw.forward(100) draw.left(360/5) draw.end_fill() time.sleep(5)
#!usr/bin/env python # -*- coding:utf-8 -*- from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from DataDrivenFrameWork.util.objectMap import * from DataDrivenFrameWork.action.pageaction import * from DataD...
#!/usr/bin/env python # omicron-server.py # # Copyright 2015 Tony Agudo <antoniusmisfit@gmail.com> # # 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 2 of the License, or...
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ from odoo.exceptions import AccessError, UserError, ValidationError from datetime import date, timedelta import xlsxwriter import io import base64 import openpyxl from pathlib import Path import xlrd from xlrd import open_workbook class HotelRoom(models....
import sys sys.stdin = open("input.txt") T = int(input()) def count_color() : # 줄별 색깔 갯수 white = [0] * N blue = [0] * N red = [0] * N for y in range(N): for x in range(M) : tmp = inp_arr[y][x] if tmp == "R" : red[y] +=1 elif tmp == "B" : ...
#!/usr/bin/env python # encoding: utf-8 """ @author: Wayne @contact: wangye.hope@gmail.com @software: PyCharm @file: Minimum Difference Between Largest and Smallest Value in Three Moves @time: 2020/07/11 22:44 """ class Solution: def minDifference(self, nums: list) -> int: if len(nums) <= 4: return 0 ...
# -*- coding: utf-8 -*- # Домашнее задание. Лучше если каждая задачка будет оформлена в виде одного файла .py # 2) min/max # написать программу найти макс и мин элемент в массивее - сделать через цикл # a=[1,7,13,-2,7 ....] #len (a)==10 a = [int(i) for i in input().split()] #a = [] min = a[0] max = a[0] for i in range...
# from rest_framework import serializers # from models import * # # class DoctorSerializer(serializers.ModelSerializer): # class Meta: # model = Doctor # # # class UserInfoSerializer(serializers.ModelSerializer): # class Meta: # model = UserInfo # # # class ReviewSerializer(serializers.ModelSeri...
from lxml import etree class MathML2String: def __is_leaf(self, mt_ele): return len(mt_ele) == 0 def __prefix(self, mt_eles): def __join_math_eles(self, mt_eles): mt_str = mt_eles[0]["text"] for i in range(1, len(mt_eles)): if mt_eles[i]["tag"] != "mo" and mt_...
import pyttsx3 engine=pyttsx3.init('sapi5') voices=engine.getProperty('voices') engine.setProperty('voice',voices[0].id) engine.say('hello') engine.runAndWait()
# vim: ts=2:sw=2:tw=80:nowrap import re from .register import register_converter def to_0_1_6( vardict ): """ Convert configuration data from version 0.1.5 to 0.1.6 """ from ...processor import messages as msg msg.info('Converted configuration file from version ' '<span color="red">0.1.5</span> ...
from dataclasses import dataclass from opsi.manager.manager_schema import Function from opsi.util.cv import MatBW __package__ = "opsi.mask" __version__ = "0.123" class Erode(Function): @dataclass class Settings: size: int @classmethod def validate_settings(cls, settings): if setting...
# -*- coding: utf-8 -*- """ Created on Sat Feb 10 18:23:50 2018 @author: faraz """ import tweepy from tweepy import OAuthHandler import json import argparse import urllib.request import os import operator from collections import Counter from nltk.corpus import stopwords import string import streamListener as sl imp...
from bisect import bisect_left # 最小の手数は、部分増加列に入っていないカードの枚数である n = int(input()) c = [] ans = 0 for i in range(n): c.append(int(input())) dp = [10**10 for i in range(10**5)] for i in range(n): dp[bisect_left(dp, c[i])] = c[i] print(n-bisect_left(dp, 10**10))
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"Orientador"),(3,"Aluno")) user_type=models.CharField...
import paho.mqtt.client as mqtt import time """ Data: 27.09.2020 Author: Michael Wachl Contact: wachlm@web.de Project: Fleet Manager Coding Challenge """ class MQTTClient(): """A simple class for mqqt clients """ def __init__(self): self.client = mqtt.Client() self.client.connec...
# code snippets that goes along with the 2_implicit.ipynb notebook import os import numpy as np import pandas as pd from subprocess import call def create_rating_mat(file_dir): """create movielens rating matrix""" # download the dataset if it isn't in the same folder file_path = os.path.join(file_dir, 'u...
from tkinter import * import random from tkinter import messagebox #WORDS FOR GAME words = ['grapes','mango','laptop','television','toy','software','music','dance','helicopter','life','snake','jelly','hardware','live','drawing' ,'silly','stupid','jungle','college','team','dream','school','daily','household','t...
""" @author : arjun-krishna @desc : Read the byte encoded MNIST data in Lecun's page """ from __future__ import print_function import struct import numpy as np from PIL import Image """ display flattended image with (r,c) dimension """ def display_img(img, r, c, file=None) : img = img.reshape(r,c) disp = Image.from...
import os import time import string import argparse import random import re import torch import torch.backends.cudnn as cudnn import torch.utils.data import torch.nn as nn import torchvision import numpy as np import pandas as pd from nltk.metrics.distance import edit_distance from utils import CTCLabelConverter, Att...
from django.urls import path from . import views driver_detail = views.DriverViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) storage_detail = views.OrderViewset.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', ...
''' Created on Jan 22, 2018 @author: PATI ''' class Jucator(object): ''' Clasa jucator retine pt un jucator un nume un prenume o inaltime si un post ''' def __init__(self, nume,prenume,inaltime,post): ''' initializam campul nume prenume inaltime si post cu valorile corespunzatoare ...
import os import nose import requests import fixture from tangelo.server import Content from tangelo.server import Directive cwd = os.getcwd() @nose.with_setup(fixture.start_tangelo, fixture.stop_tangelo) def test_closed_source(): analysis = requests.get(fixture.url("analyze-url/analyze-url", test=1)).json() ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def plot(x): if type(x) is list: for i in x: plt.plot(i, label=i.index.name) plt.xticks(np.arange(0, 30.25, 0.25)) else: plt.plot(x, label=x.index.name) plt.xticks(x.index) plt.legend() p...
bringup jspec write pechip[0] register pg_cxlmacpcs misc_cfg misc_reset 0x00000000 bringup jspec write pechip[0] register pg_cxlmacpcs misc_cfg misc_reset 0x00000000 bringup jspec write pechip[0] register pg_chmac 0 chan_misc misc_reset 0x00000000 bringup jspec write pechip[0] register pg_chmac 1 chan_misc ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'takingnote.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObject...
print(''' This is a sample structural_dhcp_rst2pdf extension. Because it is named 'sample.py' you can get structural_dhcp_rst2pdf to import it by putting '-e sample' on the structural_dhcp_rst2pdf command line. An extension is called after the command-line is parsed, and can monkey-patch any necessary changes into st...
import csv import math # Even probability vals = [0, 1, 2, 3, 4, 5, 6] # Method 1 def expected_val(arr, var): arr.append(var) ex = 0 for i in range(0, len(arr)): ex += (float(arr[i]) / len(arr)) return ex # Method 2 def expected_val2(arr, var): arr.append(var) ex = 0 for x in rang...
from flask_socketio import SocketIO import eventlet socketio = SocketIO() def createSocket(app): asyncMode = 'eventlet' socketio.init_app(app, asyncMode=asyncMode, cors_allowed_origins="*") return True
from django.conf import settings from django.urls import path, re_path, include from rest_framework.routers import DefaultRouter from restaurant.api import views router = DefaultRouter() router.register(r'client', views.MasterClientViewSet) router.register(r'restaurant', views.MasterRestaurantViewSet) router.regist...
# The file in which we define all known tracking # configurations for HLT2 # __author__ = "V. Gligorov vladimir.gligorov@cern.ch" from Hlt2Tracking import Hlt2Tracking #from HltTrackNames import HltBiDirectionalKalmanFitSuffix from HltTrackNames import HltDefaultFitSuffix #from HltTrackNames import HltUniDirectional...
a=int(input()) b=0 c=1 while a>b: b=b+c c+=1 for i in range(b-a+1): g = c-(i+1) h = i+1 if c%2!=0: print('{}/{}'.format(str(g), str(h))) else: print('{}/{}'.format(str(h), str(g)))
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-12-20 16:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('checkout', '0001_initial'), ] operations = [ ...
import json import os import boto3 # Helper function to get the extension of a filename. def get_file_ext(path): return path.split('.')[-1] # Filename extension to meme-type map. content_type = { 'html': 'text/html', 'css': 'text/css', 'js': 'text/javascript', 'json': 'application/json', 'jp...
from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email.mime.application import MIMEApplication import settings import smtplib SMTP_USER = settings.SMTP_USER SMTP_PASSWORD = settings.SMTP_PASSWORD SMTP_SERVER = settings.SMTP_SERVER SM...
"""Some basic routines for working with microphones.""" import numpy as np import matplotlib.pyplot as plt from scipy.stats import linregress from scipy.interpolate import CubicSpline import sys from calibrations import microphones as MICROPHONES def plot_microphone_transfer_function(microphone_id): try: ...
#!/usr/bin/env python3 import os import socket import threading import json import uuid import subprocess from Crypto.PublicKey import RSA from connection import Connection class Server: def __init__(self, portNumber): self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.por...
""" 1193번) 분수찾기 무한히 큰 배열에 다음과 같이 분수들이 적혀있다. 1/1 1/2 1/3 1/4 1/5 … 2/1 2/2 2/3 2/4 … … 3/1 3/2 3/3 … … … 4/1 4/2 … … … … 5/1 … … … … … … … … … … … 이와 같이 나열된 분수들을 1/1 -> 1/2 -> 2/1 -> 3/1 -> 2/2 -> … 과 같은 지그재그 순서로 차례대로 1번, 2번, 3번, 4번, 5번, … 분수라고 하자. X가 주어졌을 때, X번째 분수를 구하는 프로그램을 작성하시오. """ #입력: 첫째 줄에 X(1 ≤ X ≤ 10,000,0...
# Problem: given a cost matrix cost[row][col] and a position (m, n) ( m < row and n < col) # Question: find minimum cost path from (0, 0) to (m, n) # Using recursive approach to returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C] def min_path_recursive(graph, m, n): if m < 0 or n < 0: retu...
from random import randint import random import string import sys import getpass import os successful_decrypted_message = "<<<Successful file decrypt>>>" #a "unit" that has 2 locations to be swapped(1,2) class Scramble_unit: first = 0 second = 0 def __init__(self, first,second): self.first = first ...
""" EJERCICIO 7 """ nombreMayor=" " nombreMenor=" " i=1 ns=int(input("¿Cuantos numeros ingresara?")) while i<=ns: print("Ingrese el promedio: ",i) t=eval(input()) print("Ingrese el nombre: ",i) nombre=input() if (i==1): may=t men=t nombreMenor=nombre n...
from unittest import TestCase from adapters.validators.function_type_validator import FunctionTypeValidator class FunctionTypeValidatorTest(TestCase): def test_found_f(self): assert FunctionTypeValidator.valid('fibonacci') def test_not_found_f(self): assert not FunctionTypeValidator.valid('ze...
from flask import Flask """ Commented out Mongo stuff for now while we figure out the server situation. from flaskext.mongoalchemy import MongoAlchemy app = Flask(__name__) app.config['MONGOALCHEMY_DATABASE'] = 'x' app.config['MONGOALCHEMY_USER'] = 'x' app.config['MONGOALCHEMY_PASSWORD'] = 'x' app.config['MONGOALCHEM...
""" """ # ----------------------------------------------------------------------------- # import: # ----------------------------------------------------------------------------- # fuggvenyek: def szamrendszerben_kiir(szam, szamrendszer) : if szam == 0 : return szamrendszerben_kiir(szam ...
from selenium.webdriver import Chrome from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from time import sleep import tkinter as tk import xlsxwriter webdriver = "C:/Users/Brendan/Documents/Python Projects/HelloCoding/chromedriver.exe" options = Options() def sear...
import smtplib import pynput from pynput.keyboard import Key, Listener from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText keys = [] #this list will have all the keys ### a function to add the key pressed to the list ##### def on_press(key): keys.append(key) write_file(keys) ...
def is_passphrase_valid(phrase, trans=str): words = tuple(trans(w) for w in phrase.split()) unique_words = set(words) return len(words) == len(unique_words) def valid_passphrases(passphrases, trans=str): return [p for p in passphrases if is_passphrase_valid(p, trans=trans)] def sorted_word(word): ...
""" Swiss Army Knife of Python """ __author__ = 'Kirill V. Belyayev' __version__ = '0.01.28' __license__ = 'MIT'
# map/reduce from functools import reduce def add(x,y): return x+y print(reduce(add,[1,2,3,4,5])) def fun(x,y): return x*10 + y print(reduce(fun,[1,2,3,4,5]))
# Generated by Django 2.0.5 on 2018-06-15 06:44 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('Article', '0004_auto_20180615_1153'), ] operations = [ migrations.CreateModel( name='Comment', ...
from django.shortcuts import render from django.http import HttpResponseRedirect from django.template.context_processors import csrf from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required # Create your views here. from .forms import Logindata def loginscreen(request):...
pg_user = "admin" pg_password = "secret" pg_host = "127.0.0.1" pg_port = "5432" pg_database = "postgres"
from flask import Flask, request import traceback import configparser import datetime from apihelper import SparkAPICaller app = Flask(__name__) spark_api = SparkAPICaller() @app.route('/') def hello(): """Run your server and go browse to the root of your server: http://localhost:5000 and see if it is working. It...
from PIL import Image from .artpiece import Artpiece #function to pull image off of database def pull_picture(id): # handle invalid id artpiece = Artpiece.get_by_id(id) image = Image.frombytes("RGBX", (616, 414), artpiece.raw_image) image.show() return image
from django.db import models # from Faculty import Faculty from portal.models import Course # Create your models here. # FACULTY STAFF # ID ---- NOT NULL Integer Primary Key # Faculty ID ---- NOT NULL Integer Foreign Key(Faculty) # Course Code ---- NOT NULL String Foreign Key(Courses) # Username ---- NOT NULL Str...
#! /usr/bin/env python3 #! _*_ coding: utf-8 _*_ from __future__ import print_function import torch x = torch.rand(5, 3) print(x) print('cuda = %s' % str(torch.cuda.is_available()))
import numpy as np import folium from folium import Map from shapely.geometry import mapping class HospMap(Map): def __init__(self, location=(39.8333333, -98.585522), zoom_start=4): super().__init__(location, zoom_start=zoom_start) self.has_layer_control = False def add_point_subset(self, gdf...
#@+leo-ver=5-thin #@+node:ekr.20110605121601.18002: * @file ../plugins/qtGui.py """qt gui plugin.""" #@@language python #@@tabwidth -4 print('===== qtGui.py: this module is no longer used.') #@-leo
# -*- coding: utf-8 -*- """ flask_wtf ~~~~~~~~~ Flask-WTF extension :copyright: (c) 2010 by Dan Jacob. :copyright: (c) 2013 - 2015 by Hsiaoming Yang. :license: BSD, see LICENSE for more details. """ # flake8: noqa from __future__ import absolute_import from .csrf import CSRFProtect, CsrfProte...
class ProductionDataRouter(object): using = 'production' app_label = 'production' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.using def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: ...
import argparse import os import shutil import random import numpy as np import torch import torch.nn as nn import torchvision from torch.utils.tensorboard import SummaryWriter from model import DQN from tetris import Tetris from utils import ReplayBufferOld, str2bool import utils import logging import sys import mat...
from turtle import Turtle import random from turtle import * import turtle colormode(255) class Square(Turtle): def __init__(self, size): Turtle.__init__(self) self.shape("square") self.shapesize(size) def random_color(self): rgb = (random.randint(0,256), random.randint(0,256), random.randint(0,256)) ...
#region headers # escript-template v20190611 / stephane.bourdeaud@nutanix.com # * author: Bogdan-Nicolae.MITU@ext.eeas.europa.eu, # * stephane.bourdeaud@nutanix.com # * version: 2019/09/17 # task_name: PcGetAdGroup # description: Given an AD group, return information from the directory. # output ...
#! /usr/bin/env python """ hw 4 """ from __future__ import division, print_function from itertools import izip # Task 2 def p_distance(seq1, seq2): """ :type seq1: str :param seq1: :type seq2: str :param seq2: :return: p-distance between seq1 and sec2 """ if len(seq1) != len(seq2)...
max_int = (1 << 31) -1 min_int = - (1 << 31) class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if divisor < 0 : divisor = - divisor dividend = - dividend if divide...
import packagetrack from packagetrack.carriers.errors import * from packagetrack.configuration import DotFileConfig import time import datetime import json import random import traceback import requests from ..plugin import PollPlugin, CommandPlugin from ..shorturl import short_url from .hesperus_irc import IRCPlugin f...
import pytest from src.messaging_service import MessagingService from src.message import Message def test_exercise(): message = Message("Grace","Hello there!") service = MessagingService() service.add(message) assert service.get_messages() == ["Grace: Hello there!"]
"""Add Build.priority Revision ID: 36cbde703cc0 Revises: fe743605e1a Create Date: 2014-10-06 10:10:14.729720 """ # revision identifiers, used by Alembic. revision = '36cbde703cc0' down_revision = '2c6662281b66' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('build', sa.Column('pri...
import sys import csv from sklearn.model_selection import train_test_split from classifier import svm_tasks, ann_tasks def convert_row_to_int(row): new_row = [] for value in row: new_row.append(float(value)) return new_row if __name__ == "__main__": if len(sys.argv) != 2: sys.exit("U...
import re import os import json import pickle import numpy as np from collections import OrderedDict from typing import List, Tuple, List, Any import torch from transformer.tokenizer.utils import load_tokenizer_from_pretrained from transformer.utils.common import init_path def get_length_penalty(length, alpha=1.2, min...
#!/usr/bin/python3 #coding:utf-8 a = 100 b = ['1','a','c'] def printer(x): print(x) if __name__ == '__main__': printer(a) printer(b)
from django.conf import settings from .models import Answer import uuid class Anonymous(): def __init__(self, request): self.session = request.session self.anonym_user = self.session.get('anonym_user') if not self.anonym_user: anonym_user = self.session['anonym_user'] = {} ...
from django.contrib import admin from django.urls import path, include import orders.views urlpatterns = [ path('', orders.views.index, name="show_order_route"), path('create/<product_id>', orders.views.create_order, name="create_order_route"), path('detail/<order_id>', orders.views.view_order_details, nam...
from django.contrib import admin from django.urls import path from apps.person import views app_name = "person_app" urlpatterns = [ path("", views.HomeView.as_view(), name="home"), path( "list-employees/", views.ListAllEmployees.as_view(), name="all_employees" ), path( ...
import memcache # 在连接之前一定要切记先启动memcached mc = memcache.Client(["127.0.0.1:11211"], debug=True) # 设置数据 # mc.set('username', 'abc', time=120) # # 获取数据 # print(mc.get('username')) # 设置多个键值对 # mc.set_multi({"title": "钢铁是怎么练成的", 'content': "你好世界"}, time=120) # 删除键 # mc.delete("username") # 已设置了age=20 # 自动增长10, 若不设置delt...
# -*- coding: utf-8 -*- """ # moar.storages.filesystem Local file system store. """ import errno import io import os import urlparse def make_dirs(path): try: os.makedirs(os.path.dirname(path)) except (OSError), e: if e.errno != errno.EEXIST: raise return path class Storage...
from flask import Flask, render_template from flask_restful import reqparse, abort, Api, Resource import requests import json from flask_cors import CORS, cross_origin app = Flask(__name__) api = Api(app) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) parser = reqparse.RequestParser() parser.add_argument('...
from steem import Steem from steem.blockchain import Blockchain from steem.post import Post from steem.account import Account import json import datetime import os def converter(object_): if isinstance(object_, datetime.datetime): return object_.__str__() def create_json(): user_json = {} for user...
#!/usr/bin/env python from subprocess import STDOUT, check_call import re # Set the hostname. def set_host_name(domain,hostname): # set hostname fqdn = hostname + "." + domain hostname_file = open("/etc/hostname","w") hostname_file.write(fqdn + "\n") hostname_file.close() try: check_c...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import logging logger = logging.getLogger("webapi") import socorro.lib.util as util import socorro.webapi.webapiService...