text stringlengths 3.07k 12.6k |
|---|
# vim: set fileencoding=utf-8
# Copyright © 2020, 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
#
# Unless required by applic... |
from enum import Enum
from functools import partial
from typing import Dict, List
from tqdm import tqdm
import pandas as pd
class RelationGroup(Enum):
# Implicit-Implicit Temporal Relation
I_I = 0
# Implicit-Explicit Temporal Relation
I_E = 1
# Explicit-Implicit Temporal Relation
E_I = 2
... |
import os
from multiprocessing import Pool
import pandas as pd
from scipy.stats import hypergeom
import nltk
from argparse import ArgumentParser
import logging
nltk.download('stopwords')
nltk.download('words')
stop_words = set(nltk.corpus.stopwords.words('english'))
words = set(nltk.corpus.words.words())
def ge... |
import re
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from userapp.models import User, CustomUser
from addressapp.serializers.activity import ActivitySerializer,\
ActivityAreaSerializer
from addressapp.... |
from math import ceil
from docx import Document
from docx.enum.table import WD_ROW_HEIGHT_RULE, WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm, Pt, Length
from docx.table import Table
import argparse
def setup_margins(doc: Document, margin: float):
s... |
"""
Loads historical data and upload it to BQ.
Years Files should be in json and GZIP Format.
This script will do:
1- Locate (devices and messages).
2- Per each device ID will list all the messages ID.
3- Add the device info in the message info and save a NEWLINEJSON.
4- Compress again in a separate folder.
Ex.
pytho... |
import discord
from discord.ext import commands
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Page 1",description="This is help page 1!"),
discord.SelectOption(label="Page 2",description="This is help page 2!"),
discor... |
#!/usr/bin/env python
import time
import rospy
import math
import copy
import numpy
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Point
from tf.transformations import euler_from_quaternion
class CubeRLUtils(object):
def __i... |
from typing import Union
import numpy as np
def moore_n(
n: int, position: tuple, grid: np.ndarray, invariant: Union[int, np.ndarray] = 0
):
"""Gets the N Moore neighborhood at given postion."""
row, col = position
nrows, ncols = grid.shape
# Target offsets from position.
ofup, ofdo = row +... |
# -*- encoding: utf-8 -*-
"""
Query the S3 bucket containing Sierra progress reports, and log
a report in Slack
"""
import datetime as dt
import itertools
import json
import os
import boto3
import requests
from interval_arithmetic import combine_overlapping_intervals, get_intervals
def get_matching_s3_keys(s3_clie... |
#!/usr/bin/env python3
import optparse
import pathlib
import subprocess
import os
import shutil
from tools.utils import prompt as pmt
from tools.utils.subprocess_runner import subprocess_runner
_file_path = pathlib.Path(__file__).parent
_add_script = _file_path.joinpath("./tools/leetcode_add.py")
_del_script = _file_... |
# Copyright (c) 2018 Sony Pictures Imageworks 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... |
#!/usr/bin/python
"""
The analyser is the entrypoint for the analysis
>>> analyser = GitAnalyser('repos/django')
>>> analyser.analyse()
>>> analyser.output_html('django_analysis.html')
"""
import git
import datetime as dt
import argparse
import json
__version__ = '0.0.1'
class AnalysisEmptyError(E... |
import numpy as np
import skimage.segmentation
import skimage.io
import keras.backend as K
import tensorflow as tf
debug = False
def channel_precision(channel, name):
def precision_func(y_true, y_pred):
y_pred_tmp = K.cast(tf.equal( K.argmax(y_pred, axis=-1), channel), "float32")
true_positives = ... |
"""
Add samples
This script takes a wav file that must have n peaks and create n different files for each peak.
"""
import numpy as np
from scipy.io.wavfile import read,write
import peakutils, os
# average
# 3169 / 2 = 1584.5
side = 10000
# The stander for the peaks
stander = 0
"""
Write the .wav file
"""
def exp... |
"""
Utility functions for QS files.
"""
import traceback
import re
import math
from PyQt5 import QtCore
from pineboolib.core.utils.utils_base import ustr
from pineboolib.core.utils import logging
from typing import Any, Optional, Union, Match, List, Pattern, Generator, Callable
logger = logging.getLogger("qsa.utils"... |
from copy import deepcopy
from unittest.mock import Mock
from dataactcore.utils import fileE
_VALID_CONFIG = {'sam': {
'wsdl': 'http://example.com', 'username': 'un', 'password': '<PASSWORD>'}}
def test_configValid_empty(monkeypatch):
monkeypatch.setattr(fileE, 'CONFIG_BROKER', {})
assert not fileE.con... |
#!/usr/bin/env python
"""
Add MR comments from the Scan Completed instrument on REDCap to the database.
Usage:
dm_redcap_scan_completed.py [options] <study>
Arguments:
<study> Name of the study to process
Options:
-q --quiet Less logging
-v --verbose Verbose logging
-d... |
"""Provide helper functions for generating configuration.
ONLY the constants module should import this module.
"""
import copy
import csv
import functools
import os
from pathlib import Path
# HACK HACK HACK HACK HACK HACK HACK HACK HACK THIS IS A DUMB HACK HACK HACK
# Importing qgis before fiona is absolutely necess... |
#!/bin/usr/python3
# coding=UTF-8
#Copyright (c) 2021 <NAME>(<EMAIL>)
#
# 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 r... |
#_ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# <NAME>
# Copyright 2019 Keeper Security Inc.
# Contact: <EMAIL>
#
import argparse
import logging
import requests
from contextlib import contextmanager
from .. import api
from . import imp_exp
fro... |
#####################################################
#
# smartcomponent.py
#
# Copyright 2007 Hewlett-Packard Development Company, L.P.
#
# Hewlett-Packard and the Hewlett-Packard logo are trademarks of
# Hewlett-Packard Development Company, L.P. in the U.S. and/or other countries.
#
# Confidential computer software. ... |
from aiohttp import web, ClientSession, request
from bs4 import BeautifulSoup
from datetime import datetime
import json
import uvloop
import asyncio
import sqlite3
import aiosqlite
import hashlib
import time
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
routes = web.RouteTableDef()
# async def get_session(... |
import traceback
import h5py
import matplotlib.pyplot as plt
import numpy as np
import os
import seaborn as sn
import sys
import tensorflow as tf
from support.data_model import CLASSES, TAG_CLASS_MAP, Track, UNCLASSIFIED_TAGS
from support.track_utils import convert_frames, convert_hdf5_frames
START_TIME = '2021-03... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
(c) Copyright 2018 Sensirion AG, Switzerland
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 copy... |
# The model for the skin cancer classifier
# Import the libraries
import numpy as np
import keras
from keras import backend as K
from keras.layers.core import Dense, Dropout
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.models impor... |
import re
import datetime
from Constants import *
from ..Hashes import *
from StringUtils import *
from TimeZoneUtils import *
from ..ScheduleEvent import *
from .Scraper import *
def SupplementSchedule(sched, navigator, sport, league, season):
supplement = ScrapeAllStarGame(sport, league, seas... |
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
from rest_framework import mixins
from rest_framework.decorators import detail_route, list_route
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import Bot, TelegramUser, Aut... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import UploadFileForm
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import exifread
import uuid
from .models import images
from exif.settings import MEDIA_ROOT, APPROVED_SIG... |
from __future__ import print_function
import math
import numpy
import theano
import itertools
from theano import tensor, Op
from theano.gradient import disconnected_type
from fuel.utils import do_not_pickle_attributes
from picklable_itertools.extras import equizip
from collections import defaultdict, deque
from toposo... |
import numpy as np
import re
import random
def prepare_data():
"""This method prepares input positive and negative datasets as bitvectors for the Rap1 binding problem. Output: three lists of bitvectors, one containing positive samples, negative samples that are similar to positive samples, and negative examples t... |
import json
import pytest
from stix2 import TAXIICollectionSource
from test_data.mitre_test_data import ATTACK_PATTERN, COURSE_OF_ACTION, INTRUSION_SET, MALWARE, TOOL, ID_TO_NAME, \
RELATION, STIX_TOOL, STIX_MALWARE, STIX_ATTACK_PATTERN
class MockCollection:
def __init__(self, id_, title):
self.id = i... |
# Copyright 2016 <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
#
# Unless required by applicable law or agreed to in writing, software
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
try:
import cPickle as pickle
except:
import pickle
import numpy as np
import scipy.misc
IMAGE_SIZE = 32
def to_one_hot(y, num_label):
"""Converts a one-dimensional label array to a two-dime... |
import functools
import inspect
import types
from arrowhead.core import ErrorArrow
from arrowhead.core import NormalArrow
from arrowhead.core import Step
from arrowhead.core import ValueArrow
def step(func_or_label=None, **kwargs):
"""
Decorator for converting functions to steps.
This decorator can be a... |
from typing import Dict, Any, Optional
from django.utils.module_loading import import_string
from django.utils.translation import gettext_lazy as _
from django.db import models
from django.http.request import HttpRequest
from django.http import HttpResponseRedirect
from django.utils.functional import cached_property
f... |
"""
Tests for inequality.py
"""
import numpy as np
from numpy.testing import assert_allclose, assert_raises
from scipy.stats import linregress
from quantecon import lorenz_curve, gini_coefficient, \
shorrocks_index, rank_size
def test_lorenz_curve():
"""
Tests `lorenz` function, which calculates the l... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
### importing OGB-LSC
from ogb.lsc import PCQM4MEvaluator
from ogb.lsc.pcqm4m_pyg import PygPCQM4MDataset
import torch
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torch.optim.lr_scheduler import StepLR
fro... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os
import gzip
import time
import copy
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
fro... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
import pandas as pd
import os
import numpy
import MySQLdb
#conn= MySQLdb.connect("localhost","root","admin","omdb")
#df_mysql = pd.read_sql("select * from sitedb",conn)
omdb = os.getcwd() + "\\" + "OMDB.csv"
single = os.getcwd() + "\\" + "single.csv"
pntxt = os.getcwd(... |
"""
Useful tools when working with Figura configs.
"""
import os
from .settings import get_setting
from .errors import ConfigError, ConfigParsingError, ConfigValueError
from .path import to_figura_path
from .container import ConfigContainer
from .parser import ConfigParser
from .importutils import is_impor... |
# 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 random
from cmath import exp
import math
def rotation_scale(origin, theta, scale, points):
return [origin + (point-origin)*scale*e(theta) for point in points]
def translate(origin, points):
# offset = points[0]-origin
return [point-origin for point in points]
def flip(z1, z2, points):
z1z2 = ... |
"""
This module contains functions which implement conversion between different
(neighbouring) versions of RunDescriber.
"""
from typing import Dict, List
from ..dependencies import InterDependencies_
from ..param_spec import ParamSpec, ParamSpecBase
from .rundescribertypes import (RunDescriberV0Dict, RunDescriberV... |
#!/usr/bin/env python
#--------Include modules---------------
from copy import copy
import rospy
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyGrid
import tf
from rrt_slam.msg import PointArray
from time import time
from numpy import array
from numpy im... |
import random
import matplotlib.pyplot as plt
import numpy as np
def cmap(label: str) -> str:
"""Return RGB string of color for given standard psp label"""
_, pp_family, pp_z, pp_type, pp_version = label.split("/")
if pp_family == "sg15" and pp_version == "v1.0":
return "#000000"
if pp_fami... |
#%%
import argparse
import time
import math
import os
import torch
import torch.nn as nn
import torch.onnx
from collections import Counter
import data
import model
import utils
args_cuda = torch.cuda.is_available()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Hyper-parameters
args_train_ba... |
from collections import Counter
import numpy as np
import tensorflow as tf
from copy import copy
from constraint.dfa import DFA
class Constraint(object):
def __init__(self,
name,
dfa_string,
is_hard,
violation_reward=None,
tran... |
import os
import zipfile
import csv
import pandas as pd
import requests
import json
from itertools import islice
import sklearn.preprocessing
from lightfm.data import Dataset
import pandas
import numpy as np
from lightfm import LightFM
# restaurant_metadata = pd.read_json('rating_final.json', lines=True)
from scipy... |
import uuid
import datetime
from typing import List, Union, Dict
from plugins.adversary.app.engine.database import EncryptedDictField
from plugins.adversary.app.engine.objects import Log
from plugins.adversary.app.util import tz_utcnow
version = 1.1
class Operation(dict):
def __init__(self):
super().__i... |
import attr
import pandas
from sarif_om import *
from src.exception.VulnerabilityNotFoundException import VulnerabilityNotFoundException
VERSION = "2.1.0"
SCHEMA = "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json"
class SarifHolder:
def __init__(self):
self.... |
import json
import unittest
import logging
from flask import appcontext_pushed, g
import flask_unittest
from contextlib import contextmanager
from src.utils.did.eladid import ffi, lib
from src.utils.did.did_wrapper import DID, Credential
from src import create_app
from hive.util.constants import HIVE_MODE_TEST
from h... |
from __future__ import annotations
import argparse
import json
import logging
import os
from datetime import datetime
from datetime import timedelta
import git
import humanfriendly
from datalad.plugin import export_archive
from github import Github
from scripts.datalad_utils import get_dataset
from scripts.datalad_u... |
from __future__ import print_function
from six import iteritems
from itertools import chain
import ipyparallel as ipp
from ipyparallel.client.client import ExecuteReply
# Remotely-called function; imports requirement internally.
def dummyTask(key):
from os import getpid
from time import sleep
from ipypara... |
#!/usr/bin/env python3
from __future__ import print_function
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
import re
import timeit
import os
import pathlib
from mzlib.spectrum_library_index import SpectrumLibraryIndex
from mzlib.spectrum import Spectrum
from mzlib.in... |
class VehiclesDataset:
def __init__(self):
self.num_vehicle = 0
self.num_object = 0
self.num_object_with_kp = 0
self.vehicles = dict()
self.valid_ids = set()
self.mean_shape = None
self.pca_comp = None
self.camera_mtx = None
self.image_names = ... |
from .__init__ import EntroQ
from . import entroq_pb2 as pb
import click
import datetime
from datetime import timezone
import grpc
import json
from google.protobuf import json_format
class _ClickContext: pass
def _task_str_raw(task):
return EntroQ.to_dict(task)
def _task_str_json(task):
return EntroQ.to_... |
import argparse
import cv2
import numpy as np
import torch
import kornia as K
from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint
def draw_keypoint(img: np.ndarray, det: FaceDetectorResult, kpt_type: FaceKeypoint) -> np.ndarray:
kpt = det.get_keypoint(kpt_type).int().tolist()
return cv... |
# coding: utf-8
import os
from django.utils import simplejson
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import DetailView, TemplateView, ListView
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from datetime import datet... |
import numpy as np
class Poblacion:
"""Posibles soluciones del óptimo de una función.
Esta clase crea posibles soluciones para una función a optimizar. Toma la dimensión
del espacio, los límites de búsqueda y el número de elementos a tomar en cuenta.
Attributes:
dimension: Un entero que dete... |
import tensorflow as tf
import numpy as np
class MaxoutNN():
def __init__(self, input_dim, hidden_layers, output_dim):
self.input_dim = input_dim
self.hidden_layers = hidden_layers
self.output_dim = output_dim
self.inp = tf.placeholder(tf.float32, [None, self.input_dim], 'inp')
... |
#-------------------------------------------------------------------------------------------------------------------
# Packages & Settings
#-------------------------------------------------------------------------------------------------------------------
# General packages
import time
import sys
import os
import date... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of command_runner module
"""
wmi_queries wrapper
transforms wmi objects into python dicts
Handles most runtime errors
Versioning semantics:
Major version: backward compatibility breaking changes
Minor version: New functionality
Patch v... |
from glob_def import CarEvent
class SimpleMsg:
can_id = 0
desc = ""
byte_len = 0
bit_start_pos = 0
bit_num = 0
scale = 0.0
offset = 0.0
unit = ""
def __init__(self, can_id, byte_len, bit_start_pos, bit_num,
scale, offset, desc="", unit=""):
self.can_id = c... |
# coding: utf-8
""" This is part of the Python's module to manage the DP-EH600 thermal printer.
Source: https://github.com/BoboTiG/thermalprinter
"""
from enum import Enum
# pylint: disable=unsubscriptable-object
class BarCode(Enum):
""" Available bar code types: """
# (code, (min len(text), max len(t... |
import logging
from django.core.management import call_command
from math import ceil
from multiprocessing import Pool, Event
from time import perf_counter
from typing import Generator, List
from usaspending_api.broker.helpers.last_load_date import update_last_load_date
from usaspending_api.common.elasticsearch.client... |
import pytest
from eth_utils import ValidationError
from hypothesis import (
given,
settings,
strategies as st,
)
from trinity._utils.tree_root import Tree, RootTracker
@given(st.permutations(range(10)))
def test_tree_linking(add_order):
# node and parent id
nodes = (
('A0', '_'),
... |
from carla_utils import carla
DestroyActor = carla.command.DestroyActor
import weakref
from typing import Dict
from ..system import debug
from ..basic import flatten_list
from .sensor_callback import RawCallback, DefaultCallback
from .sensor_create import create_sensor, create_sensor_command
def createSensorListMas... |
import argparse
import csv
import os
import signal
import shutil
import sys
import zlib
VERSION = "1.0.4"
class StatusBar:
def __init__(self, title):
terminal_width = shutil.get_terminal_size()[0]
self.bar_len = min(100, terminal_width - (7 + len(title)))
self.progress = 0
self.bar... |
import copy
import typing as ty
from collections.abc import MutableMapping
_AT = ty.Union[list, bool, str, float, dict, int]
_UT = ty.Union[int, float, str, bool]
_KT = ty.List[ty.Tuple[str, ...]]
_VT = ty.List[_AT]
_IT = ty.List[ty.Tuple[ty.Tuple[str, ...], _AT]]
Path = ty.Union[str, ty.Tuple[str, ...]]
def topath... |
#!/usr/bin/env python
from local_settings import PORT, PASSWORD
from threading import Thread
import logging
import select
import SocketServer
import time
logger = logging.getLogger("socket-state-server")
logger.setLevel(logging.INFO)
format_string = "%(asctime)s - %(client_ip)s:%(client_port)s - %(levelname)s - %(me... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
This m... |
# -*- coding: utf-8 -*-
"""This module contains the core function of the *PLUTO_gen* program and the first subfunction of *PLUTO_gen*.
"""
import xmltodict
def read_xml(filename):
"""Reads in the XML to be converted
Reads a *XML-Timeline* file. And returns a dictionary
Arguments:
filename (str... |
import copy
from mock import patch
from ruskit.failover import FastAddMachineManager
from ruskit.distribute import RearrangeSlaveManager, NodeWrapper
from test_base import TestCaseBase
class DummyCluster(object):
def __init__(self):
self.nodes = []
def dummy_gen_distribution_for_move_masters(nodes, ne... |
import asyncio
import discord
import json
import os
from urllib.parse import quote
from discord.ext import commands
from Cogs import Settings
from Cogs import DisplayName
from Cogs import TinyURL
from Cogs import Message
from Cogs import DL
from pyquery import PyQuery as pq
def setup(bot):... |
import struct
import ctypes
import json
maxBoosts = 50
maxCars = 10
class Vector3(ctypes.Structure):
_fields_ = [("X", ctypes.c_float),
("Y", ctypes.c_float),
("Z", ctypes.c_float)]
class Rotator(ctypes.Structure):
_fields_ = [("Pitch", ctypes.c_int),
("Y... |
import argparse
import boto3
import json
import time
IN_FILE = "initial-servers.json"
OUT_FILE = "temp-servers.json"
# Network ID for main network, gamma, and beta
NETWORK_ID="1"
NETWORK_ID_FILTER = {'Name': 'tag:NetworkId', 'Values': [NETWORK_ID]}
RUNNING_FILTER={'Name': 'instance-state-name', 'Values': ['running']}... |
""" Batched Render file. """
import dirt
import numpy as np
import tensorflow as tf
from dirt import matrices
import dirt.lighting as lighting
from tensorflow.python.framework import ops
def orthgraphic_projection(w, h, near=0.1, far=10., name=None):
"""Constructs a orthographic projection matrix.
This func... |
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.label import Label
import os
import shutil
import json
import codecs
class MyApp(App):
def build(self):
self.root = "/home/Games/Crusader-HDUP/CrusaderAIManager"
self.ai_shorts =... |
""" Resources related to starting AppServer instances. """
import logging
import os
import psutil
from tornado.options import options
from appscale.admin.constants import UNPACK_ROOT
from appscale.admin.instance_manager.constants import (
PHP_CGI_LOCATION, PIDFILE_TEMPLATE, TRUSTED_APPS)
from appscale.admin.instanc... |
import aioredis
import time
from ..util import get_dependency
from ..errors import ConfigurationError
from .base import AsyncStorage
class AsyncRedisInteractor(object):
SCRIPT_MOVING_WINDOW = """
local items = redis.call('lrange', KEYS[1], 0, tonumber(ARGV[2]))
local expiry = tonumber(ARGV... |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
"""BioMASS core functions"""
import multiprocessing
import warnings
from biomass.dynamics import SignalingSystems
from biomass.ga import GeneticAlgorithmInit, GeneticAlgorithmContinue
from biomass.analysis import (ReactionSensitivity,
InitialConditionSensitivity,
... |
from datetime import datetime
from logging import getLogger
from ..databases import Item
from ..databases import Source, get_source
from ..databases import get_group, get_groups_ids_recursive
from ..modules import get_module
from .item import add_item
from .utils import with_db
__all__ = ('list_sources', 'show_sourc... |
"""重要単語リスト生成器"""
import csv
import os
import MeCab
from gensim.models import word2vec
from directory import Directory
from iomanager import IOManager
from file import File
class Imporwords(IOManager):
"""重要単語リストクラス"""
def __init__(self,
output_path="./resource/imporwords/",
... |
# Copyright 2018 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... |
import os
import torch
import argparse
import numpy as np
import torch.nn as nn
import torch.optim as optim
from torchviz import make_dot
import torch.nn.functional as F
from timeit import default_timer as timer
from utils import load_data, DEVICE, human_time
class Net(nn.Module):
def __init__(self, gpu=False):
... |
# coding: utf-8
#
# Copyright (c) 2018-present <NAME>
# Copyright (c) 2008—2016 <NAME>
#
# This file is part of django-autoslug.
#
# django-autoslug is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README for co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 14 16:26:11 2022
@author: sergio
"""
# 2 - Crear una Criptomoneda
# Para Instalar:
# Flask==1.1.2: pip install Flask==1.1.2
# Cliente HTTP Postman: https://www.getpostman.com/
# requests==2.25.1: pip install requests==2.25.1
# Importar las librerí... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2019 Nortxort
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,... |
from PIL import Image
import numpy as np
import tensorflow as tf
# colour map
label_colours = [(0,0,0)
# 0=background
,(128,0,0),(0,128,0),(128,128,0),(0,0,128),(128,0,128)
# 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle
,(0,128,128),(128,128,128),(64,... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from numpy import argsort
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from submodules.url_strip import url_strip
from ... |
from PIL import Image, ImageDraw
from io import BytesIO
from math import hypot
from multiprocessing import Pool
import ginit as g
import math
from enums import *
from util import *
def imageOutput(pixels,output,maskfile=None):
iSize = (len(pixels),len(pixels))
picture = Image.new("RGB",iSize)
for x in range(len(pi... |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import itertools
import copy
class Node:
def __init__(self, index, chars, pos=None, head_index=-1, relation=None, lefts=None, rights=None):
self.index = index
self.chars = chars if chars else []
self.pos = pos
self.head_index = head_... |
"""Functions to create and plot outlier scores (or other) in a fixed bounded range. Intended to use to
show the results of an outlier algorithm in a user friendly UI"""
import numpy as np
def make_linear_part(max_score, min_score):
"""
:param bottom: the proportion of the graph used for the bottom "sigmoid"
... |
"""This is a somewhat delicate package. It contains all registered components
and preconfigured templates.
Hence, it imports all of the components. To avoid cycles, no component should
import this in module scope."""
import logging
import typing
from typing import Any, Dict, List, Optional, Text, Type
from rasa.nlu ... |
# EIA_CBECS_Land.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
import pandas as pd
import numpy as np
import io
from flowsa.common import *
from flowsa.flowbyfunctions import assign_fips_location_system
"""
2012 Commercial Buildings Energy Consumption Survey (CBECS)
https://www.eia.gov/consumption/commercial/rep... |
import datetime
import time
from google.appengine.api import urlfetch
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengine.ext.db import polymodel
from tweetengine import oauth
from tweetengine.i18n import _
class UserAccount(polymodel.PolyModel):
def get_usern... |
import os
import time
import random
import torch
import logging
import numpy as np
import torch.nn as nn
from pathlib import Path
from args import get_parser
from models.model import MLMBaseline
from data.data_loader import MLMLoader
from utils import IRLoss, LELoss, MTLLoss, AverageMeter, rank, classify
# define crit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.