content stringlengths 5 1.05M |
|---|
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.models.enums import CheckResult, CheckCategories
class GoogleCloudDNSKeySpecsRSASHA1(BaseResourceCheck):
def __init__(self):
name = "Ensure that RSASHA1 is not used for the zone-signing and key-signing ... |
#!/usr/bin/env python
from mountaintools import client as mt
mt.login()
sha1_path = mt.saveFile('mountaintools_basic.simg', upload_to='spikeforest.spikeforest2')
print(sha1_path)
|
r""" COCO-20i few-shot classification and segmentation dataset """
import os
import pickle
from torch.utils.data import Dataset
import torch.nn.functional as F
import torch
import PIL.Image as Image
import numpy as np
class DatasetCOCO(Dataset):
"""
FS-CS COCO-20i dataset of which split follows the standard ... |
# This program prints some text
print('Changed text!')
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
# Generated by Django 3.0.10 on 2020-11-29 12:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inbox', '0009_message_id_default_clear_prev_uuid4'),
]
operations = [
migrations.AlterField(
model_name='message',
... |
# -*- coding:utf-8 -*-
"""
Example settings for local development
Use this file as a base for your local development settings and copy
it to umap/settings/local.py. It should not be checked into
your code repository.
"""
from umap.settings.base import * # pylint: disable=W0614,W0401
SECRET_KEY = 'hello,world'
IN... |
#! /usr/bin/env python3
# Copyright 2016 Euclidean Technologies Management 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/LIC... |
import pytest
import numpy as np
import pandas as pd
import pathlib
import FlowCytometryTools
import itertools
from sklearn.pipeline import Pipeline
from test_fixtures import fcs_path, locle_dir
from bactoml.fcdataset import FCDataSet
from bactoml.decision_tree_classifier import HistogramTransform, DTClassifier
from... |
# code was based on https://github.com/tamarott/SinGAN
import paddle.nn as nn
from ..generators.generator_singan import ConvBlock
from .builder import DISCRIMINATORS
@DISCRIMINATORS.register()
class SinGANDiscriminator(nn.Layer):
def __init__(self,
nfc=32,
min_nfc=32,
... |
import cv2
import csv
import numpy as np
def read_test_img(root_path, omission_image_times=0, first_classes_number=0, last_classes_number=43):
test_images = []
test_labels = []
gt_file = open(root_path + '\\' + 'GT-final_test.csv') # annotations file
gt_reader = csv.reader(gt_file, delimiter=';') #... |
"""
# Copyright 2020 Xiang Wang, 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
Author: Xiang Wang, xiangking1995@163.c... |
SAMPLEEXECUTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleExecution"
SAMPLEEXECUTION_TYPE_NAME = "SampleExecution"
GRID_TYPE_URI = "https://w3id.org/okn/o/sdm#Grid"
GRID_TYPE_NAME = "Grid"
DATASETSPECIFICATION_TYPE_URI = "https://w3id.org/okn/o/sd#DatasetSpecification"
DATASETSPECIFICATION_TYPE_NAME = "DatasetSpecifi... |
# Generated by Django 2.1.4 on 2019-05-05 16:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0002_auto_20190505_1027'),
]
operations = [
migrations.AddField(
model_name='recommender',
name='description... |
import typing
JsonDict = typing.Dict[str, typing.Any]
|
import os
import sys
import h5py
import tqdm
import math
import keras
import random
import urllib
import Bio.PDB
import argparse
import statistics
import numpy as np
import open3d as o3d
import urllib.request
from multiprocessing import Pool
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelEncod... |
from flask import (
Blueprint,
request
)
from soulsion_api.utils.utils import get_random_file_name
from soulsion_api.models.articles import Articles
articles = Blueprint('articles',__name__)
__article_data_directory = "/data/article/" #folder to articles data (file)
@articles.route('/api/articles/get',metho... |
# -*- coding: utf-8 -*-
import os
import socket
import sys
import time
import six
import pytest
from itertools import chain
from multiprocessing import Process
from flask import Flask
from flask.ext.cdn import CDN
from six.moves.urllib.request import urlopen
from six.moves.urllib.parse import urljoin
def pytest_... |
# Copyright (c) 2013 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.
import os
PROFILE_TYPE_MAPPING = {
'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1',
'power_user': 'chrome/test/data/extensio... |
import codecs
import os
from setuptools import setup
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding option to open
return codecs.open(os.path.join(here, *parts), 'r').read()
setup(
name='antools',
pa... |
import secrets
import string
from decimal import Decimal
from typing import Callable
import django
import pytest
from stellar_sdk import Keypair
from polaris_wyre.wyre import Wyre
from polaris_wyre.wyre.api import WyreAPI
from polaris_wyre.wyre.dtos import TransferData
ALPHABET = string.ascii_uppercase + string.digi... |
from django.urls import path, include
from .views import *
urlpatterns = [
path('', OrderView.as_view()),
path('<int:order_id>/', ModifyOrderView.as_view()),
path('close/<int:order_id>/', AdminUserPutOrder.as_view()),
] |
from crescent.core import Resource
from .constants import ResourceRequiredProperties, AllowedValues
class Route(Resource):
__TYPE = "AWS::ApiGatewayV2::Route"
def __init__(self, id: str):
super(Route, self).__init__(
id=id,
type=self.__TYPE,
allowed_values={self.Au... |
# -*- coding: utf-8 -*-
"""
TODO:
Remove Bloat
multi_index.py as well
https://github.com/spotify/annoy
"""
import logging
import numpy as np
import utool as ut
import vtool as vt
from vtool._pyflann_backend import pyflann as pyflann
# import itertools as it
# import lockfile
from os.path import basename
from wbia... |
# pylint: disable=invalid-name,missing-docstring,line-too-long
from __future__ import print_function
import os
import re
from subprocess import Popen, PIPE
from distutils.core import setup
from distutils.extension import Extension
VERSION = '0.2.2'
REQUIRES = ['cython>=0.2', 'pip']
CPATH_BASE_ = []
CFLAGS = []
LD... |
# Copyright 2020 MONAI Consortium
# 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, s... |
# -*- coding: utf-8 -*-
from lamvery.actions.base import BaseAction
from lamvery.actions.set_alias import SetAliasAction
class RollbackAction(BaseAction):
def __init__(self, args):
super(RollbackAction, self).__init__(args)
self._set_alias = SetAliasAction(args)
def action(self):
fu... |
# coding=utf-8
"""
test.context
~~~~~~~~~~~~
Import (relatively) the package which is under the test.
:copyright: (c) 2016 by Ali Ghaffaari.
:license: MIT, see LICENSE for more details.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import stream #noqa pylint: disable=wron... |
# Generated by Django 2.0.3 on 2018-05-11 18:09
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('game', '0003_auto_20180511_1908'),
]
operations = [
migrations.RemoveField(
model_name='game',
name='mode',
),
]... |
from common import AV_STATUS_METADATA, AV_SIGNATURE_METADATA
def sns_message_attributes(s3_object, scan_result = None, scan_signature = None):
message_attributes = {}
if 'sns-msg-attr-application' in s3_object.metadata:
message_attributes['application'] = {"DataType": "String",
... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Strategy module.
"""
__author__ = 'Ziang Lu'
from abc import ABC, abstractmethod
from typing import List
class SortingStrategy(ABC):
"""
Abstract sorting strategy class to define the sorting task to perform
(sorting problem to solve).
"""
__slot... |
import requests
import re
class ProxyWebsite(object):
def __init__(self, url, pattern, ip_pos, port_pos):
self.url = url
self.pattern = pattern
self.ip_pos = ip_pos
self.port_pos = port_pos
class Crawler(object):
@staticmethod
def get_html(proxy_website):
try:
... |
# This file exists within 'easy-as-pypi-termio':
#
# https://github.com/tallybark/easy-as-pypi-termio#🍉
#
# Copyright © 2018-2020 Landon Bouma. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 14-02-2021
"""
from typing import List, Sequence
import numpy
__all__ = ["get_strides_f", "get_strides_c"]
def get_strides_f(shape: Sequence) -> List:
"""Get strides of a F l... |
import numpy as np
import catboost as cb
import vaex.ml.catboost
import vaex.ml.datasets
# the parameters of the model
params_multiclass = {
'leaf_estimation_method': 'Gradient',
'learning_rate': 0.1,
'max_depth': 3,
'bootstrap_type': 'Bernoulli',
'subsample': 0.8,
'sampling_frequency': 'PerTr... |
"""Generador del tokens para el registro de usuarios
"""
# Django Library
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
"""Esta clase genera un token que se envía en correo para validadar el
registro del usuar... |
import numpy as np
class Mask:
"""Defines method to create and draw masks."""
def __init__(self,size,value=255):
self._image=np.full((size[1],size[0],3),value,dtype=np.uint8)
self._sx,self._sy=size
def asimage(self):
return self._image
def ellipse(self,center,axes,borde... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(test_suite='dropboxfs.tests')
|
#!/usr/bin/env python
'''
File name: select_model.py
Author: Varun Jampani
'''
# ---------------------------------------------------------------------------
# Video Propagation Networks
#----------------------------------------------------------------------------
# Copyright 2017 Max Planck Society
# Distribu... |
from jsk_recognition_utils import chainermodels
from jsk_recognition_utils import color
from jsk_recognition_utils import conversations
from jsk_recognition_utils import datasets
from jsk_recognition_utils import feature
from jsk_recognition_utils import mask
from jsk_recognition_utils import visualize
from jsk_recogni... |
# -*- coding: utf-8 -*-
'''
The rcctl service module for OpenBSD
'''
from __future__ import absolute_import
# Import python libs
import os
# Import salt libs
import salt.utils.path
import salt.utils.decorators as decorators
from salt.exceptions import CommandNotFoundError
__func_alias__ = {
'reload_': 'reload'
}... |
from pptx import Presentation #라이브러리
from pptx.util import Inches #사진,표 등을 그리기 위해
prs=Presentation() #파워포인트 객체 선언
title_slide_layout=prs.slide_layouts[0] #0 : 제목 슬라이드에 해당
slide=prs.slides.add_slide(title_slide_layout) #슬라이드 추가
# 제목-제목에 값 넣기
title=slide.placeholders[0] #제목
title.text = "Hello World!" #제목에 값넣기
#부제목
s... |
# %% Imports and Functions
from util import Perceptron
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.neural_network import MLPClassifier
from sklearn.svm import... |
# Generated by Django 3.0.4 on 2020-04-04 07:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20200402_1849'),
]
operations = [
migrations.RemoveField(
model_name='phaseselectionmodel',
... |
"""Project settings"""
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
RAW_DATA_DIR = os.path.join(BASE_DIR, "data/01_raw/")
|
"""Version 0.65.008
Revision ID: ab55a08d3539
Revises: 7b0431792061
Create Date: 2020-03-18 06:04:22.110170
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from sqlalchemy import Enum
# revision identifiers, used by Alembic.
revision = 'ab55a08d3539'
down_revision = '7b04317... |
import psycopg2
import psycopg2.extras
import networkx as nx
from networkx.algorithms.traversal.depth_first_search import *
from networkx.algorithms.simple_paths import *
from lxml import etree
from datetime import date, timedelta
import requests
def examine(node,ap):
if len(list(g.successors(node)))==0:
print(n... |
from collections import namedtuple
from typing import Dict, Iterable, Hashable
Result = namedtuple("Result", ["score", "reg_alpha", "is_neg", "min_weights"])
def drop_keys(dict_: Dict, keys: Iterable[Hashable]) -> Dict:
"""
Drop multiple keys from dict
Args:
dict_:
keys:
Returns:
... |
import binascii
import re
import uuid
from collections import OrderedDict
from typing import Union, List, Optional
import graphene
from django.core.exceptions import FieldDoesNotExist
from django.db import models
from graphene import InputObjectType
from graphene.utils.str_converters import to_camel_case
from graphene... |
import os
from datetime import datetime
from unittest import TestCase
from unittest.mock import Mock
import jsonpickle
from dateutil.tz import tzoffset
from octopus_energy.mappers import (
_calculate_unit,
consumption_from_response,
to_timestamp_str,
meters_from_response,
_get_page_reference,
... |
DAY = 10
from itertools import groupby
def look_and_say(ma, num="3113322113"):
while ma:
yield num
num = "".join(str(len(list(listt))) + n for n, listt in groupby(num))
ma -= 1
def part1():
for j in look_and_say(41):
pass
return(len(j))
def part2():
for j in look_and_say(51):... |
import pytest
import base64
from pythclient.solana import SolanaPublicKey
from pythclient.pythaccounts import PythPriceComponent, PythPriceInfo, PythPriceStatus
@pytest.fixture
def price_component_bytes() -> bytes:
return base64.b64decode((
b'92Z9u4180xchiUFKI8JrUh2MGcZFBFVV4+KOglaOZXjgewKnDgAAACDF+wAAAA... |
from django.forms import ModelForm
from django import forms
from wanted.models import *
class FlagForm(ModelForm):
item = forms.ModelChoiceField(queryset=Item.objects.all())
type = forms.ModelChoiceField(queryset=FlagType.objects.all())
value = forms.CharField(max_length=255)
class ItemForm(ModelForm):
... |
from limite.telaGenerica import TelaGenerica
import PySimpleGUI as sg
class TelaPersonagemMovimentar(TelaGenerica):
def __init__(self, controlador):
super().__init__(controlador)
self.__janela = None
def init_components(self, **kwargs):
sg.ChangeLookAndFeel('Reddit')
layout ... |
# Python - 3.6.0
Test.describe('get change')
Test.it('should define money and set value')
Test.assert_equals(money, 10)
Test.it('should define candy and set value')
Test.assert_equals(candy, 1.42)
Test.it('should define chips and set value')
Test.assert_equals(chips, 2.4)
Test.it('should define soda and set value')
Te... |
# -*- coding: utf-8 -*-
from django.core.files import File
from django.db import models
from django.db.models.signals import post_delete, post_save
from colorfield.fields import ColorField
import os
class Theme(models.Model):
@staticmethod
def post_migrate_handler(sender, **kwargs):
Theme.get_or_c... |
#!/usr/bin/python2.4
# Copyright (c) 2006-2008 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.
'''The 'grit build' tool along with integration for this tool with the
SCons build system.
'''
import os
import getopt
import ... |
from tornado.testing import AsyncHTTPTestCase
from tornado_http2.server import CleartextHTTP2Server
class AsyncHTTP2TestCase(AsyncHTTPTestCase):
def get_http_server(self):
# TODO: call get_app() a second time or use the non-public self._app?
app = self.get_app()
return CleartextHTTP2Serve... |
#!/usr/bin/env python
import os
from datetime import datetime
import requests
from polib import POEntry, POFile
def main():
out_dir = os.path.join(
os.path.dirname(__file__), "archetypes", "en", "LC_MESSAGES"
)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
out_path = os.path.join(out_dir, "django.po")... |
import logging
from ibmsecurity.utilities import tools
logger = logging.getLogger(__name__)
# URI for this module
uri = "/isam/application_logs"
def get_all(isamAppliance, file_path='', recursive='yes', flat_details=None, check_mode=False, force=False):
"""
Retrieving the contents of a directory from the ap... |
try:
import micropython
except ImportError:
class micropython(object):
@staticmethod
def native(func):
return func
class _TimingConst(object):
"""
Constants used to calculate the bit timing registers
If wanting to expand the bitrate calculations so it will support a
... |
from .observation_map import *
|
import sys
from awsglue.utils import getResolvedOptions
import pandas as pd
from config.env import Env
import boto3
import io
import s3fs
args = getResolvedOptions(sys.argv, ['stage', 'project'])
# Job input parameters
stage = args['stage']
project = args['project']
def to_excel(csv_filepath, excel_buc... |
from pal.logger import logger
from pal.exception import PalWriterException
from pal.writer.access_mechanism.access_mechanism \
import AccessMechanismWriter
class GnuInlineAarch64AccessMechanismWriter(AccessMechanismWriter):
def declare_access_mechanism_dependencies(self, outfile, register,
... |
'''
@Autor: Paulo https://github.com/alpdias
'''
# Programa principal
from datetime import date # Biblioteca de datas
import os # Biblioteca de comandos do sistema
from time import sleep # Biblioteca de tempo
import calculos # Biblioteca de cálculos
import tratamento # Biblioteca de tratamento
tratamento.barraProgresso... |
"""Preparing the data to be plotted with bokeh"""
import pickle
import numpy as np
from scipy import spatial
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
embeddings_dict = {}
with open("data/glove.6B.50d.txt", 'r', encoding="utf-8") as file_imp:
for line in file_imp:
values = l... |
#!/usr/bin/env python3
"""Mapping functions"""
import json
import logging
import urllib.parse
import ipyleaflet
import namedtupled
import requests
logger = logging.getLogger(__name__) # pylint: disable=C0103
class GeocodeResult():
"""The result of a geocode lookup"""
def __init__(
self,
... |
# __init__.py
import os
file_name = "phrases.txt"
current_path = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_path, file_name)
file_handler = open(file_path)
phrases = [phrase.strip() for phrase in file_handler.readlines()]
from .cookie import fortune
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 18:53
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import habitat.timezone.models.martian_s... |
def a():
print("a")
print("b")
if True:
print("True!")
if False:
print("False!")
print("c")
a()
|
from src.platform.coldfusion.interfaces import CINTERFACES
from src.module.deploy_utils import parse_war_path
from os.path import abspath
from log import LOG
import utility
title = CINTERFACES.CFM
versions = ['8.0']
def deploy(fingerengine, fingerprint):
""" Exploits the exposed FCKeditor in CF 8.x
"""
c... |
# 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... |
#!/usr/bin/python3
import mythic
import json
import base64
import requests
import time
import ast
import types
import math
import random
import socket
import struct
import platform
import os
import getpass
import threading
# from pynput import keyboard
import re
import sys
# import Xlib
# import Xlib.display
import ti... |
__all__= ['apiclient', 'models']
from .apiclient import MediaAccountClient
import logging
logger = logging.getLogger("mediaaccount") |
# Copyright 2018 The TensorFlow Probability 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 o... |
from scipy import stats
from scipy import ndimage
import numpy as np
import graph
def arrange(cd):
# get indices of nonzero elements
nonzero = cd.image.nonzero
# buffer size for group ranges
b = cd.params.buffer_size
# number of nonzero points per group
groups = [[]]
# group ranges in t... |
import os
import sys
import csv
import time
from difflib import SequenceMatcher
from pandas_datareader import data as data_reader
from pandas_datareader._utils import RemoteDataError
from utilities.log import root_folder_all_code
dir_path = os.path.dirname(os.path.realpath(__file__))
dir_root = dir_path.split(root_fol... |
from threading import Thread
import pytest
from assertpy import assert_that
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
from sylenium import SyleniumDriver
from sylenium import SyleniumElement
from sylenium.element import ById
from sylenium.sylenium import find
from sylenium.sylenium ... |
db_host = ""
db_username = "root"
db_password = "password"
db_name = "hwdb"
|
# -*- coding: utf-8 -*-
#
# Sync Unit Tests
#
# To run this script use:
# python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3/s3sync.py
#
import unittest
from gluon import current
from lxml import etree
try:
import json # try stdlib (Python 2.6)
except ImportError:
try:
import simplej... |
from isitopen.tests import *
import isitopen.forms as forms
import isitopen.model as model
class TestForms:
@classmethod
def setup_class(self):
self.enq_id, self.msg_id = Fixtures.create()
@classmethod
def teardown_class(self):
Fixtures.remove()
def test_message(self):
# o... |
from obb.views.people import PersonViewSet
from obb.views.platforms import PlatformViewSet
from obb.views.train_stations import TrainStationViewSet
from obb.views.train_sections import TrainSectionViewSet
from obb.views.trains import TrainViewSet
from obb.views.railjets import RailjetsViewSet
from obb.views.ices import... |
#
# Copyright (c) 2020 The rlutils authors
#
# This source code is licensed under an MIT license found in the LICENSE file in the root directory of this project.
#
from abc import ABC, abstractmethod
def simulate(mdp, policy, transition_listener, max_steps=5000):
"""
Train the agent on the given MDP for one ... |
# Original version taken from https://djangosnippets.org/snippets/605/
# Orignal version taken from http://www.djangosnippets.org/snippets/186/
# Original author: udfalkso, hauser
# Modified by: Anudeep Samaiya
import re
from django.conf import settings
from pyprofile import Profiler
words_re = re.compile(r"\s+")
g... |
"""
Builds wheel files for the dependencies of an app, specified in requirements.txt, into the wheels/
folder of the app repo, and updates the app's JSON config specifying any generated wheels as pip
dependencies.
NOTE: If running this script with the --repair_wheels flag, make sure the script is executed from
a manyl... |
import os
import tempfile
import shutil
from lxml import etree
from hs_core.hydroshare import resource
from .base import ModelInstanceSciMetaTestCase
class TestScienceMetadataSWAT(ModelInstanceSciMetaTestCase):
def test_put_scimeta_swat_model_instance(self):
# Update science metadata XML
title_... |
try:
from time import clock, sleep
except ImportError:
from time import perf_counter as clock
from flask import jsonify, json
from InstagramAPI import InstagramAPI
import cons
class libInsta:
delayTime = 0
def __init__(self, API: InstagramAPI):
self.API = API
def delay(self):
s... |
import math
import torch
import torch.nn as nn
class MultiHeadLinear(nn.ModuleList):
def __init__(self, in_features, out_features, bias=True, no_grad=True):
super(MultiHeadLinear, self).__init__()
self.out_features = out_features
for _ in range(out_features):
self.append(nn.Lin... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 05 19:52:02 2015
@author: Paco
"""
from api import API
class Delicious(API):
_class_name = 'Delicious'
_category = 'Social'
_help_url = 'https://delicious.com/rss'
_version = '2'
_api_url = 'http://feeds.delicious.com/v' + _version + '/json/'
d... |
# Copyright(c) 2018 Nippon Telegraph and Telephone Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
# coding:utf-8
from textda.data_expansion import data_expansion
import json
json_data = []
for line in open('./iflytek/train.json','r', encoding='utf-8'):
json_data.append(json.loads(line))
dic = {}
f = open('./iflytek/train_new.json','w', encoding='utf-8')
for tmp in json_data:
sen_list = data_expansion(tmp['... |
#!/usr/bin/env python3
import tensorflow.keras as K
resnet50 = __import__('4-resnet50').resnet50
if __name__ == '__main__':
model = resnet50()
model.summary()
|
"""Base class for the "modules" of FavaLedger."""
class FavaModule:
"""Base class for the "modules" of FavaLedger."""
def __init__(self, ledger):
self.ledger = ledger
def load_file(self):
"""Gets called when the file has been (re)loaded."""
|
PREFIX = '[U:1:'
BASE = 76561197960265728
def convert_id3_to_id64(steamid: str) -> int:
if not isinstance(steamid, str):
raise TypeError('steamid must be a string')
if PREFIX not in steamid or ']' not in steamid[-1]:
raise ValueError("Expected steam id3 string such as [U:1:22202] instead got ... |
"""
This parameter file is designed for continuous action environments.
For discrete action environments minor modifications might be required.
See Also:
:ref:`ref-parameter-files`
"""
import numpy as np
from copy import deepcopy
from digideep.environment import MakeEnvironment
from collections import OrderedDic... |
# Copyright 2016 Cloudera 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 in writing, so... |
import os
import requests
import argparse
import MDAnalysis as mda
from pensa import download_from_gpcrmd
def subsample(psf_file, xtc_file, out_file):
u = mda.Universe(psf_file,xtc_file)
print(len(u.trajectory))
a = u.select_atoms('all')
with mda.Writer(out_file, a.n_atoms) as W:
for ts in u.t... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
if len( sys.argv ) == 1:
print('Usage: find_path.py filename1 [filename2] ...')
paths = []
for path in os.environ['PATH'].split(os.pathsep):
if os.path.isdir(path):
paths.append(os.path.abspath(p... |
import numpy as np
import os
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch import autograd
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm
from .utils import plot_img, plot_scalar, save_images, to_device
class ONE_SIDED(nn.Modu... |
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import os
import pprint
import html5lib_to_markdown
from html5lib_to_markdown.transformer import Transformer
# ==============================================================================
_dir_base = os.path.dirname(__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.