content
stringlengths
5
1.05M
#Title: SelectProteins.py #Author: Stephen Tanner, Samuel Payne, Natalie Castellana, Pavel Pevzner, Vineet Bafna #Created: 2005 # Copyright 2007,2008,2009 The Regents of the University of California # All Rights Reserved # # Permission to use, copy, modify and distribute any part of this # progr...
# TPPM wrapper # Copyright 2021 kensoi # works with projects that's has generated root.py file via TPPM # put this file into folder where you located all your projects. It shall look like this: # your_dir/ # manage.py <-- TPPM wrapper # botName1/ # assets/ # library/ # root.py # botName2/ # asse...
from machamp.models.machamp_model import MachampModel from machamp.models.sentence_decoder import MachampClassifier from machamp.models.tag_decoder import MachampTagger from machamp.models.dependency_decoder import MachampBiaffineDependencyParser from machamp.models.mlm_decoder import MachampMaskedLanguageModel from ma...
from __future__ import division from gltbx import wx_viewer import wx from gltbx.gl import * from scitbx.math import minimum_covering_sphere from scitbx.array_family import flex class MyGLWindow(wx_viewer.show_points_and_lines_mixin): def __init__(self, *args, **kwds): super(MyGLWindow, self).__init__(*args, **...
import json import re from unidecode import unidecode def load_jsonl(filename): examples = [] with open(filename) as f: for line in f: _example = json.loads(line) examples.append(_example) return examples def load_jsonl_table(filename): tables = dict() with open(f...
from .visualwakewords import VisualWakeWords
# MIT License # # Copyright (c) 2018-2019 Red Hat, Inc. # 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, modify, m...
from helper import get_input, flatten def get_neighbours(pos, data): row = pos[0] col = pos[1] height = pos[2] neighbours = [] for r in range(-1, 2): for c in range(-1, 2): for h in range(-1, 2): if r == 0 and c == 0 and h == 0: continue ...
from make_dataframe import make_df df = make_df() print(df.dtypes) print(df.to_markdown())
import logging from pip._internal.cli.base_command import Command class FakeCommand(Command): name = 'fake' summary = name def __init__(self, error=False): self.error = error super(FakeCommand, self).__init__() def main(self, args): args.append("--disable-pip-version-check")...
import logging import subprocess import os def read_bam(bamfilePath): """Reads a .bam line by line""" logging.debug( '[DEBUG] (read_bam) Launching samtools in subprocess to yield the lines of the bamfile {}'.format(bamfilePath)) # Samtools must be installed ! cmd = 'samtools view '+os.path.real...
import copy import logging import random import numpy as np import torch from matminer.featurizers.composition import ElementProperty from sklearn.feature_selection import VarianceThreshold from torch.utils.data import Dataset from tqdm import tqdm from cacgan.data.schema import AtmoStructureGroup, FormulaEncoder, pd...
import numpy as np from skimage import measure as measure def keep_largest_connected_components(mask, n_classes): ''' Keeps only the largest connected components of each label for a segmentation mask. ''' out_img = np.zeros(mask.shape, dtype=np.uint8) for struc_id in np.arange(1, n_classes): ...
from __future__ import print_function from future.utils import iteritems from xgcm.grid import Axis, raw_interp_function import xarray as xr def generate_axis( ds, axis, name, axis_dim, pos_from="center", pos_to="left", boundary_discontinuity=None, pad="auto", new_name=None, at...
from typing import Union class Vocab(object): def __init__(self, vocab_path: str, unk_token: str = '<unk>', bos_token: str = '<s>', eos_token: str = '</s>', pad_token: str = '<pad>', sep_token: str = '<sep>'): ...
""" Cellular provisioning classes """ import hashlib import binascii from time import sleep import boto3 from cryptography import x509 from cryptography.hazmat.primitives import serialization from pyawsutils.mar import aws_mar from pyawsutils.aws_cloudformation import MCHP_SANDBOX_ATS_ENDPOINT from pyawsutils.aws_ca_...
# Inspired by https://github.com/pytorch/vision/blob/6e10e3f88158f12b7a304d3c2f803d2bbdde0823/torchvision/ops/boxes.py#L136 import numpy as np import torch from deeptech.model.layers.roi_ops import BoxToRoi convert_to_corners = BoxToRoi() def similarity_iou_2d(pred_boxes, true_boxes): """ Return intersecti...
import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Boolean from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, autoincrement=True) arroba = ...
#!/usr/bin/env python import argparse import os.path import shutil import sys import urllib2 FL_URL='http://rdadolf.com/hosted/fathom-lite/data' VERSION='1.0' DATA_FILES=[ 'mnist-inputs.npz', 'mnist-labels.npz', 'imagenet-inputs.npz', 'imagenet-labels.npz', 'babi-stories.npz', 'babi-questions.npz', 'ba...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from __future__ import division import copy import psychopy from .text import TextStim fro...
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return ...
from django.shortcuts import render from django.http import HttpResponse # Include the `fusioncharts.py` file that contains functions to embed the charts. from ..fusioncharts import FusionCharts from ..models import * # The `chart` function is defined to load data from a `Country` Model. # This data will be convert...
""" Attacks for TensorFlow Eager """ from distutils.version import LooseVersion import numpy as np from six.moves import xrange import tensorflow as tf from cleverhans import attacks from cleverhans import utils from cleverhans.compat import reduce_sum from cleverhans.model import CallableModelWrapper from cleverhans...
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # Content: # 地址:http: //www.runoob.com/python/python-exercise-example.html # 知识点: # 地址: # Notes: from bs4 import BeautifulSoup import requests, sys, urllib2 reload(sys) sys.setdefaultencoding("utf8") wttr = "http://wttr.in/?format=1" wttrre = urllib2.Request(wttr) wttr...
import datetime import warnings from django.test import TestCase from django.core.exceptions import ImproperlyConfigured from regressiontests.views.models import Article, UrlArticle class CreateObjectTest(TestCase): fixtures = ['testdata.json'] urls = 'regressiontests.views.generic_urls' def setUp(self):...
# Copyright (c) 2021 Mira Geoscience Ltd. # # This file is part of geoapps. # # geoapps is distributed under the terms and conditions of the MIT License # (see LICENSE file at the root of this source code package). import numpy as np from geoh5py.workspace import Workspace from SimPEG import utils from geoapps.ut...
import carto2gpd import pytest import pandas as pd def test_limit(): url = "https://phl.carto.com/api/v2/sql" gdf = carto2gpd.get(url, "shootings", limit=5) assert len(gdf) == 5 def test_fields(): url = "https://phl.carto.com/api/v2/sql" fields = ["age", "fatal"] gdf = carto2gpd.get(url, "sh...
# <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> __metaclass__ = type from . import values as valuesModule from . import base as baseModule from . import standards as standa...
########################################################################## # # Copyright (c) 2017, Image Engine Design 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: # # * Redistrib...
#!/usr/bin/env python import rospy from std_msgs.msg import Float32MultiArray from sensor_msgs.msg import Joy EPS = 0.22 SPEED_FACTOR = 500 class teleJoy(object): def __init__(self): self.joy = rospy.Subscriber('/joy', Joy, self.__callback_func) self.pub = rospy.Publisher('/bot_vel', Float32Multi...
import math import sys file = 'input.txt' # For using test input instead of file input comment out following line # file = 'input_example.txt' with open(file) as f: t = f.read() # read complete file, results string of lines with endings print(' -------------- part 1: -------------- ') print(' -------------- re...
import logging from re import T from algs_wrapper.base import Base logger = logging.getLogger(__name__) class VPCC(Base): def __init__(self): super().__init__() def make_encode_cmd(self, in_pcfile, bin_file): cmd = [ self._algs_cfg['encoder'], f'--uncompressedDataPath...
import glob import os SOUNDSCAPES_FOLDER = "../data/Analysis/" # input OUTPUT_FILE = "n_events.txt" output = [] for soundscape_jam in glob.glob(SOUNDSCAPES_FOLDER + "*.jams"): soundscape_name = str(os.path.basename(soundscape_jam).split(".")[0]) n_events = "err" with (open(soundscape_jam)) as jams_file...
""" Protocol Constants """ """ Message Codes First Byte of Frame payload contains the messages code """ # TODO: Does not need a full byte to be transfered REQUEST = 0 REQUEST_ACK = 1 ACK = 2 RESPONSE_INFO = 3 DATA = 4 REQUEST_FIN = 5 """ IDs For a better performance: Lower IDs are better than higher IDs Identifier ...
import json from typing import Optional import pytest from requests import Response from fidesops.schemas.saas.saas_config import SaaSRequest from fidesops.schemas.saas.shared_schemas import SaaSRequestParams, HTTPMethod from fidesops.common_exceptions import FidesopsException from fidesops.schemas.saas.strategy_confi...
#!/usr/bin/env python2 # -*- coding: utf8 -*- import sys reload(sys) sys.setdefaultencoding("utf8") import time from selenium import webdriver from bs4 import BeautifulSoup import codecs from selenium.common.exceptions import NoSuchElementException import os import os.path chrome_options = Options() chro...
import asyncio from chunk import Chunk from datetime import datetime import pickle from typing import Callable, Dict import numpy as np import open3d as o3d from .message import BaseMessage, ResponseMessage, MeshesMessage, DeformableMeshesMessage class MeshChunksHandler: """ A middleware to merge chunks into its...
# coding=utf-8 # Copyright 2018 The Batfish Open Source Project # # 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 requi...
# encoding: utf-8 __author__ = 'jesuejunior'
"""Task definitions for machine translation tasks.""" import codecs import collections import math import os from typing import Iterable, List, Sequence, Type from allennlp.data import Instance from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.training.metrics import Average from ..utils.dat...
import os from uploader.api import ( get_repo_list, create_repo, get_repo, upload_file, get_share_link, get_token ) from uploader.logger import get_logger logger = get_logger(__name__) def upload_local_file( server, token, repo_id, upload_url, repo_path, file_path, replace=True ): file_na...
from django.contrib.gis.db import models from django.utils.translation import ugettext_lazy as _ from ..reversion_utils import InitialRevisionManagerMixin class WaterParcelManager(InitialRevisionManagerMixin, models.GeoManager): pass class WaterParcel(models.Model): """ A parcel defined by the Philadel...
'''OpenGL extension INGR.color_clamp This module customises the behaviour of the OpenGL.raw.GL.INGR.color_clamp to provide a more Python-friendly API Overview (from the spec) Various RGBA color space conversions require clamping to values in a more constrained range than [0, 1]. This extension allows the defi...
#-*- coding:utf-8 -*- from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal from PyQt5.QtGui import QPainter, QColor from board import Board class Tetris(QMainWindow): def __init__(self): super().__init__() self.initUI()...
# Generated by Django 2.1 on 2018-08-19 14:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("mainapp", "0057_add_status_to_relief_camp"), ] operations = [ migrations.CreateModel( name="DataCollection", fields=[ ...
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # from typing import Any, Dict, List, Mapping from unittest.mock import patch import pytest from airbyte_cdk import AirbyteLogger from source_s3.source_files_abstract.stream import FileStream from .abstract_test_parser import create_by_local_file, memory_lim...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 5 12:39:28 2022 @author: brunocr """ '''Define a function that removes from a given array of integers all the values contained in a second array''' def popper (father_array: list, popper: list)->list: res=[] for i, c in enumerate(father...
import logging import os.path import json logger = logging.getLogger(__name__) uri = "/isam/ssl_certificates" def get_all_certificates (isamAppliance, check_mode=False, force=False): """ Get information about all certificates on the appliance """ import time epoch_time = int(time.time()) ...
import unittest as t from py3tftp.exceptions import BadRequest, UnacknowledgedOption from py3tftp.tftp_parsing import (blksize_parser, parse_req, timeout_parser, validate_req) class TestTimeoutParser(t.TestCase): def test_lower_bound(self): low_val = b'-11' with ...
print("""Exercício Python 078: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. """) lista=[] cont = 0 for i in range (0,5): lista.append(str(input("digite um numero "))) cont += 1 ...
import praw import datetime import time from requests.exceptions import HTTPError from praw.errors import ExceptionList, APIException, InvalidCaptcha, InvalidUser, RateLimitExceeded import sqlite3 as sql from bs4 import BeautifulSoup from emailGlobals import sendEmail from inboxHandler import readInbox from getMatchInf...
from selenium import webdriver import time PATH = "driver/geckodriver.exe" try: browser = webdriver.Firefox(executable_path=PATH) print("Success.") except Exception as e: print(f"Browser cannot be started. ERROR {e}") URL = "https://curso-python-selenium.netlify.app/exercicio_01.html" browser.get(URL)...
from pydantic import BaseModel, Field class ViveTrackerMessage(BaseModel): valid: bool = Field(default=False) x: float = Field(default=0.0) y: float = Field(default=0.0) z: float = Field(default=0.0) roll: float = Field(default=0.0) pitch: float = Field(default=0.0) yaw: float = Field(defa...
# -*- coding: utf-8 -*- import json import re from django.conf import settings from django.utils import six from rest_framework.parsers import JSONParser, ParseError # Parser logic taken from vbabiy's djangorestframework-camel-case project # https://github.com/vbabiy/djangorestframework-camel-case first_cap_re = re...
from keras.models import model_from_json import cv2 import numpy as np class GazeNN(object): def __init__(self, json_model_file, h5_model_file): json_file = open(json_model_file, 'r') self.loaded_model_json = json_file.read() json_file.close() self.loaded_model = model_from_json(se...
class Solution(object): def movesToChessboard(self, board): """ :type board: List[List[int]] :rtype: int """ size = len(board) half, raw_sum, col_sum = size >> 1, 0, 0 for i in range(size): raw_sum += board[0][i] col_sum += board[i][0] ...
# Generated by Django 2.0.8 on 2018-08-27 09:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [("hordak", "0026_auto_20190723_0929")] operations = [ migrations.RunSQL( """ CREATE OR REPLACE FUNCTION update_full_account_codes() ...
#! /usr/bin/env python3 # _*_ coding:utf-8 _*_ import re import os import time import operator import serial import json import serial.tools.list_ports #from serial.serialutil import * """ operate on windows COM """ def test_com(): """test windows COM recv and send data""" port = [] plist = list(serial...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-11-03 18:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Speake...
#Adapted from https://github.com/hpcaitech/ColossalAI-Examples/blob/main/language/gpt/model/gpt1d.py #!/usr/bin/env python # -*- encoding: utf-8 -*- import math from colossalai.utils.activation_checkpoint import checkpoint import torch from torch import nn as nn, Tensor from colossalai.core import global_conte...
from pathlib import Path import pandas as pd from typer import secho import os from shutil import move # from os import path def read_list(list_path:Path): if str(list_path).endswith('.csv'): list = pd.read_csv(list_path, sep=';') from_col = [] to_col = [] for i in list['from']...
from delivery.extensions.auth.controller import create_user, save_user_photo from delivery.extensions.auth.form import UserForm from flask import Blueprint, redirect, render_template, request bp = Blueprint("site", __name__) @bp.route("/") def index(): return render_template("index.html") @bp.route("/about") d...
import tensorflow as tf def vgg_block(num_convs, num_channels): blk = tf.keras.models.Sequential() for _ in range(num_convs): # strides默认 = (1, 1) blk.add(tf.keras.layers.Conv2D(num_channels,kernel_size=3, padding='same',activation='relu')) blk.add(tf.ker...
# Copyright 2014-2015 PUNCH Cyber Analytics Group # # 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...
import torch from ..utils.manifold_multi import multiprod, multitransp, multisym from .manifold import Manifold class Hyperbolic(Manifold): """ Class for Hyperbolic manifold with shape (k x N) or N With k > 1 it applies product of k Hyperbolas """ def __init__(self, n, k=1): if n < 2: ...
""" Small WSGI filter that interprets headers added by proxies to fix some values available in the request. """ import re from typing import Callable, Dict, Any SEP_RE = re.compile(r', *') class Filter: def __init__(self, application: Callable[[Dict[str, str], Any], Any]): self._application = applicatio...
class Job(object): def __init__(self, pipeline_connector, **kwargs): self.kwargs = kwargs self._pipeline_connector = pipeline_connector def pipeline_context(self): return self._pipeline_connector.pipeline_context() def serialize(self): from foundations_internal.serialize...
""" To run: $ python lstm_frag.py --data_path=path/to/train.list """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.insert(0, "../src/") from utils.vector_manager import VectorManager import numpy as np import tensorflow as tf impor...
from django.apps import AppConfig class PofileDiffReduceConfig(AppConfig): name = 'pofile_diff_reduce'
#!/usr/local/bin/python3 def main(): # Test suite tests = [ [None, None], # Should throw a TypeError [0, False], [1, True], [2, True], [15, False], [16, True], [65536, True], [65538, False] ] for item in tests: try: t...
# Lesson 6 # Sometimes, we want to protect some of the data or methods in our classes class RestroomStall: def __init__(self): self._occupants = 0 # protected variables discourage use self.__bathroom_cam = 0 # private variables prevent use def is_occupied(self): return sel...
import numpy as np from numpy import load from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt import matplotlib.patches as mpatches train_split = 0.8 lead_time = 1 data_path = 'data/' out_path = 'out/' y = load(data_path + 'y.npy') for lead_time in [1, 2, 3, 6, 12, 23]: ...
# -*- coding: utf-8 -*- __all__ = [ "cublas", ] from functools import reduce from operator import mul import numpy as np # Local imports from cublas_import import (cublas_axpy, cublas_copy, cublas_destroy, cublas_gemm, ...
from citrination_client.search.core.query.filter import Filter from citrination_client.search.pif.query.chemical.chemical_field_query import ChemicalFieldQuery from citrination_client.search.pif.query.chemical.composition_query import CompositionQuery from citrination_client.search.pif.query.core.base_object_query impo...
from twilio.rest import TwilioRestClient import os, sys TWILIO_NUMBER = os.environ.get('TWILIO_NUMBER') # Helpful link content FLASK = """ Some helpful links: - Flask: http://bit.ly/1eU7R5M - twilio-python: http://bit.ly/1pKlW3E - Ngrok: https://ngrok.com/""" TESTING = """ Interested in testing? - py.test http:/...
# Copyright 2022 Xanadu Quantum Technologies 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...
""" Calculate the subcomponents that will later be combined into the moving foreground. """ from baboon_tracking.stages.motion_detector.generate_mask_subcomponents.foreground.foreground import ( Foreground, ) from baboon_tracking.stages.motion_detector.generate_mask_subcomponents.generate_history_of_dissimila...
####################################################################################################################################################### #######################################################################Imports######################################################################### ################...
from time import time import subprocess import os def lambda_handler(event, context): file_size = event['file_size'] byte_size = int(event['byte_size']) file_write_path = '/tmp/file' start = time() with open(file_write_path, 'wb', buffering=byte_size) as f: f.write(os.urandom(file_siz...
import threading # on importe threading, une librairie qui permet du faire du multithread import socket # on importe socket, une libraire pour le tcp/ip import chess # on importe chess, une librairie moteur d'échec import json # on importe json, une librairue pour traiter du json import random # on i...
import re import unicodedata import numpy as np import torch def get_ner_BIO(label_list): # list_len = len(word_list) # assert(list_len == len(label_list)), "word list size unmatch with label list" list_len = len(label_list) begin_label = 'B' inside_label = 'I' whole_tag = '' index_tag = '...
import os from pathlib import Path import numpy as np from padertorch.contrib.examples.audio_tagging.data import get_datasets from padertorch.contrib.examples.audio_tagging.models import CRNN from paderbox.utils.timer import timeStamped from padertorch.contrib.je.modules.augment import ( MelWarping, LogTruncNormal...
from shared.card import CARD_PLACEHOLDER_LENGTH import pygame import pygame.locals as pl from twisted.logger import Logger class View(object): log = Logger() def __init__(self, display): self.display = display self.first_call = False self.tab_order = [] self.tab_position = 0 if self.disp...
from sympy import Matrix from numbers import Number from CompartmentalSystems.helpers_reservoir import numsol_symbolical_system, numerical_function_from_expression ,make_cut_func_set,f_of_t_maker from copy import copy,deepcopy from testinfrastructure.helpers import pe from scipy.interpolate import interp1d, Univariat...
# Copyright (C) 2020 The Android Open Source Project # # 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 multiprocessing from time import time import socket import websocket from socscrollsave.core.constants import Constants from socscrollsave.common.logger import Logger as Log TAG = "Socket" class SocketProcess(multiprocessing.Process): """ Socket client """ def __init__(self, parser_process)...
try: from src import __wallaby_local as w # for VSCode support except ImportError: import imp; wallaby = imp.load_source('wallaby', '/usr/lib/wallaby.py') import wallaby as w # so it works on actual robot from src.helpers.functions import map MOTOR_MAX_TIME = 5.0 """This is multiplied by `motor.speed` to...
# Copyright (c) 2012-2019, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 10.2.0 from . import AWSObject from . import AWSProperty from .validators import boolean from .validators import i...
# # Copyright (c) 2015 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use...
"""Tests for the object departures module.""" import responses # initialize package, and does not mix up names import test as _test import navitia_client import requests class DeparturesTest(_test.TestCase): def setUp(self): self.user = 'leo' self.core_url = "https://api.navitia.io/v1/" ...
""" cloudRemover.py, Sam Murphy (2017-07-11) Collection of cloud removal methods for Sentinel 2 and Landsat for details: https://github.com/samsammurphy/cloud-masking-sentinel2 """ import ee import math def ESAclouds(toa): """ European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 6...
# models.py # cavaliba.app_sirene # (C) Cavaliba - 2020 import datetime from datetime import datetime, timedelta from django.db import models from django.utils import timezone from django.forms import ModelForm # null : DB # blank : forms # char/text : null=False # ------------------------------------------------...
import pandas as pd def get_dataset_dtypes(dataframe_list): # dataframe_list # List of pandas dataframe objects ### # Student code (create additional functions as necessary) ### # mock-up for demonstration - remove after development # this is only a partial column list # actual li...
import os import time import torch import torch.nn as nn from torch.optim import SGD from modules.binarizer import L1ColBinarizer, L1RowBinarizer, MagnitudeBinarizer from modules.masked_nn import MaskedLinear # # Returns mask of inputs matrix # # mask = 0 in rows of inputs with smallest L1 norm # def l1_percentage_...
######################################## # CS/CNS/EE 155 2018 # Problem Set 1 # # Author: Andrew Kang # Description: Set 1 SGD helper ######################################## import numpy as np import matplotlib.pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D from matplotl...
"""Utilities for dealing with wordlists.""" import fnmatch import os from typing import List def find_wordlist(wordlist_dirs: List[str], fnpattern: str) -> None: """Recursively search wordlist directories for a specified filename.""" for wordlist_dir in wordlist_dirs: _walk_iter = os.walk(wordlist_d...
"""Defines exceptions that can occur when interacting with job data""" class InvalidConnection(Exception): """Exception indicating that the provided job connection was invalid """ pass class InvalidData(Exception): """Exception indicating that the provided job data was invalid """ pass clas...
#!/usr/bin/env python # coding: utf-8 import json from pyquery import PyQuery query = PyQuery("https://nijisanji.ichikara.co.jp/member/") member_urls = [element.get("href") for element in list(query("#liver_list a"))] member_list = [] for member_url in member_urls: query = PyQuery(member_url) member_name_r...
import gym import os import re import argparse import pickle import torch import datetime from train import PolicyGradientTrainer from test import Tester from paint import Painter class Options(object): def __init__(self): parser = argparse.ArgumentParser() parser.add_argument('...
#!/usr/bin/python3 # Halide tutorial lesson 6. # This lesson demonstrates how to evaluate a Func over a domain that # does not start at (0, 0). # This lesson can be built by invoking the command: # make tutorial_lesson_06_realizing_over_shifted_domains # in a shell with the current directory at the top of the hali...