text stringlengths 1 927k |
|---|
def findDecision(obj): #obj[0]: Passanger, obj[1]: Coupon, obj[2]: Education, obj[3]: Occupation, obj[4]: Restaurant20to50, obj[5]: Distance
# {"feature": "Occupation", "instances": 23, "metric_value": 0.9656, "depth": 1}
if obj[3]<=21:
# {"feature": "Passanger", "instances": 21, "metric_value": 0.9183, "depth": 2}... |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Machine/LamSlotWind.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Machine/LamSlotWind
"""
from os import linesep
from sys import getsizeof
f... |
################################################################################
#
# BFIELD
#
# Simple example of plot of the magnitude of the magnetic field
# produced by a current loop, using its Cartesian components
#
#
################################################################################
import num... |
from steiner.main import main
main() |
from contextlib import contextmanager
from unittest import mock
import pytest
from dagster import (
DagsterEventType,
DagsterInvariantViolationError,
DagsterResourceFunctionError,
Enum,
EnumValue,
Field,
Int,
ModeDefinition,
PipelineDefinition,
ResourceDefinition,
String,
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Iterable, Union
import gym
from compiler_gym.envs import CompilerEnv
from compiler_gym.util.gym_type_hints import Observat... |
import _plotly_utils.basevalidators
class RowValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self, plotly_name="row", parent_name="layout.ternary.domain", **kwargs
):
super(RowValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent... |
"""Test the Hardkernel config flow."""
from unittest.mock import patch
from homeassistant.components.hardkernel.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import RESULT_TYPE_ABORT, RESULT_TYPE_CREATE_ENTRY
from tests.common import MockConfigEntry, MockModule, m... |
from . import Analysis, register_analysis
from .. import SIM_PROCEDURES
import logging
l = logging.getLogger('angr.analyses.callee_cleanup_finder')
class CalleeCleanupFinder(Analysis):
def __init__(self, starts=None, hook_all=False):
self.results = {}
if starts is None:
starts = [imp.... |
from .coco_entity import CoCoEntity
from .const import KEY_BASICSTATE, VALUE_TRIGGERED, VALUE_ON, KEY_STATUS
from .helpers import extract_property_value_from_device
class CoCoGeneric(CoCoEntity):
@property
def is_on(self):
return self._is_on
def __init__(self, dev, callback_container, client, pr... |
# -*- coding: utf-8 -*-
"""
File : pyhaystackTest.py (2.x)
This module allow a connection to a haystack server
Feautures provided allow user to fetch data from the server and eventually, to post to it.
See http://www.project-haystack.org for more details
Project Haystack is an open source initiative to streamline wor... |
## TODO: define the convolutional neural network architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init_... |
import decimal
import numpy as np
import pandas as pd
import pandas.util.testing as tm
import pytest
from pandas.tests.extension import base
from .array import DecimalDtype, DecimalArray, make_data
@pytest.fixture
def dtype():
return DecimalDtype()
@pytest.fixture
def data():
return DecimalArray(make_dat... |
import pickle
import pandas as pd
from sklearn.utils import resample
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
import os
class PokemonTypeIdentifier():
"""
This class identifies the pokemon type of a user given pokemon name.
"""
def __init__(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import optparse
import csv
import re
import datetime as dt
from random import choice
from collections import defaultdict
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import DashTestFramework
from test_frame... |
from .peewee import *
from .async_task import *
CACHE_BACKEND = "Redis"
MIDDLEWARES = [
"sea.middleware.ServiceLogMiddleware",
"sea.middleware.RpcErrorMiddleware",
]
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 0
TIMEZONE = "Asia/Shanghai"
GRPC_GRACE = 0
PROMETHEUS_SCRAPE = True |
from tests.system.action.base import BaseActionTestCase
class MotionCreateAmendmentActionTest(BaseActionTestCase):
def setUp(self) -> None:
super().setUp()
# create parent motion and workflow
self.set_models(
{
"motion_workflow/12": {
"name":... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\fishing\aquarium_object.py
# Compiled at: 2018-02-28 22:55:27
# Size of source mod 2**32: 6387 bytes... |
# PyAlgoTrade
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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 ap... |
def main():
maximum = 20
for w in range( maximum ):
for x in range( maximum ):
for y in range( maximum ):
for z in range( maximum ):
#print ( w, x, y, z )
positive_Y = float( float(y+z+1)/float(w+x+y+z+2) * ( float(z+1)/float(y+z+2) ) )
negative_Y = float( float(w+x+1)/float(w+x+y+z+2) * ( f... |
from __future__ import unicode_literals
import unittest
import os
from pymatgen.util.testing import PymatgenTest
from monty.serialization import loadfn
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'test_files')
class IRDielectricTensorTest(PymatgenTest):
def set... |
import os
from collections import Counter
import copy
dialog_file = 'data/crowded_300k_jinyong_dialog_filter_sort.txt'
prob_file = 'data/crowded_300k_jinyong_dialog_probs_filter_sort.txt'
out_file = 'data/crowded_300k_jinyong_dialog_resp2post_5cand.txt'
n_cand = 5
dialog_data = []
with open(dialog_file) as f:
res... |
#!/usr/bin/env python3
# AV-98 Gemini client
# Dervied from VF-1 (https://github.com/solderpunk/VF-1),
# (C) 2019, 2020 Solderpunk <solderpunk@sdf.org>
# With contributions from:
# - danceka <hannu.hartikainen@gmail.com>
# - <jprjr@tilde.club>
# - <vee@vnsf.xyz>
# - Klaus Alexander Seistrup <klaus@seistrup.dk>
# -... |
#!python3
#encoding:utf-8
from abc import ABCMeta, abstractmethod
import AGitHubUser
import BasicAuthenticationUser
class TwoFactorAuthenticationUser(BasicAuthenticationUser.BasicAuthenticationUser):
def __init__(self, username, password, secret):
super().__init__(username, password)
self.__secret =... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import platform
import random
from abc import ABCMeta, abstractmethod
from typing import ClassVar, Dict, List
import torch
i... |
import copy
class Website:
def __init__(self, name, domain, description, author, **kwargs):
'''Examples of optional attributes (kwargs):
category, creation_date, technologies, keywords.
'''
self.name = name
self.domain = domain
self.description = description... |
"""
atom_data.py
Data
stores the essential data
"""
atomic_weights = {
'H': 1.00784,
'C': 12.0107,
'N': 14.0067,
'O': 15.999,
'P': 30.973762,
'F': 18.998403,
'Cl': 35.453,
'Br': 79.904,
}
atom_colors = {
'H': 'white',
'C': '#D3D3D3',
'N': '#add8e6',
'O': 'red',
'... |
# Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
# @author: ww
import os
import pickle
import re
import yaml
def read_yaml(yaml_file):
"""
Read yaml file
:param yaml_file:
:return:
>>> read_yaml('test_resource/test_read.yml')
{'date': datetime.date(2019, 11, 6), 'pkg': {'python': {'version': '3.6.8', 'date': '{{ date }}'}, 'django': {'ver... |
"""the lti_launch module."""
from . import views # noqa |
"""
ASGI config for ms4 project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 8 16:12:32 2018
@author: jack.lingheng.meng
"""
try:
import vrep
except:
print ('--------------------------------------------------------------')
print ('"vrep.py" could not be imported. This means very probably that')
print ('eithe... |
from typing import Type
from django.db import models
from rest_framework import mixins, permissions, serializers, viewsets
from posthog.api.routing import StructuredViewSetMixin
from posthog.constants import AvailableFeature
from posthog.exceptions import EnterpriseFeatureException
from posthog.filters import TermSea... |
# -*- coding: utf-8 -*-
########################################################################
#
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
#
########################################################################
import sys
import threading
from region import geometry as mygeo
from region import... |
# -*- coding: UTF-8 -*-
# Copyright (c) 2017 Intel 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 applica... |
# -*- coding: utf-8 -*-
# Global imports
import os,re
import glob
import argparse as ap
# Local imports
from StorePDBFilenames import *
# Script information
__author__ = "Sergi Rodà"
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Sergi Rodà"
__email__ = "sergi.rodallordes@bsc.es"
# Global variables
Pro... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 Tobias Weber <tobi-weber@gmx.de>
#
# 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 ... |
from keckdrpframework.primitives.base_primitive import BasePrimitive
from kcwidrp.primitives.kcwi_file_primitives import kcwi_fits_writer, \
kcwi_fits_reader, get_master_name, strip_fname
from kcwidrp.core.kcwi_correct_extin import kcwi_correct_extin
import os
import numpy as np
from scipy.interpolate import inter... |
""" Setup for pyHealthchecks """
import os
from setuptools import setup, find_packages
NAME = "pyhealthchecks"
AUTHOR = "Mark Kuchel"
AUTHOR_EMAIL = "mark@kuchel.net"
DESCRIPTION = "An async client library for ping HealthChecks.io"
URL = "https://github.com/kuchel77/pyhealthchecks"
REQUIRES = [
'aiohttp>=3.5.4'
... |
import sys
# package need to be installed, pip install docker
import docker
import time
import yaml
import os
import random
import subprocess
import signal
import urllib2
import shutil
import xlwt
# package need to be installed, apt-get install python-memcache
import memcache
auto = False
private_registry = "202.114... |
def sum_dig_pow(a, b):
res = []
for i in range(a, b + 1):
temp = []
for idx, elem in enumerate(str(i), start=1):
# print(elem, idx)
# print(int(elem) ** idx)
temp.append(int(elem) ** idx)
# print(temp)
# print(i, sum(temp))
if sum(temp)... |
'''
FastAPI Demo
SQLAlchemy ORM Models
'''
# Standard Imports
# PyPi Imports
from sqlalchemy import (
Boolean,
Column,
Integer,
String
)
# Local Imports
from database.setup import Base
###############################################################################
class User(Base):
'''ORM Models - users'''
_... |
import EELSpecNet
import GenerateData as gene
import tensorflow as tf
import numpy as np
import tensorflow.experimental.numpy as tnp
tnp.experimental_enable_numpy_behavior()
def main():
model = EELSpecNet.EELSpecNetModel_CNN_10D(2048)
op = tf.keras.optimizers.Adam(learning_rate=5e-5)
model.compile(optimiz... |
# Copyright 2021 The PyMC Developers
#
# 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... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Nsimd(CMakePackage):
"""NSIMD is a vectorization library that abstracts SIMD programming.
It was designed to ... |
# -*- coding: utf-8 -*-
"""Views to manipulate dataframes."""
from django.urls import path
from ontask import models
from ontask.dataops import services, views
from ontask.tasks import task_execute_factory
app_name = 'dataops'
urlpatterns = [
# Show the upload merge menu
path('uploadmerge/', views.uploadmerg... |
# -- coding: utf-8 --
import os
import csv
def go_though(open_file):
for root, dirs, files in os.walk(r''+str(open_file)):
for file in files:
# # 获取文件所属目录
# print(root)
# 获取文件路径
print(os.path.join(root, file))
def re_hour(hour):
if len(str(hour))<2:retu... |
# 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... |
import sys, fmdata
"""
Simple script to extract a 'test' data set from a real '.dat' file.
"""
f = open(sys.argv[1], "r")
d = fmdata.readFromDatFile(f)
f.close()
linenums = []
for x in xrange(0, d.nx, 2):
for y in xrange(0, d.ny, 2):
for z in xrange(0, d.nz, 6):
linenums.append(x*d.ny*d.nz + ... |
'''
Created on 11.07.2018
@author: yvo
Main script to import all VAW volume change data files into the GLAMOS database.
'''
import configparser
import os
from dataflow.DataReaders.DatabaseReaders.GlacierReader import GlacierReader
from dataflow.DataObjects.Exceptions.GlacierNotFoundError import GlacierNotFoundError... |
'''
.. Stuff specific to MS Windows
.. Copyright (c) 2016 Richard Plevin
See the https://opensource.org/licenses/MIT for license details.
'''
from __future__ import print_function
import os
import platform
from errno import EEXIST
from .config import getParamAsBoolean, unixPath
IsWindows = platform.system() == 'Win... |
from __future__ import print_function
import pytest
import xarray as xr
import numpy as np
from xgcm.grid import Grid, Axis
from xgcm.test.datasets import datasets_grid_metric
@pytest.mark.parametrize("funcname", ["interp", "diff", "min", "max", "cumsum"])
@pytest.mark.parametrize("grid_type", ["B", "C"])
@pytest.ma... |
"""empty message
Revision ID: 2018_03_22_user_model_refactor
Revises: 2018_03_20_remove_unused_fields
Create Date: 2018-03-22 10:23:42.850491
"""
from alembic import op
import sqlalchemy as sa
from psycopg2._psycopg import ProgrammingError
from sqlalchemy.dialects import postgresql
from sqlalchemy.dialects.postgresql... |
"""
Module containg all the tests provided for the util module.
"""
import pytest
from recipe_tagger import util
# @pytest.mark.skip()
def test_process_ingredient():
"""
Test for process_ingredient method.
Test is passed only if the provided ingredient is processed correctly.
"""
assert (
... |
from mxnet import gluon
def _make_conv_block(block_index, num_chan=32, num_layer=2, stride=1, pad=2):
out = gluon.nn.HybridSequential(prefix='block_%d_' % block_index)
with out.name_scope():
for _ in range(num_layer):
out.add(gluon.nn.Conv2D(num_chan, kernel_size=3, strides=stride, padding... |
# from parent folder, run 'python -m xutil.tests.helpers_test'
import unittest, os
from path import Path
from unittest.mock import patch
from xutil.helpers import *
from xutil.database.base import get_conn
import docker # https://github.com/docker/docker-py
from collections import namedtuple
class BaseDBTest(unit... |
_base_ = [
'../../_base_/models/swin_base.py', '../../_base_/datasets/nyu.py',
'../../_base_/iter_runtime.py', '../../_base_/schedules/schedule_cos24x_iter.py'
]
model = dict(
pretrained='./nfs/checkpoints/swin_large_patch4_window12_384_22k.pth', # noqa
backbone=dict(
pretrain_img_size=384,
... |
import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
import game_functions as gf
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
from mouse_move import MouseMove
from musics import Musics
def run_game():
# 初始化游戏并且创建一个屏幕对象
... |
import numpy as np
from matplotlib import pyplot as plt
from scipy import interpolate
from abc import ABCMeta, abstractmethod
from utils.sorting import bubble_sort
class ABSMethods(metaclass=ABCMeta):
def __init__(self, function):
self.function = function
@abstractmethod
def drawGraphic(self, ve... |
#!/usr/bin/env python3
# A plugin to nmap targets slow motion, to evade sensors
from plugins.base.attack import AttackPlugin, Requirement
class MetasploitScreengrabPlugin(AttackPlugin):
# Boilerplate
name = "metasploit_screengrab"
description = "Grab a screenshot"
ttp = "T1055"
references = ["h... |
# Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask_mailer.backends.base import Mailer
class DummyMailer(Mailer):
"""Dummy mailing instance for unittests.
Keeps all sent messages in *oubox* list.
"""
def __init__(self, **kwargs):
self.outbox = []
def send(self, message):
"""Send... |
import contextlib
import logging
import os
import shlex
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Dict, List, Optional, Union
from django.conf import settings
from coreapp.error import SandboxError
logger = logging.getLogger(__name__)
class Sandbox(contex... |
"""
Extract commit comments from git to a report. Makes for a lousy CHANGELOG.md
"""
import shlex
from navio_tasks.cli_commands import (
check_command_exists,
config_pythonpath,
execute_get_text,
)
from navio_tasks.settings import VENV_SHELL
from navio_tasks.utils import inform
def do_gitchangelog() -> N... |
"""Shared support for scanning document type declarations in HTML and XHTML.
This module is used as a foundation for the html.parser module. It has no
documented public API and should not be used directly.
"""
import re
_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match
_declstringlit_match = re.com... |
""" Build the README.rst either locally, or on Github for tagged commits.
Usage:
build_docs.py <TRAVIS_REPO_SLUG>
build_docs.py (-h | --help)
The TRAVIS_REPO_SLUG has following Format : "github_username/github_repository"
Options:
-h --help Show this screen
"""
# STDLIB
import datetime
import errno
i... |
print(callable(abs)) |
def func():
x = 2
def say():
print x
return say
f = func()
f() |
import argparse
import os
import numpy as np
from torch.utils.data import DataLoader
from . import ImageDataset
from .core import get_inception_feature
def calc_and_save_stats(path, output, batch_size):
dataset = ImageDataset(path, exts=['png', 'jpg'])
loader = DataLoader(dataset, batch_size=batch_size, num... |
"""
This module contains a collection of tasks for interacting with Postgres databases via
the psycopg2 library.
"""
try:
from prefect.tasks.postgres.postgres import (
PostgresExecute,
PostgresExecuteMany,
PostgresFetch,
)
except ImportError:
raise ImportError(
'Using `prefe... |
# 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... |
import string
try:
f = open('ports.inf','r+')
for line in f:
print line
splitstring=string.split(line, '=')
if splitstring[0] == "ScreenPort":
ScreenPort = splitstring[1].rstrip()
print "Setting screenport to: " + ScreenPort
elif splitstring[0] == "OptPo... |
"""
In Class Ex:
Constrained \infty-norm minimization
Problem:
minimize:
\norm{x}_\infty
subject to:
A x \leq b
Notes:
\norm{x}_\infty = \max_i \abs{x_i}
= \max_i \{x_i, -x_i\}
= \max_i \{x_1, \dots, x_n, -x_1, \dots, -x_n\}
Epigraph Form:
minim... |
import discord
import ksoftapi
import logging
import aiohttp
import os
import json
import datetime
import time
import sys
import asyncpg
from utils import permissions, usefull
from main import context, prefix
from discord.ext import commands
from collections import namedtuple
c = usefull.colors
#AutoShardedClient.sha... |
from copy import deepcopy
import cv2
import imageio
import numpy as np
import matplotlib.pyplot as plt
from os.path import join
from PIL import ImageFont, ImageDraw, Image
from disagreements.common.utils import make_clean_dirs, save_image, create_video
from disagreements.logging_info import log
from disagreements.get... |
# Copyright 2021 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
# coding: utf-8
__author__ = 'jsun'
class BaseFormat(object):
def __init__(self):
self.name = "base_format"
self.id = -1
self.description = ""
self.html_pre = ""
self.html_post = ""
self.child_formats = []
self.usep = False
self.useheader = False
c... |
# Copyright 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.
"""Defines the PerfOptions named tuple."""
import collections
PerfOptions = collections.namedtuple('PerfOptions', [
'steps',
'flaky_steps',
'pr... |
#!"C:\Users\IsaacB\Documents\GitHub\steam-key-safe\Steam Key Safe\venv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==9.0.1','console_scripts','pip'
__requires__ = 'pip==9.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\... |
from django.db import models
from django.utils import timezone
from autores.models import Autor
class Podcast(models.Model):
titulo = models.CharField(max_length=255)
autor = models.ForeignKey(Autor, on_delete=models.DO_NOTHING)
data = models.DateTimeField(default=timezone.now())
descricao = models.Te... |
import numpy as np
def read_data(path, M, N, offset=0):
"""
Read u.data in the default format.
The memory cost associated with a [943, 1682] matrix of floats are not big,
so we can still do this.
"Might" run into trouble for larger datasets,
where we will need to handle things in batches.
Params:
M:... |
from starlette.routing import Route
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware import Middleware
from .home import HomePage
from .column_groups import ColumnGroups
from .project import ProjectsAPI
from .geometries import geometries, get_l... |
_base_ = [
'../../lvis/cascade_rcnn_r50_fpn_sample1e-3_mstrain_1x_lvis_v1.py'
]
data = dict(train=dict(oversample_thr=0.0))
model = dict(roi_head=dict(bbox_head=[dict(
type='Shared2FCBBoxHead',
in_channels=256,
fc_out_channels=1024,
roi_feat_size=7,
num_classes=1203,
bbox_coder=dict(
... |
# -*- coding: utf-8 -*-
import os
import random
import shutil
import socket
import struct
import time
import uuid
from contextlib import contextmanager
from datetime import datetime, timedelta
from functools import partial
from importlib import import_module
from urllib.parse import parse_qs, urlparse
from unittest imp... |
from odoo import models, api, _
from odoo.exceptions import UserError
class ValidateAccountMove(models.TransientModel):
_name = "validate.account.move"
_description = "Validate Account Move"
@api.multi
def validate_move(self):
context = dict(self._context or {})
moves = self.env['acco... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2009 Doug Hellmann All rights reserved.
#
"""
"""
#end_pymotw_header
import subprocess
cat = subprocess.Popen(['cat', 'index.rst'],
stdout=subprocess.PIPE,
)
grep = subprocess.Popen(['grep', '.. include::'],
... |
from aceinna.devices.base import UpgradeWorkerBase
class ErrorWorker(UpgradeWorkerBase):
def __init__(self):
super(ErrorWorker, self).__init__()
self._total = 1024*1024 # 1M size
def get_upgrade_content_size(self):
return self._total
def work(self):
current = 0
s... |
"""The main class file representing a kernel."""
# Author: Ioannis Siglidis <y.siglidis@gmail.com>
# License: BSD 3 clause
import collections
import warnings
import copy
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
from sklearn.exceptions import NotFittedError
fr... |
import os
import platform
import shutil
import stat
import sys
import unittest
import mock
import six
from parameterized.parameterized import parameterized
from conans.client import tools
from conans.client.build.cmake import CMake
from conans.client.build.cmake_flags import cmake_in_local_cache_var_name
from conans.... |
import os
from os.path import isfile, join
import adal
from settings import settings
from office365.graph_client import GraphClient
def get_token():
"""Acquire token via client credential flow
"""
authority_url = 'https://login.microsoftonline.com/{0}'.format(settings['tenant'])
auth_ctx = adal.Auth... |
#!/usr/bin/env python
# Copyright (c) 2020-2021 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
import logging
import os
import queue
import threading
from lydian.apps import config as config... |
import os
import numpy as np
import pandas as pd
import cv2
import matplotlib.pyplot as plt
import fnmatch
from sklearn.model_selection import train_test_split
from glob import glob
imagePatches = glob('./IDC_regular_ps50_idx5/**/*.png',recursive = True)
def multiplot():
plt.rcParams['figure.figsize'] = (10.0, 10.... |
#!/usr/bin/env python3
#
# Copyright (c) 2018, The OpenThread Authors.
# 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
# ... |
# 3613
# <(?<tag>\w*|\w*\.+\w*)>+((.|[\n\t\f\r\s])*?)<\/\k<tag>>
# EXPONENT
# nums:5
# EXPONENT AttackString:"<>"+"\t\t"*16+"! _1_EOD(i2)"
import re2 as re
from time import perf_counter
regex = """<(?<tag>\w*|\w*\.+\w*)>+((.|[\n\t\f\r\s])*?)<\/\k<tag>>"""
REGEX = re.compile(regex)
for i in range(0, 150000):
ATTAC... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# from ansible.module_utils.basic import *
from ansible.module_utils.basic import AnsibleModule
import json
import pipes
import subprocess
import logging
try:
basestring
except NameError:
basestring = str
DOCUMENTATION = '''
---
module: dokku_config
short_description... |
"""
Given a sorted array (sorted in non-decreasing order) of positive numbers, find the smallest positive integer value that cannot be represented as sum of elements of any subset of given set.
Expected time complexity is O(n).
Examples:
Input: arr[] = {1, 3, 6, 10, 11, 15};
Output: 2
Input: arr[] = {1, 1, 1, 1};
... |
# Dash components
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
# Core data science libraries
import altair as alt
import pandas as pd
import random
# Data loading functions
from temp_data i... |
"""
This module reads and writes xyz files.
"""
import os
import numpy as np
def open_xyz(file_location):
# Open an xyz file and return symbols and coordinates.
xyz_file = np.genfromtxt(fname=file_location, skip_header=2, dtype='unicode')
symbols = xyz_file[:,0]
coords = (xyz_file[:,1:])
coor... |
import hjson
def read_config(filename: str) -> dict:
with open(filename, 'r') as f:
ret = f.read()
return hjson.loads(ret)
def read_labels(filename: str) -> list:
with open(filename) as f:
lines = f.read().splitlines()
return lines |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.