text
stringlengths
8
6.05M
from db.DBConnectionFactory import MongoConnection Connection=MongoConnection() Connection.createDBConnection()
# Generated by Django 2.2.2 on 2019-06-12 20:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bearddb', '0002_auto_20190612_1332'), ] operations = [ migrations.AlterField( model_name='beardlog', name='event_id'...
try: import Image #import cv2 except ImportError: from PIL import Image import pytesseract img = Image.open('test.png') img.load() #cv2.imshow('image',img) #print img i = pytesseract.image_to_string(img) print i
#Additon,ubtraction,Multipalication,Divition a = 10 b = 5 c = a + b d = a - b e = a * b f = a / b print("\nAddition:",a," + ",b," = ",c) print("\nSubtraction:",a," - ",b," = ",d) print("\nMultiplication:",a," * ",b," = ",e) print("\nDivition:",a," / ",b," = ",f)
"""empty message Revision ID: 729a6131b19f Revises: 2236be5f3ade Create Date: 2018-10-28 11:18:18.668668 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '729a6131b19f' down_revision = '2236be5f3ade' branch_labels = None...
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import OrderedDict d = OrderedDict() for _ in range(int(input())): item, price = input().rsplit(' ', 1) d[item] = d.get(item, 0) + int(price) [print(item, d[item]) for item in d]
from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth import authenticate from django import forms from .interface import interface from product_mgr_app.models import Product, Rating def index_view(request): user = request.user if not user.is_authenticated: ...
from xml.dom.minidom import parse dom = parse('../date_file/config.xml') root = dom.documentElement tag_name = root.getElementsByTagName('platform') print(tag_name[0].firstChild.data)
from flask import Blueprint bp = Blueprint('separacao',__name__) from . import routes
"""User model""" from sqlalchemy import Column, Integer, BigInteger, ForeignKey, DateTime, Float, VARCHAR from models.db import Model from models.base_object import BaseObject class Trial(BaseObject, Model): id = Column(Integer, primary_key=True) TaskID = Column(Integer) UserNo = ...
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from collections import Counter from lifelines.statistics import multivariate_logrank_test from mvmm_sim.data_analysis.utils import argmax, drop_small_classes from mvmm_sim.data_analysis.super_means import get_super_means from exp...
from django import forms from .models import Container, Item MAX_NAME_LENGTH = 50 MAX_COLOR_LENGTH = 20 class ContainerForm(forms.ModelForm): class Meta: model = Container fields = ['name', 'length', 'width', 'height', 'color', 'purpose', 'note'] def clean_name(self): name = self.cle...
import numpy as np import pyqtgraph as pg app = pg.mkQApp() def test_nan_image(): img = np.ones((10,10)) img[0,0] = np.nan v = pg.image(img) v.imageItem.getHistogram() app.processEvents() v.window().close() def test_init_with_mode_and_imageitem(): data = np.random.randint(256, size=(256,...
from django.db import models # Create your models here. class TempModel(models.Model): temp_name = models.CharField(max_length = 100) def __str__(self): return self.temp_name class Meta: verbose_name_plural = "Temp Models"
import pytest from staffuser import * from food import * from order import * from system import * from id_generator import IdGenerator class TestSystem(): def setup_class(self): self.system = System() def test_system_setup(self): s = self.system assert len(s.staff) == 3 assert...
if __name__ == '__main__': s = input() has_alphanumeric = False has_alphabetical = False has_digits = False has_lowercase = False has_uppercase = False for c in s: if (c.isalnum()): has_alphanumeric = True if (c.isalpha()): has_alphabetical = True ...
""" IMIPS Implentation Author: Alex Butenko """ import cv2 import numpy as np from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as fu import sys import os dirname = os.path.dirname(__file__) sys.path.append(dirname+'/imips_misc/imips_open/python') sys.path.append(dirn...
""" This script permits to setup the python package. """ from setuptools import find_packages, setup from kili import __version__ setup( # name on pypi name='kili', # code version version=__version__, # List packages packages=find_packages(), author="Kili Technology", author_email...
/home/ajitkumar/anaconda3/lib/python3.7/hashlib.py
N = int( input()) print( N*800 - 200*(N//15))
from crm_app.models import ( Department, MealCategory, Meal, Table, Order, Check, ServicePercentage, Status, OrderedMeal) from rest_framework import serializers , fields from rest_framework.response import Response class DepartmentSerializer(serializers.ModelSerializer): cl...
#!/usr/bin/python #\file kdl_test2.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Jan.22, 2018 import numpy as np from kdl_kin2 import TKinematics if __name__=='__main__': np.set_printoptions(precision=3) print 'Testing TKinematics (robot_description ...
# -*- coding: utf-8 -*- import simplejson from django.db import transaction from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.shortcuts import (get_object_or_404, render_to_resp...
#Criando dicionário com chave do tipo inteiro clientes = { 1:'Ana', 2:'Paulo', 3:'Luiz', 4:'Claudia', 5:'Evelyn', 6:'Marcos' } #Para exibir chave do tipo int converter para string print('Mostrando dicionário completo...') print('ID: Cliente') for key, value in clientes.items(): print(str(ke...
import sys #!pip install geopy #USAGE: <script> <starting longitude> <starting lattiude> <end longitude> <end lattiude> #https://en.wikipedia.org/wiki/Great-circle_distance from geopy.distance import great_circle def geoGreatCircleDistance(startLat, startLong, endLat, endLong): startLocation = (startLat, startLong...
import tensorflow as tf import input_data import numpy as np from PIL import Image batch_size = 64 z_dim = 100 learning_rate = 0.001 beta1 = 0.5 epochs = 5000 def model_inputs(image_width, image_height, image_channels, z_dim): # Real imag inputs_real = tf.placeholder(tf.float32, (None, image_width, image_hei...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup import time import csv import requests import pandas as pd from pymongo import MongoClient #--------------------------------------------------------------------------- def data_to_dataframe(): ...
# Reading files # we import argv feature from sys module from sys import argv # we use argv feature so that it will take two names # the first, as always, script name and the second is the name of the file that we will open this_script, filename = argv # opends the file a person passes to the filename and assigns th...
import webapp2 import caesar import cgi def build_page(textarea_content): rot_label = "<label>Rotate by: </label>" rot_number = "<input name ='rot' type='number'/>" message_label = "<label>Type a message: </label>" textarea = "<textarea name='message'>" + textarea_content + "</textarea>" submit=...
from base import Base import collections import requests import datetime class Logger(Base): def initialize(self): super().initialize() self.q = collections.deque() self.listen_event(self.log_event, 'LOG_WRITE') self.listen_event(self.event) self.listen_state(self.state) ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Packet Rx Teste # Generated: Tue Oct 17 11:24:19 2017 ################################################## if __name__ == '__main__': import ctypes import sys if sys.platfo...
import if97 from if97 import ThermoDynState, get_state_by_p_and_h,\ get_state_by_p_and_s, get_state_by_h_and_s def test_Region1(): print("Table 5 - Region 1\n") print("v\t, h\t, u\t, s\t, cp\t, w\t") for T, p in ((300, 3), (300, 80), (500, 3)): state = ThermoDy...
from i_resource_protocol import IResourceProtocol from i_resource_manager import IResourceManager from file_resource_protocol import FileResourceProtocol from http_resource_protocol import HTTPResourceProtocol from no_such_resource_error import NoSuchResourceError from package_resource_protocol import PackageResourceP...
#!/usr/bin/python #\file slider3.py #\brief Expanding slider. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Apr.14, 2021 import sys from PyQt4 import QtCore,QtGui def Print(*s): for ss in s: print ss, print '' class TSlider(QtGui.QWidget): def __init__(self): QtGui.QWidget.__...
# This challenge's submission is broken # and causes severe run-time issues in the web app. # The problem has been reported but not fixed. def is_prime(num): if num == 0 or num == 1: return False for i in range(2, int(num**(1/2.0))+1): if num % i == 0: return False return True print(is_prime(int(in...
from collections import defaultdict as ddict in_file = open('input_7.txt', 'r') # in_file = open('test_7.txt', 'r') def search(b_map, target_bag): count = 0 to_find = list(b_map[target_bag].items()) def loop(bag): if bag[0] == 'no other': return 0 tmp = 0 for new in list(b_map[bag[0]].items()): tmp += loop...
import unittest from os.path import isfile, sep from os import getcwd, remove from ndb_adapter.ndb_download import DownloadHelper, DownloadType class DownloadTests(unittest.TestCase): def test_download(self): pdb_id = "5dg7" file = DownloadHelper.download(pdb_id) self.assertIsNotNone(file)...
from pwn import * import sys #import kmpwn sys.path.append('/home/vagrant/kmpwn') from kmpwn import * #fsb(width, offset, data, padding, roop) #config context(os='linux', arch='i386') context.log_level = 'debug' FILE_NAME = "./admin" HOST = "35.186.153.116" PORT = 7002 if len(sys.argv) > 1 and sys.argv[1] == 'r': ...
#-------------------------------------------------------------------------------- # G e n e r a l I n f o r m a t i o n #-------------------------------------------------------------------------------- # Name: Exercise 5.16 # # Usage: python "Exercise 5.16.py" # # Description: Helps estimate average error for an arbitr...
# Copyright (c) 2017 Jes Frellsen and Wouter Boomsma. 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 # # Unless requir...
song={"Song name":"Gordzilla","Artist":"Eminem","Released":"31/01/2019","Genre":"Hip-Hop","Producers":"Eminem "+ "and"+" D.A.Doman"} for key,value in song.items(): print(key,":",value) list = [1,2] for i in list: print (i)
from enum import Enum from pathlib import Path from lib.common.exceptions import EtypeCastError class Etype(Enum): """ The 'Any' etype returns all paths to all media in an element { "media": { "paths": [ /* all paths as strings */ ] } } """ Any = 0 # a single image Image = 1 # a single vi...
# Generated by Django 3.0.8 on 2020-10-16 15:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main_app', '0003_auto_20201015_1858'), ] operations = [ migrations.RenameField( model_name='smartphone', old_name='sd_volume...
#B from turtle import forward, right #get height input #get width input #loop twice: #draw 1 line (height) #turn 90 degrees #draw another line (width) #turn 90 degrees making_rectangle = True while making_rectangle: try: height = int(input("Height: ")) width = int(input("Width: ")...
# Generated by Django 2.0.7 on 2019-01-06 21:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basedata', '0037_auto_20190106_2107'), ] operations = [ migrations.AlterField( model_name='worknode', name='doc', ...
from itertools import cycle import re from urllib.request import urlopen import logging from random import SystemRandom RE_PROXYLINE = re.compile(r"^([^:]+):(\d+)$") RE_PROXYLINE_AUTH = re.compile(r"^([^:]+):(\d+):(.+?):(.+)$") logger = logging.getLogger("crawler.proxylist") randomizer = SystemRandom() class Proxy(o...
#!/usr/bin/python from bs4 import BeautifulSoup import sqlite3 class db: def __init__(self, filename): self.Filename = filename self.Connection = sqlite3.connect(filename) self.Cursor = self.Connection.cursor() def SaveProfile(self, url, soup): # Extract the info from the soup...
from bs4 import BeautifulSoup as bs from urllib.request import (urlopen, urlretrieve) import re class Scraper: @staticmethod def get_plain_text_from_url(url: str) -> str: soup = bs(urlopen(url), 'html.parser') text = soup.get_text().strip() text = re.sub(r'(\n\s*)+\n+', '\n\n', text) ...
# problem statement: # program should calculate the salary of all employess on # particular dob, # ex: for dob 01-01-1980 o/p shuld be 100+300=400 # ex: for dob 01-01-1981 o/p shuld be 200+400=600 data="""id,fname,lname,age,dob,salary 1,abhi,jit,34,01-01-1980,100 2,aabhi,jit2,35,01-01-1981,200 13,aaabhi,jit3,36,01-01-...
# -*- coding: utf-8 -*- #helloworld file print('Hello World, glad to be in GCI-2019') #comment comment
import configparser import numpy as np def parse_glove(path, dim=300): print("Parsing glove", flush=True) glove_embeddings = {} with open(path, "r", encoding="utf8") as f: for line in f.readlines(): elements = line.strip().split(" ") word = elements[0] vec = np....
# Generated by Django 2.2.2 on 2019-12-10 01:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DataSetCondition', fields=...
from . import real_debrid def get_cached_url(magnet_hash, filename): rd_cached_url = real_debrid.get_cached_url(magnet_hash, filename) if rd_cached_url: return rd_cached_url return None
import time import os def tac_newPayInstruction(driver): time.sleep(5) frame = driver.find_element_by_xpath(".//*[@id='form-tabs-iframeArea']/iframe[2]") driver.switch_to_frame(frame) driver.find_element_by_xpath(".//*[@id='tbNew']/input").click() time.sleep(5) driver.switch_to.default_content(...
import Util import pygame import Naves class Andromeda(Naves.Nave): def __init__(self,img,vel,pos,sonidos): Naves.Nave.__init__(self, img, pos, vel,sonidos) self.imagen = [img.imgEnemigo] self.team = 10 #friend or foe self.vista=0 self.escudo.energia=0 self.e...
from .detection import Detect from .prior_box import PriorBox from .receptive_field_prior import ReceptiveFieldPrior __all__ = ['Detect', 'PriorBox', 'ReceptiveFieldPrior']
from .actions import * from .grid import * from .report import * from .query import *
''' Gil Garcia ASTR232 - Cosmology Sept 11, 2019 HW1 ''' ### routines needed for the assignment ### #To find the line of best fit's slope and y-int, I created a method of least squares fxn def least_squares(x,y): N=float(len(x)) #We know will use the equations given in class to find A and B #A= y-int, B= slope d...
# Generated by Django 2.1 on 2019-06-07 08:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maths', '0001_initial'), ] operations = [ migrations.AlterField( model_name='maths', name='description', f...
# -*- coding: utf-8 -*- from database import init_db, db_session from models import User, Group, Location, Event from werkzeug import generate_password_hash import datetime init_db() session = db_session() user = User( username='martin.czygan@gmail.com', first_name='Martin', last_name='Czygan', dob=datetime.date...
from random import randrange from time import sleep jokenpo = ['Pedra', 'Papel', 'Tesoura'] random_index = randrange(len(jokenpo)) escolha_computador = jokenpo[random_index] print('[0] Pedra (punho fechado)') print('[1] Papel (mão aberta)') print('[2] Tesoura (dois dedos esticados)') opcao = int(input('Qual você quer...
from .cross import cross from .load_obj import load_obj from .look import look from .look_at import look_at from .mesh import Mesh from .optimizers import Adam from .perspective import perspective from .rasterize import rasterize, rasterize_silhouettes, rasterize_rgba, rasterize_rgb, rasterize_depth, rasterize_all from...
#!/usr/bin.python # -*- coding: utf-8 -*- import os, sys, inspect, csv, json, time import Queue, threading pfolder = os.path.realpath(os.path.abspath (os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],".."))) if pfolder not in sys.path: sys.path.insert(0, pfolder) import sframe as sf from...
import re import itertools with open("input.txt") as f: aoc_input_data = f.readlines() position_regex = re.compile(r'([0-9]+),([0-9]+)') size_regex = re.compile(r'([0-9]+)x([0-9]+)') def calculate_square_inches(input_data): points = set() common_points = set() for data in input_data: positi...
#!/usr/bin/python from Bio import SeqIO from sklearn.svm import SVC from sklearn.model_selection import GridSearchCV, cross_val_score, KFold import numpy as np import csv from featuresetup_module import transcript_info, transcript_info_dict from sklearn.externals import joblib from sklearn import preprocessing import ...
__author__ = __maintainer__ = "Elyas Heidari" __email__ = 'eheidari@student.ethz.ch' __version__ = "0.1.1" from . import classifier, model, sage, utils, MGA_data, DHH_data
#!/usr/bin.python # -*- coding: utf-8 -*- import os from luigi import six import luigi import luigi.contrib.hadoop import luigi.contrib.hdfs import commands def cmd(cmdstr): #执行Liunx Shell命令并返回状态码 #cmmands:Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果。 exit_code = commands.getstatusoutput(cmdstr)[0] ...
import json import logging import typing import aiohttp from aiohttp import hdrs import aiohttp_socks from . import config from . import common from . import models logger = logging.getLogger(config.LOGGER_NAME) class RZDClient: def __init__(self): self._session: typing.Optional[aiohttp.ClientSession]...
from sklearn.datasets import load_files from keras.utils import np_utils import numpy as np from glob import glob def load_dataset(path): print(path) data = load_files(path) print('데이타 로드') dog_files = np.array(data['filenames']) print('넘파이 어레이 화') dog_targets = np_utils.to_categorical(n...
import mysql.connector import constants myCon = mysql.connector.connect( host=constants.DB_HOST, user=constants.DB_USER, # password= constants.DB_PASSWORD, database=constants.DB_NAME) mycur = myCon.cursor() with open('schema.sql') as f: mycur.execute(f.read()) myCon.commit() myCon.close()
import os from Tkinter import * import imp import tkjv.TreeWidget from tkjv.TreeWidget import TreeItem from tkjv.TreeWidget import TreeNode from tkjv.TreeWidget import ScrolledCanvas import redis_tree class RedisItem(TreeItem): def __init__(self, node_id): self.node_id = node_id self.node = redis...
from django.shortcuts import get_object_or_404, redirect from django.contrib import messages from django.forms.models import inlineformset_factory, modelformset_factory, formset_factory, modelform_factory from apps.tests.models import Test, TestCase def test(request): test_id = request.session.get('test', None)...
import tkinter as tk from webscrapper import search import webbrowser COLOR = "#ffa200" def query(var): newVar = search(var) label['text'] = newVar[0] def linkopen(var, num): new = 1 url = search(var)[1][num] webbrowser.open(url,new=new) # innit tkinter root = tk.Tk() root.attri...
"""This module contains various utility functions""" import matplotlib.pyplot as plt from scipy.stats import norm def group_res(data, group_cols, statistic): """Splits dataframe into dictionary based on grouping :param data: input data to be split :param group_cols: group columns for data ...
import os import sys print("version of python: ", sys.version) # r for reading # w for writing # a for appending # creating file with content f0 = open("F:\\file1.txt", "w") print("opening a new file file1.txt & writing contents to it") f0.write("Hi Hello Good morning \n") f0.write("End of File") f0.close() # # rea...
import json import psutil from was import app from was.models import * from was.decorators import args, auth from utils import mongodb from flask import request, jsonify, json from pony.orm import db_session, core, select from pony.orm.core import ObjectNotFound from datetime import datetime, timedelta def search_db(u...
from sklearn.datasets import fetch_20newsgroups from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer emails = fetch_20newsgroups() print(emails.target_names) categories = ['rec.sport.baseball', 'rec.sport.hockey'] emails = fetch_20newsgroups(categories=categories) ...
class Solution: def build_string(self, string): stack = [] for s in string: if s != '#': stack.append(s) elif s == '#' and stack: stack.pop() return ''.join(stack) def backspaceCompare(self, S, T): """ :type S: str...
# function are first class citizen in Python # can be used anywhere where an indetifier could be used # passed to functions, return from functions etc. def logusage(f): def function_wrapper(*args, **kwargs): print("="*30) print("calling function: %s" % f.__name__) print("args=%s, kwargs=%s"...
# property # 定义一个person类,具有name,age属性 # 对于任意输入的姓名,我们希望都用大写方式保存 # 年龄,我们希望内部统一用整数保存 # x = property(fget,fset,fdel,doc) ''' class Person(): def fget(self): # 函数的名称可以任意 return self._name def fset(self,name): self._name = name.upper() # 所有输入的姓名以大写形式保存 def fdel(self): self._name = "...
''' Author: Sonal Ranjit This script transforms a give time series to the frequency domain using the method of Least Squares. The main concept here is to determine the coefficients of a sum of sine and cosines functions that best fit the given time series. The function to fit in the problem is: p(w_j) = c1*sin(2piw_j...
import cv2 import os import math labels_path = 'labels/train/' img_path = 'images/train/' labels = [] for file in (os.listdir(labels_path)): if file.split('.')[1] == 'txt': labels.append(labels_path + file) print(labels) for label in labels: l = label aux = label.split('/')[2] img = img_path + aux.split('.')...
# encoding: utf8 from __future__ import unicode_literals STOP_WORDS = set(""" а або адже але алло багато без безперервно би більш більше біля близько був буває буде будемо будете будеш буду будуть будь була були було бути в важлива важливе важливий важливі вам вами вас ваш ваша ваше ваші вгорі вгору вдалині вже ви ...
# -*- coding: utf-8 -*- import pywapi result = pywapi.get_weather_from_yahoo('JAXX0085') weather = '---\n' + \ result['title'] + '\n現在の' + \ result['location']['city'] + u'の天気:' + \ result['condition']['text'] + u'\n' +\ u'---' print weather
import numpy as np def compute_error_for_given_points(b, m , data_points): totalError = 0 for i in range(0, len(data_points)): x = data_points[i, 0] y = data_points[i, 1] #By the Error Formula totalError = totalError + (y - (m * x + b)) ** 2 return totalError / float(len(d...
import replitdb.commands def main(): import sys import os del sys.argv[0] url = False setUrl = os.environ['REPLIT_DB_URL'] args = [] for i in sys.argv: if(url): url = False setUrl = i elif(i.lower()=='-url'): url = True else: args.append(i) ...
""" distutilazy.command.clean_jython_class -------------------------------------- Command to clean compiled .class files created by Jython. :license: MIT. For more details see LICENSE file or https://opensource.org/licenses/MIT """ import distutilazy.clean class clean_jython_class(distutilazy.clean.CleanJythonClass...
import numpy as np def productoMatrix(a,b): """ Producto de Matrices (m x n) = (m x l)(l x n) """ c = np.zeros((len(a),len(b[0]))) for i in range(len(a)): for j in range(len(b[0])): for k in range(len(b)): c[i,j] += a[i,k]*b[k,j] return c def productoM...
a = "whats good" b = 2 print('hello world') #this is the new change c = 5
me = {} me['Name'] = 'Pete' me['Age'] = 29 me ['Country of Birth'] = "USA" me ["Favorite Langauge"] = 'JavaScript' def dictionaryInputs (dictionary): for key, data in dictionary.iteritems(): print 'My', key, 'is', data dictionaryInputs(me)
import randStr def test_randWord(self): # Failure message: # Tests if random word is returned s1 = "Hello, this is my test string and should only be one word in return" t1 = randStr.randWord(s1, "a") t3 = randStr.randWord(s1, "b") t4 = randStr.randWord(s1, 5) t5 = randStr.randWord(s1) ...
import base64 def get_base64_diff_value(s1, s2): """get base64 diff value""" base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for i in range(len(s2)): if s1[i] != s2[i]: return abs(base64chars.index(s1[i]) - base64chars.index(s2[i])) return 0 def so...
# coding: utf-8 class Solution: # @param nums, a list of integer # @param k, num of steps # @return nothing, please modify the nums list in-place. def rotate(self, nums, k): for x in range(k): num = nums[-1] nums.pop() nums.insert(0, num) return None ...
class Graph(object): def __init__(self, entities, triggers, relations, roles, vocabs, mentions=None): """ :param entities (list): A list of entities represented as a tuple of (start_offset, end_offset, label_idx). end_offset = the index of the end token + 1. :param triggers (...
from flask import Flask, request, jsonify, Blueprint from db import db import json from .api_utils import create_http_response app = Flask(__name__) betting = Blueprint('betting', __name__) @betting.route('/api/betting/place_bet', methods=['POST']) def place_bet(): ''' Places a bet into the database, and ret...
# -*- coding: utf-8 -*- ############# # # Copyright - Nirlendu Saha # # author - nirlendu@gmail.com # ############# import inspect import sys from libs.logger import app_logger as log import database as discover def get_discovery( person_id, ): log.info('IN - ' + sys._getframe().f_code.co_name) ...
import pygame import gameLogic # pygame initialization pygame.init() gameLogic.intro() gameLogic.instructions() gameLogic.game() pygame.quit() quit()
#Programa: act20.py #Propósito: una compañía de transporte internacional tiene servicio en algunos países de América del Norte, América Central, América del Sur, Europa y Asia. El costo por el servicio de transporte se basa en el peso del paquete y la zona a la que va dirigido. #Autor: Jose Manuel Serrano Palomo. #Fech...
from scipy.io import loadmat ''' Step 0: Load the data from './data/lab8spam_train.mat' and './data/lab8spam_test.mat' ''' dataset_train = loadmat('data/lab8spam_train.mat') print(dataset_train.keys()) dataset_test = loadmat('data/lab8spam_test.mat') print(dataset_test.keys()) print('\n') X_train = dataset_train[...
from ..bases.imag_ffts import _ImagFFTBasis import numpy as np from ..fmks.func import deprecate class CahnHilliardSimulation(_ImagFFTBasis): r""" Solve the `Cahn-Hilliard equation <https://en.wikipedia.org/wiki/Cahn-Hilliard_equation>`__ for multiple samples in arbitrary dimensions. The concentration ...