text
stringlengths
3.07k
12.6k
# coding=utf-8 from __future__ import print_function import re import cPickle import numpy as np import pandas as pd from sklearn import linear_model, svm from sklearn import preprocessing from sklearn.ensemble import RandomForestRegressor def add_rul(df): # Remaining useful life df['RUL'] = df.groupby('id'...
import matplotlib matplotlib.use("Agg") import warnings warnings.filterwarnings("ignore", module="matplotlib") from IPython.display import display from ipywidgets import widgets import signal import matplotlib.pyplot as plt import time import thread import tensorboard import numpy as np from tensorboard import Tenso...
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import csv import filters import jinja2 import logging import os import random import urllib import webapp2 from google.appengine.api import users fr...
# -*- coding: utf-8 -*- """A simple application to read joystick inputs and send them over UART Modified from: http://www.pygame.org/docs/ref/joystick.html Example: $ python joystick_uart.py Attributes: Todo: """ import pygame import serial import argparse import debug_messages as dm # Define some colo...
import random from collections import deque from typing import Deque, Any, Dict, List, Optional, Tuple import numpy as np import torch class ReplayBuffer: """Fixed-size buffer to store experience tuples.""" def __init__( self, action_size: int, buffer_size: int, ...
import os import math import xlwt def serpentineForward(wb): ws = wb.add_sheet('SerpentineForward') lag = .5712 # Phase lag between segments frequency = 1 # Oscillation frequency of segments. amplitude = 40 # Amplitude of the serpentine motion of the snake rightOffset = 5 # Right turn offset l...
""" Convert input to Detectron2's default dictionary format. """ import glob import os from typing import List import xml.etree.ElementTree as ET from detectron2.structures import BoxMode from pycocotools.coco import COCO from .data_error import IncompatibleDatasetsError def get_class_names_pvoc(ann_dirs: List[str])...
from tompkins.ilp import schedule as schedule_tompkins from tompkins.ilp import jobs_when_where from tompkins.util import (reverse_dict, dictify, intersection, merge, unique, groupby) from collections import defaultdict def precedes_to_dag(jobs, precedes): return {a: [b for b in jobs if precedes(a, b)] fo...
import numpy as np from ml.utils import * import warnings class Layer(object): def __init__(self, optimizer='Momentum SGD', lr=0.01, momentum_alpha=0.9, beta1=0.9, beta2=0.999, weight_decay_rate=5e-4): """ Layerオブジェクトの実装 このあとの各層に共通する機能を実装する """ self.params = {} self....
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import random import math import torch import torch.nn.functional as F def compute_masked_loss(ar...
import os from collections import defaultdict import random import numpy as np from skimage.morphology import erosion, disk import cv2 import torch import torch.nn.functional as F from .core import Callback # @TODO: refactor class InferCallback(Callback): def __init__(self, out_dir=None, out_prefix=None): ...
import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from typing import Tuple, List from .tools import edit_fpath from .template import Processor from .normalization import CountNormalization class PlotHeatmaps(Processor): DSTDIR_NAME = 'heatmap' tsvs: List[...
# -*- coding: utf-8 -*- # Copyright (c) 2015-2019, Exa Analytics Development Team # Distributed under the terms of the Apache License 2.0 """ Periodic Table of Elements and Isotopes ######################################## This module provides a database of the atomic elements and their isotopes. Visualization paramete...
"""Object-Oriented Programming: Twitter example === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module description === This module contains two sample classes Tweet and User that we developed as a way to introduce the major concepts of object-orien...
# -*- coding: utf-8 -*- import json from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse, JsonResponse from blueking.component.client import ComponentClient from blueapps.account.models import User from blueking.component.shortcuts import get_client_by_user import base64 import...
# <NAME> # mqt0029 # 1001540029 # 2019-05-13 #---------#---------#---------#---------#---------#--------# import sys #---------#---------#---------#---------#---------#--------# class _Unique() : c_nameIndex = 0 def name( prefix = 'g' ) : _Unique.c_nameIndex += 1 name = f'{prefix}{_Unique.c_nameIndex}' ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import os import time import numpy as np import torch from torchvision import datasets, transforms def convert_coco_mask_to_top_class(dataset): # return the numpy array of top class of each img targets = [] for (_, target) in dataset: ...
#Pluginname="NQ Vault (Android,FS)" #Category="Extraction" #Type=FS import struct import os import tempfile from Library.java import JavaFunc from binascii import hexlify, unhexlify def findnqvault(): #Lets see where the nq vault files are ctx.gui_setMainLabel("Seeking for NQ Vault database") result={...
#!/usr/bin/env python # Copyright (c) 2015 Mirantis 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 l...
import pygame from random import randrange #colors white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (46,139, 87) blue = (0, 0, 255) try: pygame.init() except: print("Não foi possivel inicar com sucesso") #variables width = 320 height = 280 size = 10 score = 40 hour = py...
import numpy as np import sympy as sp import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from IPython.display import Math, display from sympy import lambdify def genGIF(x, y, figName, xlabel=[], ylabel=[], fram=200, inter=20): ''' Create and save a plot animation as GIF ...
# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import math import torch import argparse import random import numpy as np from vocab import Vocab from data import Dataset from model import LanguageModel def parse_ar...
from scipy.sparse import csr_matrix from sklearn.base import TransformerMixin from scipy.stats import norm from numpy import ndarray, memmap from typing import Union from DocumentFeatureSelection.init_logger import logger import numpy as np import joblib import logging def bns(X:Union[memmap, csr_matrix], fea...
# Copyright (c) 2013 OpenStack Foundation. # 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...
import marius as m import torch from omegaconf import OmegaConf from pathlib import Path from marius.tools.preprocess.dataset import LinkPredictionDataset from marius.tools.preprocess.utils import download_url, extract_file from marius.tools.preprocess.converters.torch_converter import TorchEdgeListConverter from mar...
from pyramid import httpexceptions from sqlalchemy.orm import Query from pyramid_views import utils from pyramid_views.paginator import Paginator, InvalidPage from pyramid_views.utils import ImproperlyConfigured, _ from pyramid_views.views.base import ContextMixin, View, TemplateResponseMixin, DbSessionMixin, MacroMix...
#!/usr/bin/env python3 import socket import threading import json import os from threading import Event from time import localtime, strftime VERSIONSTRING = "netlog server v0.1 alpha" connDict = { } # This dictionary contains all threaded user connections envDict = { } # This dictionary contains all log environments ...
from keras.layers import Input, Conv2D, Activation, BatchNormalization, GaussianNoise, add, UpSampling2D, Dropout, Concatenate, Merge from keras.layers.merge import concatenate from keras.models import Model from keras.regularizers import l2 import tensorflow as tf from keras.engine.topology import Layer from keras.eng...
from datetime import timedelta from dateutil.parser import isoparse from django.conf import settings from django.http import Http404 from rest_framework import viewsets from rest_framework.response import Response from accelerator.models import MentorProgramOfficeHour from ...minimal_email_handler import MinimalEmail...
""" Command line tool to run luigi tasks for project ≋ labe List tasks: $ labe.pyz -l CombinedUpdate IdMappingDatabase IdMappingTable OpenCitationsDatabase OpenCitationsDownload OpenCitationsSingleFile SolrDatabase SolrFetchDocs Run task: $ labe.pyz -r...
#! /usr/bin/python # coding:utf-8 import OpenSSL import base64 import zlib import json import time ecdsa_pri_key = """ -----<KEY> """ ecdsa_pub_key = """ -----BEGIN PUBLIC KEY----- <KEY> -----END PUBLIC KEY----- """ def list_all_curves(): list = OpenSSL.crypto.get_elliptic_curves() for...
from pathlib import PurePath import ueimporter.path_util as path_util class ChildMock: def __init__(self, name): self._name = name @property def name(self): return self._name class PathMock: @classmethod def create(cls, *pathsegments): leaf = PathMock(*pathsegments) ...
from django.shortcuts import render, get_list_or_404, redirect, get_object_or_404 from django.http.response import HttpResponseRedirect from django.urls import reverse from ecommerce.models import Categorias, Productos from django.db.models import Q from .formularios import FormProducto, FormCarrito from django.contrib...
# import scipy.io as sio import numpy as np import pandas as pd import matplotlib.pyplot as plt import sys python3 = sys.version_info > (3, 0) # Alias for len length = len def mat_var(data, struc, field): """Get the 'field' from the 'struc' in the 'data' imported from Matlab""" return data[struc][field].ite...
from flask import Flask, request, Response import os import requests import logging import sys import json app = Flask(__name__) logger = None format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logger = logging.getLogger('catalystone-service') # Log to stdout stdout_handler = logging.StreamHandler...
import socket import numpy as np import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html import dash_table import plotly.graph_objs as go import plotly.plotly as py from dash.dependencies import Input, Output from plotly import tools from utils import get_infos app = da...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2021 <NAME> # # 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...
#!/usr/bin/env python """A simple mod of SkiFree""" # Source code taken from <NAME> at # http://www.manning-source.com/books/sande/All_Files_By_Chapter/hw_ch10_code/skiing_game.py # Released under the MIT license http://www.opensource.org/licenses/mit-license.php import pygame, sys, os, random, urllib, urllib2 skier...
import random from parsec.tree import Node, Tree _CONSTRAINTS_FILE = '/constraints.yml' _PARAMETERS_FILE = '/parameters.yml' # Python 2.7 compatibility try: input = raw_input except NameError: pass def run(input): # Extract input values (passed this way for multiprocessing) processor = input[0] ...
import numpy as np import tensorflow as tf from tensorflow.python.framework import ops import matplotlib.pyplot as plt import contrib.coursera as c import utils as utils def initialize_params( layers_dim): L = len(layers_dim) params = {} for l in range(1,L): params["W" + str(l)] = tf.get_variable(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2017 Google 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 requir...
import time import logging from typing import Tuple import requests from retrying import retry from goodguy.feishu.access_token import get_tenant_access_token from goodguy.service.crawl import get_recent_contest from goodguy.util.catch_exception import catch_exception from goodguy.util.config import GLOBAL_CONFIG fro...
#!/usr/bin/env python # Author: # <NAME> (<EMAIL>) import json import os from random import shuffle, randint import sys import argparse as_ips_file = "./config/as_ips.cfg" asn_2_id_file = "./config/asn_2_id.json" out_fname = "./config/asn_2_ip.json" def getMatchHash(part, peer, count): if "AS" in part: part = ...
""" File needs to be run with python -m scripts.run-preprocessing {config_file} {language} {partition} from the command line. {config_file} is a .yaml file with configurations for stage1 preprocessing. The script is intended to be run thrice for each {language}: 1. partition="train" 2./3. partition="valid"/"test" """ ...
import math from skimage import io, color import numpy as np from tqdm import trange class Cluster(object): cluster_index = 1 def __init__(self, h, w, l=0, a=0, b=0): self.update(h, w, l, a, b) self.pixels = [] self.no = self.cluster_index Cluster.cluster_index += 1 def u...
#!/usr/bin/env python3 import sys import subprocess import argparse import time from collections import OrderedDict from threading import Thread import logging logging.disable(logging.WARN) from gridvm.simplescript.runtime.runtime import Runtime, LocalRequest # YO DWAG, WE HEARD YOU LIKE RUNTIME...
from typing import Dict, Optional, List from enum import Enum # AUTO GENERATED class CustomType(str, Enum): group = 'group' direct = 'direct' class MemberState(str, Enum): joined = 'joined' invited = 'invited' class BannedUser: def __init__(self, in_data: dict): self.description: str...
#!/usr/bin/env python # coding: utf-8 class RobotPosture: """ Class describing a robot posture """ STAND = "Stand" STAND_INIT = "StandInit" STAND_ZERO = "StandZero" CROUCH = "Crouch" def __init__(self, posture_name): """ Constructor Parameters: po...
# import tensorflow as tf import numpy as np import math """ From """ def Quaternion2Mat(quat): """ :param quat: 4 :return: 3x3 """ quat = tf.squeeze(quat) w = quat[0] x = quat[1] y = quat[2] z = quat[3] val00 = 1 - 2 * y * y - 2 * z * z val01 = 2 * x * y - 2 * z * w ...
#!/usr/bin/env python """score.py: MNEFUN stimulus event scoring functions.""" import datetime import os from os import path as op import re import glob import json import numpy as np from pytz import timezone import mne from mne.epochs import combine_event_ids from mnefun import extract_expyfun_events, read_params...
#!/usr/bin/env python3 """ Copyright 2019 Internet Archive 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 agre...
#!/usr/bin/env python from __future__ import print_function import argparse ''' This script allows transfer of DNS from an upstream DNS server via AXFR as defined in RFC 5936 and submits entries to Route 53 via boto3. It uses the UPSERT action to either create a record or update the existing one. You can use it to do ...
#!/usr/bin/env fontforge # # Copyright (c) 2016, <NAME> (https://sungsit.com | gibbozer [at] gmail [dot] com). # # This Font Software is licensed under the SIL Open Font License, Version 1.1 (OFL). # You should have received a copy of the OFL License along with this file. # If not, see http://scripts.sil.org/OFL # # T...
""" Build using pyinstaller with the following command pyinstaller --hidden-import pystray._win32 --onefile HApyAudio.py """ import PySimpleGUI as sg from psgtray import SystemTray import vlc import time import os import json import threading import paho.mqtt.client as mqtt from gtts import gTTS MACHINE_NAME = os....
import abc import itertools from nmtwizard import utils from nmtwizard.preprocess import tu class Loader(abc.ABC): """Base class for creating batches of TUs.""" def __init__(self, batch_size): self._batch_size = batch_size @property def batch_size(self): return self._batch_size ...
import torch import torch.nn as nn import torchvision.transforms as T import torchvision.utils as vutils from PIL import Image from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from dataset import LoLDataset from model import MIRNet from utils impo...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2014-2015, <NAME> <EMAIL> import logging logger = logging.getLogger(__name__) from os.path import bas...
# Day4 - 2021 Advent of code # source: https://adventofcode.com/2021/day/4 import os import numpy as np def clear_console(): os.system('clear') print('< .... AoC 2021 Day 4, part 1 .... >') print() return def draw_number(numbers_drawn, pos): numberX = int(numbers_drawn[pos]) ret...
import numpy as np import torch import pandas as pd import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch.utils.tensorboard import SummaryWriter class IKDataSet(Dataset): def __init__(self, file, transform=None): # self.ik_frame = pd.read_csv(file...
# -*- coding: utf-8 -* # ALGG 14-01-2017 Creación de módulo de asignaciones de puestos a trabajadores. class Tarea(object): '''Clase Tarea''' def __init__(self, conn): '''Constructor''' # Conexión. self.__conn = conn def get_tarea(self, equipo_id = None, anno ...
""" Reference: https://github.com/adsodemelk/PRST GRIDTOOLS Functions in MRST: checkGrid - Undocumented utility function compareGrids - Determine if two grid structures are the same. connectedCells - Compute connected components of grid cell subsets. findEnclosingCell - Find cell...
import json from datasets import load_dataset, load_metric from nltk import word_tokenize from tqdm import tqdm from tokenizers.processors import TemplateProcessing from tokenizers import ByteLevelBPETokenizer import torch import os from dataclasses import dataclass @dataclass class TransformersConfig: tgt_vocab...
# Copyright 2015 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 ag...
import time, inputsim, autopy lastsprint = time.time() def removeNonAscii(s): return "".join(i for i in s if ord(i)<128) def now_playing(): try: f = open("np.txt", 'r') npp = removeNonAscii(f.read()) except: return "???? shit broke d00d" f.close() return None if npp=="0" else npp #M...
#!/usr/bin/python3 import argparse import math from statistics import median import sys from utils import open_history_file, process_rows def find_min_time(gmres_times, ilu_times): min_time = math.inf min_ilu_time = math.inf min_loc = None for loc, times in gmres_times.items(): med_time = medi...
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache License, Version 2.0 (t...
import math import os import subprocess from csv import DictWriter from glob import glob from pathlib import Path from shutil import move from uuid import uuid4 from symbench_athens_client.exceptions import FDMFailedException from symbench_athens_client.models.designs import QuadCopter from symbench_athens_client.mode...
import math from typing import Optional import torch from torch import nn, Tensor from torch.nn import functional as F import torch.distributed as distributed from models.vqvae.vqvae import Quantize from trainer.networks import register_model from utils.util import checkpoint, opt_get class PositionalEncoding(nn.M...
import sys, os from scapy.all import * import simpy import array from hwsim_utils import HW_sim_object, BRAM, Tuser, Fifo SEG_SIZE = 64 # bytes of packet data MAX_SEGMENTS = 64 MAX_PKTS = 64 class Pkt_segment(object): def __init__(self, tdata, next_seg=None): # SEG_SIZE pkt segment self.tdata = t...
import os import platform import subprocess import multiprocessing import shutil from pathlib import Path from typing import Tuple import requests import uvicorn from triggercmd_cli import __version__ from triggercmd_cli.command.webview import PythonWebView from triggercmd_cli import settings from triggercmd_cli.util...
import argparse import importlib import json import logging import os import sys from typing import List, Optional, Tuple import flask from flask.testing import FlaskClient # Allow import from current working directory modules sys.path.append(os.getcwd()) # Constants CLI_VERSION = "0.0.1" HTTP_METHODS = ["GET", "P...
from django.conf import settings from django.contrib.admin.widgets import AdminTextInputWidget, AdminTextareaWidget from django.core.exceptions import ValidationError, ImproperlyConfigured from django.core.urlresolvers import NoReverseMatch from django.utils.html import conditional_escape from django.utils.safestring i...
import numpy as np import cv2 as cv import os #### Hyper Parameters EPS = 1e-5 NUM_PRETRAIN = 128 LR = 0.125 ##################### ## Data augmention during training , here just use 'Rotation' def random_wrap(img): h, w = img.shape[:2] angle = (np.random.rand() - 0.5) * 60 transform_ma...
import logging import serial import threading import time logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) class Colors: OFF = 0 RED = 1 GREEN = 2 BLUE = 4 class Panel(object): SWITCHES = {} BINARY_INDICATORS = {} COLORED_LED...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 2 07:20:08 2019 This code is used for testing the noise2self code on our medical images. @author: yxw """ from __future__ import print_function, division import os import torch import pandas as pd from skimage import io, transform import numpy as n...
import numpy as np from skimage.filters import sobel def slope_from_dem(dem, res, degrees=False): """Calculates slope from a Digital Elevation Model using a Sobel filter. Parameters ---------- dem : array a Digital Elevation Model res : numeric spatial resolution of the Digital Elevat...
import time import torch import torch.backends.cudnn as cudnn from numpy import random from models.experimental import attempt_load from utils.datasets import LoadStreams, LoadImages from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \ scale_coords, x...
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A buildbot command for running and interpreting webkit layout tests.""" import re from buildbot.process import buildstep from buildbot.steps import ...
import json import re from kqml import KQMLString from .kqml_list import KQMLList from .kqml_token import KQMLToken from .kqml_exceptions import KQMLException class CLJsonConverter(object): def __init__(self, token_bools=False): self.token_bools = token_bools def cl_from_json(self, json_obj): ...
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
# Copyright 2021 The Armada Authors. # # 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 w...
""" This file was created by <NAME> in August and September of 2021 with the purpose of evaluating the sentiments associated with various words found in movie reviews.""" def stripFile(): """Purpose: to turn the file input into list of words that contain no newline characters Parameters: none ...
import json import requests import spacy import nltk from collections import Counter import sys ##################### # Given user-input subreddits, this script grabs all # submissions in them that are deemed to be "recommendation/advice" # posts, then grabs all the comments associated with them. # This data is # Th...
# Copyright (c) 2019, <NAME>. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 940...
from app import db # These are the association tables needed for the many-many model relationships character_event = db.Table('character_event', db.Model.metadata, db.Column('character_id', db.Integer, db.ForeignKey('character.id')), db.Column('event_id', db.Intege...
# Copyright (c) 2018, MD2K Center of Excellence # - <NAME> <<EMAIL>> # 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, th...
from copy import deepcopy import numpy as np from scipy.linalg import norm from sklearn.base import BaseEstimator from sklearn.decomposition import PCA from sklearn.linear_model import Ridge class HHCARTNode: def __init__(self, depth, labels, **kwargs): self.depth = depth self.labels = labels ...
#!/usr/bin/env python from genericpath import exists import numpy as np import glob from distort_calibration import * from cartesian import * from registration_3d import * from optical_tracking import * from em_tracking import * from eval import * from pathlib import Path import argparse import csv def parse_args() -...
""" Multilabel classification example on HICO-DET The code employs Faster R-CNN (ResNet-50-FPN) pretrained on MS COCO as a feature extractor. Features (fc7) for the union of ground truth box pairs are computed and fed into a simple MLP to compute class logits for the 600 interactions. <NAME> <<EMAIL>> The Australian...
############################################################################## # # Original Copyright 2019 Amazon.com Inc # Original: https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container/decision_trees # Modifications to this file Copyright 2019 Leap Be...
import pickle import pandas as pd import random random.seed(1111) RAW_DATA_FILE = './data/alipay_data/ijcai2016_taobao.csv' DATASET_PKL = './data/alipay_data/dataset.pkl' def to_df(file_name=RAW_DATA_FILE): df = pd.read_csv(file_name) df.columns = ['uid', 'sid', 'iid', 'cid', 'btype', 'time'] # use_ID,sel_I...
from cached_property import cached_property import pandas as pd from typing import Union, List, Dict, Tuple, Optional import io from .uniformat import UNIBaseParser from .misc import open_filename, sort_mixed_list, date_range def get_parser(path_or_buff: Union[str, io.StringIO, io.FileIO]) -> 'TwoWireParser': pr...
import numpy as np import tensorflow as tf def load_dataset(): # load the dataset (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data() # reshape the dataset to have a single channel X_train = np.expand_dims(X_train, axis=3) X_test = np.expand_dims(X_test, axis=...
"""Metadata for kaggle classification datasets.""" import itertools from collections import OrderedDict from .kaggle_base import KaggleCompetition from ..data_types import FeatureType, TargetType from .. import scorers from .feature_maps import ( kaggle_costa_rican_household_poverty_prediction, kaggle_home...
def rotate(el,val): eval(rotors[el])[0]=eval(rotors[el])[0][val:]+eval(rotors[el])[0][:val]; pos[el]+=val #Rotar spin calculation def convert(text,converted=""): for ch in text: if ch.isalpha(): if chr(pos[-2]+65) in eval(rotors[-2])[1:]: rotate(-3,1),rotate(-2,1) #Medium Rotor Notch Triggerred (Double M...
""" Halmos' handshake problem in cpmpy. Problem formulation from Alloy (examples/puzzles/handshake) ''' Alloy model of the Halmos handshake problem Hilary and Jocelyn are married. They invite four couples who are friends for dinner. When they arrive, they shake hands with each other. Nobody shakes hands with him or h...
class MatchableString(str): pass def match_pattern(xs, ps): if callable(ps): return ps(xs) if isinstance(ps, dict): if not isinstance(xs, dict): return None ks = set(xs.keys()) if ks != set(ps.keys()): return None return match_pattern([xs.get...
from django.utils import timezone import factory from factory.django import DjangoModelFactory from factory import SubFactory, Faker from paprika_sync.core.models import PaprikaAccount, Recipe, Category from paprika_sync.users.tests.factories import UserFactory class PaprikaAccountFactory(DjangoModelFactory): u...
import argparse import logging import json import math import os from rapidstream.BE.Utilities import getAnchorTimingReportScript from rapidstream.BE.GenAnchorConstraints import getSlotInitPlacementPblock from rapidstream.BE.Utilities import loggingSetup loggingSetup() def getPlacementScript(slot_name): script = ...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2016-2017 by I3py Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ----------------...