index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
14,000
bcf1de927127300be85a1cb869fed97a7eeb8f8f
import csv import time import re import nltk import numpy as np import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from convertor import convert_docs_in_dic TFIDF_FILE = "./data/output/tfidf_predictions_optimized.tsv" BOOK_EVAL_FILE = "./dat...
14,001
43f020b380935cb022fe37020aca3240feda04cf
import numpy as np import scipy import sympy from numpy import linalg as lg from numpy.linalg import solve from numpy.linalg import eig from scipy.integrate import quad # Question 1 ''' If uequalsStart 2 By 1 Table 1st Row 1st Column x 2nd Row 1st Column y EndTable is in​ W, then the vector cuequalscStart 2 By 1 ...
14,002
3b91f72272c3a6f68e72cb75d6fd9740b8a37f03
"""Create and solve SMT problems related to the search of characteristics."""
14,003
ebcd38d15a2c9816a80e72cd0a1dd3408d122848
import sys import os import re import operator as o #### docs ############ # to append to notes.txt use . as first arg followed by lines # to append to other textfiles in cwd set in first arg # if thetextfile does not exist don't worry #### improvements #### # delete lines based on numbers # other cmd fun...
14,004
f79345638d6d8add93437d98ffccb2375f501f7e
__version__ = "0.4.3" default_app_config = 'rest_registration.apps.RestRegistrationConfig'
14,005
39aa5b43986c63ec68bef1de84c2f95a7ddbb93c
from django.urls import path from .views import ( CommentListView, CommentDetailView, CommentCreateView, CommentUpdateView, CommentDeleteView ) app_name = 'comments' urlpatterns = [ path('', CommentListView.as_view(), name='comment-list'), path('<int:pk>/', CommentDetailView.as_view(), nam...
14,006
8b736d90ff1e411c3fea39d278a6e778c70a9e7a
import os class Board: def __init__(self): self.blocks = [' '] * 81 self.score = 0 def update(self, pos, marker): self.blocks[pos] = marker def update2(self, pos, pos1, marker, marker1): self.blocks[pos] = marker self.blocks[pos1] = marker1 def scoreup(self)...
14,007
d760f7f19cde0fccdd2a549f831913c2325e9b60
# /bin/etc/env Python # -*- coding: utf-8 -*- print(1 ** 2) print(2 ** 1, 2 ** 2, 2 ** 3, 2 ** 4, 2 ** 5, 2 ** 6, 2 ** 7, 2 ** 8, 2 ** 9, '\n') # +-*/就不多说了 # **两个星号代表乘方 # +=、-=、*=、是 'a = a + 1' == a += 1 简单写法。 # 整数 print(3 / 2) print(3.0 / 2) print(3.0 / 2.0, '\n') """ 在Python2中,3/2=1 会将小数直接删掉。 """ print(5 + 3) prin...
14,008
cf56dd726a2a76fee89013fd3afe807fa4c02b53
#!/usr/bin/env python __author__ = "Bill Ferrell" """Parses the Sierra avalanche center status page. Page found here: http://www.sierraavalanchecenter.org/advisory This class parses the page and returns an object that allows you to get various status bits. """ import re import logging import models from mmlib.sc...
14,009
20c03df1cf1a57a7f663563433fae9030d96e686
# not required, but nice for predictive text and tab completion from aiogram import Bot, Dispatcher, executor, types # importing modules import asyncio from datetime import datetime import credentials import re, math async def startMessage(bot, message): await bot.send_message(message['from']['id'], "Welcome to t...
14,010
6fe02a9cfd27d2a5c7e065521b88f4a206d9a0f7
from app import db from app.models import Movie from sqlalchemy import text from flask_sqlalchemy import Pagination def search_movie(search_text, page, per_page): sql = text(''' WITH similar_words AS ( SELECT string_agg(word, ' | ') AS words FROM ( SELECT word ...
14,011
57dff9feb10de13bdc22230fbd5ca3d4b591b0b6
import logging import sys import shutil import hashlib import json from unittest import TestCase from unittest import mock from ansit.environment import ( Environment, Drivers) from ansit.manifest import Manifest from ansit.util import read_yaml_file from ansit import drivers logging.basicConfig(level=loggin...
14,012
fd2c33778fa6d84a686c4c63c62e668f8d771447
n,m = list(map(int,input().split())) edges = [[False for _ in range(n+1)] for _ in range(n+1)] visited = [[False for _ in range(n+1)] for _ in range(n+1)] flag = False # 并查集 检查连通性 v = [i for i in range(n+1)] def find(x): if x==v[x]:return x else: v[x] = find(v[x]) return v[x] def union(x,y): ...
14,013
cd77183719ee72b38882e6db5c7d3c1f48008990
def add_to_deck(card, original_deck, n_deck): if card in original_deck: n_deck.append(card) return n_deck else: print('Card not found.') def remove_from_deck(card, n_deck): if card in n_deck: n_deck.remove(card) return n_deck else: print('Card not found....
14,014
19c91817c1adbda41a16b835958867ef4ae2e84b
#!/usr/bin/env python3 import os import unittest import socket import time import pdb import json import requests from sure import expect import subprocess HOST = os.getenv("HOST", "localhost") HTTP_PORT = os.getenv("HTTP_PORT", 8888) HTTPS_PORT = os.getenv("HTTPS_PORT", 443) INSECURE = not os.getenv("INSECURE", True)...
14,015
baf83491a3ed03ab0ff4aebe0ebc92c0060e50ce
import ROOT as root import numpy as np class BuildRoots(): def __init__(self, tree, ext): self._tree = tree self._root_file = ext self._max_index = [] def build_max_energy(self): self._get_max_energy() def _get_max_energy(self): f = root.TFile("~/workspace/hgtd/roo...
14,016
89e70463eae52ccf78c1c613d4a2ef9d05fa79ee
#!/usr/bin/env python ########################################################################### # Replacement for save_data.py takes a collection of hdf5 files, and # # builds desired histograms for rapid plotting # #####################################################################...
14,017
f7dc1ca0b52d7df87ac40f5cff6083c0bdde8a31
""" TSG Data Sender Author: Morgan Allison Updated: 03/18 This script allows you to send IQ data to the TSG and utulize its internal baseband generator to use it as a simple IQ modulator. This example creates a dual sideband modulation. Windows 10 64-bit, TekVISA 4.2.15 Python 3.6.4 64-bit PyVISA 1.8, NumPy 1.13.1 """ ...
14,018
4ec2f39cc4fd2f07c574c6e9587c2104ab902055
#!/usr/bin/python # -*- coding: UTF-8 -*- from __future__ import unicode_literals import sys from wsgiref.handlers import CGIHandler from __init__ import create_app from libs.links import get_all_groups app = create_app() CGIHandler().run(app) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000,)
14,019
23abb4fe21d4e83edb4a89573f3fe0d0b70767a5
#version1: import math def factorial(x): return math.factorial(x) print factorial(10) print factorial(3) print factorial(1) print factorial(0) #version2: def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) print factorial(10) print factorial(3) print factorial(1) pri...
14,020
5295a28ff756281a2b954c87bacb4b8153bf3d03
''' @author: xiongfei @license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. @contact: 386344277@qq.com @file: SVD++.py @time: 2018/5/21 下午6:29 @desc: shanghaijiaotong university ''' from __future__ import division, print_function import itertools import os from scipy.sparse import csr_matrix...
14,021
456c1c8f9864883011a0dd4385946aa9bcda97b7
from flask import Flask, render_template,json,jsonify,request,current_app as app from datetime import date import requests import os app = Flask(__name__) @app.route('/') def index(): name = 'Abdul Q' friends =['joe','bob','robert','bobby'] return render_template('index.html',greeting = name,friends =...
14,022
99b9a48da4ac67f98009acaa276a4581484d821d
from flask import Flask, jsonify, request import json from db_connector import DB_TEST from werkzeug.serving import WSGIRequestHandler import numpy as np import time import tensorflow as tf import os CUR_DIR = os.path.dirname(os.path.abspath(__file__)) # initialize inference model MODEL_FILENAME = 'inference_model...
14,023
af8b1b5059130d5be69763afe9ccfb73d7cb0f8a
from .Worker import Worker from .Site import Site from .BaseObject import BaseObject from mkdir_p import mkdir_p import os crab_file_template = """import os from WMCore.Configuration import Configuration from CRABClient.UserUtilities import config, getUsernameFromSiteDB config = Configuration() taskName ...
14,024
47b0db3c22d6f0cc27ae097cfeb37b16a97e30b4
# # PySNMP MIB module Juniper-IP-TUNNEL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-IP-TUNNEL-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:03:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
14,025
eb5d2bcce5bd64c5f8a498837aa13f292d3b88ac
#!/usr/bin/env python r""" Python CPlusPlus Reflection =========================== This package provides wrapper methods for clang's python The available modules are: sbind A simplified wrapper of clang.cindex.py that deals more with strings than objects. """ __all__ = ['sbind']
14,026
71b1ed2563cca32438385a72577c3bc3c4a15814
import niftynet import sys def start_training(base_dir, gpu_num, cuda_devices, model_dir, config_file): model_dir = base_dir + 'models\\' + model_dir config_file_path = '.\\configFiles\\' + config_file sys.argv = ['', 'train', '-a', 'net_segment', '--conf', config_file_path,...
14,027
31e5b32d5ab245f2ea15c05cf1eb1d0f1c552a6f
# flake8: noqa from .builders import OpenApiBuilder import pyopenapi3.objects import pyopenapi3.data_types from pyopenapi3.utils import create_schema __all__ = ( "OpenApiBuilder", "objects", "data_types", "create_schema" ) __version__ = "0.1.dev0"
14,028
706f454f49e7b93ae7a02309c88bb91c1550fec8
#!/bin/python # -*- coding: utf-8 -*- from settings import * from os.path import join from datetime import datetime from ctrls.Reader import Reader import matplotlib.pyplot as plt class SimpleDrawer(): '''畫出近 n 天收盤價圖''' def _getFigTitle(self, stock_number): t = datetime.now() return ('%s, Upd...
14,029
8d1c25b0c72a032d5faa9619d60e376e8e278681
import streamlit as st from datetime import datetime, time import database as db import pandas as pd import patient import doctor # function to verify medical test id def verify_medical_test_id(medical_test_id): verify = False conn, c = db.connection() with conn: c.execute( """ ...
14,030
9c709187de5d06a51d76f1ecff69b693a8c1a293
# plot 5-10um data from Hill paper import numpy as np import matplotlib from matplotlib import pyplot as plt from math import * import astropy.io.ascii as ascii data=ascii.read data = ascii.read('table2.txt') wavelength = data['col1'] total = data['col2'] most_lum = data['col3'] medium_lum = dat...
14,031
a1641e9f87e0c777d56d131d7928f7ee30f96caf
#!/usr/bin/env python3 import doctest import functools as fn import itertools as it import typing FACTOR_A = 16807 FACTOR_B = 48271 MULT_A = 4 MULT_B = 8 TEST_A = 65 TEST_B = 8921 PAIRS1 = 40000000 PAIRS2 = 5000000 def no_test(_: int) -> bool: return True def is_multiple_of(m: int) -> typing.Callable[[int], b...
14,032
31b036da78ad6aeae8c18fd12561f85bcabde033
from .SearchEngine import SearchEngine, Navigator from bs4 import BeautifulSoup class Bing(SearchEngine): def __init__(self, navigator=None): """ :type navigator: Navigator """ super().__init__(base_url='https://bing.com', navigator=navigator) def reset(self): super().reset() def get_search_url(self, ...
14,033
9c585f7dbbeb681a8b7cec8555cf6b214cc84324
# encoding: utf-8 # module PySide.QtMultimedia # from /corp.blizzard.net/BFD/Deploy/Packages/Published/ThirdParty/Qt4.8.4/2015-05-15.163857/prebuilt/linux_x64_gcc41_python2.7_ucs4/PySide/QtMultimedia.so # by generator 1.138 # no doc # imports import PySide.QtCore as __PySide_QtCore # no functions # classes class _Q...
14,034
84d9bae3ebd0f0104dabe37ccb82de00acbcd3e8
""" A super cool file for helping with DRAG stuff.""" import numpy as np import scipy import dsp_utils # Empty envelopes def empty_detuning_envelope(t, args): return 0 def empety_x_envelope(t, args): return 0 def empty_y_envelope(t, args): return 0 # Helper functions for building gaussian pulses def ...
14,035
77bba44a1f072088e21a1cdc6afb37a88c52d3fb
from location import RIGHT, LEFT, UP, DOWN, Location from game import SQUARE_SIZE class Player(): ''' This class represents the character which reacts to user inputs in two dimensional grid worlds. A player is equipped with the various capabilities: - It can sense its own surroundings (location, fac...
14,036
0d6faeab7d9fcca8a47204a9c502f6b7f3783d87
N, A, B = map(int, input().split()) print(sum(i * (A <= sum(map(int, str(i))) <= B) for i in range(N + 1)))
14,037
57d9632c1cf0944bc0ce374bf2c0f9bc64f0b4ce
""" inout.py Prompt the user for their age. Then tell them how old they are in dog years. """ import sys try: years = input("How old are you? ") except EOFError: sys.exit(0) try: years = float(years) except ValueError: print("Sorry,", years, "is not a number.") years = 0.0 print("I'll assum...
14,038
44a99aecf857fe138d4b793718ee58d66a0d5bff
""" Waits two seconds between sending each character """ import socket import time server_socket = socket.socket() # listen for connections on provided port server_socket.connect(('127.0.0.1', 8000)) for c in b'hello\n': time.sleep(1) server_socket.sendall(bytes([c])) print(server_socket.recv(4096)) server_so...
14,039
856142153c8682be8568b31c00dbf8606c83afa1
class Solution(object): def twoSum(self, nums, target): map = {} diff = 0 for i in range(0, len(nums), 1): map[str(i)] = nums[i] #print map['1'] for k in range(0, len(nums), 1): #print "======",nums[k],k,"=====" diff = target - ...
14,040
b2474383784aeaf77e47f5a9afa702e851fee5ee
import logging import logging.config logging.config.fileConfig('logging.conf') import os from .file import File from utils.page_loader import PageLoader class Page: def __init__(self, link_source = None, path = "", \ url=None, dp=None, lp=None, use_same_url=False, loader=None,\ data_version=1, link_versio...
14,041
d02047581a7aa1fbfd1e394edbbc9c4d109af84c
from django.shortcuts import render def index(request): context = { 'judul': 'Selamat Datang', 'subjudul': 'MNUR', } return render(request, 'index.html', context)
14,042
041aa83ea46a7d788ed2fdb843543fc2944b0897
#!/usr/bin/env python # coding: utf-8 # # Setup and import libraries # In[2]: import streamlit as st import pandas as pd import numpy as np import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go import matplotlib.pyplot as plt from ipywidgets import AppLayout, Butto...
14,043
7d47a877d4f536d838dcbc52778c85e2aed897eb
import gevent from gevent import socket import Tkinter as tk # class SockLoop(object): # def __init__(self, callback): # self.callback = callback # def __call__(self, sock, client): # while 1: # mes = sock.recv(256) # ret = self.callback(client, mes) # if r...
14,044
7c8d99e44f77f607ff83c10900750b52caceb7c1
#!/usr/bin/env python # coding: utf-8 import pandas as pd # 调用pandas工具包的read_csv函数/模块,传入训练文件和测试文件的地址参数,获得返回的数据并存于变量 df_train = pd.read_csv('../Datasets/Breast-Cancer/breast-cancer-train.csv') df_test = pd.read_csv('../Datasets/Breast-Cancer/breast-cancer-test.csv') # 选取'Clump Thickness'与'Cell Size'作为特征,构建测试集中的正负分类样本 #...
14,045
5e10527f97214c03cbd96a3b114e6fc4a64d5d51
# Generated by Django 3.0.7 on 2021-04-08 10:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Transaction', '0005_auto_20210404_0957'), ] operations = [ migrations.AlterField( model_name='transactionhistorymodel', ...
14,046
cb6bcf508b34e28c2e274b90efc78b1faa6268a9
import sys class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def min_distance(self, distance_array, visited): min_val = sys.maxint for i in range(self.V): ...
14,047
a398445a92eb0d5a97f621f7f98fbb287e15263b
string = input() substring = 'f' kst = len(string) pos = string.find(substring) newString = string[pos + 1:] if pos == -1: print(-2) elif pos != -1: pos2 = newString.find(substring) if pos2 == -1: print(pos2) else: print(pos2 + pos + 1)
14,048
1431f2d9bcc5eb312e96fc6350524ac5ef44a718
import pygame from plane_sprites import * screenHeight = 700 screenWidth = 480 heroWidth = 120 heroHeight = 125 hero_rect = pygame.Rect(100, 500, heroWidth, heroHeight) print(hero_rect.x, hero_rect.y, hero_rect.size) pygame.init() # 创建游戏窗口 480*700 screen = pygame.display.set_mode((screenWidth, screenHeight)) # 绘制背景图像 b...
14,049
4077778184da79fc85eea14472ccdf8e218538b0
import networkx as nx from modelo.veiculo import Veiculo import random #Função que calcula o tempo da trajetória que determinado veículo fez def CalculaTempo(listaDeVisitados, veiculo, G): tempoInicial = 0 for i in listaDeVisitados: if i != listaDeVisitados[0]: tempoInicial += G.node[i]["n...
14,050
385f494dbd2ffc62082b4f190bcfe2a246cb0702
# Generated by Django 2.2.4 on 2020-01-28 18:51 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('meet', '0008_auto_20200128_1850'), ] operations = [ migrations.AlterField( model_name='meet', name='...
14,051
46646bbedb478f7105e8132e575cb1fc6872b5f2
def info(): return 'Modul tentang menghitung luas segitiga' def hitung_segitiga(alas, tinggi): luas_segitiga = alas * tinggi / 2 return luas_segitiga
14,052
7c8d7d6d75f8339d7b48901da16de3b894b3f631
import func while True: cnpj1 = input('Digite um CNPJ: ') if func.valida(cnpj1): print(f'O CNPJ: {cnpj1} é Válido') else: print(f'O CNPJ {cnpj1} é Inválido')
14,053
432207d2ad527519ea907f9f1c0d47c6cf7e73c7
rule merge_interaction_matrices: input: mat = expand( os.path.join( hic_data_path, "hic_results", "matrix", "{sample}", "raw", "{{bin}}", "{sample}_{{bin}}.matrix" ), sample = samples ), bed = expand( os.path.joi...
14,054
8733aa6901af6ef26d0f8941afc474ad208464d9
# importing the calendar module import calendar yy = 2020 # yy stands for year mm = 03 # mm stands for month # To take month and year as input from the keyboard you may use # yy = int(input("Enter year: ")) # mm = int(input("Enter month: ")) # displays the calendar print(calendar.month(yy, mm))
14,055
6958e294c9d1e248844aa66d68ba8476a203ced1
''' Function: 鸟类 作者: Charles 微信公众号: Charles的皮卡丘 ''' import pygame # Bird类 class Bird(pygame.sprite.Sprite): def __init__(self, HEIGHT, WIDTH): pygame.sprite.Sprite.__init__(self) # 基准 self.ori_bird = pygame.image.load("./resources/images/bird.png") # 显示用 self.rotated_bird = pygame.image.load("./resource...
14,056
b1e1eb9f0bd983c2a2f38361022fe7a3a85700b7
# Generated by Django 3.0.8 on 2020-07-19 21:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('persons', '0001_initial'), ] operations = [ migrations.CreateModel( name='T...
14,057
3984630f6fd2c80e298c24c4dd4cc3a15ed04627
__author__ = 'LiGe' #encoding:Utf-8 import csv ##########################加类标,去用户-商品名,取纯特征文档############################# def put_on_label(feature_csv,feature_txt_label): f=open(feature_txt_label,'w') for line in csv.reader(file(feature_csv, 'rb')): f.write(line[2]+' '+line[3]+' '+line[4]+' '+li...
14,058
55b988ebfd86cda76a9a95715a99b2328b0513fd
# Generated by Django 2.1.2 on 2021-03-17 18:47 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0003_position_assetid'), ] operations = [ migrations.AddField( model_name='asset', name...
14,059
19abef0c900052bd03ad434196fecda7595a7a44
import ssl from socket import timeout, error def recv_all(conn, bite): text = b"" for i in range(bite): rec = conn.recv(1) if not rec: raise error text += rec if len(text) >= 2 and text[-2:] == b"\r\n": break return text def input_user(ask_for="", ...
14,060
0db466801eadc2eae40156ee96cc2faa7c47faa2
from bs4 import BeautifulSoup import requests from crawlers.Crawler import Crawler class GeniusCrawler(Crawler): def __init__(self): super().__init__('Genius Lyric') def search_for_lyrics(self, artist, song): try: _artist = str(artist).strip().replace(' ', '-').replace("'", '') ...
14,061
27a00bd6943bb3c29da3c889f28939dcecd521df
from __future__ import print_function def main(): inputVariableNumber = '4lay' inputVariabelAlpha = 'Alay' inputVariableSpace = ' AlayAnjay' hasilNumber = inputVariableNumber.isalnum() hasilAlpha = inputVariabelAlpha.isalpha() hasilSpace = inputVariableSpace.isspace() print('Variabel Number...
14,062
e062c71ed64cac5f48db074be7ba06eaf7c91baa
def more_n(sp, n): # объявление функции for i in sp: # для каждого числа if i>n: # если число больше n print(i, end=' ') # то вывести число more_n((5, 4, 4, 9), 4)
14,063
cd7ba97177825fd93d87732d8502fc8795efcda5
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/17 9:58 # @Author : zhujinghui # @File : xueqiu_headers_middlewares.py # @Software: PyCharm import random from ...utils.header import agents class UserAgentMiddleware(object): """ CHANGE USER-AGENT """ def process_request(self,re...
14,064
b0c405359a3ff5145e359e13aeaa05ccf1f48592
## 1. Data Structures ## import pandas as pd #Read the csv file to create a dataframe fandango = pd.read_csv("fandango_score_comparison.csv") #use the .head() method to print the first two rows. print(fandango.head(2)) ## 2. Integer Indexes ## fandango = pd.read_csv('fandango_score_comparison.csv') #Select the FI...
14,065
3b5b0c3bb83dd937393cd85e2522fc7b40c4c448
# -*- coding: utf-8 -*- import os import time import shutil from threading import Thread from flask import render_template, Response, request from app import app from app.chat import itchat_run from app.utils import generator_string_id from app.models import GroupMsg from app.models import User from app.models import...
14,066
c9e44baad537f447a9409de948ece2aeffba71d5
#!/usr/local/bin/python3 import os, sys, time import psutil from multiprocessing import Manager from multiprocessing import Process def task(pids): pid = os.getpid() pids.append(pid) print('run task(pid): ', pid) time.sleep(1000) class Worker(object): def __init__(self): self.pids = Manage...
14,067
95dd4ef3d705fb8bd2fb5d403efd67b5e6629843
import tensorflow as tf with tf.GradientTape() as tape: w=tf.Variable(tf.constant(3.0)) loss=tf.pow(w,2) grad=tape.gradient(loss,w) print(grad)
14,068
4c4f9ebc1970934d249a01d9e6bb9e3194d352b5
class Node(object): def __init__(self, value): self.value = value self.next = None class Cycle_Linked_list(object): def __init__(self): self.head == None: self.tail == None: def insert_element(self, value): if self.head == None: self.head == Node(value) self.head.next = self.he...
14,069
65995791af2258500a940070b469ff7cc5935170
import datetime from werkzeug.security import generate_password_hash, check_password_hash commentslist = [] def save_comment(data): """Add comment to list""" data['comment_id'] = len(commentslist) + 1 data['message'] ="message" data['author'] = "author" data['date_created'] = datetime.datetime.now...
14,070
97abcc8ed3fc9b3de987ce53d48c4f43d1201c4c
#from django.db.models import Q from django.shortcuts import render from products.models import Product # Create your views here. def search_product_view(request): method_dict = request.GET query = method_dict.get('q','Loren') #lookups = Q(title__icontains=query) | Q(description__icontains=query) queryset = Produc...
14,071
b886de3a408b60cc271e4cf94a6982578c15fedb
import copy import getpass import subprocess from db.connectors import connection_factory from settings import DB_CREDENTIALS, DB_TYPE admin_credential = copy.deepcopy(DB_CREDENTIALS) del admin_credential['db'] cnx, connector = None, None # Create connection to mysql with admin credentials while not cnx: usernam...
14,072
50e003ca1cf355e15ad6f30ba23831b4f72a7438
from .pairwise_dist_torch import pairwise_dist_torch def cdist_kNN_graph_dict_generator_torch(transformed_dict_torch): cdist_kNN_graph = {} for key, value in transformed_dict_torch.items(): each_group_data = value each_group_cdist_torch = pairwise_dist_torch(each_group_data, each_group_data) ...
14,073
9aaa6cea83aa724280636b3cd20cf06f5d0908a3
#!/bin/python3 # Arithmetic Operators # https://www.hackerrank.com/challenges/python-arithmetic-operators/problem def solve(a, b): return (a + b, a - b, a * b) if __name__ == '__main__': a = int(input()) b = int(input()) print("\n".join(map(str,solve(a, b))))
14,074
d495a7b732091aee77b37c004df797541fc4ea43
import requests import sys url = 'http://localhost:9090/ords/hr/soda/latest/' + sys.argv[1] response = requests.delete(url) if (response.status_code == 200): print("Collection droped") else: print("Erro")
14,075
a8c68ea4caae1f05bfcf41d3cbe39efc7dc5e71e
from django.urls import path from . import views urlpatterns = [ path('',views.store, name="store"), path('checkout/',views.checkout, name="checkout"), path('cart/',views.cart, name="cart"), path('update_item/',views.UpdateItem, name="update_item"), path('process_order/',views.ProcessOrder, name="pr...
14,076
8115890f9346cbf38a9d8f7846fe9b31b5ed7809
from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse # Create your views here. from resume.models import Comm_div, Comm_code from django.views import generic from books.models import Author, Book, Log, Author_book, Best_book from .forms import AuthorForm, Boo...
14,077
b8e57e160190c95a87618570fbe3bbfdded33353
#This is where the source code is written. import datetime from BeautifulSoup import BeautifulSoup from urllib2 import Request, urlopen, URLError, HTTPError from sqlalchemy import create_engine from sqlalchemy.orm import Session import swp_database def initialise_database(): engine = create_engine('sqlite:///swp...
14,078
e139c5e968ad75d7434920fc66db3761e919da19
from django.contrib import admin from .models import Clientes # Register your models here. class ClientesAdmin(admin.ModelAdmin): list_display = ( 'id', 'Nombres', 'Apellidos', 'Direccion', 'Telefono', 'Correo', 'Cedula', 'Fecha_Nacimiento', ...
14,079
78a30b5e868cfcfd2b2666572814a9e218940827
import os import math out = open('ans.txt', 'w') fin = open('input.txt', 'r') instr = fin.readlines() fin.close() t = int(instr[0]) for i in range(0, t): row = instr[i + 1] cnt = int(0) r = float(0.0) p = float(0.0) for s in row.split(): if(cnt == 0): r = float(...
14,080
054af9f5b03b7a7d6f9742aebb7c6af1f6c80501
#################################################################### # The goal of this script is to download as much of the timeline as # possible (3200 tweets) of each neutral twitter feed. # This script is meant to be run once, in the beginning of the data # mining phase. ############################################...
14,081
62031f88627d793e83641559a8963f1e07868bb4
import argparse from functools import partial import torch from disent.metrics import METRIC_REGISTRY from disent.models import MODEL_REGISTRY from disent.optim import OPTIMIZER_REGISTRY from disent.optim.lr_scheduler import LR_SCHEDULER_REGISTRY from disent.optim.hparam_scheduler import HPARAM_SCHEDULER_REGISTRY fro...
14,082
7d09d8bfe90c17c4c22b796fffecc317b8aab01b
from sklearn.externals import joblib import cPickle as Pickle from SystemUtilities.Configuration import * from Processing import * from Extraction import Classification def train_event_detectors(patients): # Retrieve features and labels per every sentence sent_feat_dicts, labels_per_subst = sentence_features_...
14,083
a6da6154431bfb06832f0a61419975975336e2d8
from __future__ import annotations from rich.cells import cell_len from rich.console import Console, RenderableType from rich.protocol import rich_cast def measure( console: Console, renderable: RenderableType, default: int, *, container_width: int | None = None, ) -> int: """Measure a rich r...
14,084
341a39673f57049a3f28d111b7b4e46428714cc8
''' Set and change time series frequency In the video, you have seen how to assign a frequency to a DateTimeIndex, and then change this frequency. Now, you'll use data on the daily carbon monoxide concentration in NYC, LA and Chicago from 2005-17. You'll set the frequency to calendar daily and then resample to month...
14,085
f7d662066a09d3d7d6986ccddfe3d6bee0b59373
from PIL import Image from OpenGL.GL import * import numpy as np # read and save image def save_image(width, height, image_name): buffer = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE); image = Image.frombytes(mode="RGB", size=(width, height), data=buffer) image = image.transpose(Image.FLIP_...
14,086
2d420c95fd52ed90ce551dc1c49f3df434cbeafe
from django import forms from.models import Visitor class EventVisitorForm(forms.ModelForm): class Meta: model = Visitor fields = ['first_name', 'last_name', 'email']
14,087
e5a76528a7f840857543fd5c191604f6191e9c27
# add button recognition module to path import sys sys.path.append('./ButtonRec') import cv2 import bigBrother from ButtonRec import recognizer class tracker(): rec = None cam = None target = None yDims = 480 xDims = 640 center = [int(xDims/2), int(yDims/2)] effectorYOffset = 110 # effec...
14,088
60806ba1df91a80d9cfeaa9288bc3e8830b6d744
__author__ = 'kingofspace0wzz' import projection as pro import numpy as np from scipy import linalg as la from numpy.linalg import matrix_rank as rank ''' This file gives methods that analyze subspaces' relationships, those of which include: Distance between subspaces by different definitions Angles be...
14,089
d5710d06968f399db1f6aa047f1e5344451a1a89
# Write a Program to pass two variable into a function and then perform arthemtic operations (+,-,*,/).print the result def cal(a,b): print("sum is:" ,a+b) print("diff is:", a-b) print("product is:",a*b) print("quotient is",a/b) return() x=int(input("enter a no 1: ")) y=int(input("enter a no...
14,090
f3b3c01f3327032818227adb6f344951807d4930
from .eyes import Eyes
14,091
67ff15d130e284411e48421389fe53cb14b83742
from django.shortcuts import render from django.http import HttpRequest,HttpResponse # Create your views here. def home(request): return render(request,'firstapp/login.html')
14,092
c58754f97f155dfa5dd2064229adf482b7663c15
import single #f = single.Solution() print single.Solution().singleNumber([3,5,5,3,7,7,4,2,2]) #print s
14,093
eaaefe56dd84d9b1a208727453b66ae8d0b84c82
import pygame as pg import constants as c from sys import exit import setup class Main(object): def __init__(self): self.modes_dict = None self.now_mode = None def setup_modes(self, modes_dict, mode_name): self.modes_dict = modes_dict self.now_mode = self.modes_dict[mode_name]...
14,094
9dfc3cda3a9d90e02e7257731c1603972facf1a4
#! /usr/bin/python import argparse import os.path import sys import configparser class Analysis: """Class Analysis: """ def __init__(self): self.tableDD = [] parser = argparse.ArgumentParser(description="PyG : The Python Geocube Library.") parser.add_argument("--conf", help="Path to co...
14,095
66934c0fdadc6cd288779367f143bc6e67995dfd
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:hpcm # datetime:19-4-29 下午3:31 import rpyc s_obj = rpyc.connect("localhost", 22222) print(s_obj.root.now_time()) print(s_obj.root.new()) s_obj.close()
14,096
d5648c479cc4c3ceb4fd3f964f54fd992dfefba6
import torch import torch.nn as nn import numpy as np class MorseBatchedLSTMStack(nn.Module): """ LSTM stack with dataset input """ def __init__(self, device, nb_lstm_layers=2, input_size=1, hidden_layer_size=8, output_size=6, dropout=0.2): super().__init__() self.device = device # Thi...
14,097
a5ee062989d674eba2cfc9bf4d05a09d841c938c
# coding=UTF-8 import numpy as np import pandas as pd from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from scipy.spatial.distance import cdist import matplotlib.pyplot as plt import os from features.week_data import get_user_pay_week_data import params def shop_clusters(): #构造商...
14,098
d8606881e22e903f7c6bad55a95f30001640722e
import datetime from django.contrib.auth.models import User from django.db import models class Maker(models.Model): """ Создаем модель производителей машин """ name = models.CharField(max_length=20) def __str__(self): return self.name class AutoModel(models.Model): """ Создаем ...
14,099
a12a0a6cbb74b54fbc9e18f692691e116940a42d
# -*- coding: utf-8 -*- ''' Created on 24. Sep. 2015 @author: dietmar ''' import sys sys.path.insert(1, '../') from drivers.driver import * import time import threading class USBHIDDS18B20(Driver): ''' ds18b20 driver via USB HID ''' def __init__(self, parameters,logger ): ''' Con...