id
stringlengths
3
8
content
stringlengths
100
981k
106172
import torch import random from torch.utils.data import Dataset, DataLoader from collections import defaultdict import os import unicodedata import re import time from collections import defaultdict from tqdm import tqdm import numpy as np from transformers import * from helpers import * class DatasetWebQSP(Dataset): ...
106210
from django.utils.translation import ugettext_lazy as _ MEETINGS_CONTRIBUTION_TYPES = [ ('talk', _('Talk')), ('poster', _('Poster')) ] MEETINGS_PAYMENT_CHOICES = ( ('cash', _('cash')), ('wire', _('wire transfer')), ) MEETINGS_PARTICIPANT_DETAIL_KEYS = [] MEETINGS_ABSTRACT_MAX_LENGTH = 2000
106215
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: if not intervals: return 0 result, curr = 0, 0 for i, val in sorted( x for interval in intervals for x in [(interval[0], 1), (interval[1], -1)] ): curr += val ...
106239
import sys settings_file_path = "../quisk_settings.json" #hamlib_port = 4575 # Standard port for Quisk control. Set the port in Hamlib to 4575 too. hamlib_port = 4532 # Default port for rig 2. Use this if you can not set the Hamlib port. if sys.platform == "win32": pass elif 0: digital_input_name = 'pulse' ...
106263
from keras import backend as K from overrides import overrides from ..masked_layer import MaskedLayer class CollapseToBatch(MaskedLayer): """ Reshapes a higher order tensor, taking the first ``num_to_collapse`` dimensions after the batch dimension and folding them into the batch dimension. For example, ...
106273
import pytest pytestmark = pytest.mark.asyncio async def test_clean_query_prefix(client): response = await client.get("/api/clean_query/192.0.2/24") assert response.status_code == 200 assert response.json() == {"cleanedValue": "192.0.2.0/24", "category": "prefix"} async def test_clean_query_prefix_misa...
106327
import numpy as np import logging import time from stereovis.framed.algorithms import StereoMRF from spinn_utilities.progress_bar import ProgressBar import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt logger = logging.getLogger(__file__) class FramebasedStereoMatching(object): def __init__(...
106330
from docker.errors import DockerException, ImageNotFound from pytest import raises from yellowbox import build_image def test_valid_image_build(docker_client): with build_image(docker_client, "yellowbox", path=".", dockerfile="tests/resources/valid_dockerfile/Dockerfile") \ as image: containe...
106335
import attr @attr.s class Ellipsoid: """Ellipsoid used for mesh calculations Args: a (float): semi-major axis b (float): semi-minor axis """ a: float = attr.ib() b: float = attr.ib() e2: float = attr.ib(init=False) def __attrs_post_init__(self): self.e2 = 1 - (se...
106361
from string import ascii_lowercase LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)} def alphabet_position(text): text = text.lower() numbers = [LETTERS[character] for character in text if character in LETTERS] return ' '.join(numbers) def cifrario(one,two): ...
106367
from bitmovin_api_sdk.encoding.encodings.muxings.ts.ts_api import TsApi from bitmovin_api_sdk.encoding.encodings.muxings.ts.customdata.customdata_api import CustomdataApi from bitmovin_api_sdk.encoding.encodings.muxings.ts.drm.drm_api import DrmApi from bitmovin_api_sdk.encoding.encodings.muxings.ts.ts_muxing_list_quer...
106368
import pandas as pd import numpy as np from misc import data_io DATA_DIR = 'data/ut-interaction/' """ Folder structure <'set1' or 'set2'>/keypoints <video_name>/ <video_name>_<frame_num>_keypoints.json ... Ex: DATA_DIR + 'set1/keypoints/0_1_4/0_1_4_000000000042_keypoints.json' """ VIDEOS = [ ...
106387
pkgname = "libmodplug" pkgver = "0.8.9.0" pkgrel = 0 build_style = "gnu_configure" configure_args = ["--enable-static"] hostmakedepends = ["pkgconf"] pkgdesc = "MOD playing library" maintainer = "q66 <<EMAIL>>" license = "custom:none" url = "http://modplug-xmms.sourceforge.net" source = f"$(SOURCEFORGE_SITE)/modplug-xm...
106401
import numpy as np from sklearn.metrics import average_precision_score def load_data(data_path): """load array data from data_path""" data = np.load(data_path) return data['X_train'], data['y_train'], data['X_test'], data['y_test'] def calculate_average_precision(label, index, similarity, num_search_sam...
106422
import pytest import attr import xsimlab as xs from xsimlab.tests.fixture_process import SomeProcess, AnotherProcess, ExampleProcess from xsimlab.variable import _as_dim_tuple, _as_group_tuple @pytest.mark.parametrize( "dims,expected", [ ((), ((),)), ([], ((),)), ("", ((),)), ...
106466
import datetime timenow = datetime.datetime.now() class user: def __init__(self, name, information) -> str: self.name = name self.information = information def get_username(self) -> str: return self.name def get_user_information(self) -> str: return self.information cl...
106503
import rospy from rospy.msg import AnyMsg class GdbPublisher(object): def __init__(self, topic, msgtype, queue_size = 1): self.topic = topic self.msgtype = msgtype # Construct publisher lazily, since we don't know whether to latch or not yet. self.publisher = None self.queue_size = queue_size ...
106580
from __init__ import * import sys import subprocess import numpy as np from fractions import Fraction import math sys.path.insert(0, ROOT) from compiler import * from constructs import * def maxfilter(pipe_data): # Pipeline Variables x = Variable(Int, "x") y = Variable(Int, "y") c = Variable(Int, "c") t = Vari...
106591
from templeplus.pymod import PythonModifier from toee import * import tpdp import char_class_utils import tpactions ################################################### def GetConditionName(): return "Swashbuckler" print "Registering " + GetConditionName() classEnum = stat_level_swashbuckler classSpecModule = __imp...
106613
import argparse from baseline.utils import read_config_stream from mead.utils import hash_config, convert_path def main(): parser = argparse.ArgumentParser(description="Get the mead hash of a config.") parser.add_argument('config', help='JSON/YML Configuration for an experiment: local file or remote URL', typ...
106706
from pyramid.security import unauthenticated_userid from .models import User def get_user(request): user_id = unauthenticated_userid(request) if user_id is not None: return User.fetch_by_id(user_id) def group_finder(user_id, request): user = request.user if user: return ['admin'] if ...
106714
import orca import pandas as pd from urbansim_templates import modelmanager, shared, utils, __version__ from urbansim_templates.shared import CoreTemplateSettings, OutputColumnSettings class ExpressionSettings(): """ Stores custom parameters used by the :mod:`~urbansim_templates.data.ColumnFromExpressio...
106748
import machine tcounter = 0 p1 = machine.Pin(18) p1.init(p1.OUT) p1.value(1) def tcb(timer): global tcounter if tcounter & 1: p1.value(0) else: p1.value(1) tcounter += 1 if (tcounter % 100) == 0: print("[tcb] timer: {} counter: {}".format(timer.timernum(), tcounter)) # t1...
106754
from openbiolink.graph_creation.metadata_db_file.edge.dbMetadataEdge import DbMetadataEdge from openbiolink.graph_creation.types.dbType import DbType class DbMetaEdgeDisGeNet(DbMetadataEdge): NAME = "Edge - DisGeNet - Gene Disease" # URL = "http://www.disgenet.org/ds/DisGeNET/results/curated_gene_disease_asso...
106762
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "com_fasterxml_jackson_module_jackson_module_paranamer", artifact = "com.fasterxml.jackson.module:jackson-module-paranamer:2.9.6", artifact_sha256 = "dfd66598c0094d9...
106790
def draw_model(lik, mean, covariance): if lik == "normal": var = "𝐲" else: var = "𝐳" msg = f"{var} ~ 𝓝({mean}, {covariance})" msg += _lik_formulae(lik) return msg def draw_alt_hyp_table(hyp_num, stats, effsizes): from limix._display import Table cols = ["lml", "cov. ef...
106791
from .map_aiter import map_aiter from .join_aiters import join_aiters def message_stream_to_event_stream(event_template, message_stream): """ This tweaks each message from message_stream by wrapping it with a dictionary populated with the given template, putting the message is at the top level under "...
106796
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import torch import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import time import sys sys.path.append('./net') from fun import * from protnet_att import * from loader import * from data_gentor import * class Tester: ...
106810
class Solution: def getRow(self, rowIndex: int) -> List[int]: if rowIndex == 0: return [1] s = [1] for i in range(1, rowIndex + 1): s = [sum(x) for x in zip([0] + s, s + [0])] return s
106823
from pipeline.pipeline import * from pipeline.entitylinker import * from pipeline.triplealigner import * from pipeline.datareader import DBpediaAbstractsDataReader from pipeline.writer import * from pipeline.coreference import * from pipeline.placeholdertagger import * from utils.triplereader import * from utils.triple...
106828
def countWords(s): count=1 for i in s: if i==" ": count+=1 return count print(countWords("Hello World This is Rituraj"))
106832
import sys, os from basic.common import checkToSkip, ROOT_PATH, makedirsforfile from basic.annotationtable import readConcepts, readAnnotationsFrom, writeAnnotationsTo, writeConceptsTo from basic.data import readImageSet if __name__ == '__main__': args = sys.argv[1:] rootpath = '/var/scratch2/xirong/VisualSea...
106835
import sys sys.path.append('./') import numpy as np import torch import glob import cv2 from skimage import img_as_float32 as img_as_float from skimage import img_as_ubyte import time import os from codes.models.modules.VDN import VDN as DN from codes.data.util import imresize_np def denoise(noisy_path, pretrained_pat...
106847
from awxkit.api.resources import resources from . import base from . import page class Dashboard(base.Base): pass page.register_page(resources.dashboard, Dashboard)
106942
import pytest pytestmark = [ pytest.mark.requires_salt_states("echo.text"), ] def test_echoed(salt_call_cli): echo_str = "Echoed!" ret = salt_call_cli.run("state.single", "echo.echoed", echo_str) assert ret.exitcode == 0 assert ret.json assert ret.json == echo_str def test_reversed(salt_cal...
106983
import json def convert(path:str): with open(path, 'r') as f: data = json.load(f) output_path = path.replace('convert', 'triplets').replace('json', 'txt') with open(output_path, 'w') as f: for ins in data: temp_ins = [] for a, o in zip(ins['aspects'], ins['opinions']...
107028
import opendbpy as odb import os current_dir = os.path.dirname(os.path.realpath(__file__)) tests_dir = os.path.abspath(os.path.join(current_dir, os.pardir)) opendb_dir = os.path.abspath(os.path.join(tests_dir, os.pardir)) data_dir = os.path.join(tests_dir, "data") db = odb.dbDatabase.create() odb.read_lef(db, os.pat...
107065
from ..core.tooling.htstrings import HeadTailString class WalletURL(HeadTailString): __head__ = "https://edge.qiwi.com/" class urls: me = WalletURL("person-profile/v1/profile/current") identification = WalletURL("identification/v1/persons/{}/identification") history = WalletURL("payment-history/v2/p...
107087
import subprocess import sys config_dir_path = None history_file_path = None log_file_path = None def open(path): if sys.platform == 'darwin': subprocess.Popen(['open', path]) elif sys.platform == 'win32': subprocess.Popen(['start', '', path]) else: subprocess.Popen(['xdg-open', p...
107128
from packaging import version from .code_cell import Cell from .nbresult import NbResult from .nbglobals import push_globals from .cell_conductor import * import os import sys import errno import warnings import nbformat SUPPORTED_LANGUAGES = [ "python" ] PYTHON_MIN_REQ = "3.5" KNOWN_NBFORMAT = 4 class Noteb...
107142
map = [200090710, 200090610] sm.sendSay("Where would you like to go? \r\n#L0#Victoria Island#l\r\n#L1#Orbis#l") sm.warp(map[answer], 0)
107204
import importlib import site from abc import abstractmethod from typing import ( TYPE_CHECKING, Any, Iterable, Iterator, List, Optional, Set, Tuple, Type, Union, cast, ) import django.core.checks from rest_framework.serializers import ModelSerializer, Serializer from ..ast....
107254
from collections import defaultdict import django import csv import sys import os import json os.environ['DJANGO_SETTINGS_MODULE'] = 'carebackend.settings' sys.path.append(os.path.dirname(__file__) + '/..') django.setup() from places.models import EmailSubscription outfl = sys.argv[1] by_place = defaultdict(list) for...
107272
from model.network import LeNet5 from saliency.vanilla_gradient import save_vanilla_gradient from model.data import mnist_train_test_sets import numpy as np # Get MNIST dataset, preprocessed train_images, train_labels, test_images, test_labels = mnist_train_test_sets() # Load net and 98% acc weights net = LeNet5(weig...
107277
from statefun_tasks.messages_pb2 import Pipeline import unittest from statefun_tasks import in_parallel from tests.utils import TestHarness, tasks, TaskErrorException join_results_called = False join_results2_called = False join_results3_called = False say_goodbye_called = False @tasks.bind() def _say_hello(first_n...
107281
import coremltools as ct def model_convert(model_name, stride_num, H, W): saved_model_path = f'{model_name}/{stride_num}/saved_model_{H}x{W}' input = ct.TensorType(name='sub_2', shape=(1, H, W, 3)) mlmodel = ct.convert(saved_model_path, inputs=[input], source='tensorflow') mlmodel.save(f'{saved_model_p...
107365
import mock import unittest from .helper import _ResourceMixin class SearchTest(_ResourceMixin, unittest.TestCase): def _getTargetClass(self): from .. import Search return Search @mock.patch('requests.get') def test_charge(self, api_call): class_ = self._getTargetClass() ...
107368
import os from getpass import getpass import yaml from netmiko import ConnectHandler def load_devices(device_file="lab_devices.yml"): device_dict = {} with open(device_file) as f: device_dict = yaml.safe_load(f) return device_dict if __name__ == "__main__": # Code so automated tests will ru...
107374
from datetime import datetime, date from marqeta.response_models.currency_conversion import CurrencyConversion from marqeta.response_models.response import Response from marqeta.response_models.merchant_response_model import MerchantResponseModel from marqeta.response_models.store_response_model import StoreResponseMod...
107393
from aiogram import types from bot.misc import dp @dp.inline_handler() async def example_echo(iq: types.InlineQuery): await iq.answer(results=[], switch_pm_text='To bot', switch_pm_parameter='sp')
107399
import unittest from bubuku.id_extractor import _search_broker_id class TestBrokerIdExtractor(unittest.TestCase): def test_match_valid(self): assert '123534' == _search_broker_id(['broker.id=123534']) assert '123534' == _search_broker_id(['\tbroker.id=123534']) assert '123534' == _search_...
107400
import os import shutil def process_subset(data_root, subset): coord_path = os.path.join(data_root, subset, 'coordinate') for accid in sorted(os.listdir(coord_path)): coord_file_path = os.path.join(coord_path, accid) for filename in sorted(os.listdir(coord_file_path)): vid = filenam...
107414
import networkx as nx from graphilp.imports import networkx as impnx from graphilp.network import atsp_desrochers_laporte as tsp from gurobipy import GRB def test_atsp_desrochers_laporte(): # create graph instance n=10 G = nx.complete_graph(n) G.add_weighted_edges_from([(u, (u+1)%n, 2) for u in range...
107531
PAD = 0 EOS = 1 BOS = 2 UNK = 3 UNK_WORD = '<unk>' PAD_WORD = '<pad>' BOS_WORD = '<s>' EOS_WORD = '</s>' NEG_INF = -10000 # -float('inf')
107538
from django.db.models.signals import post_save, pre_save, post_delete from django.contrib.auth.models import User from .models import UserProfile def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create( user=instance, name=instance.username, username=instan...
107545
import setuptools from pathlib import Path this_directory = Path(__file__).parent long_description = (this_directory / "README.md").read_text() setuptools.setup( name='valentine', version='0.1.4', description='Valentine Matcher', license_files=('LICENSE',), author='<NAME>', author_email='<EMAI...
107559
a=[] n=int(input("Enter no. of elements: ")) print("Enter array:") for x in range(n): element=int(input()) a.append(element) a.sort() b=[] for i in range(0,len(a)-1): if a[i]==a[i+1]: b.append(a[i]) b=list(set(b)) a=set(a) while(len(b)>0): a.remove(b[0]) b.pop(0) print("Output:",end=" ") pri...
107573
from scipy.stats import multivariate_normal # 生成多维概率分布的方法 import numpy as np class GaussianMixture: def __init__(self, n_components: int = 1, covariance_type: str = 'full', tol: float = 0.001, reg_covar: float = 1e-06, max_iter: int = 100): self.n_components = n_components self.m...
107577
from .elastic import ElasticsearchSourceForm, ElasticsearchStatusCheckForm from .grafana_elastic import GrafanaElasticsearchStatusCheckForm from .grafana import GrafanaInstanceAdminForm, GrafanaDataSourceAdminForm, GrafanaInstanceForm, GrafanaDashboardForm, \ GrafanaPanelForm, GrafanaSeriesForm, GrafanaStatusCheckF...
107627
from mock import Mock, sentinel, patch import pytest import selenium import pytest_webdriver def test_browser_to_use(): caps = Mock(CHROME=sentinel.chrome, UNKNOWN=None) wd = Mock(DesiredCapabilities = Mock(return_value = caps)) assert pytest_webdriver.browser_to_use(wd, 'chrome') == sentinel.chrome ...
107651
from collections import namedtuple import numpy as np from scipy.interpolate import Akima1DInterpolator as Akima import openmdao.api as om """United States standard atmosphere 1976 tables, data obtained from http://www.digitaldutch.com/atmoscalc/index.htm""" USatm1976Data = namedtuple("USatm1976Data", ["al...
107652
import unittest import io from ppci import ir from ppci.irutils import verify_module from ppci.lang.c import CBuilder from ppci.lang.c.options import COptions from ppci.arch.example import ExampleArch from ppci.lang.c import CSynthesizer class CSynthesizerTestCase(unittest.TestCase): def test_hello(self): ...
107657
import os import numpy as np import cv2 import sys import argparse import pathlib import glob import time sys.path.append('../../') from util import env, inverse, project_so, make_dirs from mesh import Mesh import scipy.io as sio """ Draw a 3 by n point cloud using open3d library """ def draw(vertex): import o...
107695
import os import re import json from functools import partial from .constants import * def convert(s): a = re.compile("((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))") return a.sub(r"_\1", s).lower() def convertArray(a): newArr = [] for i in a: if isinstance(i, list): newArr.append(con...
107706
from allennlp_semparse import DomainLanguage, predicate class NlaLanguage(DomainLanguage): def __init__(self): super().__init__( start_types={int}, allowed_constants={ "0": 0, "1": 1, "2": 2, "3": 3, "4...
107717
import numpy as np import logging class PID(object): def __init__(self, kp, ki, kd): self.kp = kp self.ki = ki self.kd = kd self.reset() def update(self, t, e): # TODO add anti-windup logic # Most environments have a short execution time # the co...
107720
from sikr.db.connector import Base, engine from sikr.models.users import UserGroup, User from sikr.models.entries import Group, Entry from sikr.utils.logs import logger def generate_schema(): """Generate the initial schema for the database.""" start_msg = "Creating database schema..." end_msg = "Database ...
107731
import os import numpy as np import cv2 as cv from tests_common import NewOpenCVTests def generate_test_trajectory(): result = [] angle_i = np.arange(0, 271, 3) angle_j = np.arange(0, 1200, 10) for i, j in zip(angle_i, angle_j): x = 2 * np.cos(i * 3 * np.pi/180.0) * (1.0 + 0.5 * np.cos(1.2 + ...
107746
import math from pygame.math import Vector2 class Geometry: @classmethod def polygon_point_intersection(cls, point_list, point): """ :param point_list: Reference to polygon object :param point: Reference to point object :return: true if point is inside polygon """ ...
107749
import json from schematics.exceptions import ConversionError from nose.tools import eq_,raises from enum import Enum from moncli import column_value as cv from moncli.enums import ColumnType from moncli.types import StatusType # default class and data mapping declaration for common use class Status(Enum): ready = ...
107752
import pytorch_lightning as pl import torch.nn as nn from loguru import logger from torch.optim import Adam from torchnlp.datasets import imdb_dataset # type: ignore from slp.data.collators import SequenceClassificationCollator from slp.modules.classifier import RNNTokenSequenceClassifier from slp.plbind.dm import PL...
107760
from unetgan.train_big import train_ubiggan from unetgan.test_model import test_model from unetgan.test_single import test_single if __name__ == "__main__": # Only for 100k iters train_ubiggan(train_path=".", latent_dim=140, num_epochs=80) # test_model() # test_single()
107776
from .mplayer_pool import MplayerPool from .mplayer_pool import ManagedMplayer from .gstreamer_pool import GstreamerPool from .gstreamer_pool import ManagedGstreamer from .director_media_bridge import DirectorMediaBridge from .mplayer_pool import DEFAULT_ARGS, SRV_QUERY, ROS_NODE_NAME
107800
import re from emoji.unicode_codes import UNICODE_EMOJI from nonebot import on_regex from nonebot.params import RegexDict from nonebot.plugin import PluginMetadata from nonebot.adapters.onebot.v11 import MessageSegment from .config import Config from .data_source import mix_emoji __plugin_meta__ = PluginM...
107809
import numpy as np from tensorflow import keras from tensorflow.keras import backend as K class WarmUpLearningRateScheduler(keras.callbacks.Callback): """Warmup learning rate scheduler """ def __init__(self, warmup_batches, init_lr, verbose=0): """Constructor for warmup learning rate scheduler ...
107840
from __future__ import absolute_import, division, print_function from concurrent.futures import Future from dask import delayed from daskos.delayed import MesosDelayed, MesosDelayedLeaf, mesos from daskos.utils import key_split from satyr.proxies.messages import Cpus, Disk, Mem # tests are not modules, so these are ...
107860
from .convnet import convnet4 from .resnet import resnet12, resnet18, resnet24 from .resnet import resnet24 from .resnet import seresnet12 from .wresnet import wrn_28_10 from .resnet_standard import resnet50 model_pool = [ 'convnet4', 'resnet12', 'resnet18', 'resnet24', 'seresnet12', 'wrn_28_10...
107916
from email.mime.image import MIMEImage from email.utils import unquote from pathlib import Path from django.core.mail import EmailMessage, EmailMultiAlternatives, make_msgid from .utils import UNSET class AnymailMessageMixin(EmailMessage): """Mixin for EmailMessage that exposes Anymail features. Use of thi...
107941
import pandas as pd import sys pgefile=sys.argv[1] df = pd.read_csv(pgefile, delim_whitespace=True) df2 = df[sys.argv[2:]] pge = df2.groupby("problem") for name, grp in pge: # print(name) # print(grp) ac_t = grp["elapsed_seconds"].iloc[2]/grp["elapsed_seconds"].iloc[0] ac_m = grp["evald_models"].iloc[2]/grp...
107956
import sqlite3 import psycopg2 from bs4 import BeautifulSoup import requests from sqlalchemy import create_engine # db engine import pandas as pd """ delays = [12, 3, 9, 21, 5, 6, 19, 7, 33, 11, 2, 17, 4] def get_random_ua(): random_ua = '' ua_file = 'ua_file.txt' try: with open(ua_file) as f: ...
107968
def betweenness_centrality(G, k=None, normalized=True, weight=None, endpoints=False, seed=None): # doesn't currently support `weight`, `k`, `endpoints`, `seed` query = """\ CALL gds.betweenness.stream({ nodeProjection: $node_label, relationshipProjection: { relType: { ...
108001
from flask import Flask from flask import render_template from flask import request import json import dbconfig if dbconfig.test: from mockdbhelper import MockDBHelper as DBHelper else: from dbhelper import DBHelper app = Flask(__name__) DB = DBHelper() @app.route("/") def home(): crimes = DB.get_all_cri...
108056
event_aliases = { 'halloween 2020': 1, 'candy': 2, 'swimsuits 2020': 3, 'maids': 5, 'christmas 2020': 6, 'countdown': 7, 'monster hunter pt1': 9, 'mh1': 9, 'monster hunter pt2': 10, 'mh2': 10, }
108060
import os import logging DOCKER_PID_CMD = "docker inspect {} --format='{{{{.State.Pid}}}}'" NSS_CMD = "lsns -p {} -t pid | tail -n 1 | awk '{{print $1}}'" def replace_namespace(text, args): nss = None text = text.replace("SAVE_NAMESPACE", """ struct task_struct *t = (struct task_struct *) bpf_get_curre...
108073
import pickle import base64 from flask import Flask, request app = Flask(__name__) @app.route("/") def index(): try: user = base64.b64decode(request.cookies.get('user')) user = pickle.loads(user) username = user["username"] except: username = "Guest" return "Hello %s" % us...
108112
import os import faker import pandas as pd from django.test import TestCase from django_datajsonar.models import Node from elasticsearch_dsl.connections import connections from series_tiempo_ar_api.apps.dump.generator import constants from series_tiempo_ar_api.apps.dump.generator.dta import DtaGenerator from series_t...
108157
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible_collections.community.general.tests.unit.compat import unittest from ansible_collections.manala.roles.plugins.filter.users_groups import users_groups from ansible.errors import AnsibleFilterError class Test(unittest...
108185
import qcore from qcore.asserts import AssertRaises class Foo(metaclass=qcore.DisallowInheritance): pass def test_disallow_inheritance(): with AssertRaises(TypeError): class Bar(Foo): pass
108206
from .decorators import run_only_once from .directives import GraphQLCostDirective, schema_with_cost_directive, cost_directive_source_doc from .execution import ExtendedExecutionContext from .utilities import build_schema_with_cost __version__ = "0.4.0" __all__ = [ "run_only_once", "ExtendedExecutionContext",...
108222
from django.contrib import admin from .models import Board, List, Item, Label, Comment, Attachment, Notification admin.site.register(Board) admin.site.register(List) admin.site.register(Item) admin.site.register(Label) admin.site.register(Comment) admin.site.register(Attachment) admin.site.register(Notification)
108225
from random import choice NETWORKING_AGENT_FILENAME = "networking/user-agents" agents = None def _get_agents(): global agents if agents is None: with open(NETWORKING_AGENT_FILENAME) as user_agents: agents = [x.strip() for x in user_agents.readlines()] return agents def get_agent():...
108228
from django.test import TestCase from django.contrib.auth import get_user_model from django.test import Client from suite.views import ClubCreate from django.urls import reverse from suite.models import Club class View_Club_Search_TestCase(TestCase): def setUp(self): self.client = Client() self.cl...
108280
import copy import numpy as np class Objective(): pass class MeanSquaredError(): def calc_acc(self,y_hat,y): return 0 def calc_loss(self,y_hat,y): loss = np.mean(np.sum(np.power(y_hat-y,2),axis=1)) return 0.5*loss def backward(self,y_hat,y): ...
108330
from torchtext import data from torch.utils.data import DataLoader from graph import MTBatcher, get_mt_dataset, MTDataset, DocumentMTDataset from modules import make_translation_model from optim import get_wrapper from loss import LabelSmoothing import numpy as np import torch as th import torch.optim as optim import ...
108333
from stretch_body.dynamixel_hello_XL430 import DynamixelHelloXL430 from stretch_body.hello_utils import * class WristPitch(DynamixelHelloXL430): def __init__(self, chain=None): DynamixelHelloXL430.__init__(self, 'wrist_pitch', chain) self.poses = {'tool_up': deg_to_rad(45), 't...
108337
import os from haikunator import Haikunator from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.resource import ResourceManagementClient from azure.mgmt.eventgrid import EventGridManagementClient from azure.mgmt.eventgrid.models import Topic, EventSubscriptionFilter, EventSubscription, We...
108346
def test_get_custom_properties(exporters, mocker): blender_data = mocker.MagicMock() vector = mocker.MagicMock() vector.to_list.return_value = [0.0, 0.0, 1.0] blender_data.items.return_value = [ ['str', 'spam'], ['float', 1.0], ['int', 42], ['bool', False], ['vect...
108361
import xadmin from .models import Video, HotSearchWords class VideoAdmin(object): list_display = ["content", "cover_duration", "cover_start_second", "video", "longitude", "latitude" , "poi_name", "poi_address", "first_create_time", "source"] search_fields = ['content', ] list_editable = ["is_hot", ] li...
108410
import factory from django_google_optimize.models import ( ExperimentCookie, ExperimentVariant, GoogleExperiment, ) # pylint: disable=too-few-public-methods class GoogleExperimentFactory(factory.django.DjangoModelFactory): class Meta: model = GoogleExperiment experiment_id = factory.Fake...
108439
import json import pytest from clld.db.models.common import Parameter, Language from clld.web.adapters import geojson from clld.web.datatables.base import DataTable geojson.pacific_centered() def test_GeoJson(mocker): adapter = geojson.GeoJson(None) assert len(list(adapter.feature_iterator(None, None))) ==...