text stringlengths 3.07k 12.6k |
|---|
"""Feature selection model with generative models.
Algorithm between SAM and CGNN
Author : <NAME> & <NAME>
.. MIT License
..
.. Copyright (c) 2018 <NAME>
..
.. Permission is hereby granted, free of charge, to any person obtaining a copy
.. of this software and associated documentation files (the "Software"), to deal
... |
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
from urllib.parse import unquote
from falcon import HTTPError, HTTP_201, HTTPBadRequest
from ujson import dumps as json_dumps
from ...utils import load_json_bod... |
# Copyright (c) 2019 Science and Technology Facilities Council
# All rights reserved.
# Modifications made as part of the fparser project are distributed
# under the following license:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condi... |
from . import ast
from .errors import ParseError, TypeErrors
from .tokenizer import TokenKind, tokenize
from .typechecker import Typechecker
def parse(source, *, filename="[STRING]", typecheck=True):
"""Parse the source into a Cedar Module.
Parameters:
source(str): The input string to parse.
file... |
import sys
import os
from typing import Tuple, List, Dict
import pandas as pd
from multiprocessing.dummy import Pool as ThreadPool
import citation_normalisation as cn
import reference_parser as rp
def read_COCONUT_references(coconut_references_csv_path: str) -> List[str]:
'''This function reads a csv fi... |
import networkx as nx
import pandas as pd
#from community import community_louvain
from random import choice
from multiprocessing import Pool
import itertools
import os
def import_graph(path):
"""
Import and read a networkx graph to do some calculations
Args:
path (string): path of the networkx g... |
from .constants import PRIVILEGED_COMMANDS, POSITIVE_REACTIONS, NEGATIVE_REACTIONS
from .config import Config
from .state import State
from .scores import Scores
from .player_skill import PlayerSkill
import re
from datetime import date, datetime
def fmt_duration(secs, show_ms=False):
ms = 0
if isinstance(secs, fl... |
# source: slightly modified https://codereview.stackexchange.com/questions/177523/simple-oop-blackjack-game-in-python
from random import shuffle
# I'm creating a table class where the rest of the object will reside to play the game
# this will allow different object to interact with each other 'on the table'
class Ta... |
# -*- coding: utf-8 -*-
# KivyUnitTest
# Copyright (C) 2016 - 2017, KeyWeeUsr(<NAME>) <<EMAIL>>
# License: The MIT License (MIT)
#
# 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 rest... |
from sys import stderr, stdout, stdin
from board import Board, PASS, RESIGN, BLACK, WHITE, INVLD
from network import Network
from mcts import Search
from config import BOARD_SIZE, KOMI, INPUT_CHANNELS, PAST_MOVES
from time_control import TimeControl
class GTP_ENGINE:
def __init__(self, args):
self.args = a... |
"""
Author: <NAME>
Adapted from: https://github.com/MiguelMonteiro/CRFasRNNLayer
"""
"""
MIT License
Copyright (c) 2017 <NAME> , <NAME>
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 res... |
""" API v0 views. """
import logging
from django.urls import reverse
from edx_rest_api_client import exceptions
from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework.authentication imp... |
"""
Simulate a program where two threads write to the same log
file. Exhibit nondeterminism in scheduling threads. Try to synchronize
so that only one thread at a time can write to the log. Detect unsafe
states where both threads may write to the log. Identify log messages
that may have been corrupted by unsynch... |
#!/usr/bin/env python3
import configparser
import random
import json
import requests
import os
from flask import Flask, render_template, send_from_directory, redirect, url_for, request, current_app as app
import frontend_assets
config = configparser.ConfigParser()
config.read('158.ini')
if 'services' not in config... |
import numpy as np
import numpy as np
from gym import utils
from . import mujoco_env
from . import geom_utils
def mass_center(model, sim):
mass = np.expand_dims(model.body_mass, 1)
xpos = sim.data.xipos
return (np.sum(mass * xpos, 0) / np.sum(mass))
class BaseProprioceptiveHumanoidEnv(mujoco_env.MujocoEnv... |
import math
import numpy as np
import cv2
from sklearn.metrics import mutual_info_score, normalized_mutual_info_score
from skimage.measure import compare_ssim
from skimage.util.arraycrop import crop
import pandas as pd
import scipy.stats as stats
from scipy.ndimage import measurements
from skimage.morphology import ... |
"""
Import this module to get access to dimension instances.
.. code-block:: python
from msgvis.apps.dimensions import registry
time = registry.get_dimension('time') # returns a TimeDimension
time.get_distribution(a_dataset)
"""
from msgvis.apps.dimensions import models
_dimension_registry = {}
_create_... |
import xml.etree.ElementTree as et
import os
import sys
import re
def findIndices(pattern, text):
reList = []
for match in re.finditer(pattern, text):
reList.append(match.start())
return reList
def formatHandler(cell):
#handling linebreaks
cell = re.sub("<br/>", "\n", cell)
#handling t... |
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.animation import FuncAnimation
from resemblyzer import sampling_rate
from matplotlib import cm, colors
from time import sleep, perf_counter as timer
from umap import UMAP
from sys import stderr
import matplotlib.pyplot as plt
import numpy as np
imp... |
# coding: utf-8
import pandas as pd
import numpy as np
# load the dataset
papers_data = pd.read_csv('../../../Downloads/papers.csv')
# removing data which doesn't contain abstract
papers = papers_data.replace('Abstract Missing', "NaN")
dataset = papers.dropna()
dataset.index = np.arange(0, len(dataset))
""" Prelimin... |
import datetime, logging
from collections import defaultdict
from operator import itemgetter
from flask import render_template, Markup
from fbvoting.apis.fb import get_user_id
from fbvoting.db.directvote import has_direct_or_delegate_vote
from fbvoting.db.delegatevote import delegation_category_and_date_generator
fro... |
from typing import Dict
import pytest
from CommonServerPython import *
from DataEnrichmentThreatIntelligence import Client
from pytest import raises
BASE_URL = 'https://example.com/api/v1/'
FILE_RESULTS = {
'result': [
{
'id': 1,
'severity': 75,
'md5': 'd1e09edea866f35... |
# -*- coding: utf-8 -*-
import numpy as np
from collections import deque
from sortedcontainers import SortedDict
class Buffer(object):
# __slots__ = ('types', 'size', 'batches')
def __init__(self, size):
self.size = size
self.clean()
def clean(self):
self.types = {}
self.batches = []
def get_batche... |
import os
import math
import torch
import random
import numpy as np
from tqdm import tqdm
from gensim import utils
from smart_open import open
from nltk.corpus import stopwords
from torch.utils.data import Dataset
from src.utils import load_pickle, save_pickle
class VocabularyDict:
def __init__(self, filename, mi... |
import torch
import os
from elit.components.amr.amr_parser.data import REL
from elit.datasets.parsing.amr import unlinearize, remove_unconnected_components, un_kahn
if os.environ.get('USE_TF', None) is None:
os.environ["USE_TF"] = 'NO' # saves time loading transformers
from amr_parser.data import Vocab, DataLoad... |
import os
import cv2
import logging
import argparse
import numpy as np
def fill_gaps(track, target_id):
logging.info('Gap-filling: Length before filling: {}'.format(len(track)))
output_trajectory = []
current_frame = -1
for i in range(len(track)):
if current_frame > -1 and track[i][0] - curren... |
import numpy as np
import matplotlib.pyplot as plt
GRAY_SCALE_RANGE = 255
import pickle
data_filename = 'data_deskewed.pkl'
print('Loading data from file \'' + data_filename + '\' ...')
with open(data_filename, 'rb') as f:
train_labels = pickle.load(f)
train_images = pickle.load(f)
test_labels = pickle.l... |
#!/usr/bin/env python
# Copyright 2019 Palo Alto 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... |
"""Test for SlidingBoundariesArchive."""
import numpy as np
import pytest
from ribs.archives import AddStatus, SlidingBoundariesArchive
from .conftest import get_archive_data
from .grid_archive_test import assert_archive_elite
# pylint: disable = redefined-outer-name
@pytest.fixture
def data():
"""Data for sli... |
from rllab.sampler.utils import rollout
from rllab.sampler.stateful_pool import singleton_pool
from rllab.misc import ext
from rllab.misc import logger
from rllab.misc import tensor_utils
import numpy as np
def _worker_init(G, id):
import os
os.environ['THEANO_FLAGS'] = 'device=cpu'
G.worker_id = id
def... |
'''RTool/video.py
This module is a combination of various video related functions for
converting sequences to video, vise-versa, extracting audio, etc.
Most of these functions work based on directory paths since that was
the functionality needed when these were written.
Todo:
* Auto-handle directories creation
... |
import gc
import time
import asyncio
import threading
from pytest import raises
from testutils import run_tests
from itemdb import asyncify, ItemDB, AsyncItemDB
side_effect = [0]
def plain_func(x):
time.sleep(1) # emulate io
side_effect[0] += 10
return x + 5
def plain_func_that_errors(x):
raise... |
# coding=utf-8
# Copyright 2021 The Meta-Dataset 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 ... |
"""
This is a copy of the websecmap celery file, the only change is that a different settings file is imported,
including both the websecmap and dashboard tasks.
"""
# https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/
# http://oddbird.net/2017/03/20/serializing-things/
# http://docs.celeryp... |
# Copyright (c) OpenMMLab. All rights reserved.
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import functools
import os
import socket
import subprocess
from collections import OrderedDict
import torch
import torch.multiprocessing as mp
from torch import distributed as dist
from torch._utils i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2020, Nokia"
__license__ = "BSD-3"
from pybgl.automaton import *
from pybgl.property_map import ReadWritePropertyMap
EPSILON = "\u03b5"
class Nfa(DirectedG... |
import numpy as np
import json
import os
from ..metrics.metrics import accuracy_calc
class Sequential:
__slots__ = ["NN_structure", "reverse_NN_structure", "x", "y", "learning_rate", "iteration", "cost_list",
"loss_func", "loss_func_derivative", "accuracy_list"]
def __init__(self, x, y, lear... |
#! /usr/bin/env python
""" crypto.cipher.cbc_test
Tests for cbc encryption, uses AES for base algorithm
Copyright (c) 2002 by <NAME>
Read LICENSE.txt for license information.
"""
from crypto.cipher.cbc import CBC
from crypto.cipher.aes import AES
from crypto.cipher.rijndael import Rijndael
from... |
#!/usr/bin/python
import argparse
import sys
import os
import random
import itertools
def parse_arguments( argv ):
argv_tmp = sys.argv
sys.argv = argv
description = 'blueprint file generator for helical bundles. <EMAIL> 2020-02-12'
parser = argparse.ArgumentParser( description = description )
pars... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the duecredit package for the
# copyright and license terms. This file ... |
#!/usr/bin/env python
"""
BSD 2-Clause License
Copyright (c) 2021 (<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:
1. Redistributions of source code must retain the above copyright notice, thi... |
import pytest
import copy
from rasa.nlu.classifiers.keyword_intent_classifier import KeywordIntentClassifier
# TODO: add tests for other classifers
# from rasa.nlu.classifiers.mitie_intent_classifier import MitieIntentClassifier
from rasa.nlu.training_data.formats.rasa import RasaReader
from rasa.nlu.training_data im... |
from datetime import datetime
from typing import List, Tuple, Any, Optional, Dict
from dateutil.tz import tzutc
from blurr.core.store_key import Key, KeyType
from blurr.runner.local_runner import LocalRunner
def execute_runner(stream_bts_file: str,
window_bts_file: Optional[str],
... |
#encoding:utf/8
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: <NAME>
## ECE Department, Rutgers University
## Email: <EMAIL>
## Copyright (c) 2017
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this sourc... |
# 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"); you may not u... |
# -*- coding: utf-8 -*-
"""
Support for the 'format' key in the swagger spec as outlined in
https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#dataTypeFormat
"""
from __future__ import unicode_literals
import base64
import functools
import dateutil.parser
import pytz
import six
import typing
fro... |
# Part of the Crubit project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""
The tool creates Rust source code with the C++ API projection as well as implementation of the API
projection. See <internal link> and ... |
#!/usr/bin/env python3
import os
import sys
from subprocess import run, Popen, PIPE
from time import sleep
def vm_setup():
run("vm init", shell=True)
def vm_select_iso(tmp_vm_dir, vm, systype, sysname, workspace):
iso_dir = f"{workspace}/tests/iso/"
if not os.path.isdir(iso_dir):
os.makedirs(is... |
import lime
from sklearn.externals import joblib
import numpy as np
from src.encoding.common import retrieve_proper_encoder
from src.explanation.models import Explanation
def _init_explainer(df, features, columns, mode):
return lime.lime_tabular.LimeTabularExplainer(
df,
feature_names=features,
... |
"""
libraries needed
machine: for uart usage
uio: packet buffer
struct: serlization
_TopicInfo: for topic negotiation
already provided in rosserial_msgs
"""
import machine as m
import uio
import ustruct as struct
from time import sleep, sleep_ms, sleep_us
from rosserial_msgs import TopicInfo
import sys
import o... |
"""
Contains OpenID provider functionality
"""
import logging
import os
from collections import OrderedDict
from galaxy.util import parse_xml, string_as_bool
log = logging.getLogger(__name__)
NO_PROVIDER_ID = 'None'
RESERVED_PROVIDER_IDS = [NO_PROVIDER_ID]
class OpenIDProvider:
'''An OpenID Provider object.'... |
import torch
from torch import nn
from torch import Tensor
def log_compression(inputs: Tensor, epsilon=1e-6) -> Tensor:
"Log compression"
return torch.log(inputs+epsilon)
class ExponentialMovingAverage(nn.Module):
"""Computes of an exponential moving average of an sequential input."""
def __init__(se... |
import time
import torch
import numpy as np
import sys
sys.path.append('../global_module/')
import d2lzh_pytorch as d2l
def evaluate_accuracy(data_iter, net, loss, device):
acc_sum, n = 0.0, 0
with torch.no_grad():
for X, y in data_iter:
test_l_sum, test_num = 0, 0
X = X.to(devi... |
import logging
import os
import re
import shutil
from collections import defaultdict
import click
import jsonlines
from dataloaders import get_dataloaders
from models.cb import build_model as build_model_cb
from models.copa import build_model as build_model_copa
from models.multirc import build_model as build_model_mu... |
from urllib.parse import urlparse, urljoin
from pathlib import Path, PurePath
import re
from lettersmith.func import compose
from lettersmith.lens import Lens, put
from lettersmith import query
_STRANGE_CHARS = "[](){}<>:^&%$#@!'\"|*~`,"
_STRANGE_CHAR_PATTERN = "[{}]".format(re.escape(_STRANGE_CHARS))
def _space_to... |
# Copyright (c) 2022 PaddlePaddle 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 app... |
# Created by Lena
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
torch.manual_seed(2021)
device = torch.device("cuda:0" if... |
import os
import signal
import socket
import sys
import time
import threading
import unittest
from unittest import mock
if sys.platform != 'win32':
raise unittest.SkipTest('Windows only')
import _overlapped
import _winapi
import asyncio
from asyncio import windows_events
from test.test_asyncio import utils as te... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, NODUX and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils import nowdate
from frappe import _
from frappe.model.mapper import get_mapped_doc
c... |
from collections import OrderedDict
from io import StringIO
import pandas as pd
import numpy as np
from metabolinks import datasets
from metabolinks.cdaccessors import create_multiindex_with_labels
from metabolinks.utils import _is_string
def _ensure_DataFrame(data):
"""Retrieves information from data structure... |
# Copyright 2015 Ufora 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 or agreed to i... |
import argparse
import cPickle
import sys
import os
import tensorflow as tf
from utils.config import load_config, gan_from_config
from classifiers.cifar_model import Model
from blackbox import get_cached_gan_data
from utils.network_builder import model_a, DefenseWrapper
from cleverhans.utils_tf import model_train, mod... |
#!/usr/bin/python3
# A little bit messy, but it works. Now shut up
import configparser
import os
from pathlib import Path
import shutil
from distutils import util
import argparse
from enum import Enum
import filecmp
def createFileName(fileName):
counter = 1
newName = Path(fileName + ".old")
if not newName.exis... |
'''
SPDX-License-Identifier: Apache-2.0
Copyright 2017 Massachusetts Institute of Technology.
'''
import base64
import os
import subprocess
import socket
import time
import requests
import shutil
import sys
import simplejson as json
from keylime import config
from keylime import keylime_logging
from keylime import s... |
# Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from scipy.special import erfc
import time
from ..core.errors import InvalidConfigError
def compute_integrated_acquisition(acquisition,x):
'''
Used to compute the acquisition function when s... |
from telegram.ext import CommandHandler
from telegram.ext import Updater
from telegram.ext import MessageHandler, Filters
from telegram.error import Unauthorized
import logging
from pymongo import MongoClient
from vkutils import get_posts_with_audio, vk_connect
import time
import json
with open('settings.json', 'r') a... |
"""
IP Types
"""
import logging
from ipaddress import ip_address
from socket import AF_INET, AF_INET6
from vpp_papi import VppEnum
from vpp_object import VppObject
try:
text_type = unicode
except NameError:
text_type = str
_log = logging.getLogger(__name__)
class DpoProto:
DPO_PROTO_IP4 = 0
DPO_P... |
import torch
import torchvision
import json
import os
import PIL
import argparse
import time
import numpy as np
import sys
def benchmark_model(model,batch,device,warm,iters,train,use_solver):
if train:
model.train()
else:
use_solver = False
model.eval()
inp = torch.randn(batch,3,224... |
# -*- coding:utf-8 -*-
#
# Copyright (C) 2008 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 re... |
"""
Image processing functions:
adjust_to_see: adjust an image to better visualize it (rotate and transpose)
augmentation: apply variations to a list of images
normalization: apply normalization and variations on images (if required)
preprocess: main function for image preprocessing before
text_stan... |
import argparse
import gym
import os
import sys
import pickle
import time
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from utils import *
from models.mlp_policy import Policy
from models.mlp_critic import Value
from models.mlp_policy_disc import DiscretePolicy
from core.trpo import ... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
#! /usr/bin/env python3
# This is a script for publishing the wasmer crates to crates.io.
# It should be run in the root of wasmer like `python3 scripts/publish.py --no-dry-run`.
# By default the script executes a test run and does not publish the crates to crates.io.
# install dependencies:
# pip3 install toposort
... |
import numpy as np
from sklearn.datasets import fetch_mldata
import matplotlib.pyplot as plt
np.random.seed(1847)
class BatchSampler(object):
'''
A (very) simple wrapper to randomly sample batches without replacement.
You shouldn't need to touch this.
'''
def __init__(self, data, targets, batch... |
# -*- coding:utf-8 -*-
import datetime
import pytz
import screen
import xlwt
from django import http
from django.conf import settings
from django.db.models.query import QuerySet
from django.utils import timezone
from django_six import Support_ValuesQuerySet, ValuesQuerySet
try:
from cStringIO import StringIO
ex... |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon SNS
:configuration: This module accepts explicit sns credentials but can also
utilize IAM roles assigned to the instance trough Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necess... |
import random
import numpy as np
import random
import matplotlib.pyplot as plt
from arms.bernoulli import BernoulliArm
from arms.normal import NormalArm
from matplotlib import rcParams
rcParams['font.family'] = ['Roboto']
for w in ["font.weight", "axes.labelweight", "axes.titleweight", "figure.titleweight"]:
rcPar... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appli... |
from __future__ import print_function, unicode_literals
def add_download_entity_parser(subparsers, formatter_class):
subparser = subparsers.add_parser(
"download-entity", formatter_class=formatter_class,
help="Download resources for a builtin gazetteer entity")
subparser.add_argument(
... |
from __future__ import print_function
import os
import sys
import shutil
import zipfile
import shlex
from zipfile import ZipFile
from urllib.request import urlretrieve
from subprocess import Popen, PIPE
from distutils.cmd import Command
def zip_directory(dir, zip_file):
zip = ZipFile(zip_file, 'w', compression=zi... |
#
# The Python Imaging Library.
# $Id$
#
# a Windows DIB display interface
#
# History:
# 1996-05-20 fl Created
# 1996-09-20 fl Fixed subregion exposure
# 1997-09-21 fl Added draw primitive (for tzPrint)
# 2003-05-21 fl Added experimental Window/ImageWindow classes
# 2003-09-05 fl Added fromstring/tostring me... |
"""
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
"""
import logging
import os
import time
import numpy as np
import torch
import torch.nn.functional as F
from parse import parse
# Some tricks to make rasterio faster when using vsicurl
# see https://github.com/pangeo-data/c... |
import constants
import datetime
import json_plus
import logging
from gluon import current
import inspect
class Procedure(json_plus.Serializable):
""""This is the base class of all procedures.
The initializer sets the procedure api.
The class has a "run" method, which is the one called to trigger
proce... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
... |
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... |
import traceback
import disnake
from disnake.ext import commands
import asyncio
from subprocess import check_output
from os import path
from utils.music.errors import GenericError
from utils.music.local_lavalink import run_lavalink
from utils.client import BotCore
from utils.db import MongoDatabase, LocalDatabase, guil... |
# SPDX-License-Identifier: Apache-2.0
"""CDS data dictionary module."""
import json
from logging import getLogger, Logger
from onapsdk.exceptions import FileError, ValidationError
from .cds_element import CdsElement
class DataDictionary(CdsElement):
"""Data dictionary class."""
logger: Logger = getLogger(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from django.apps import apps
from django import template
from django.conf import settings as django_settings
from django.contrib.contenttypes.models import ContentType
from django.db.models import Model
from django.forms import BaseForm
from dj... |
#!/usr/bin/env python
# Copyright 2018 Nagoya University (<NAME>)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import logging
import os
from distutils.version import LooseVersion
import librosa
import numpy as np
from scipy.io.wavfile import write
from espnet.utils.cli_utils import F... |
from datetime import datetime
import numpy as np
import pytest
import xarray as xr
from affine import Affine
from datacube import Datacube
from datacube.model import Measurement
from datacube.utils.dates import mk_time_coord
from datacube.utils.geometry import GeoBox, CRS
# Taken from https://github.com/opendatacube... |
# coding=utf-8
# Copyright 2020 Google LLC.
#
# 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 ... |
# This file is part of beets.
# Copyright 2015, <NAME>.
#
# 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, ... |
"""Tests for Sopel's ``choose`` plugin"""
from __future__ import annotations
import pytest
from sopel import formatting
from sopel.modules import choose
UNICODE_ZS_CATEGORY = [
'\u0020', # SPACE
'\u00A0', # NO-BREAK SPACE
'\u1680', # OGHAM SPACE MARK
'\u2000', # EN QUAD
'\u2001', # EM QUAD
... |
"""
DC2 matched table reader
This reader was written by <NAME>.
The reader ingests the matching table provided by <NAME>
(fits file format). The tables are produced by matching objects in the DC2
object catalogs with objects in the cosmoDC2 catalog. Code can be found in
https://github.com/LSSTDESC/CatalogMatcher/blob/... |
import torch
import torch.utils.data as data
class PoisonedDataset(data.Dataset):
def __init__(self, path, subset='clean_train', transform=None, num_per_label=-1, poison_tuple_list=[], poison_indices=[],
class_labels=[i for i in range(10)], subset_group=0):
"""
Made to be compatib... |
import concurrent
from abc import abstractmethod
import pingouin as pg
from tfce_toolbox.cluster_value_calculator import ClusterValueCalculator
class TwoByTwoF(ClusterValueCalculator):
def __init__(self, dv, within1, within2, subject, datapoint_name):
self.dv = dv
self.within1 = within1
... |
"""
Event bus
Worked as a backgrund thread
Run events handler and background task worker
"""
from queue import Queue
from concurrent.futures import ThreadPoolExecutor
import traceback
import inspect
import uuid
import time
from lyrebird.base_server import ThreadServer
from lyrebird import application
from lyrebird.moc... |
"""
This script cleans and prepares the data set of properties' features for the future usage
"""
import argparse
import logging
import sys
import pandas as pd
from preprocessing.common import raw_data_to_df, check_processed_columns, check_data
INTERESTING_COLS = [u'propcode', u'year', u'desc1', u'desc2']
FEATURES... |
#!/usr/bin/env python
""" pygame.examples.chimp
This simple example is used for the line-by-line tutorial
that comes with pygame. It is based on a 'popular' web banner.
Note there are comments here, but for the full explanation,
follow along in the tutorial.
"""
# Import Modules
import os
import pygame as pg
from py... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.