content
stringlengths
5
1.05M
from setuptools import setup exec(open("shmistogram/version.py").read()) from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='shmistogram', version=__version__, auth...
import unittest from .helpers import * from .. import * from ..timed import timed_note_iterator from ...timing import Beat, TimingData class TestTimedNoteStream(unittest.TestCase): def test_timed_note_stream(self): timed_notes = list(timed_note_iterator( note_data=NoteData.from_chart(testing_...
import numpy as np from project.cell import cell print(cell(3)) #> [,1] [,2] [,3] #> [1,] numeric,0 numeric,0 numeric,0 #> [2,] numeric,0 numeric,0 numeric,0 #> [3,] numeric,0 numeric,0 numeric,0 print(cell(2,3)) #> [,1] [,2] [,3] #> [1,] numeric,0 numeric,0 numeric,...
import logging from datetime import datetime, timedelta from typing import Optional, Dict, List, Union from airflow.decorators import task from toloka.client import Assignment, Pool, Project, Task, Training from toloka.util._managing_headers import add_headers from ..hooks.toloka import TolokaHook from ..utils impor...
def write_file(path, outputs): with open(path, "w") as fp: for output in outputs: line = ' '.join([str(value) for value in output]) fp.write(line)
import functools import operator import time import sys import click import os.path def ensure_dir_exists(path): if not os.path.exists(path): os.makedirs(path) def product(iterable): return functools.reduce(operator.mul, iterable, 1) class Timer: def __init__(self, name=None, verbose=True): ...
from typing import TYPE_CHECKING import requests from ravendb.documents.session.misc import DocumentQueryCustomization from ravendb.http.topology import Topology if TYPE_CHECKING: from ravendb.documents.session.in_memory_document_session_operations import InMemoryDocumentSessionOperations class EventArgs: ...
#!/usr/bin/env python3 # Copyright 2018 Christian Henning # # 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 l...
import matplotlib.pyplot as plt import matplotlib.image as mpimg from matplotlib.widgets import Slider def update(val): #do your update here pass image_path = "charts/chart" + str(1) + ".png" img=mpimg.imread(image_path) plt.axis('off') plt.imshow(img) cat_plot = plt.axes([0.13, 0.02, 0.75, 0.02]) samp = ...
import sys import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): ''' Input: messages_filepath: File path of messages data categories_filepath: File path of categories data Output: Two dataframes messages and categories '...
#!/usr/bin/env python import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import bluetooth import struct import time from sphero_driver import sphero_driver import sys from tornado.options import define, options define("port", default=8888, help="run on the given port", type=in...
#Ordered Dictionary: from collections import OrderedDict Programming_words = OrderedDict() Programming_words = { 'method' : 'function or process to do something in a program', 'list' : 'Collection of values which can be accessible through index starting from 0.', 'dictionary' : 'Collection of values not st...
import logging from collections import defaultdict from collections.abc import MutableMapping from typing import List, Any import numpy as np import pandas as pd from elasticsearch import ( TransportError, Elasticsearch, ElasticsearchException, NotFoundError, ) from elasticsearch.client import IndicesC...
import json from gdata.spreadsheet.service import CellQuery, ListQuery from googlesheets.util import normalize_header class Sheet(object): """ A sheet is a particular table of data within the context of a ``Spreadsheet``. Each sheet is comprised of a set of rows which can be iterated over, filtered, adde...
# Single response columns/questions # Duplicate names have indexes appended by Pandas REGION = "Where are you from?" GENDER = "What is your gender?.1" AGE = "How old are you?.1" OTHER_GAMES_IDOL = "Do you play other idol-like games?" OTHER_GAMES_RHYTHM = "Do you play other rhythm games?" CHARACTER_POPIPA = "Who is your...
""" Sample reading plan""" from __future__ import absolute_import import ctypes from ddls.base import check_call, LIB, c_str, c_array from ddls.feeder.plan import Plan class PlanMaker(object): """ The sample reading plan maker """ def __init__(self): """ init a new PlanMaker instance """ ...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-24 18:21 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import main.models import unixtimestampfield.fields class Migration(migrations.Migration): initial = True dependencies = [...
myArray = [[0] * width] * height # DOES NOT WORK AS INTENDED!!!
from drone import plugin import subprocess import sys class DroneTower(object): def __init__(self): args = plugin.get_input() try: self.cwd = args['workspace']['path'] except KeyError: self.cwd = None self.vargs = args['vargs'] def run(self): i...
from __future__ import absolute_import import collections import logging import pika import pika.exceptions from tornado import gen, locks from typing import Callable, Any, Generator, Union from .common import BaseChannel from . import compat from .compat import Awaitable from . import common from . import exceptions ...
# proxy module from __future__ import absolute_import from scimath.units.convert import *
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import defaultdict, Iterable try: from itertools import izip as zip from itertools import imap as map from itertools ...
# coding: utf-8 # In[ ]: # plot a ugrid mesh # In[1]: get_ipython().magic(u'matplotlib inline') # In[2]: import matplotlib.tri as tri import pyugrid # In[3]: #url = 'http://www.smast.umassd.edu:8080/thredds/dodsC/fvcom/mwra/fvcom' url = 'http://geoport.whoi.edu/thredds/dodsC/usgs/vault0/models/tides/vdatum_...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages try: long_description = open("README.md").read() except IOError: long_description = "" setup( name="paulmann", version="0.1.0", description="lib for accessing Paulmann Lichts BLE enabled lights", license="MIT", author="mje...
# -*- coding: utf-8 -*- import sys sys.path.insert(0, '/srv/wcdo/src_viz') from dash_apps import * databases_path = '/srv/wcdo/databases/' data_scripts_path = '/srv/wcdo/src_data/' apps_scripts_path = '/srv/wcdo/src_viz/' n_lines_default = 100 ### FUNCTIONS ### ### ### ### ### ### ### ### ### ### ### ### ### ### #...
import cv2 as cv VIDEO_URL= "" vcap = cv.VideoCapture(VIDEO_URL) while(1): ret, frame = vcap.read() cv.imshow('VIDEO', frame) cv.waitKey(1)
"""This module implements the EmailAdapter interface for sendmail. """ # Author: Ling Thio <ling.thio@gmail.com> # Copyright (c) 2013 Ling Thio from __future__ import print_function # Non-system imports are moved into the methods to make them an optional requirement from flask_user import current_app, ConfigError f...
# Example: amorphous silicon, Tersoff potential # Computes: Quasi Harmonic Green Kubo (QHGK) thermal conductivity for amorphous silicon (512 atoms) # Uses: LAMMPS # External files: forcefields/Si.tersoff # Import necessary packages from ase.io import read from kaldo.conductivity import Conductivity from kaldo.forcec...
from ._gal_hel import hel_to_gal, gal_to_hel
""" .. module: dispatch.plugins.google_gmail.plugin :platform: Unix :copyright: (c) 2019 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ import base64 import logging import os import platform from email.mime.tex...
# Sudoku Solver in python. class Solver: def __init__(self, board): self.board = board #Finds the next empty space. def findSpace(self): for i in range(9): for x in range(9): if self.board[i][x] == 0: return (i, x) return False #Checks the puzzle...
from model.details import Details import random from model.group import Group from fixture.orm import ORMFixture dba = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="") def test_delete_contact_from_group(app, db): if len(db.get_group_list()) == 0: app.group.create(Group(name="tes...
# coding=utf-8 # Copyright 2014-2016 F5 Networks Inc. # # 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 o...
"""Convert mel to python. :created: 23/01/2019 :author: Benoit GIELLY <benoit.gielly@gmail.com> """ from __future__ import print_function import pymel.tools.mel2py def convert_command(command, namespace="cmds", verbose=True): """Convert mel command-string to python. Args: command (str): The mel com...
# -*- coding: utf-8 -*- """ Created on Fri Jul 12 09:39:20 2019 @author: ASUS """ class Solution: def judgeCircle(self, moves: str) -> bool: # stack = [] # for move in moves: # stack.append(move) # if len(stack) > 1 and (stack[-2:] == ['U','D'] or stack[-2:] == ['D','U'] or sta...
# -*- coding: utf-8 -*- """VGG.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1CiYlyt-_cK_3PMG69THnPYXb5V-Gy83H """ import torch.nn as nn import torch.utils.model_zoo as model_zoo __help__="you can call VGGnet(kind='vgg16',num_classes=1000,batc...
def sum_(n): if n / 10 == 0: return n ** 5 else: return (n % 10) ** 5 + sum_(n / 10) n = 10 total = 0 while n < 1000000: if n == sum_(n): total += n n += 1 print total
from random import choice, sample from discord import AllowedMentions from discord.ext.commands import Bot, Cog, Context, command class Entrust(Cog): def __init__(self, bot: Bot): self.bot = bot @command(aliases=["p", "random", "choice", "dice"]) async def pick(self, ctx: Context, *args): ...
import torch import numpy as np import torch.nn.functional as F from torch import nn import time from utils import Trigonometric_kernel, computeRGB class DenseLayer(nn.Linear): def __init__(self, in_dim: int, out_dim: int, activation: str = "relu", *args, **kwargs) -> None: self.activation = activation ...
# pylint: disable=R0903 import os import json import uuid import logging import tornado.testing from codebase.utils.sqlalchemy import dbc from codebase.utils.swaggerui import api from codebase.app import make_app from codebase.models import User from codebase.utils.common import scrub class Bcolors: HEADER = '...
#!/usr/bin/env python3 # Copyright 2019 The TensorFlow Authors. 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 # # Unl...
"""wxPython data-type models"""
import asyncio import socket from unittest.mock import MagicMock, patch import pytest from asynctelegraf import TelegrafClient, UDPProtocol from tests.conftest import wait_for pytestmark = pytest.mark.asyncio @pytest.mark.parametrize('global_tags', [['key:value'], {'key': 'value'}], ids=["global_tags-list", "globa...
# Copyright (C) Midhun KM 2020 # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # # This program is distributed in the hope that it ...
import numpy as np import cv2 import copy import matplotlib.pyplot as plt import matplotlib.animation as animation positions_file = open("/Users/2017-A/Dropbox/fpga_simulation_result.txt") data = [] count = 0 new_frame = [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]] for frame in range(1000): object_num = in...
n = int(input()) dentro = 0 fora = 0 for i in range(n): x = int(input()) if (x >= 10) and (x <= 20): dentro += 1 else: fora += 1 print('{} in'.format(dentro)) print('{} out'.format(fora))
from django.contrib import admin from talon.models import Todo admin.site.register(Todo)
from toscaparser.elements.entity_type import EntityType from toscaparser.tosca_template import ToscaTemplate class TopologyValidator(): customDefinition = {} toscaBaseTypes = {} # Checks whether type1 is coherent with type2 (i.e., whether type1 is the same type or a sub-type of type2) def checkTypeCoherence(self...
# -*- coding: utf-8 -*- ''' Download images from flickr with specifit labels. ''' import flickrapi import urllib import fileutils import flickrutils # number of images to download within each label n = 5000 # images are downloaded to the following directory-- hardcoded booooo! maindir = '/home/mkayvanrad/scratch/fl...
# -*- coding: utf-8 -*- import vimbastructure as structs from vimbaexception import VimbaException from vimbadll import VimbaDLL from ctypes import * # class may extend a generic Vimba entity class one day... class VimbaFeature(object): """ A feature of a Vimba object. """ @property def name(se...
from archive_updater import check_env import os import sys import unittest sys.path.insert(0, '..') sys.path.append('..\src') sys.path.append('src') from main_functions import findNovel #target = __import__("my_sum.py") #sum = target.sum class TestMainFunctions(unittest.TestCase): def test_find(self): ...
import cv2 import numpy as np from scipy import interpolate def normal(x, width): return (int)(x * (width - 1) + 0.5) def spline3(x,y,point=360,deg=3): tck,u = interpolate.splprep([x,y],k=deg,s=0) u = np.linspace(0,1,num=point,endpoint=True) spline = interpolate.splev(u,tck) return spline[0],spl...
import pickle as pk import numpy as np import pandas as pd import subprocess from corpus_utils import PatentCorpus from plot_utils import plot_score_distr, calc_simcoef_distr, group_combis, calc_auc def make_input_file(dir_name='/home/lea/Documents/master_thesis/patent_search/database/human_eval/patent_sheets/*'): ...
import os import os.path as osp from pathlib import Path from pytest_shutil.cmdline import chdir from pytest_shutil.run import run, run_as_main from pytest_check import check ### Tests EXAMPLE = "Lysozyme" def test_dir(datadir_factory, printer): datadir = datadir_factory.mkdatadir(f'../_examples/{EXAMPLE}') ...
# MIT License # Copyright (c) 2018-2019 Groupe Allo-Media # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
constants.physical_constants["proton mag. mom. to nuclear magneton ratio"]
# The categories are fixed, do not change them. import json import pandas as pd # reading config with open('../config.json') as data: config = json.load(data) # setting up variables out_path = config["output_path_files"] outfile = config["categories"]["outfile"] language = config["language"] categories = { "...
from .card import Card from .game import Game from .players import Player
#!/usr/bin/env python import typer from guhs import guhs_cli from guhs.guhs_configuration import GuhsParameters app = typer.Typer() @app.command() def install(): """ Installs GUHS in the system """ guhs_cli.install() @app.command() def show(): """ Shows current configuration """ g...
from cpu import Cpu from screen import Screen from input_handler import InputHandler import sys class Chip8: cpu = None screen = None input_handler = None MAX_MEMORY = 4096 def __init__(self): self.screen = Screen(640, 320) self.input_handler = InputHandler(self....
import json from collections.abc import Iterable import re import logging logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s: %(message)s', level=logging.DEBUG) logger = logging.getLogger(__file__) class JsonParser: # @search returns a list with results # @searchIn is the dict/list we search in ...
import os import yaml import json from jsonref import JsonRef def get_swagger(): schema_file_path = os.path.dirname( os.path.realpath(__file__)) + '/../../mocks/server.yml' with open(schema_file_path) as f: swagger_data = yaml.load(f) swagger = JsonRef.replace_refs(swagger_data) ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 7 00:19:59 2017 @author: Mayur """ """ Exercise: apply to each Here is the code for a function applyToEach: def applyToEach(L, f): for i in range(len(L)): L[i] = f(L[i]) Assume that testList = [1, -4, 8, -9] For each of the following que...
from __future__ import absolute_import # import models into sdk package from .models.base_response import BaseResponse from .models.enumeration_item import EnumerationItem from .models.enumeration_item_response import EnumerationItemResponse from .models.error import Error from .models.issue import Issue from .models....
import torch.nn as nn class BottleNeck(nn.Module): expansion = 4 C = 32 depth = 4 base_depth = 64 def __init__(self, in_channels, out_channels, stride): super().__init__() D = BottleNeck.depth * out_channels // BottleNeck.base_depth self.split_transforms = nn.Sequential(...
#! /usr/bin/python3 #By Ismail Prada import random from collections import Counter from city import City from culture import start_Cultures from field import * from interface import Application class SimMap(object): def __init__(self, width, height): self.reach_limit = 15 self.terrain_change...
from .. import kernel_source import pyopencl as cl import pytest @pytest.fixture(scope="session") def context(): platform = cl.get_platforms() devices = platform[0].get_devices(cl.device_type.GPU) if devices == []: devices = platform[0].get_devices(cl.device_type.DEFAULT) context = cl.Context(...
import os """Application configuration""" class Config(object): """Base config class""" DEBUG = True SECRET = os.getenv("SECRET_KEY") class DevelopmentConfig(Config): """Development configurations""" DEBUG = True class TestingConfig(Config): """Testing configurations""" DEBUG = True ...
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("Masters"), "items": [ { "type": "doctype", "name": "Disc...
# # coding=utf-8 import unittest import sys import os import logging from pptx_template.cli import main BASE_DIR = os.getcwd() log = logging.getLogger() handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) log.addHandler(handler) class MyTest(unittest.TestCase): def tearDown(self): os.chdir...
# This file was automatically generated by SWIG (http://www.swig.org). # Version 1.3.36 # # Don't modify this file, modify the SWIG interface instead. # This file is compatible with both classic and new-style classes. import _highgui import new new_instancemethod = new.instancemethod try: _swig_property = property...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #200. Number of Islands #Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed ...
from transformers.modeling_bert import * import torch.nn.functional as F from torch.nn import MarginRankingLoss class BertHingeForSequenceClassification(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bert = BertModel(conf...
from tkinter import Frame, Scrollbar, Canvas, TOP, BOTTOM, BOTH, X, NW, HORIZONTAL class XScrollFrame(Frame): """ Inspired by the post at : https://stackoverflow.com/questions/16188420/tkinter-scrollbar-for-frame """ def __init__(self, root, xscrollside=BOTTOM, **cfg): bg = cf...
import io import re import requests import bonobo from bonobo.commands import BaseCommand EXAMPLES_BASE_URL = 'https://raw.githubusercontent.com/python-bonobo/bonobo/master/bonobo/examples/' """The URL to our git repository, in raw mode.""" class DownloadCommand(BaseCommand): def handle(self, *, path, **option...
# Assume python 2.7 # Path to the interpreter is deliberately not mentioned. import os import errno import sys import optparse import shlex import subprocess import threading import getpass from datetime import datetime import json def print_and_exit(rc, message): if len(message): print message sys.ex...
from itertools import chain from rest_framework import status, viewsets from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.decorators import action from django.contrib.auth import get_user_model from django.db.models import Q, Case, When, Value, Integ...
from insightconnect_plugin_runtime.helper import clean import requests from insightconnect_plugin_runtime.exceptions import PluginException import json from time import sleep from logging import Logger from urllib.parse import urljoin class CheckPhishAPI: def __init__(self, api_key: str, logger: Logger): ...
import streamlit as st import sqlite3 as lite import sys import datetime from PIL import Image image = Image.open('logo.jpg') st.sidebar.title('-------------Ray-------------') st.sidebar.image(image, caption='') st.title("Blood Request Portal") def blood_bank_location_list(): blood_bank_location_list=[] try: c...
"""Filter creation. 3D especially for FST and WST """ from collections import namedtuple import itertools import numpy as np import pdb winO = namedtuple('winO', ['nfilt', 'filters', 'filter_params', 'kernel_size']) def tang_phi_window_3D(J, kernel_size): x_pts = np.linspace(0, kernel_size[0]-1, kernel_size[...
from flask import Flask from flask import request from flask import Response from flask import jsonify import requests import json from harperDBUtil import * import sys app = Flask(__name__) #CONFIG FIND_URL = "http://localhost:18003/track" @app.route("/") def hello(): return "Hello World!" @app.route("/tra...
from argparse import ArgumentParser from xml.dom.minidom import parse import os from glob import glob def run_replace(filepath): dom = parse(filepath) namespaces = set() for wf_node in dom.getElementsByTagName('ui:InvokeWorkflowFile'): keys = [] values = [] parent = wf_node.parentN...
"""Test module for dpthree.""" from __future__ import print_function, absolute_import import sys import warnings import dpthree from dpthree import kludges from dpthree import removed from dpthree import builtins from dpthree import modules try: import unittest2 as unittest except ImportError: import unitt...
from tests import testsSetup testsSetup from paperThinRest.test.baseRestTestCase import BaseRestTestCase class Test(BaseRestTestCase): def testPing(self): data = self.expect(status=200).get('/operational-info/ping').json self.assertEqual(data, {'pong':True})
#!/usr/bin/env python3 # coding: utf-8 # @Author: ArthurBernard # @Email: arthur.bernard.92@gmail.com # @Date: 2019-05-06 20:53:46 # @Last modified by: ArthurBernard # @Last modified time: 2020-08-26 23:25:38 """ Kraken Client API object. """ # Built-in packages import hashlib import hmac import time import base64 im...
# Python Program to demonstrate the FIFO principle using doeque from collections import deque print("Queues utilize the FIFO (First In First Out) Principle") print() q = deque() # Initializating Empty Queue print("Initial empty queue :", q) # Printing empty queue # Adding items to the queue q.append("Hey") q.appen...
#!/bin/python # -*- coding: utf-8 -*- import os import csv import numpy as np from settings import * from datetime import datetime import matplotlib.pyplot as plt from os.path import isfile, join, isdir from scipy.stats.mstats import gmean from scipy.stats import norm HEADERS = [ "Description", "Model Versio...
# -*- coding: utf-8 -*- """This package defines various passives template classes. """ from typing import TYPE_CHECKING, Dict, Set, Any from bag.layout.util import BBox from bag.layout.routing import TrackID from bag.layout.template import TemplateBase from abs_templates_ec.analog_mos.mos import DummyFillActive fr...
import mock import sys from io import StringIO from tests.ModuleBaseTestCase import ModuleBaseTestCase, MockLumberMill from lumbermill.input import StdIn class TestStdIn(ModuleBaseTestCase): def setUp(self): super(TestStdIn, self).setUp(StdIn.StdIn(mock.Mock())) def testStdInSingleLine(self): ...
if __name__ == '__main__': a,b = int(input()), int(input()) print(a//b) print(a%b) print(divmod(a,b)) # print('{0}\n{1}\n({0}, {1})'.format(*divmod(int(input()), int(input())))) # a, b = int(input()), int(input()) # print("{d[0]}\n{d[1]}\n{d}".format(d=divmod(a, b)))
#!/usr/bin/env python ## ## Copyright 2009-2010 Adriana Lukas & Alec Muffett ## ## 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 ...
import requests from typing import Tuple, Optional, List from resotolib.args import ArgumentParser from resotolib.x509 import ( csr_to_bytes, load_cert_from_bytes, cert_fingerprint, gen_rsa_key, gen_csr, ) from resotolib.jwt import decode_jwt_from_headers, encode_jwt_to_headers from cryptography.x50...
# -*- coding: utf-8 -*- from lektor.pluginsystem import Plugin import datetime class DatetimenowPlugin(Plugin): name = 'DatetimeNow' description = u'Add now() to Jinja Templates.' def on_setup_env(self, **extra): self.env.jinja_env.globals['now'] = datetime.datetime.utcnow
"""An achievement group which manages and groups achievements.""" from random import choice from mpf.core.events import event_handler from mpf.core.machine import MachineController from mpf.core.mode import Mode from mpf.core.mode_device import ModeDevice from mpf.core.player import Player from mpf.core.device_monitor...
#!/usr/bin/env python3.6 # -*- Coding: UTF-8 -*- """ Classe Abstrada de Seleção de Indivíduos para cruzamento. Programa sob licença GNU V.3. Desenvolvido por: E. S. Pereira. Versão 0.0.1. """ from numpy.random import random from numpy import array class Selecao: """ Seleciona indivíduos para cruzamento. ...
import nltk from nltk import sent_tokenize from nltk.corpus import stopwords import os import pdb import re from tqdm import tqdm from itertools import chain import numpy as np import json from collections import OrderedDict import argparse def clean_data(parent_folder, store=False, filename=None, freqency_threshold=1...
from __future__ import print_function import itertools import pandas as pd from scipy.spatial.distance import cosine, jaccard import numpy as np def distance(data, metadata, field=None, value=None, method='cosine'): patient='D233' df = data.join(metadata) df = df[df[field]==value] df = df.iloc[:, :-len...
N=int(input()) p=list(map(int,input().split())) diff=0 for i in range(N): if p[i]!=i+1:diff+=1 print("YES" if diff==0 or diff==2 else "NO")
# coding:utf-8 import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import os import time import sys import datetime import ctypes import json import numpy as np from sklearn.metrics import roc_auc_score import copy from tqdm import tqdm from openke.config import Tester cl...