text stringlengths 2 999k |
|---|
''' Routines and Fitting algorithms
Fitting: means where ALL other non-object points
have been removed, determining the transform frame
of the object
Segment: means seperating clusters from a single cloud
'''
from director.filterUtils import *
import director.visualization as vis
from director import obj... |
"""
Django settings for feder project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import sys
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myf... |
import singer
import sys
from tap_google_analytics.ga_client import GAClient
LOGGER = singer.get_logger()
class ReportsHelper:
def __init__(self, config, reports_definition):
self.reports_definition = reports_definition
# Fetch the valid (dimension, metric)
# names and their types from ... |
# Copyright (c) 2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the handling of various mapping tasks."""
import cartopy.crs as ccrs
import pytest
from metpy.plots.mapping import CFProjection
def test_cfprojection_arg_mapping():
"... |
# -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
'''
This module provides one useful class: NodeHandler
The NodeHandler class is designed to be subclassed. Each subclass
should support the processing that createpdf.RstToPdf needs to do
on a particular type of node that could appear in a document tree.
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Copyright (C) 2013-2014 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This progr... |
#!/usr/bin/env python
#
# Copyright (c) 2016, 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
# ... |
import re
import logging
from . import settings
from .utils import choplist
log = logging.getLogger(__name__)
class PSException(Exception):
pass
class PSEOF(PSException):
pass
class PSSyntaxError(PSException):
pass
class PSTypeError(PSException):
pass
class PSValueError(PSException):
pas... |
import enum
from pathlib import Path
import os
from typing import Optional
@enum.unique
class CacheType(enum.Enum):
"""
Supported caching mechanisms
"""
Cache = 0 # Enable caching
NoCache = 1 # Disable caching
Auto = 2 # Enable or disable caching based on AlkymiConfig.cache setting
class ... |
import copy
import json
from functools import update_wrapper
from urllib.parse import urlparse
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django.contrib.auth.admin import csrf_protect_m
from django.db import transaction
from django.http import (
HttpResponse, HttpResponseBadR... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012-2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# ... |
# Copyright 2018 The TensorFlow 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 applica... |
#coding: utf-8
import pickle
import networkx as nx
import matplotlib.pyplot as plt
layers = ['0_communication.txt','1_financial.txt','2_operationalaggregated.txt','3_trustaggregated.txt']
graphs = []
# nodes_infor = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, ... |
from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
@register.filter
def understored_name(value):
return value.replace("-", "_")
|
# The MIT license:
#
# Copyright 2017 Andre Netzeband
#
# 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 use, copy, modify, merg... |
import pytest
from auspixdggs.callablemodules.util import dggs_cell_id_to_obj
def test_cell_id_to_cell_obj():
# read in the file
c = dggs_cell_id_to_obj('R7751215231')
print(c)
verts = c.vertices(plane=False)
vertices = [(138.75323883554336, -34.710999884272056), (138.75476299344612, -34.710999884... |
"""
Nonlinearities
"""
# sigmoid
from theano.tensor.nnet import sigmoid
# softmax (row-wise)
from theano.tensor.nnet import softmax
# tanh
from theano.tensor import tanh
# rectify
# The following is faster than lambda x: T.maximum(0, x)
# Thanks to @SnippyHolloW for pointing this out.
# See: https://github.com/Sni... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
import asyncio
from typing import Optional
import aiohttp
from asgiproxy.config import ProxyConfig
class ProxyContext:
semaphore: asyncio.Semaphore
_session: Optional[aiohttp.ClientSession] = None
def __init__(
self,
config: ProxyConfig,
max_concurrency: int = 20,
) -> None:... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import subprocess
import sys
import time
import py.path
import _pytest.pytester as pytester
import pytest
from _pytest.config import PytestPluginManager
from _pytest.main imp... |
from io import BytesIO
import torch
from ts.torch_handler.base_handler import BaseHandler
class NetHandler(BaseHandler):
def preprocess(self, data):
# TODO: temporarily set the model in training mode,
# instead of eval mode until model is fixed.
self.model.train()
return torch.lo... |
import pytest
import torch
import random
from molbart.decoder import DecodeSampler
from molbart.tokeniser import MolEncTokeniser
from molbart.models.pre_train import BARTModel
regex = "\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9]"
# Use dummy SMILES strings
re... |
# @author: vinay
import subprocess
import sys
# execution of c program
def c_calling():
try:
with open(sys.argv[1], encoding="utf8") as file:
for line in file:
word_list = line.split()
for word in word_list:
word = alphabet_numbers(wo... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[0;31mERRO: Por favor, digite um número inteiro válido.\033[m')
continue
except KeyboardInterrupt:
print('\033[0;31mERRO: Usuáio preferiu não, dig... |
# coding: utf-8
"""
Transaction Management Bus (TMB) API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: V3.2.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re ... |
import warnings
import pytest
from pathlib import Path
from unittest.mock import call, patch
from pdoc import pdoc
from pdoc.__main__ import cli, _nicer_showwarning
here = Path(__file__).parent
def test_cli(capsys, tmp_path):
cli([str(here / "testdata" / "demo_long.py"), "-o", str(tmp_path)])
assert (tmp_p... |
import argparse
import pytorch_lightning as pl
from core.Pytorch_Implimentation_2 import DQNLightning
def main(hparams) -> None:
model = DQNLightning(hparams)
trainer = pl.Trainer(
gpus=1,
distributed_backend="dp",
max_epochs=5000,
val_check_interval=1000
)
trainer.fit(model)
parser ... |
#!/usr/bin/env python3
# Copyright (C) 2018 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import sys
from testrunner import run
def testfunc(child):
child.expect_e... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "alpha.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... |
#! /usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2018, ARM Limited and contributors.
#
# 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/l... |
import pytest
from django.contrib.sites.models import Site
from django.db.utils import IntegrityError
from django.test.client import RequestFactory
from django.urls import reverse
from django.utils.encoding import smart_text
from saleor.dashboard.sites.forms import SiteForm, SiteSettingsForm
from saleor.site import ut... |
#!/usr/bin/env python
import numpy as np
import geostatsmodels.utilities as utilities
def lagindices(pwdist, lag, tol):
'''
Input: (pwdist) square NumPy array of pairwise distances
(lag) the distance, h, between points
(tol) the tolerance we are comfortable with around (lag)
... |
expected_output = {
'OSPF2202BGP': {
'statements': {
10: {
'actions': {
'set_community_list': 'DCBQ_VOZ',
'set_next_hop': '10.20.96.53',
'set_local_pref': 330
},
'conditions': {
... |
# 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.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
# For webcam input:
cap = cv2.VideoCapture(0)
with mp_hands.Hands(
min_detection_confidence=0.5,
min_tracking_confidence=0.5) as hands:
while cap.isOpened():
success, image = cap.read()
... |
print("***************FUVEST***************")
#dados de concorrencia
curso = input("Digite o curso desejado: ")
local = input("Digite o campus desejado: ")
turno = input("Digite o turno desejado: ")
print("****************************************************************************")
red = float(input("Digite a sua no... |
from datatypes import *
Emotes = ["NORMAL", "PAIN", "HAPPY", "SURPRISE", "ANGRY", "BLINK"]
PlayerFlags = ["PLAYING", "IN_MENU", "CHATTING", "SCOREBOARD", "AIM"]
GameFlags = ["TEAMS", "FLAGS"]
GameStateFlags = ["GAMEOVER", "SUDDENDEATH", "PAUSED"]
Emoticons = ["OOP", "EXCLAMATION", "HEARTS", "DROP", "DOTDOT", "MUSIC",... |
import operator
import re
from functools import cached_property
from typing import Any, Callable, Dict, List, Tuple, Union
import frappe
from frappe import _
from frappe.boot import get_additional_filters_from_hooks
from frappe.model.db_query import get_timespan_date_range
from frappe.query_builder import Criterion, F... |
from .utils import *
import copy
def s_swap_price_i(params, substep, state_history, prev_state, policy_input):
"""
Calculates and returns the swap price for a trade Qi for Ri
"""
Q_reserve = int(prev_state['UNI_Qi'])
R_reserve = int(prev_state['UNI_Ri'])
# input 1000 q token get r
delta_q ... |
"""Auto-generated file, do not edit by hand. LU metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_LU = PhoneMetadata(id='LU', country_code=352, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[24-9]\\d{3,10}|3(?:[0-46-9]\\d{2,9}|5[0... |
import numpy as np
import pickle
import gzip
class Transition:
def __init__(self, size):
self.score_matrix = np.full((size, size), -np.inf)
def put(self, prev_pos_id, cur_pos_id, score):
self.score_matrix[prev_pos_id][cur_pos_id] = score
def get(self, prev_pos_id, cur_pos_id):
sc... |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in grand/__init__.py
from grand import __version__ as version
setup(
name='grand',
version=version,
description='Grand Hypermarket Qatar',
autho... |
import numpy as np
import pylab as plt
from scipy.special import erf
from scipy.integrate import simps
from scipy.linalg import cho_solve
#from ChoSolver import choSolve, choBackSubstitution
def styblinsky(x):
return (x[0]**4 - 16*x[0]**2 + 5*x[0] + x[1]**4 - 16*x[1]**2 + 5*x[1])/2.
def rosenbrock(x):
... |
import graphene
from graphene_django import DjangoObjectType
from users.models import User
from django.contrib.auth import authenticate
class UserType(DjangoObjectType):
class Meta:
model = User
def get_user(info):
token = info.context.session.get('token') or info.context.META.get('HTTP_AUTHORIZAT... |
# Copyright 2017 Google Inc.
#
# 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 notice,
# this list of conditions and the following disclaimer.
#
#... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
#!/usr/bin/env python
u"""
ecco_read_realtime.py
Written by Tyler Sutterley (10/2021)
Reads 12-hour ECCO ocean bottom pressure data from JPL
Calculates monthly anomalies on an equirectangular grid
https://ecco.jpl.nasa.gov/drive/files/NearRealTime/Readme
https://ecco.jpl.nasa.gov/drive/files/NearRealTime/Kalma... |
"""
ResNet code gently borrowed from
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
"""
from collections import OrderedDict
import math
import torch.nn as nn
from torch.utils import model_zoo
__all__ = ['SENet', 'senet154', 'se_resnet50', 'se_resnet101', 'se_resnet152',
'se_res... |
import gdsfactory as gf
import gdsfactory.simulation.gtidy3d as gt
from gdsfactory.config import CONFIG
from gdsfactory.simulation.gtidy3d.get_results import get_results
def test_results_local(data_regression) -> None:
"""Loads local results"""
component = gf.components.straight(length=3)
sim = gt.get_si... |
# coding: utf-8
"""
Experimental Looker API 3.1 Preview
This API 3.1 is in active development. Breaking changes are likely to occur to some API functions in future Looker releases until API 3.1 is officially launched and upgraded to beta status. If you have time and interest to experiment with new or modifie... |
class carro:
pass
NORTE = 'Norte'
LESTE = 'Leste'
SUL = 'Sul'
OESTE = 'Oeste'
class direcao:
rotacao_a_direita_dct = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE}
rotacao_a_esquerda_dct = {NORTE: OESTE, OESTE: SUL, SUL: LESTE, LESTE: NORTE}
def __init__(self):
self.valor = NORTE
d... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import csv
print ("Número da simulação:")
nSim = input()
print ("Número do frame:")
nFrame = input()
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
xs = []
ys = []
zs = []
fVasos = "Resultados\\{}\\vasos{}.txt".... |
import cv2
import albumentations as A
import numpy as np
from utils import plot_examples
from PIL import Image
image = Image.open("images/elon.jpeg")
mask = Image.open("images/mask.jpeg")
mask2 = Image.open("images/second_mask.jpeg")
transform = A.Compose(
[
A.Resize(width=1920, height=1080),
A.Ra... |
# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function, division
import logging
class IrcLoggingHandler(logging.Handler):
def __init__(self, bot, level):
super(IrcLoggingHandler, self).__init__(level)
self._bot = bot
self._channel = bot.config.core.logging... |
def ssh_cdp(device, username, password):
import pprint
from netmiko import ConnectHandler
host_dictionary = {}
command = "show cdp entry *"
connection_details = { # This establishes SSH connection settings for the device.
"device_type": "cisco_ios",
"host": device,
... |
from . import nonlinearities
__all__ = [
"GlorotUniformGain",
]
GlorotUniformGain = {};
GlorotUniformGain[nonlinearities.sigmoid] = 4.0;
GlorotUniformGain[nonlinearities.softmax] = 1.0;
GlorotUniformGain[nonlinearities.tanh] = 1.0;
GlorotUniformGain[nonlinearities.rectify] = 1.0;
GlorotUniformGain[nonl... |
"""
Useful testing utilities.
This module is considered public API.
"""
import time
import six
from pymemcache.exceptions import MemcacheIllegalInputError
class MockMemcacheClient(object):
"""
A (partial) in-memory mock for Clients.
"""
def __init__(self,
server=None,
... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
base_template_path = "stock.html"
import os, re
import frappe
from frappe import _
def get_context(context):
# conte... |
"""
test_php_eggs.py
Copyright 2012 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope th... |
# Import required libraries
import cv2
import numpy as np
import dlib
# Pc ye bağlı kamerayı çalıştırma
cap = cv2.VideoCapture(0)
# Kordinatları Yakala
detector = dlib.get_frontal_face_detector()
# Yüzde Kare Oluştur
while True:
# Kare kare Yakalama
ret, frame = cap.read()
f... |
# -*- coding: utf-8 -*-
# flake8: noqa
from app.authorization.queries import Query
from app.authorization.mutations import Mutation
|
from .nans import * # NOQA
from .sliding import * # NOQA
from .ts_factory import * # NOQA
|
"""The SRP Energy integration."""
import logging
from srpenergy.client import SrpEnergyClient
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ID, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady... |
import logging
from typing import List
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics
from matplotlib import gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable
from bfgn.reporting import samples
from bfgn.reporting.visualizations import colormaps, subplots
_logger = logging.g... |
import numpy as np
import pandas as pd
import pytest
from dku_timeseries import WindowAggregator
from recipe_config_loading import get_windowing_params
@pytest.fixture
def columns():
class COLUMNS:
date = "Date"
category = "country"
aggregation = "value1_avg"
return COLUMNS
@pytest.f... |
import json
import os
from pathlib import Path
from django.conf import settings
from tacticalrmm.test import TacticalTestCase
from model_bakery import baker
from .serializers import ScriptSerializer
from .models import Script
class TestScriptViews(TacticalTestCase):
def setUp(self):
self.authenticate()
... |
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
from sklearn.svm import SVR, LinearSVR, NuSVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
from sklear... |
#http://unicode.org/Public/emoji/12.0/
from efdir import fs
import os
import sys
import re
import elist.elist as elel
import edict.edict as eded
from xdict.jprint import pobj,pdir,parr
import dtable.dtable as dtdt
import estring.estring as eses
import string
from nvhtml import htmldb
URLS = {
'emoji_data':'https:... |
from nntool.abc.functionabc import FunctionABC
def mle(y,out):
"""log对数损失函数,常见于logistic 回归,不实现"""
return NotImplemented
|
import pygame
import numpy as np
import cv2
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
BROWN = (184, 134, 11)
GRAY = (169, 169, 169)
DISPLAY_BATTERY = True
class ContinuousWorldRenderer:
def __init__(self, num_grid=500, obs_range=25, ... |
"""Support for UPnP/IGD Sensors."""
from __future__ import annotations
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import DATA_BYTES, DATA_RATE_KIBIBYTES_PER_SECOND, TIME_SECONDS
from homeassistant.core import HomeAssistant
from... |
from django.urls import include, path
from . import views
#app_name = 'recommender'
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('best/', views.searchform_get, name='best'),
path('recommender/bestp/', views.searchform_post, name='bestp'),
path(... |
from .models import EventLog
def log_event(actor, verb, target=None, object=None, template='',
timestamp=None, extra=None, using=None):
EventLog.objects.log_event(actor, verb, target, object, template,
timestamp, extra, using)
|
import subprocess
import os
import benchmark.util as Util
import benchmark.tools.template
import benchmark.result as result
class Tool(benchmark.tools.template.BaseTool):
"""
This class serves as tool adaptor for ESBMC (http://www.esbmc.org/)
"""
def getExecutable(self):
return Util.findExecu... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from redis import StrictRedis
from datetime import datetime
from pprint import pprint
from serpent.config import config
import json
class AnalyticsClientError(BaseException):
pass
class AnalyticsClient:
def __init__(self, project_key=None):
if project_key is None:
raise AnalyticsClien... |
"""
Copyright (c) 2020 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 applicable law or agreed to in writin... |
# Scrapy settings for PluMA project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.h... |
""" Users Schemas
"""
from typing import List
from pydantic import BaseModel, Field
from .answers_schema import Questions
class UsersRequestSchema(BaseModel):
""" Request schema for User requests.
"""
username: str = Field(None, max_length=15)
group: str = Field(None, max_length=15)
class Answers(Ba... |
"""A semi-secure external process keyring.
This allows storage (but not retrieval) of signing keys, by name, within an external process. Data may then be sent
for signing against a specific key. Theoretically, should the host application be compromised, your keys will remain
safe.
"""
from atexit import register, unr... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from collections import Counter
def matchingStrings(strings, queries):
ans = []
c = Counter(strings)
for i in queries:
if i in c:
ans.append(c[i])
else:
ans.append(0)
return ans
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""
Tests a variety of export options with our surgery methods applied, including
torchscript, torch.fx, and ONNX.
"""
import os
import pathlib
from typing import Any, Callable, Type
import pytest
import torch
import torch.fx
from compo... |
# -*- coding: utf-8 -*-
"""Logging Filters."""
from __future__ import unicode_literals
import logging
# logging levels from https://docs.python.org/2/library/logging.html#logging-levels
LEVELS = {
"CRITICAL": 50,
"ERROR": 40,
"WARNING": 30,
"INFO": 20,
"DEBUG": 10,
"NOTSET": 0,
}
class Exce... |
r"""
John Jones's tables of number fields
In order to use the Jones database, the optional database package
must be installed using the Sage command !sage -i
database_jones_numfield
This is a table of number fields with bounded ramification and
degree `\leq 6`. You can query the database for all number
fields in Jone... |
def maxProfit(self, prices: List[int]) -> int:
"""
>>> Dynammic Programming
A state compression problem. We have three state:
- sold
- buy
- cd
to store the maximum profit ending with selling, buying and cooldown.
And the next state is... |
import uuid
from datetime import datetime
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from pyrules import RuleContext, RuleEngine, RuleStore
from . import forms
def index(request):
result = None
logs = None
if request.... |
# 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 ... |
# -*- coding:utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals,
)
import time
from django.db import connections
from django.db.utils import DEFAULT_DB_ALIAS
from django.utils.functional import SimpleLazyObject
from django_mysql.exceptions import TimeoutError
class B... |
import discord
import random
from redbot.core import commands
from typing import Union, Optional
class Mock(commands.Cog):
"""mock a user as spongebob"""
def __init__(self, bot):
self.bot = bot
async def cap_change(self, message: str):
result = ""
for char in message:
... |
from typing import Callable
from httpx import Request, Response, codes
from pytest import raises
from pytest_httpx import HTTPXMock
from firebolt.client.auth import Token
from firebolt.utils.exception import AuthorizationError
from tests.unit.util import execute_generator_requests
def test_token_happy_path(
htt... |
#!/usr/bin/env python
from mi.core.log import get_logger
from mi.dataset.driver.flord_l_wfp.sio.resource import RESOURCE_PATH
import unittest
import os
from mi.dataset.driver.dosta_ln.wfp_sio.dosta_ln_wfp_sio_telemetered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
__author__ = 'mwor... |
#!/usr/bin/python
from distutils.core import setup
from Cython.Distutils import build_ext
from distutils.extension import Extension
cy_mod = Extension(
"polygon",
sources=["polygon.pyx"],
# extra_compile_args=['-fopenmp'],
# extra_link_args=['-fopenmp']
)
setup(ext_modules=[cy_mod], cmdclass={"b... |
import logging
import pytest
from log import JSONFormatter, LogConfiguration, LogglyHandler, StringFormatter
from model import ExternalIntegration
from . import DatabaseTest
class TestLogConfiguration(DatabaseTest):
def loggly_integration(self):
"""Create an ExternalIntegration for a Loggly account."""... |
"""Pylons environment configuration"""
import os
from mako.lookup import TemplateLookup
from pylons.error import handle_mako_error
from pylons import config
import _rename_to_your_app_.lib.app_globals as app_globals
import _rename_to_your_app_.lib.helpers
from _rename_to_your_app_.config.routing import make_map
def ... |
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('firstapp.urls')),
path('quoteapp/', include('quoteapp.urls'))
] |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 07 08:37:00 2016
@author: atto
"""
import numpy as np
import scipy.io as sio
from glob import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Data folder path",type=str)
parser.add_argument("ch",help="Channel A or B",n... |
# Copyright (c) 2018 Graphcore Ltd. All rights reserved.
import sys
import os
import c10driver
import popart
import cmdline
from popart.torch import torchwriter
import torch
import numpy as np
args = cmdline.parse()
nInChans = 3
nOutChans = 8
batchSize = 2
batchesPerStep = 4
anchors = {
"l1LossVal": popart.Anchor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.