text
stringlengths
38
1.54M
{ "id": "mgm4442949.3", "metadata": { "mgm4442949.3.metadata.json": { "format": "json", "provider": "metagenomics.anl.gov" } }, "providers": { "metagenomics.anl.gov": { "files": { "100.preprocess.info": { ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: Gavin from odoo import models, fields, api, exceptions class Checkout(models.Model): _name = 'library.checkout' _description = 'Checkout Request' _inherit = ['mail.thread','mail.activity.mixin'] # track_visibility='onchange'表示带有该属性值的字段在被修改时记录到...
import sys from Crypto.Cipher import AES import struct import argparse def decrypt_file(key, in_file, out_file=None): """ AES file decryption script. Adaptation of script written by Eli Bendersky. params: - key: key to used to decrypt file - in_file: encrypted file to decry...
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ counter = {} offset = 0 for idx, n in enumerate(nums): if counter.get(n,0)==2: offset += 1 continue coun...
import sys import os import urllib.request, urllib.error import csv from PyQt5.QtWidgets import * from PyQt5.uic import loadUi class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() loadUi("mainwindow.ui", self) self.main_window = self ...
# Lists a = [66.25, 333, 333, 1, 1234.5] print a.count(333), a.count(66.25), a.count('x') a.insert(2, -1) a.append(333) print a a.remove(333) print a a.reverse() print a a.sort() print a a.pop() # Functional Programming Tools def f(x): return x % 3 == 0 or x % 5 == 0 print filter(f, range(2, 25)) def cube(x): retur...
import pygame from pygame.locals import * from stack import * import time pygame.init() #COLORS BLACK=[0,0,0] WHITE=[255,255,255] GREY=[128,128,128] GREEN=[0,255,0] RED=[255,0,0] BLUE=[0,0,255] SILVER=[192,192,192] def reset(): #stack global s,emptystr,highscore,show_score,launched,Start,win,speedvar,change_spee...
# A partir de la lista de "numeros" que contiene numeros del 1 al 10, obtener mediante filter # una lista llamda "pares" con los numeros pares de la lista "numeros" numeros = list(range(10+1)) # def pares(): # pares = list() # for numero in numeros: # if numero % 2 == 0: # pares.append(nu...
import gzip import os import urllib.request import numpy as np import pickle class Mnist: def __init__(self, dataset_dir: str) -> None: self._url_base: str = 'http://yann.lecun.com/exdb/mnist/' self._mnist_files: str = { 'train_img':'train-images-idx3-ubyte.gz', 'train_labe...
import PySimpleGUI as sg layout = [[sg.Text('What is your name?')], [sg.InputText()], [sg.Button('Ok')]] window = sg.Window('Title of Window', layout) event, values = window.read() window.close() sg.popup('Hello {}'.format(values[0]))
import os import docx #python-docx needs to be installed via pip (give details?) """ Solving people with more than two names still required I'm sure we can tidy this up too """ #establish working directory directory = './rename/files_to_rename/' files = os.listdir(directory) for f in files: #split filename from e...
class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: ret = "" array = [[a,"a"], [b,"b"], [c,"c"]] array.sort(reverse= True) while 1: top = array[0][0] mid = array[1][0] bot = array[2][0] if top > mid+bot and to...
# --- # jupyter: # jupytext: # cell_metadata_json: true # formats: ipynb,py:percent # notebook_metadata_filter: language_info # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.5.2 # kernelspec: # display_name: Pyt...
from instagram_private_api import Client, ClientCompatPatch import json import sys user_name = 'socialweb554' password = 'socialweb554.' #1518284433 - rober downey jr if __name__ == '__main__': if len(sys.argv) < 2: print('Usage: python3 get_feed.py [query] [file_result]') sys.exit(0) query...
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from datetime import datetime, timedelta from airbyte_cdk.models import SyncMode from airbyte_cdk.sources.streams.http.auth import NoAuth from dateutil.parser import isoparse from pytest import raises from source_paypal_transaction.source import Balances, P...
print "this is fun \n" #print "I love coding on the shell" print "wft, are you talking about" x = 10 print "the value of x is ", x
import argparse import enum import os import sys import time import Bio import Bio.PDB import Bio.PDB.Vector import numpy as np import simtk import simtk.openmm import simtk.openmm.app import simtk.unit basepath = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(1, basepath) import grid def extract_atomi...
''' Sorting Given a list of toy prices and an amount to spend, determine the maximum number of gifts you can buy. - Each toy can only be purchased once. ''' prices1, k1 = [1,2,3,4], 7 # 3 items prices2, k2 = [1, 12, 5, 111, 200, 1000, 10], 50 # 4 items def maximumToys(prices, k): # loop through prices # sum...
# This test file provides unit tests for functions in prediction.py from datetime import datetime from prediction import diff_month, check_date, timeseries_predict, adjust_predict, predict_price from collections import OrderedDict import pandas as pd # test diff_month() def test_diff_month(): d1 = datetime.strpt...
import os import datetime import numpy as np import xarray as xr import requests import logging log=logging.getLogger('noaa_coops') from ... import utils from .common import periods all_products=dict( water_level="water_level", air_temperature="air_temperature", water_temperature="water_temperature", ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-05-02 12:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0006_auto_20161124_2342'), ] operations = [ migrations.AddField( ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # docker_services.py # 暂未添加ssh管理接口,若要添加,直接连接至主机交换机即可 # 关于任何一步出错反馈的处理,最终需考虑到。(改成每个Popen单独执行一条命令然后捕捉返回值?) import re import sys import logging from midbox.southbound.remote_ssh import remote_ssh from midbox._config import DOCKER_REGISTRY_IP, DOCKER_REGISTRY_PORT, CTRL_PLANE_SW_...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-01-11 08:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0001_initial'), ] operations = [ migrations.AddField( mode...
'''Enunciado: Escreva um algoritimo que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta, pinta uma área de 2m2. ''' print('Calculo da quantidade tinta para pintar uma parede:') print('obs.:fornecer o valor em metro...
import torch import torch.nn as nn import torch.optim as optim # 裸写一个线性模型:定义数据,定义模型,定义train model = nn.Linear(20, 1) optimizer = optim.SGD(model.parameters(), lr = 1e-2) def train(epochs, model, loss, optimizer, train_param, train_value, valid_param, valid_value): for epoch in range(1, epochs + 1): train_...
import os import pandas as pd import numpy as np import logging as log from sutils import * log.basicConfig(level = log.DEBUG) log.basicConfig(format='[%(process)d]: %(levelname)s %(message)s') file = "tsl.csv" if (os.path.isfile(file)): pass else: print "File \'"+file+"\' not found" exit(0) df = pd.read_csv(...
# Write your function median_FITS here: import numpy as np import time import sys #import matplotlib.pyplot as plt from astropy.io import fits def median_datasets (datasetArr, m, n, l) : istack = np.dstack(datasetArr) median = np.median(istack, axis = 2) return median def load_fits ...
from mainHandler import * from validTemp import validTemp from solveConduct2d import * import cStringIO from plots import recentPlots, Plot from geolocation import get_coords import matplotlib.pyplot as plt from time import sleep from geolocation import gmaps_img from google.appengine.api import memcache def plotconto...
import multiprocessing import os import sys from functools import partial import numpy import pandas as pd from resources.functions import print_with_time, escape_invalid_xml_characters, escape_html_special_entities, \ text_to_lower, remove_only_special_characters_tokens, whitespace_tokenize_text from multiclassi...
import os import numpy as np import moby2 from moby2.scripting import products from moby2.analysis import hwp from todloop import Routine from .utils import * class CutSources(Routine): def __init__(self, **params): """A routine that cuts the point sources""" Routine.__init__(self) # ret...
count=0 sum=0 while count<10: count=count+1 shu=input("请输入一个数") shu=int(shu) sum=sum+shu print("之和为",sum)
weeks_in_year = 52 work_days_in_week = 5 week_days_in_year = weeks_in_year * work_days_in_week holiday_in_year = 30 working_days_in_year = week_days_in_year - holiday_in_year salary = 33660.00 day_rate = round(salary / working_days_in_year, 2) work_hours_per_day = 7.5 hourly_rate = round(day_rate / work_hours_per_day, ...
from django.db import models # Create your models here. class Word(models.Model): word = models.TextField(blank=True, null=True) meaning = models.TextField(blank=True, null=True)
import time import logging logger = logging.getLogger(__name__) # Log how long a function takes to run def instrument(func): def wrapper(*args, **kwargs): startTime = time.time() result = func(*args, **kwargs) endtime = time.time() diff = endtime - startTime logger.info( ...
#!/usr/bin/env python3 """Measure the start-up time of the modules with differing number of contracts.""" import os import statistics import subprocess from typing import List def main() -> None: """"Execute the main routine.""" modules = [ "functions_100_with_no_contract", "functions_100_with...
"""Add GroupRequest table. Revision ID: 39a5823a808 Revises: a364e6e9c14 Create Date: 2013-09-21 15:40:31.274287 """ # revision identifiers, used by Alembic. revision = '39a5823a808' down_revision = 'a364e6e9c14' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alem...
from datetime import datetime from unittest import TestCase from ddt import data, ddt, unpack # type:ignore[import] from healthcheck.security import safe_dict def make_test_dict(test_key, test_value, deep=1): if deep > 1: return dict(dummy=make_test_dict(test_key, test_value, deep - 1)) return {tes...
import connexion #app = connexion.FlaskApp(__name__, specification_dir='.', server='tornado') app = connexion.FlaskApp(__name__, specification_dir='.') app.add_api('swagger.yaml') print(app.app.__dict__) app.run(port=8080)
from utility import dataset_function as reader import pandas as pd import numpy as np from sklearn.base import TransformerMixin from sacred import Experiment def create_client_profile_features(X: pd.DataFrame, copy: bool = True) -> pd.DataFrame: """ Создание признаков на основе профиля клиентов. Paramete...
# Copyright 2017-present Open Networking Foundation # # 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 required by applicable law or ag...
from flask_appbuilder.models.sqla.interface import SQLAInterface from flask_babel import gettext as __ from myapp import app, appbuilder from myapp.models.log import Log from myapp.views.base import MyappModelView from . import LogMixin class LogModelView(LogMixin, MyappModelView): datamodel = SQLAInte...
## www.pubnub.com - PubNub Real-time push service in the cloud. # coding=utf8 ## PubNub Real-time Push APIs and Notifications Framework ## Copyright (c) 2010 Stephen Blum ## http://www.pubnub.com/ ## ----------------------------------- ## PubNub 3.0 Real-time Push Cloud API ## ----------------------------------- fr...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.fields.simple import TextAreaField from wtforms.validators import InputRequired, Email, Length class UserForm(FlaskForm): """creates a form for createing / editing""" email = StringField("Email",validators=[InputRequ...
#!/usr/bin/env python2 ## -*- coding: utf-8 -*- import json import os,sys import requests import time import multiprocessing.dummy debug = False def jsondump(item): return json.dumps(item, sort_keys=True,indent=4).decode('unicode_escape').encode('utf-8') class AnsibleAPI: def __init__(self,host,user,passwd,s...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from django.db.models.signals import post_save from django.template.loader import render_to_string from django.core.mail import se...
def nds(xs): p = 0 q = len(xs) - 1 for i, _ in enumerate(xs): if i == q: return (-1, -1) if xs[i] > xs[i+1]: p = i break for i, _ in enumerate(xs[p+1:], p+1): if xs[i-1] < xs[i]: q = i - 1 break return p, q def is_...
from typing import Dict, List, Optional, Union import numpy as np import gdsfactory as gf from gdsfactory.components.via_corner import via_corner from gdsfactory.cross_section import strip from gdsfactory.port import Port from gdsfactory.routing.manhattan import round_corners from gdsfactory.types import ( Compon...
''' Created on 22.10.2018 @author: Jarkko ''' from selenium import webdriver from Framehandling import cromedriverpath cromedriverpath = "C:\Python3.7\chromedriver.exe" driver=webdriver.Chrome(cromedriverpath) driver.get("https://google.fi") co=driver.get_cookies() print(len(co)) driver.delete_all_cookies() col=driver...
#!/usr/bin/python3 def remove_char_at(str, n): if n < 0: return str return (str[0:n] + str[n + 1:])
# Generated by Django 2.2.16 on 2020-09-21 13:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("aids", "0108_auto_20200615_1055"), ] operations = [ migrations.AddField( model_name="aid", name="in_france_relance"...
from .pluginmanager import PluginManager from .plugin import Plugin from .exceptions import PluginException _FORGOT_PARENS="""RegisterPlugin decorator called incorrectly. Looks like you forgot to put parens after the decorator, make sure the line looks like this: @RegisterPlugin()""" _POS_ARGS="""RegisterPlugin decor...
import numpy as np import pandas as pd import argparse import tensorflow as tf import re import jieba from utils.config import root,vocab_path import os from sklearn.model_selection import train_test_split from utils.multi_proc_utils import parallelize from tensorflow.keras.preprocessing.text import Tokenizer from tens...
import unittest import datetime from sno import Sno, epoch TestSnos = [ # inspired by https://github.com/rs/xid/blob/master/id_test.go { 'sno': Sno([0x2b, 0x44, 0x5f, 0x68, 0x34, 0x86, 0xe4, 0x28, 0x2d, 0xc9]), 'ts': datetime.datetime(2021, 10, 11, 15, 16, 34, 24000), 'tick': False, ...
# Generated by Django 2.2 on 2020-05-27 01:14 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('Fabricas', '0001_initial'), ] operations = [ migrations.CreateModel( name='VE...
import os from botocore.vendored import requests def handler(event, context): try: requests.get('https://' + os.environ['PrimaryUrl'] + "/ting") except Exception as e: print("Received an error, not retrying") print(e)
from abc import ABC, abstractmethod from .section import SectionAttacher class BaseElement(ABC): def __init__(self): pass class Element(BaseElement): """ All html components will be a child of Element Different element will implement different Attribute classes Element is used to contro...
from django.db import models from django.utils import timezone class Post(models.Model) : author = models.ForeignKey('auth.User', on_delete = models.CASCADE) title = models.CharField(max_length = 200) text = models.TextField() created_date = models.DateTimeField(default = timezone.now) published_...
from copy import deepcopy from .metaclasses.struct import StructMeta __all__ = ['Struct'] class Struct(metaclass=StructMeta): """Serialisable object with individual fields""" def __init__(self): self._attribute_container.register_storage_interfaces() def __deepcopy__(self, memo): """Se...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # Class called Tiles, should set and contain the values of the letter tile class Tiles: # initialise the class def __init__(self): # using a list for each of the letter groups self.value_one = ["A", "E", "I", "O", "L", "N", "R", ...
import simpy import os import random import pandas as pd import numpy as np import networkx as nx from collections import OrderedDict, namedtuple save_path = './result' if not os.path.exists(save_path): os.makedirs(save_path) class Resource(object): def __init__(self, env, model, monitor, tp_info=None, wf_inf...
class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: # split the text # from words[2] to words[n-1], check words[x-1] == second and words[x-2] == first # if yes, append to the result result = [] words = text.split() for i...
import json import os from pathlib import Path import instawow.cli import instawow.db from instawow.config import Config, setup_logging from instawow.models import Pkg, PkgList from instawow.resolvers import Defn from instawow.results import PkgUpToDate from instawow.manager import Manager import sqlalchemy class I...
#coding=utf-8 import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): while 1: conn=self.request addr=self.client_address while 1: receiver_data=str(conn.recv(1024),encoding="utf8") print(receiver_data) ...
''' Karen Sommer CS 521 Spring 2021 Assignment 5 Problem 9 pages 264-267 ''' #Write a function that takes as input an English sentence ( a string) and prints the total #numbers of vowels and the total number of consonants in the sentence. The function #returns nothing. Note that the sentece could have special char...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 23 22:19:49 2018 @author: Yuanpei Cao """ import pandas as pd ############################################################################### ## load geoIDs ############################################################################### df_train1_...
# -*- coding: utf-8 -*- """ Created on 张斌 2018-11-26 15:58:00 @author: zhang bin @email: zhangbin@gsafety.com Rest API --行情操作 """ import os, copy, ast, time, threading import mySystem from flask import jsonify, request, flash, render_template, redirect #导入模块 #引用根目录类文件夹--必须,否则非本地目录起动时无法找到自定义类 m...
from env.frame import Frame class Potential(Frame): def __init__(self,potential = 0): self.__potential = potential def set_(self,potential = 0): self.__potential = potential def get_(self): return self.__potential
from django.shortcuts import render, HttpResponse import datetime # Create your views here. class Person(object): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def say(self): return 'my name is' + self.name def show(request): ...
#! /usr/bin/python # -*-coding:utf-8-*- """ @Author: Tony 2513141027 @Date: 2019/10/9 21:28 @Description: QTreeView控件与系统定制模式 QTreeWidget Model QDirModel """ import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * if __name__ == '__main__': app = QApplication(sys.argv) model = QDirModel() ...
all_code = '' all_code2 = '' for a, b in self.progrem.items(): if a[0] == '_': self.add(open(b[0], 'r').read(), a, b[0]) for a, b in self.cods.items(): if 'def main' in b.code: main = b continue all_code += '\n###%s\n'%a all_code += b.code all_code ...
from django.conf.urls import url, include from django.views.generic import ListView, DetailView from poll.models import Poll, Choice from . import views urlpatterns = [ url(r'^$', views.new_poll, name='post_list'), url(r'^create_poll', views.create_poll, name='create_poll'), ]
#70. Climbing Stairs #https://leetcode.com/problems/climbing-stairs/solution/ class Solution: def climbStairs(self, n: int,memo={}) -> int: def solve(n,memo={}): if n==0: return 1 if n<0: return 0 if n in memo: return memo[...
import math def parse(in_file): lines = in_file.readlines() timestamp = int(lines[0].strip()) raw_buslist = lines[1].split(',') congruences = [(int(val), int(val) - i) for i,val in enumerate(raw_buslist) if val != 'x'] buslist = [x[0] for x in congruences] return timestamp, buslist, congr...
""" file and directory management File named location at storage (hard disk) Directory A directory or folder is a collection of files and subdirectories GUI command line CL (terminal) os-dependent windows - RealMode MS-DOS - Powershell dir MacOS - Terminal ls Linux/Unix - Terminal ...
from torch.utils.data import DataLoader from torch.utils.data import TensorDataset from torch.autograd import Variable import matplotlib.pyplot as plt import torch.nn as nn import numpy as np import torch import math # 神经网络主要结构,这里就是一个简单的线性结构 class Net(nn.Module): def __init__(self, in_num, hidden_num, out_num): ...
from django.contrib import admin from django.urls import path, include # admin以外の時はinvest.urlsを呼び出す urlpatterns = [ path('admin/', admin.site.urls), path('', include('invest.urls')), ]
#!/usr/bin/python # -*- coding: utf-8 -*- import requests import json import os import logging from dotenv import find_dotenv, load_dotenv import pickle def api_devices(path): total = 0 url = "https://" def api_call(limit): if limit == 0: object_type = "/api/" + PAYLOAD['api_version']...
from PIL import Image from PIL import ImageFont from PIL import ImageDraw import urllib.request import json import random import textwrap #For generating random quotes def getFont(i): switcher={ 1: "LongLiner.ttf", 2: "Chasy.otf", 3: "Summer.otf", 4: "Lemon.otf", 5: "Orange...
import sys sys.path.append('c:\\program files\\anaconda3\\lib\\site-packages') import glob, os import os, os.path import csv import operator import numpy as np import pandas as pd print("***********Showing CPU and GPU results are same****************") os.chdir("F:\\Studies\\Ph.D\\Ph.D Work\\ProteinDataSet\\") #For ...
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import * from .models import Todo # Create your views here. class TodoApiView(APIView): serializer_class = TodoSerializer def get(self, reque...
from doctest import run_docstring_examples import string import re from geo import Position class Tweet: def __init__(self, text, time, lat, lon): self.__text = text self.__time = time self.__lat = lat self.__lon = lon def get_words(self): """Return the words in a tweet...
#Make text file with pymol commands def main(): outFile = 'pymol_commands.txt' crowe_mabs = ['2050', '2082', '2094', '2096', '2130', '2165', '2196', '2479', '2499', '2677', '2832'] antibodies = ['CR3022'] # which set of data to show, and how to color surfaces. metric = 'max' # `max` looks way bett...
# -*- coding: utf8 -*- import os import gen_glyph SN_ENSO_SIZE = 28 SN_ENSO_HEIGHT = 35 SN_ENSO_WIDTH = 560 SN_TITLE_SIZE = 29 SN_TITLE_HEIGHT = 280 SN_TITLE_WIDTH = 48 SN_SUBTITLE_SIZE = 22 SN_SUBTITLE_HEIGHT = 280 SN_SUBTITLE_WIDTH = 48 BG_COLOR = 0x00000000 TXT_COLOR = 0xFFFFFFFF # For test ...
import torch.nn as nn # import torch.nn.functional as F from neural.types import TT class MLP(nn.Module): """Multi-layered perceptron (also called feed-forwards network)""" def __init__(self, idim: int, hdim: int, odim: int): """Create a feed-forward network. Args: idim: size of...
import pytest from fastapi.testclient import TestClient import pandas as pd from app import app DATA_PATH = "data/raw/example_for_online_inference.csv" @pytest.fixture def client(): with TestClient(app) as client: yield client @pytest.fixture def example_data(): return pd.read_csv(DATA_PATH).to_di...
# -*- coding: utf-8 -*- a, b, s = map(int, raw_input().split(' ')) if (abs(a) + abs(b)) <= s and (abs(a) + abs(b) - s) % 2 == 0: print('YES') else: print('NO')
#!/usr/bin/env python3 n = int(input()) for i in range(n+1): if int(i * 1.08) == n: print(i) exit() print(":(")
from tkinter import * scree_background_colour = "#363124" class Quizzgui: def __init__(self): self.window = Tk() self.window.minsize(width=400,height=400) self.window.config(padx=0,pady=50,bg=scree_background_colour) self.window.title("Quize Time") self.canvas = Canvas(wid...
import argparse import glob import json import sys from urllib.parse import unquote from http.server import SimpleHTTPRequestHandler, HTTPServer from http import HTTPStatus """ This server is very specific and very basic. Ultimately it tries to solve the the problem of finding out what files are available and their co...
import datetime import pandas as pd import logging # Import base class from .retrieval import Retrieval, get_data_dir, _data_dir_fallback log = logging.getLogger(__name__) class JHU(Retrieval): """ This class can be used to retrieve and filter the dataset from the online repository of the coronavirus visual...
# -*- coding: utf-8 -*- from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from urlparse import urlparse from urllib import unquote from lego_process import LegoProcess from os.path import basename, splitext import re # apply the post-order procedure # Leaf classes class List2Scalar(LegoProce...
""" Build a CBOW word2vec model """ import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import nltk from nltk.corpus import stopwords STOPWORDS = stopwords.words('english') from nltk.stem import WordNetLemmatizer LEMMATIZER = WordNetLemmatizer() import ...
from django.contrib import admin # Register your models here. from payment.models import Invoice, PaymentType @admin.register(Invoice) class InvoiceAdmin(admin.ModelAdmin): list_display = ('PayerID', 'Data', 'Rate', 'quantity', 'Created_date', 'Evidence', 'display_payment') list_filter = ['Created_date', 'P...
#coding=utf-8 import random import itertools as it from manimlib.constants import * from manimlib.mobject.types.vectorized_mobject import VMobject, VGroup from manimlib.mobject.svg.tex_mobject import TexMobject from manimlib.mobject.geometry import Rectangle, Square, Annulus, RegularPolygon from manimlib.once_useful_...
import time import sys from Report import Report if __name__ == '__main__': rpt = Report() if len(sys.argv) < 2: print("Usage: PATH_TO_MAIN.PY PATH_TO_DIRECTORY") else: print("Reading the databases...", file=sys.stderr) before = time.time() areaTitlesDict = {} ar...
def area1(x,y): return 0.5*float(x)*float(y) def area2(a,b,c): s= (a + b + c) / 2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 return area 1 choice = input("What are the dimensions of the triangle which you have:\n" "1.If you have height and base\n" "2...
# Data Visualization import matplotlib.cm as cm import matplotlib.pyplot as plt import numpy as np #from constants import * def plot_path_with_map(path_df, map_path, coordinates_box): img = plt.imread(map_path) fig, ax = plt.subplots() latitudes = path_df.latitude longitudes = path_df.longitude numberOfDots = le...
import tensorflow as tf import sys from src.main.python_code.utils.nnUtils import activate, softmax_cross_entropy # Activation function for neurons and Loss Function import tensorflow as tf def simple_lrp_linear(R, input_tensor, weights, biases=None): R_shape = R.get_shape().as_list() if len(R_shape)!=2: ...
import random import math import names from data import * from people import * from astronomy import * class Ship(object): def __init__(self,prefix=None,shipType=0,crewSize=1): # Name self.name = names.get_ship_name() self.hasCommandElement = False # Type if shipT...
# Tryout 2: Second attempt to solve the handwritten digits # We break the whole training set in x:y ration and treat y as the # testing dataset for calculating the accuracy of the algorithm import math import csv import operator from __builtin__ import len import plotpixel as plt import random '''-----...