text string | size int64 | token_count int64 |
|---|---|---|
from django.conf import settings
TEMPLATEADDONS_COUNTERS_VARIABLE = getattr(settings, 'TEMPLATEADDONS_COUNTER_GLOBAL_VARIABLE', '_templateaddons_counters') # NOQA
| 166 | 68 |
from random import randint
from sys import exit
from textwrap import dedent
from sys import argv
script, filename, filename2, filename3 = argv
trezor_kod = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}{randint(1,9)}"
pismo = open(filename)
transakcije = open(filename2)
nalazi = open(filename3)
class Sce... | 13,738 | 4,907 |
from django.contrib.auth.hashers import make_password
from django.core.management import base
from faker import Faker
from eahub.base.models import User
from eahub.profiles.models import Profile, ProfileAnalyticsLog
from eahub.profiles.models import VisibilityEnum
class Command(base.BaseCommand):
def handle(self... | 1,127 | 325 |
#!/usr/bin/env python3
"""
Implement the Cayley-Dickson construction to
get complex numbers, quaternions, octonions, sedenions, etc.
"""
import math, os
from isomorph import Point, Graph, search
from argv import argv
class Number(object):
def __init__(self, a):
self.a = a
self.shape = ()
d... | 10,398 | 3,651 |
#!/usr/bin/env python
# idr2 0.0.1
# Generated by dx-app-wizard.
#
# Basic execution pattern: Your app will run on a single machine from
# beginning to end.
#
# See https://wiki.dnanexus.com/Developer-Portal for documentation and
# tutorials on how to modify this file.
#
# DNAnexus Python Bindings (dxpy) documentation:... | 10,635 | 3,875 |
#!/usr/bin/python
from __future__ import unicode_literals
# https://stackoverflow.com/questions/19475955/using-django-models-in-external-python-script
from django.core.management.base import BaseCommand, CommandError
import datetime
from django.utils import timezone
from provision.models import WinDC
class Command(... | 816 | 254 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) Copyright 2019 CSSI.
# (c) This file is part of the CSSI REST API and is made available under MIT license.
# (c) For more information, see https://github.com/project-cssi/cssi-api/blob/master/LICENSE.md
# (c) Please forward any queries to the given email address. ema... | 4,250 | 1,246 |
"""Test the service module"""
# pylint: disable=C0302
from typing import Dict, Any
import unittest
from .. import service, common
from ...validation import validate_discovery_map
class ServiceTest(unittest.TestCase): # pylint: disable=R0904
"""Test the service functions."""
def test_create_service_color_... | 43,067 | 12,856 |
ERROR_ALREADY_EXISTS = 'ERROR_EMAIL_ALREADY_EXISTS'
ERROR_USER_NOT_FOUND = 'ERROR_USER_NOT_FOUND'
ERROR_INVALID_OLD_PASSWORD = 'ERROR_INVALID_OLD_PASSWORD'
| 156 | 68 |
from flask import g, jsonify
from flask_httpauth import HTTPBasicAuth
from ..models import User
from . import api
from .errors import unauthorized, forbidden
from flask_login import current_user
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(username_or_token, password):
if username_or_token ==... | 2,054 | 737 |
"""
Version numbers exposed by PyPy through the 'sys' module.
"""
import os
CPYTHON_VERSION = (2, 5, 2, "beta", 42)
CPYTHON_API_VERSION = 1012
# release 1.1.0
PYPY_VERSION = (1, 1, 0, "beta", '?')
# the last item is replaced by the svn revision ^^^
TRIM_URL_UP_TO = 'svn/pypy/'
SVN_UR... | 3,327 | 1,203 |
from .basic import PSMNet as basic
from .stackhourglass import PSMNet as disparity_expansion_v2
# 3D CNN의 채널수는 절반으로 압축하고, cost volume의 disparity 차원수를 1/2로 확장시킨 모델
| 164 | 98 |
import numpy as np
import dlib
import imutils.face_utils as face_utils
def compute_landmarks_person(person, net):
for face in person:
compute_landmarks_face(face, net)
def compute_landmarks_face(face, net):
# run the network on the bounding box of the face
dlib_box = dlib.rectangle(*face.box()... | 588 | 195 |
# TODO: cleanup into function
import pandas as pd
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
n_samples = 2000
n_features = 5
n_informative = 5 # relevant features to explain target
n_redundant = 0 # linear combinations of informative
n_repea... | 2,281 | 801 |
import json
import logging
from enum import Enum
import boto3 as boto3
from config import config
from fifo_parser.facebookmessage import FacebookMessage
from fifo_parser.googlemessage import GoogleMessage
class Source(Enum):
GOOGLE = 1
FACEBOOK = 2
def is_payload_from(payload):
if type(payload) == str... | 1,863 | 539 |
import numpy as np
import random
import argparse
import sys
import matplotlib.pyplot as plt
_EPS = 1e-14
def mpself(seq, subseq_len):
# prerequisites
exclusion_zone = int(np.round(subseq_len/2))
ndim = seq.shape[0]
seq_len = seq.shape[1]
matrix_profile_len = seq_len - subseq_len + 1
first... | 3,719 | 1,511 |
import sys
import pickle
import imageio
from munch import Munch
import torch
import numpy as np
import pcp_utils
from pcp_utils.utils import Config
#grnn_dir = pcp_utils.utils.get_grnn_dir()
#sys.path.append(grnn_dir)
#
#import model_nets
#from backend import saverloader
#import utils
class Detector:
def __in... | 2,921 | 1,017 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
List of properties for documentation purposes
"""
class V:
def __init__(self, *, symb='', name='', unit=''):
self.symb = symb
self.name = name
self.unit = unit
class P:
def __init__(self, name, unit='', name_long='', *, log=False, s... | 4,652 | 1,769 |
#!/usr/bin/env python
import wx
import wx.adv
import scrapy # web scraping
from scrapy import signals
from scrapy.crawler import CrawlerProcess
import json # dumping and loading variabls
import re # regex
from pandas import DataFrame # excel
from pandas import ExcelWriter
from bs4 import BeautifulSoup
df1 = Fal... | 9,830 | 3,275 |
from django.views.generic.list import ListView
from books.models import Books
from farjad.utils.permission_checker import PermissionCheckerMixin, LoginRequired
from members.views.area_setter import PanelAreaSetter
class UserBooksListView(PanelAreaSetter, PermissionCheckerMixin, ListView):
model = Books
permi... | 534 | 157 |
##############################################################################
#
# Copyright (c) 2001,2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THI... | 1,334 | 453 |
import sys,time
from scapy.all import *
from random import randint
from threading import Thread
class Ack(Thread):
def __init__(self,target,port,nbPacket):
self.t = target
self.p = int(port)
self.nb = int(nbPacket)
self.listePort = []
Thread.__init__(self)
def addPort... | 1,872 | 845 |
"""Collocation related modeling class"""
from typing import Optional
from pororo.tasks.utils.base import PororoFactoryBase, PororoSimpleBase
from pororo.tasks.utils.download_utils import download_or_load
class PororoCollocationFactory(PororoFactoryBase):
"""
Conduct collocation search using index file
... | 3,837 | 1,507 |
from pathlib import Path
import yaml
def get_project_root():
"""Get the path of the project root directory.
Returns
-------
pathlib.PosixPath
"""
return Path(__file__).parents[2]
def load_config(*args):
"""Load the contents of a configuration file to a dictionary.
Parameters
--... | 555 | 165 |
number_of_measurements=600
frequency=0.10
measureLocalMagnetism(number_of_measurements,frequency,led=led)
| 108 | 44 |
from collections import OrderedDict
from rest_framework.fields import ReadOnlyField, Field
from rest_framework.relations import (
HyperlinkedIdentityField, StringRelatedField)
from rest_framework.reverse import reverse
from rest_framework.serializers import HyperlinkedModelSerializer
from ...models import *
cla... | 3,146 | 907 |
# -*- coding: utf-8 -*-
"""
An very simple configuration file to run some basic simulations about stationary multi-armed bandits.
"""
from Arms import *
from Environment import MAB
from Policies import *
# --- Parameters of the experiments
HORIZON = 30
REPETITIONS = 1
NB_ARMS = 5
ARM_TYPE = Bernoulli
# Like htt... | 2,897 | 909 |
# Copyright 2018 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 3,507 | 1,335 |
from __future__ import absolute_import, division, print_function
import ipaddress
import pickle
import pytest
import six
import service_identity._common
from service_identity._common import (
DNS_ID,
SRV_ID,
URI_ID,
DNSPattern,
IPAddress_ID,
IPAddressPattern,
ServiceMatch,
SRVPattern... | 20,689 | 6,681 |
import numpy as np
import nept
task_times = dict()
task_times['on_track'] = nept.Epoch(np.array([2421.1, 4816.9]))
experiment_times = dict()
experiment_times['left_trials'] = nept.Epoch(np.array([[2436.3, 2487.4],
[3398.8, 3423.7],
... | 1,400 | 459 |
#!/usr/bin/env python
# Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ).
#
# 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... | 37,803 | 13,219 |
# global 关键字
print('-----------------------------------')
count = 5
def MyFun():
count = 10
print(count)
MyFun()
print(count)
print('-----------------------------------')
def MyFun():
global count
count = 10
print(count)
MyFun()
print(count)
print('-----------------------------------')
de... | 1,111 | 379 |
"""
energy
=====
Simulates energy meter
Configurable parameters::
{
"opening_times" : (optional) "name of an opening-times pattern"
"max_power" : (optional) maximum power level
"baseload_power" : (optional) baseload power level (e.g. night-time)
"power_variation" : (optional) how m... | 2,996 | 1,069 |
def words_numbers_counter():
entered_value = input("Enter string:")
print("Words:", len(list(filter(lambda x: x.isalpha(), entered_value))))
print("Numbers:", len(list(filter(lambda x: x.isdigit(), entered_value))))
words_numbers_counter()
| 254 | 81 |
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import Thumbnail
from django.conf import settings
class Profile(models.Model):
nickname = models.CharField(max_length=20, blank=True)
image = ProcessedImageField(
blank=True,
... | 649 | 163 |
k = random(5,15)
xCoordinate = [k]
print k
| 43 | 22 |
"""Tools for domain transfer/domain invariance losses."""
import torch
from torch import nn
import torch.nn.functional as F
class ReverseGrad(torch.autograd.Function):
"""This layer acts like the identity function on the forward pass, but
reverses gradients on the backwards pass."""
@staticmethod
def... | 3,165 | 1,064 |
from std import *
from mats.base_mat import base_mat
# constructed from a sequence of feedforward networks.
class ff_net(base_mat):
def __init__(self, w):
self.w = w
def soft_copy(self):
s = ff_net(self.w)
s.w = [x for x in self.w]
return s
def __call__(self, V):
... | 776 | 286 |
import numpy as np
import cv2
import os
import glob
# img_h, img_w = 32, 32
img_h, img_w = 32, 48 # 根据自己数据集适当调整,影响不大
means, stdevs = [], []
img_list = []
imgs_path_list = glob.glob('datasets/*/*')
len_ = len(imgs_path_list)
i = 0
for item in imgs_path_list:
img = cv2.imread(item)
img = cv2.resize(img, (img_w... | 783 | 394 |
######################################################################
#
# File: b2/account_info/test_upload_conncurrency.py
#
# Copyright 2018 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
import os... | 1,669 | 504 |
from collections import deque
from loader import load_dict
AdjList = []
def init_trie(keywords):
""" creates a trie of keywords, then sets fail transitions """
create_empty_trie()
add_keywords(keywords)
set_fail_transitions()
def create_empty_trie():
""" initalize the root of the trie """
A... | 3,238 | 1,032 |
import json
def apply(process, channel, method, properties, data):
channel.basic_ack(delivery_tag=method.delivery_tag)
response = process(data)
return response
| 173 | 51 |
"""
The irrigation system.
Each irrigation system has one source of water. It could be a faucet or a dedicated line or a well with a pump.
The system can be always on, seasonally on (above freezing?) or use a pump relay and/or master valve.
A system may be divided into zones. Each zone can take a part or all of the... | 1,163 | 374 |
from .abstractcache import AbstractCache # noqa
from .filecache import FileCache # noqa
| 90 | 25 |
"""
Tests for the generic fulltext search
These tests run within the re_api docker image, and require access to the ArangoDB, auth, and workspace images.
"""
import json
import time
import unittest
import requests
import os
from spec.test.helpers import (
get_config,
check_spec_test_env,
create_test_docs,... | 8,586 | 2,900 |
# start_marker
from dagster import ModeDefinition, OutputDefinition, fs_io_manager, mem_io_manager, pipeline, solid
@solid(output_defs=[OutputDefinition(io_manager_key="fs")])
def solid1(_):
return 1
@solid(output_defs=[OutputDefinition(io_manager_key="mem")])
def solid2(_, a):
return a + 1
@pipeline(mode... | 459 | 168 |
import tensorflow_addons as tfa
from typing import Sequence
from common.utils import *
def soft_update(source_vars: Sequence[tf.Variable], target_vars: Sequence[tf.Variable], tau: float) -> None:
"""Move each source variable by a factor of tau towards the corresponding target variable.
Arguments:
sou... | 7,422 | 2,327 |
# coding: utf-8
"""
Apteco API
An API to allow access to Apteco Marketing Suite resources # noqa: E501
The version of the OpenAPI document: v2
Contact: support@apteco.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class CommunicationSta... | 19,238 | 5,498 |
from core.entity.entity_sets.external_authorization_account_set import ExternalAuthorizationAccountSet
from .account_reader import AccountReader
class AccountSet(ExternalAuthorizationAccountSet):
"""
Declares basic ways to find a proper Google account
"""
_entity_name = "Google Account"
_entity... | 446 | 121 |
"""
log of Lin
~~~~~~~~~
log 模块,用户日志记录,只对管理员开放查询接口
:copyright: © 2018 by the Lin team.
:license: MIT, see LICENSE for more details.
"""
from functools import wraps
import re
from flask import Response, request
from flask_jwt_extended import get_current_user
from .core import find_info_by_ep, Log
... | 2,470 | 757 |
#!/usr/bin/python
# Filename: ex_func_pass.py
def maximum(x, y):
if x > y:
return x
else:
pass
if __name__ == "__main__":
print(maximum(2, 3))
| 173 | 71 |
# NN settings
# Higgs mass range in GeV
min_mass = 50
max_mass = 250
# channels to process
channels = "inclusive"
# NN structure
Nlayers = 10
Nneurons = 100
# NN training
loss = "mae"
optimizer = "Adam"
w_init_mode = "glorot_uniform"
activation = "relu"
regularizer = None
epochs = 200
# Dataset splitting
train_fra... | 1,197 | 601 |
from MagniPy.Workflow.radio_lenses.lens1115 import Lens1115
from MagniPy.util import approx_theta_E
from MagniPy.Workflow.mock_lenses.analog_base import MockLensBase
class Lens1115AnalogFold(MockLensBase):
reference_lens = Lens1115()
def __init__(self):
theta_E = approx_theta_E(self.reference_lens.x... | 1,752 | 752 |
def normalize_required_field(fields):
"""when the field comes required, it be converted to not null"""
if "required" in fields:
return map(lambda field: field.replace("required", "not null"), fields)
return fields
| 235 | 63 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Sione Taumoepeau and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.core.doctype.user_permission.user_permission import get_permitted_documents
from frappe import _
from frappe.model.document... | 6,871 | 2,411 |
#
# PySNMP MIB module RADLAN-BRGMACSWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-BRGMACSWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:37:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | 5,133 | 2,094 |
# Given a binary search tree, return a balanced binary search tree with the same node values.
# A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.
# If there is more than one answer, return any of them.
# Definition for a binary tree node.
class T... | 1,941 | 802 |
from sklearn.datasets import load_iris
from pandas.tools.plotting import andrews_curves
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
# Look pretty...
matplotlib.style.use('ggplot')
# If the above line throws an error, use plt.style.use('ggplot') instead
# Load up SKLearn's Iris Dataset into ... | 809 | 287 |
# -*- coding: utf-8
from __future__ import unicode_literals
import random
from django.core.management.base import BaseCommand
from django.utils import timezone
from nodeconductor.cost_tracking import models
class Command(BaseCommand):
def handle(self, *args, **options):
current_month = timezone.now()... | 1,624 | 405 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014-2020, Lars Asplund lars.anders.asplund@gmail.com
"""
Communication library
---------------------
... | 828 | 291 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from multiprocessing import Process, Value, Array
def f(n, a):
n.value = n.value + 1
for i in range(len(a)):
a[i] = a[i] * 10
if __name__ == '__main__':
num = Value('i', 1)
arr = Array('i', range(10))
p = Process(target=f, args=(num, arr))
p.start()
p.join()
prin... | 446 | 210 |
import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag import protocols
import ztag.test
class FtpBulletproofFtpd(Annotation):
protocol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = None
impl_re = re.compile("^220[- ]BulletProof FTP Server r... | 1,617 | 578 |
# -*- coding: utf-8 -*-
""" Model definitions for `discriminate_agkistrodon`
TODO: repeat for Conv3DTranspose
"""
from keras.layers import Input
from keras.layers.convolutional import (MaxPooling3D, Conv3D,
UpSampling3D)
from keras.models import Model
import logging
class ca... | 4,178 | 1,451 |
import gc
import logging
import pathlib
import sys
import pandas as pd
import torch
from omegaconf import OmegaConf
from gde.data.data_provider import DataProvider
from gde.eval.utils import init_loader, predict_from_loader, init_model, init_args
logging.basicConfig(format='%(asctime)s %(message)s',
... | 5,166 | 1,858 |
# coding: utf-8
"""
mParticle
mParticle Event API
OpenAPI spec version: 1.0.1
Contact: support@mparticle.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance wit... | 2,978 | 792 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# ***** BEGIN LICENSE BLOCK *****
# This file is part of Shelter Database.
# Copyright (c) 2016 Luxembourg Institute of Science and Technology.
# All rights reserved.
#
#
#
# ***** END LICENSE BLOCK *****
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.1 $"
__... | 1,510 | 482 |
name = 'invera'
loglevel = 'info'
errorlog = '-'
acceslog = '-'
workers = 2 | 75 | 33 |
"""
RabbitMQ user
"""
import lib_common
def Graphic_colorbg():
return "#CC3366"
def EntityOntology():
return ( ["Url","User"], )
def MakeUri(urlName,userName):
return lib_common.gUriGen.UriMakeFromDict("rabbitmq/user", { "Url" : urlName, "User" : userName } )
def EntityName(entity_ids_arr):
return entity_ids_a... | 352 | 141 |
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CustomUserForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'pas... | 1,725 | 467 |
from flask import redirect, render_template, request as http_request, url_for, g
from .blueprint import applications_bp
from atst.domain.exceptions import AlreadyExistsError
from atst.domain.environments import Environments
from atst.domain.applications import Applications
from atst.domain.application_roles import App... | 16,705 | 4,696 |
# Copyright 2018/2019 The RLgraph authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 7,181 | 1,974 |
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
"""
Authentication utilities
"""
import os
import json
import subprocess
from botocore.credentials import RefreshableCredentials
from botocore.session import get_session
from boto3 import Session
from botocore.exceptions import ClientError
... | 7,928 | 2,260 |
#!/usr/bin/env python
"""The GRR event publishing classes."""
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.registry import EventRegistry
class EventListener(metaclass=EventRegistry):
"""Base Class for all Event Listeners.
Event listeners can register for an event by specifying the even... | 2,354 | 664 |
# -*- coding: utf-8 -*-
""" Google Earth file output example
required simplekml module.
if you didn't install simplekml, execute the following command.
> pip install simplekml
"""
from OpenVerne import IIP
import numpy as np
import pandas as pd
import simplekml
import warnings
warnings.filterwarnings('ignore')
if __... | 960 | 387 |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
def main():
device_list = demisto.args().get('devices')
query_strs = []
query_str = 'mac_addressIN'
DEFAULT_VALUE_SIZE = 100 # each query contains 100 deviceid
res = {}
output_description = f'Total dat... | 1,009 | 344 |
from typing import Optional
from src.api.exceptions import internal_errors, room_errors, user_errors
from src.config import settings
from src.services.crud.users.logic import check_user_exist
from src.services.crud.room.logic import check_room_exists, room_members
from . import logic
from .publish import publish_even... | 1,609 | 445 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.integrate import solve_ivp
import math
plt.style.use('ggplot')
def plot_analytical(numerical=False,num_result=None):
if numerical:
z_position= num_result.altitude #altitude
else:
z_position=np.linspace(0,100000,10... | 18,798 | 7,236 |
import random
import uuid
from pyspark.sql import SQLContext
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
ID = "id"
GROUP = "group"
VALUE = "value"
GROUP_COUNT = "group_count"
def create_schema():
return StructType(
[
StructField(ID, StringType()),
... | 788 | 249 |
_file:
data_svm = json.load(json_file)
| 43 | 20 |
"""Completers for use with argcomplete."""
from __future__ import annotations
import argparse
import typing as t
from ..target import (
find_target_completion,
)
from .argparsing.argcompletion import (
OptionCompletionFinder,
)
def complete_target(completer, prefix, parsed_args, **_): # type: (OptionCompl... | 904 | 266 |
from django.contrib import auth
from django.urls import reverse
from cookbook.models import Recipe
from cookbook.tests.views.test_views import TestViews
class TestViewsApi(TestViews):
def test_external_link_permission(self):
recipe = Recipe.objects.create(
internal=False,
link='t... | 1,381 | 462 |
import torch
def accuracy(logits, y):
return torch.mean((torch.argmax(logits, dim=-1) == y).float())
def loss(logits, y):
return torch.nn.functional.cross_entropy(logits, y)
def print_metrics(metrics):
for metric, value in metrics.items():
print(f"{metric}: {value}")
| 294 | 109 |
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from panda3d.core import Vec4, Vec3, Vec2
from panda3d.core import Shader
from panda3d.core import ClockObject
from panda3d.core import WindowProperties
from panda3d.core import CardMaker
import random
class Game(ShowBase):
def __init__(s... | 6,010 | 2,087 |
# -*- coding: utf-8 -*-
import qi
import sys
from app_list_manager import AppListManager
from view_manager import ViewManager
from preferences_manager import PreferencesManager
from dialog_manager import DialogManager
import helpers
class AppLauncher:
@qi.nobind
def __init__(self, session=None):
self... | 8,852 | 2,369 |
"""Payloads of can bus messages."""
from dataclasses import dataclass
from .. import utils
@dataclass
class EmptyPayload(utils.BinarySerializable):
"""An empty payload."""
pass
@dataclass
class DeviceInfoResponsePayload(utils.BinarySerializable):
"""Device info response."""
version: utils.UInt32F... | 3,413 | 1,081 |
"""
Various webhook configurations
"""
from typing import List, Optional
from avionix.kube.apiextensions import WebhookClientConfig
from avionix.kube.base_objects import AdmissionRegistration
from avionix.kube.meta import LabelSelector, ObjectMeta
from avionix.yaml.yaml_handling import HelmYaml
class RuleWithOperat... | 18,931 | 4,844 |
#!/usr/bin/env python
#-*-*- encoding: utf-8 -*-*-
xilinx_board_type = 'PLD'
weblab_xilinx_experiment_port_number = 1
# This should be something like this:
# import os as _os
# xilinx_home = _os.getenv('XILINX_HOME')
# if xilinx_home == None:
# if _os.name == 'nt':
# xilinx_home = r'C:\Program Files\Xilinx'... | 1,423 | 640 |
"""
This example uses Approximate Nearest Neighbor Search (ANN) with FAISS (https://github.com/facebookresearch/faiss).
Searching a large corpus with Millions of embeddings can be time-consuming. To speed this up,
ANN can index the existent vectors. For a new query vector, this index can be used to find the nearest nei... | 7,909 | 2,567 |
from modules.Word.adapters.abstracts.DictionaryAdapter import DictionaryAdapter
class WebsterAdapter(DictionaryAdapter):
def __init__(self):
super().__init__()
self.base_url = "https://www.merriam-webster.com"
def is_word(self, word: str) -> bool:
html = self.parse_html(f'{self.base_u... | 488 | 157 |
# 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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_li... | 4,605 | 1,359 |
#!/usr/bin/python3
#https://practice.geeksforgeeks.org/problems/n-queen-problem/0
queens = []
results = []
def isValidNaive(grid, N, x, y):
for i in range(N):
if grid[x][i] == True:
#print('x', i)
return False
for i in range(N):
if grid[i][y] == True:
#... | 3,418 | 1,123 |
import pytest
from pyutil import drop_right_while
def test_drop_right_while_when_list_is_empty():
lst = []
drop_right_while(lst, lambda x: x)
assert lst == []
def test_drop_right_while_when_func_should_remove_one_value():
lst = [1, 2, 3, 4, 5]
func = lambda x: x % 2 == 1
drop_right_while(ls... | 1,211 | 488 |
# Copyright (C) 2020 Denso IT Laboratory, Inc.
# All Rights Reserved
# Denso IT Laboratory, Inc. retains sole and exclusive ownership of all
# intellectual property rights including copyrights and patents related to this
# Software.
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functi... | 8,459 | 2,845 |
from elasticsearch import exceptions as es_exceptions
from website.search import client as search_client
def test_query_index(client, monkeypatch):
def mockreturn(*args, **kwargs):
return [
{"_id": 21344, "image": "fakeImageUrl1", "title": "ShowTitle1"},
{"_id": 21345, "image": "fa... | 1,659 | 524 |
def clean_data():
f = open('day8.txt','r')
data = f.readlines()
for i,d in enumerate(data):
for r in (('\n',''),('bags',''),('bag',''),('.','')):
d = d.replace(*r)
data[i] = d
return data
def get_acum(data):
acum = 0
loop = []
j = 0
for i,d in enumer... | 1,387 | 518 |
#!/usr/bin/env cdat
"""
# This script demonstrates how to compute the cloud feedback using cloud radiative kernels for a
# short (2-year) period of MPI-ESM-LR using the difference between amipFuture and amip runs.
# One should difference longer periods for more robust results -- these are just for demonstrative purpos... | 16,843 | 7,125 |
import math
"""
chr1 0 1000 . 3.64092565 . 0.00364093 -1 -1 -1
chr1 500 1500 . 3.64092565 . 0.00364093 -1 -1 -1
chr1 1000 2000 . 3.64092565 . 0.00364093 -1 -1 -1
chr1 1500 2500 . 3.64092565 . 0.00364093 -1 ... | 1,240 | 584 |
from .CanOverrideConfig import CanOverrideConfig
from .CanOverrideOptionsDefault import CanOverrideOptionsDefault
class Command(CanOverrideOptionsDefault, CanOverrideConfig):
pass
| 186 | 41 |
# -*- coding: utf-8 -*-
import os
"""
文件工具
@author yihonglei
"""
def create_dir_by_date(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\\")
# 判断路径是否存在
# 存在 True
# 不存在 False
is_exists = os.path.exists(path)
# 判断结果
if not is_exists:
# 如果不存在则创... | 1,122 | 553 |
# fabric method for decorators (isnt best idea)
from abc import ABC, abstractmethod
class Fabricator(ABC):
@classmethod
@abstractmethod
def is_check_for(cls, check):
pass
@abstractmethod
def do_something(self):
pass
class Product1(Fabricator):
@classmethod
def is_chec... | 1,131 | 384 |