content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class SchoolConfig(AppConfig):
name = "school"
| django_orm/school/apps.py | 111 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Math Module Part 2
import math
# Factorial & Square Root
print(math.factorial(3))
print(math.sqrt(64))
# Greatest Common Denominator GCD
print(math.gcd(52, 8))
print(math.gcd(8, 52))
print(8/52)
print(2/13)
# Degrees and Radians
print(math.radians(360))
print(math.degrees(math.pi * 2))
| Chapter02/02_02.py | 310 | Math Module Part 2 Factorial & Square Root Greatest Common Denominator GCD Degrees and Radians | 94 | en | 0.628996 |
# Petit exercice utilisant la bibliothèque graphique tkinter
from tkinter import *
from random import randrange
# --- définition des fonctions gestionnaires d'événements : ---
def drawline():
"Tracé d'une ligne dans le canevas can1"
global x1, y1, x2, y2, coul
can1.create_line(x1,y1,x2,y2,width=2,fil... | Exemples cours 4/TK_Line.py | 1,433 | Changement aléatoire de la couleur du tracé
Tracé d'une ligne dans le canevas can1
Petit exercice utilisant la bibliothèque graphique tkinter --- définition des fonctions gestionnaires d'événements : --- modification des coordonnées pour la ligne suivante : => génère un nombre aléatoire de 0 à 7 ------ Programme prin... | 594 | fr | 0.992403 |
# -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
SECRET_KEY = 'psst'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'hfut_auth'
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME'... | test_settings.py | 579 | -*- coding:utf-8 -*- default | 28 | en | 0.462266 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import defaultdict
import os
from tabulate import tabulate # type: ignore
import onnx
from onnx import defs, helper
_all_schemas = defs.get_all_schem... | onnx/backend/test/report/coverage.py | 3,068 | type: ignore Turn list into tuple so we can put it into set As value can be string, don't blindly turn `collections.Iterable` into tuple. | 137 | en | 0.937371 |
# -*- coding: utf-8 -*-
"""poc.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e
A simple example for deep-learning-based non-rigid image registration
with the MNIST dataset.
**README:** If the below error occurs,... | register_basics.py | 20,050 | Given a moving image and a sampling grid as input, computes the
transformed image by sampling the moving image at locations given by
the grid.
Currently, only 2-D images, i.e., 4-D inputs are supported.
Parameters
----------
moving : tf.Tensor, shape (N, H, W, C)
The moving image.
grid : tf.Tensor, shape (N, H, W... | 8,668 | en | 0.729401 |
# import moonshine as ms
# from moonshine.curves import discount_factor
from .curves import get_discount_factor
from .instruments import price_cashflow
def egg(num_eggs: int) -> None:
"""prints the number of eggs.
Arguments:
num_eggs {int} -- The number of eggs
Returns:
None.
"""
... | src/moonshine/__main__.py | 658 | prints the number of eggs.
Arguments:
num_eggs {int} -- The number of eggs
Returns:
None.
import moonshine as ms from moonshine.curves import discount_factor | 169 | en | 0.783642 |
import pandas as pd
import streamlit as st
from awesome_table import AwesomeTable
from awesome_table.column import (Column, ColumnDType)
from sample import data as sample_data
st.set_page_config(page_title='AwesomeTable by @caiofaar', page_icon='📊', layout='wide')
st.title('AwesomeTable with Search')
AwesomeTable(pd... | samples/with_search/__init__.py | 777 | From FontAwesome v6.0.0 | 23 | en | 0.770154 |
import json
from decimal import Decimal
from django.core.paginator import Paginator
from django.db import transaction
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render
# Create your views here.
from django.utils import timezone
from django.views import View
from django_re... | meiduo_mall/meiduo_mall/apps/orders/views.py | 10,324 | 结算订单
提供订单结算页面
保存订单信息和订单商品信息
Create your views here. 获取登录用户 查询地址信息 如果地址为空,渲染模板时会判断,并跳转到地址编辑页面 从redis购物车中查询被勾选的商品信息 准备初始值 查询商品信息 计算总数量和总金额 补充运费 渲染界面 获取当前要保存的订单数据 校验参数 判断address_id是否合法 判断pay_method是否合法 获取登录用户 生成订单编号:年月日时分秒+用户编号 显式的开启一个事务 创建事务保存点 暴力回滚 保存订单基本信息OrderInfo 从redis读取购物车中被勾选的商品 获取选中的商品id 遍历购物车中被勾选的商品信息 TODO1: 增... | 935 | zh | 0.917187 |
import discord
from discord.ext import commands
class Mod:
"""Useful moderation commands to keep the server under control."""
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.guild_only()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, us... | cogs/mod.py | 1,548 | Useful moderation commands to keep the server under control. | 60 | en | 0.871084 |
from argparse import ArgumentParser
from google.cloud.speech import SpeechClient, types, enums
from pyaudio import PyAudio, paInt16, paContinue
from six.moves.queue import Queue, Empty
from sys import stdout
import socket
# from os import environ
# environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'C:/Users/kwea123/Download... | googlesr.py | 5,803 | Opens a recording stream as a generator yielding the audio chunks.
Continuously collect data from the audio stream, into the buffer.
from os import environ environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'C:/Users/kwea123/Downloads/MyProject-e85ed8c91456.json' Audio recording parameters 100ms Create a thread-safe buffer ... | 1,365 | en | 0.861392 |
import argparse
import sys
from os import path
import cv2 as cv
from mcrops import veget, utils
def full_imshow(name, image):
cv.namedWindow(name, cv.WINDOW_NORMAL)
cv.resizeWindow(name, 800, 600)
cv.imshow(name, image)
def main(image_path: str, resolution: float, row_sep: float):
print(f'Starting... | examples/vegetation.py | 2,861 | Load a crop field image Segment vegetation Detect the crop field ROI area Draw the contours of the ROI area Build a mask image from the ROI polyline Create a vegetation density map from the vegetation mask Convert the vegetation density map to a color image | 257 | en | 0.684321 |
# Copyright (c) 2014, Raphael Kubo da Costa <rakuco@FreeBSD.org>
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
import PyKDE4.kdecore
if __name__ == '__main__':
try:
import PyKDE4.pykdeconfig
pykdecfg = ... | attic/modules/FindPyKDE4.py | 960 | Copyright (c) 2014, Raphael Kubo da Costa <rakuco@FreeBSD.org> Redistribution and use is allowed according to the terms of the BSD license. For details see the accompanying COPYING-CMAKE-SCRIPTS file. PyQt4 >= 4.10.0 was built with configure-ng.py instead of configure.py, so pyqtconfig.py and pykdeconfig.py are not ins... | 327 | en | 0.824579 |
# -*- coding: utf-8 -*-
from random import randint
import json
from .base import analyse_process_graph, PROCESS_DICT, PROCESS_DESCRIPTION_DICT
from openeo_grass_gis_driver.process_schemas import Parameter, ProcessDescription, ReturnValue
from .actinia_interface import ActiniaInterface
__license__ = "Apache License, Ve... | src/openeo_grass_gis_driver/actinia_processing/get_data_process.py | 5,154 | Create a Actinia process description that uses t.rast.series to create the minimum
value of the time series.
:param input_time_series: The input time series name
:param output_map: The name of the output map
:return: A Actinia process chain description
Analyse the process description and return the Actinia process cha... | 592 | en | 0.613929 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2010 Søren Roug, European Environment Agency
#
# This is free software. You may redistribute it under the terms
# of the Apache license and the GNU General Public License Version
# 2 or at your option any later version.
#
# This program is distributed ... | desktop/core/ext-py/odfpy-1.4.1/tests/testform.py | 3,177 | Check that ooo exists in namespace declarations
!/usr/bin/env python -*- coding: utf-8 -*- Copyright (C) 2008-2010 Søren Roug, European Environment Agency This is free software. You may redistribute it under the terms of the Apache license and the GNU General Public License Version 2 or at your option any later vers... | 850 | en | 0.862755 |
import os
import hashlib
from django.db import models
from sample.fields import Md5Field, Sha256Field
from scanworker.file import PickleableFileSample
from scaggr.settings import SAMPLE_UPLOAD_DIR, MAX_SHA256_DIRECTORY_DEPTH
def generate_hash_directories(hash_str):
return "/".join([d for d in hash_str[:MAX_SHA256_D... | sample/abstract.py | 2,190 | todo confirm that this gets the proper upload dir off the instance todo think about memory caching this make sure we do our required hashing before we save this thing | 166 | en | 0.855753 |
""" Test the gym's code for configuring the DonkeyCar's camera settings.
"""
import os
import argparse
import gym
import gym_donkeycar
import numpy as np
import uuid
if __name__ == "__main__":
# Initialize the donkey environment
# where env_name one of:
env_list = [
"donkey-warehouse-v0",
... | examples/test_cam_config.py | 2,404 | Test the gym's code for configuring the DonkeyCar's camera settings.
Initialize the donkey environment where env_name one of:%% SET UP ENVIRONMENT%% PLAY drive straight with small speed | 187 | en | 0.828084 |
from src.pre_processing import Preprocessing
def identifyQuery(query):
q_l: str = query
if q_l.__contains__("AND") or q_l.__contains__("OR") or q_l.__contains__("NOT"):
return "B"
elif query.__contains__("/"):
return "PR"
elif len(q_l.split()) == 1:
return "S"
else:
... | src/search.py | 3,710 | dict_book structure: {"word": {doc-ID: [], ...}, ...} dict returned, {docID:[], ...} without using get() and type defining to be set not dict len_posting1 = len(posting1) len_posting2 = len(posting2) i was iterating on sets rather than its keys iterates on documents print(docI) returns a position list hilary clinton di... | 519 | en | 0.677401 |
#!/usr/bin/env python
#
# Copyright 2018 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | examples/confluent_cloud.py | 3,877 | Delivery report callback called (from flush()) on successful or failed delivery of the message.
!/usr/bin/env python Copyright 2018 Confluent Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at htt... | 2,153 | en | 0.718065 |
'''Paginatiors for Figures
'''
from rest_framework.pagination import LimitOffsetPagination
class FiguresLimitOffsetPagination(LimitOffsetPagination):
'''Custom Figures paginator to make the number of records returned consistent
'''
default_limit = None
| figures/pagination.py | 269 | Custom Figures paginator to make the number of records returned consistent
Paginatiors for Figures | 103 | en | 0.640962 |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys
from spack import *
class ScalapackBase(CMakePackage):
"""Base class for building ScaLAPACK, shared with... | var/spack/repos/builtin/packages/netlib-scalapack/package.py | 4,173 | ScaLAPACK is a library of high-performance linear algebra routines for
parallel distributed memory machines
Base class for building ScaLAPACK, shared with the AMD optimized version
of the library in the 'amdscalapack' package.
Copyright 2013-2022 Lawrence Livermore National Security, LLC and other Spack Project Devel... | 1,067 | en | 0.825993 |
"""
ParallelCluster
ParallelCluster API # noqa: E501
The version of the OpenAPI document: 3.0.0
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from pcluster_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNo... | api/client/src/pcluster_client/model/delete_cluster_response_content.py | 6,687 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the a... | 3,565 | en | 0.787663 |
"""
ASGI config for achristos project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SET... | achristos/asgi.py | 395 | ASGI config for achristos project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ | 215 | en | 0.709425 |
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure.core.pipeline.policies import ContentDecodePolicy
from azure.core.pipeline.policies import SansIOHTTPPolicy, HTTPPolicy
from ._models import T... | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py | 1,777 | coding=utf-8 ------------------------------------ Copyright (c) Microsoft Corporation. Licensed under the MIT License. ------------------------------------ pylint: disable=protected-access | 188 | en | 0.340532 |
# Copyright (c) 2016 Tzutalin
# Create by TzuTaLin <tzu.ta.lin@gmail.com>
try:
from PyQt5.QtGui import QImage
except ImportError:
from PyQt4.QtGui import QImage
from base64 import b64encode, b64decode
from libs.pascal_voc_io import PascalVocWriter
from libs.pascal_voc_io import XML_EXT
import os.path
import s... | libs/labelFile.py | 3,934 | Copyright (c) 2016 Tzutalin Create by TzuTaLin <tzu.ta.lin@gmail.com> It might be changed as window creates. By default, using XML ext suffix = '.lif'imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] Read from file path because self.imageData might be empty if saving to Pascal format Add Chris Martin Kersner, 20... | 415 | en | 0.62024 |
"""
:author: Maikel Punie <maikel.punie@gmail.com>
"""
import velbus
class VMB1BLModule(velbus.Module):
"""
Velbus input module with 6 channels
"""
def __init__(self, module_type, module_name, module_address, controller):
velbus.Module.__init__(self, module_type, module_name, module_address, co... | velbus/modules/vmbbl.py | 2,446 | Velbus input module with 6 channels
Velbus input module with 7 channels
Callback to execute on status of update of channel
:author: Maikel Punie <maikel.punie@gmail.com> | 169 | en | 0.568389 |
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.shortcuts import render, redirect
# Create your views here.
from .forms import LoginForm, RegisterForm
User = get_user_model()
def register_view(request):
form = RegisterForm(request.POST or None)
if form.is_valid():
... | accounts/views.py | 1,921 | Create your views here. 1 == True Authenticate checks if the username and password is correct User is valid and active -> is_active request.user == user Login succes redirect Count user login attempt (simple way) attempt = request.session.get("attempt") or 0 request.session['attempt'] = attempt + 1 return redirect("/in... | 372 | en | 0.694703 |
# 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... | aliyun-python-sdk-drds/aliyunsdkdrds/request/v20190123/DescribeDrdsInstancesRequest.py | 2,815 | 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 use this file... | 754 | en | 0.883564 |
# -*- coding: utf-8 -*-
# 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/.
from cli_common.log import get_logger
logger = get_logger(__name__)
WORKER_CHECKOUT = '/builds... | src/staticanalysis/bot/static_analysis_bot/task.py | 2,260 | An analysis CI task running on Taskcluster
Helper to clean issues path from remote tasks
-*- coding: utf-8 -*- 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/. Process only t... | 418 | en | 0.914483 |
import time
from array import array
from itertools import product
from time import clock
import sys
from java.lang import Math
sys.path.append("./ABAGAIL.jar")
import java.util.Random as Random
from shared import ConvergenceTrainer
from opt.example import FourPeaksEvaluationFunction
from opt.ga import DiscreteChan... | jython/peaks4.py | 6,227 | Adapted from https://github.com/JonathanTay/CS-7641-assignment-2/blob/master/tsp.py Problem Sizes MIMIC RHC SA GA | 113 | en | 0.703408 |
# Copyright 2017 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... | tensorflow/contrib/boosted_trees/estimator_batch/trainer_hooks.py | 7,130 | Hook to save feature importance summaries.
Runs feed_fn and sets the feed_dict accordingly.
Stop training after building N full trees.
Create a FeatureImportanceSummarySaver Hook.
This hook creates scalar summaries representing feature importance
for each feature column during training.
Args:
model_dir: model base ... | 1,683 | en | 0.84868 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.15.9
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
fr... | kubernetes_asyncio/client/models/v1beta2_deployment_strategy.py | 4,504 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Returns true if both objects are equal
V1beta2DeploymentStrategy - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Gets the rolling_update of this ... | 1,500 | en | 0.606777 |
"""Tests for http/wsgi.py"""
import io
import asyncio
import socket
import unittest
from unittest import mock
import aiohttp
from aiohttp import multidict
from aiohttp import wsgi
from aiohttp import protocol
from aiohttp import helpers
class TestHttpWsgiServerProtocol(unittest.TestCase):
def setUp(self):
... | tests/test_wsgi.py | 11,704 | Tests for http/wsgi.py
This header should be removed according to CGI/1.1 and WSGI but in our case basic auth is not handled by server, so should not be removed | 162 | en | 0.946874 |
#!/usr/bin/python
import socket
import fcntl
import struct
import os
ip=socket.gethostbyname(socket.gethostname())
hostname=socket.gethostname()
#def get_ip_address(ifname):
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# return socket.inet_ntoa(fcntl.ioctl(
# s.fileno(),
# 0x8915, # S... | update_inventory.py | 627 | !/usr/bin/python def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24])ip=get_ip_address('ens192') | 268 | en | 0.160998 |
from django import forms
from vlabs import Config, AppManager
class VlabsForm(forms.Form):
def __init__(self, *args, **kwargs):
self.vlcg = Config()
self.market = self.vlcg.getmarket()
super(VlabsForm, self).__init__(*args, **kwargs)
self.k = None
self.nameoftheap... | webui/vlabs/vlabs/forms.py | 5,346 | self.fields['user'] = forms.CharField(widget=forms.HiddenInput(), label='user', initial=user)da quialphalower = RegexValidator(regex=r'^[a-z]*[a-z0-9\-\_]*[a-z]') | 162 | en | 0.174006 |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicabl... | pennylane/gradients/__init__.py | 9,488 | Quantum gradient transforms are strategies for computing the gradient of a quantum
circuit that work by **transforming** the quantum circuit into one or more gradient circuits.
These gradient circuits, once executed and post-processed, return the gradient
of the original circuit.
Examples of quantum gradient transform... | 8,601 | en | 0.649527 |
import streamlit as st
import pandas as pd
from PIL import Image
import subprocess
import os
import base64
import pickle
# Molecular descriptor calculator
def desc_calc():
# Performs the descriptor calculation
bashCommand = "java -Xms2G -Xmx2G -Djava.awt.headless=true -jar ./PaDEL-Descriptor/PaDEL-Descriptor.j... | app.py | 3,136 | Molecular descriptor calculator Performs the descriptor calculation File download strings <-> bytes conversions Model building Reads in saved regression model Apply model to make predictions Page title Sidebar Read in calculated descriptors and display the dataframe Read descriptor list used in previously built model A... | 376 | en | 0.829445 |
# Copyright 2019 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... | tensorflow/lite/testing/op_tests/transpose_conv.py | 5,317 | Build a transpose_conv graph given `parameters`.
Make a set of tests to do transpose_conv.
Test configs for transpose_conv.
Copyright 2019 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 m... | 1,216 | en | 0.795577 |
# orm/query.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""The Query class and support.
Defines the :class:`.Query` class, the central
constru... | lib/sqlalchemy/orm/query.py | 133,495 | A grouping of SQL expressions that are returned by a :class:`.Query`
under one namespace.
The :class:`.Bundle` essentially allows nesting of the tuple-based
results returned by a column-oriented :class:`.Query` object. It also
is extensible via simple subclassing, where the primary capability
to override is that of h... | 57,861 | en | 0.803397 |
#!/usr/bin/env python
# license removed for brevity
import rospy, tf, socket, sys, struct
from geometry_msgs.msg import PoseStamped
topic = "/mocap_client/ARBI/pose"
UDP_IP = "10.201.0.100"
UDP_PORT = 21444
def callback(data):
x = data.pose.position.x
y = data.pose.position.y
z = data.pose.position.z
... | mocap_bridge/scripts/mocap2udp.py | 943 | !/usr/bin/env python license removed for brevity Internet UDP | 61 | en | 0.344641 |
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | tests/test_patch_wsi_dataset.py | 5,486 | Copyright (c) MONAI Consortium Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr... | 552 | en | 0.863305 |
from datetime import date, datetime
from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field
class BadRequestResponse(BaseModel):
"""The client called the endpoint incorrectly."""
detail: str = Field(
...,
description="A human-readable summary of the client... | ctms/schemas/web.py | 646 | The client called the endpoint incorrectly.
No existing record was found for the indentifier. | 93 | en | 0.947606 |
import re
from epcpy.epc_schemes.base_scheme import EPCScheme
from epcpy.utils.common import ConvertException
from epcpy.utils.regex import BIC_URI
BIC_URI_REGEX = re.compile(BIC_URI)
class BIC(EPCScheme):
"""BIC EPC scheme implementation.
BIC pure identities are of the form:
urn:epc:id:bic:<BICcon... | epcpy/epc_schemes/bic.py | 987 | BIC EPC scheme implementation.
BIC pure identities are of the form:
urn:epc:id:bic:<BICcontainerCode>
Example:
urn:epc:id:bic:CSQU3054383
This class can be created using EPC pure identities via its constructor | 220 | en | 0.645873 |
"""
Time series analysis functions.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------... | yt/data_objects/time_series.py | 24,500 | The DatasetSeries object is a container of multiple datasets,
allowing easy iteration and computation on them.
DatasetSeries objects are designed to provide easy ways to access,
analyze, parallelize and visualize multiple datasets sequentially. This is
primarily expressed through iteration, but can also be constructe... | 9,329 | en | 0.727429 |
from core.attack.attack import Attack
import random
import os
import re
import sys
import json
try:
from lxml import etree
except ImportError:
print("Failed to import ElementTree from any known place")
sys.exit(0)
try:
from bs4 import UnicodeDammit # BeautifulSoup 4
def decode_html(html_string):... | core/attack/mod_unfilter.py | 10,234 | This class implements a unfilter vulnerabilities generator.
This method do a Job.
BeautifulSoup 4 BeautifulSoup 3 Generate payloads based on what situations we met. <a href="inject_point"></a> <a inject_point="test"> <inject_point name="test" /> <span>inject_point</span> <!-- inject_point --> | 295 | en | 0.686437 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 10:11:14 2018
@author: magalidrumare
@ copyright https://github.com/fchollet/deep-learning-with-python-notebooks
"""
# Use of a pre-trained convnet : VGG16
# An effective approach to deep learning on small image dataset is to leverage a pre-tr... | 08_PreTrainedConvNet.py | 4,505 | Created on Tue Jan 23 10:11:14 2018
@author: magalidrumare
@ copyright https://github.com/fchollet/deep-learning-with-python-notebooks
!/usr/bin/env python3 -*- coding: utf-8 -*- Use of a pre-trained convnet : VGG16 An effective approach to deep learning on small image dataset is to leverage a pre-trained network A ... | 2,177 | en | 0.858811 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-02 22:29
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('database', '0037_auto_20170901_0917'),
]
operations = [
migrations.RenameModel(
... | aclarknet/database/migrations/0038_auto_20170902_1829.py | 406 | -*- coding: utf-8 -*- Generated by Django 1.11.4 on 2017-09-02 22:29 | 68 | en | 0.671106 |
# Distributed under the MIT License.
# See LICENSE.txt for details.
from spectre.Visualization.GenerateXdmf import generate_xdmf
import spectre.Informer as spectre_informer
import unittest
import os
# For Py2 compatibility
try:
unittest.TestCase.assertRaisesRegex
except AttributeError:
unittest.TestCase.asse... | tests/Unit/Visualization/Python/Test_GenerateXdmf.py | 2,243 | Distributed under the MIT License. See LICENSE.txt for details. For Py2 compatibility The script is quite opaque right now, so we only test that we can run it and it produces output without raising an error. To test more details, we should refactor the script into smaller units. | 279 | en | 0.819315 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Pint integration helpers
# (C) 2016 VRT Systems
#
from pint import UnitRegistry
HAYSTACK_CONVERSION = [
(u'_', ' '),
(u'°','deg'),
(u'per ', '/ '),
(u'per_h','per_hour'),
(u'... | hszinc/pintutil.py | 9,903 | Missing units found in project-haystack
Added to the registry
Some parsing tweaks to fit pint units / handling of edge cases.
Some parsing tweaks to fit pint units / handling of edge cases.
!/usr/bin/python -*- coding: utf-8 -*- Pint integration helpers (C) 2016 VRT Systems Those units are not units... they are imposs... | 651 | en | 0.812431 |
""" .. _Line-api:
**Line** --- Spectral line metadata.
------------------------------------
This module defines the Line class for LINE entries in BDPs.
"""
# system imports
import xml.etree.cElementTree as et
# ADMIT imports
import bdp_types as bt
from UtilBase import UtilBase
class Line(UtilBase):
... | admit/util/Line.py | 6,559 | Class for holding information on a specific spectral line.
Parameters
----------
keyval : dict
Dictionary of keyword:value pairs.
Attributes
----------
name : str
Name of the molecule/atom.
Default: "".
uid : str
Unique identifier for the transition.
Default: "".
formula : str
The chemical f... | 2,467 | en | 0.478896 |
from functools import partial
from typing import List, Optional, Sequence, cast
import dask.array as da
import dask.dataframe as dd
import numpy as np
import pandas as pd
from kartothek.core.typing import StoreFactory
from kartothek.io.dask.compression import pack_payload, unpack_payload_pandas
from kartothek.io_comp... | kartothek/io/dask/_shuffle.py | 5,613 | Categorize each row of `df` based on the data in the columns `subset`
into `num_buckets` values. This is based on `pandas.util.hash_pandas_object`
Unpack payload data and store partition
Perform a dataset update with dask reshuffling to control partitioning.
The shuffle operation will perform the following steps
1. P... | 2,207 | en | 0.817207 |
from operator import ge
from typing import List, Optional, Tuple # Dict,
from fastapi import FastAPI, HTTPException, Depends, Query, status
from fastapi.templating import Jinja2Templates
from pathlib import Path
from fastapi import Request # , Response
# from fastapi.responses import JSONResponse
# from pymongo.comm... | todoer_api/app/main.py | 5,782 | Dict, , Response from fastapi.responses import JSONResponse from pymongo.common import validate_server_api_or_none ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ task_db: TaskDatabase = database_factory("mongo... | 723 | en | 0.407405 |
import os
import numpy as np
from keras import backend as K
from keras.losses import mean_absolute_error
import utils
from model import wdsr_b
def psnr(hr, sr, max_val=2):
mse = K.mean(K.square(hr - sr))
return 10.0 / np.log(10) * K.log(max_val ** 2 / mse)
def data_generator(path, batch_size=8, input_shap... | src/train.py | 1,173 | data generator for fit_generator | 32 | en | 0.372999 |
""" Git Branch Merge Target Model tests """
from django.test import TestCase
from django.test import Client
from django.conf import settings
from django.utils import timezone
from app.logic.gitrepo.models.GitProjectModel import GitProjectEntry
from app.logic.gitrepo.models.GitBranchModel import GitBranchEntry
from app... | app/logic/gitrepo/tests/tests_model_GitBranchMergeTargetModel.py | 2,999 | Git Branch Merge Target Model tests
Create your tests here. | 62 | en | 0.784363 |
# Copyright (C) 2018 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
import asyncio
import os
from decimal import Decimal
import random
import time
from typing import (Optional, Sequence, Tuple, List, Set, D... | electrum/lnworker.py | 109,012 | Returns a read-only copy of channels.
Returns a read-only copy of channels.
return MPP status: True (accepted), False (expired) or None
Creates multiple routes for splitting a payment over the available
private channels.
We first try to conduct the payment over a single channel. If that fails
and mpp is supported by ... | 9,474 | en | 0.902375 |
# **********************************************************************************************************************
# **********************************************************************************************************************
# ****************************************************************************... | CartPole/CartPole_RL-baseline_1k_episodes.py | 6,878 | ********************************************************************************************************************** ********************************************************************************************************************** **********************************************************************************... | 2,289 | en | 0.34657 |
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
"""SQLAlchemy storage backend."""
import threading
from oslo_log import log
from oslo_config import cfg
from oslo_utils import uuidutils
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import enginefacade
from ... | fm-rest-api/fm/fm/db/sqlalchemy/api.py | 16,837 | SqlAlchemy connection.
Adds a degrade_affecting attribute from event_suppression to query.
:param query: Initial query.
:return: Modified query.
Adds an event_suppression filter to a query.
Filters results by suppression status
:param query: Initial query to add filter to.
:param include_suppress: Value for filterin... | 924 | en | 0.659626 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########################################################################
#
# Copyright (c) 2015 Baidu, 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 o... | bigflow_python/python/bigflow/transform_impls/test/reduce_test.py | 2,237 | inner function
Author: Wang, Cong(bigflow-opensource@baidu.com)
!/usr/bin/env python -*- coding: utf-8 -*- Copyright (c) 2015 Baidu, 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 Li... | 681 | en | 0.827185 |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import re, ast
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in accounting/__init__.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('accounting/__init__.... | setup.py | 666 | -*- coding: utf-8 -*- get version from __version__ variable in accounting/__init__.py | 85 | en | 0.610411 |
from .ShuntCompensator import ShuntCompensator
class LinearShuntCompensator(ShuntCompensator):
'''
A linear shunt compensator has banks or sections with equal admittance values.
:bPerSection: Positive sequence shunt (charging) susceptance per section Default: 0.0
:gPerSection: Positive sequence shunt (charging) ... | cimpy/cgmes_v2_4_15/LinearShuntCompensator.py | 1,476 | A linear shunt compensator has banks or sections with equal admittance values.
:bPerSection: Positive sequence shunt (charging) susceptance per section Default: 0.0
:gPerSection: Positive sequence shunt (charging) conductance per section Default: 0.0
:b0PerSection: Zero sequence shunt (charging) susceptance per sectio... | 417 | en | 0.759569 |
# 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 agreed to in writing, software
#... | rally/plugins/openstack/context/magnum/cluster_templates.py | 4,175 | Context class for generating temporary cluster model for benchmarks.
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 ... | 609 | en | 0.86741 |
##########################################################################
# Author: Samuca
#
# brief: returns the int part of number
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
###########################################################... | ex016.py | 624 | Author: Samuca brief: returns the int part of number this is a list exercise available on youtube: https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-we can also do it with the method trunc, from math | 223 | en | 0.755651 |
import os
import sys
import time
import random
import string
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
import numpy as np
from utils import CTCLabelConverter, AttnLabelConverter, Averager
from dataset import hiera... | train.py | 14,526 | dataset preparation
see https://github.com/clovaai/deep-text-recognition-benchmark/blob/6593928855fb7abb999a99f428b3e4477d4ae356/dataset.pyL130 'True' to check training progress with validation function. weight initialization for batchnorm. data parallel for multi-GPU ignore [GO] token = ignore index 0 loss averager... | 1,086 | en | 0.638245 |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Quantum Tomography Module
Description:
This module contains functions for performing... | qiskit/tools/qcvv/tomography.py | 37,012 | Dictionary subsclass that includes methods for adding gates to circuits.
A TomographyBasis is a dictionary where the keys index a measurement
and the values are a list of projectors associated to that measurement.
It also includes two optional methods `prep_gate` and `meas_gate`:
- `prep_gate` adds gates to a circ... | 20,126 | en | 0.724804 |
"""Test Pyvista camera parameters."""
import os
import numpy as np
import pyvista as pv
import nibabel as nb
FILE = "/home/faruk/data2/DATA_MRI_NIFTI/derived/sub-04/flattening/sub-04_ses-T2s_segm_rim_CS_LH_v02_borderized_multilaterate_perimeter_chunk_T2star_flat_400x400_voronoi.nii.gz"
OUTDIR = "/home/faruk/data2/DA... | scripts/wip/anim-test_camera.py | 1,810 | Test Pyvista camera parameters.
----------------------------------------------------------------------------- Output directory Normalize Prep pyvista plotter p.camera.roll = 0 Manipulate camera ----------------------------------------------------------------------------- | 273 | en | 0.218185 |
#!/usr/bin/env python3
import torch
import torch.cuda.profiler as profiler
from apex import pyprof
class Foo(torch.jit.ScriptModule):
def __init__(self, size):
super(Foo, self).__init__()
self.n = torch.nn.Parameter(torch.ones(size))
self.m = torch.nn.Parameter(torch.ones(size))
@torc... | apex/pyprof/examples/jit/jit_script_method.py | 689 | !/usr/bin/env python3Initialize pyprof after the JIT stepHook up the forward function to pyprof | 95 | en | 0.680089 |
from pathlib import Path
from typing import List, Optional, Dict, Union, Tuple, Literal, Sequence, Any
import fsspec
import numpy as np
from xarray import DataArray
from dataclasses import asdict, dataclass
import json
from ..io.mrc import mrc_to_dask
from ..io import read
import dask.array as da
import dacite
from xar... | src/fibsem_tools/attrs/attrs.py | 7,200 | see https://github.com/google/neuroglancer/issues/176issuecomment-553027775 neuroglancer wants the axes reported in fortran order we need this for neuroglancer | 159 | en | 0.769762 |
"""A dictionary of module names to pytype overlays.
Some libraries need custom overlays to provide useful type information. Pytype
has some built-in overlays, and additional overlays may be added to the overlays
dictionary. See overlay.py for the overlay interface and the *_overlay.py files
for examples.
Each entry in... | pytype/overlay_dict.py | 1,224 | A dictionary of module names to pytype overlays.
Some libraries need custom overlays to provide useful type information. Pytype
has some built-in overlays, and additional overlays may be added to the overlays
dictionary. See overlay.py for the overlay interface and the *_overlay.py files
for examples.
Each entry in cu... | 501 | en | 0.738299 |
''' Natural language understanding model based on multi-task learning.
This model is trained on two tasks: slot tagging and user intent prediction.
Inputs: user utterance, e.g. BOS w1 w2 ... EOS
Outputs: slot tags and user intents, e.g. O O B-moviename ... O\tinform+moviename
Author : Xueson... | SlotTaggingModel_multitask.py | 19,937 | Natural language understanding model based on multi-task learning.
This model is trained on two tasks: slot tagging and user intent prediction.
Inputs: user utterance, e.g. BOS w1 w2 ... EOS
Outputs: slot tags and user intents, e.g. O O B-moviename ... O inform+moviename
Author : Xuesong Yang
Email : ... | 1,184 | en | 0.737999 |
'''
PipedImagerPQ is a graphics viewer application written in PyQt
that receives its images and commands primarily from another
application through a pipe. A limited number of commands are
provided by the viewer itself to allow saving and some manipulation
of the displayed image. The controlling application, however,... | pviewmod/pipedimagerpq.py | 39,634 | A PyQt graphics viewer that receives images and commands through
a pipe.
A command is a dictionary with string keys. For example,
{ "action":"save",
"filename":"ferret.png",
"fileformat":"png" }
The command { "action":"exit" } will shutdown the viewer.
A Process specifically tailored for creating a P... | 10,008 | en | 0.837004 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
from typing import List, Optional
from omegaconf import OmegaConf
from hydra.core.object_type import ObjectType
from hydra.plugins.config_source import ConfigLoadError, ConfigResult, ConfigSource
class FileConfigSource(ConfigSource):
... | hydra/_internal/core_plugins/file_config_source.py | 2,465 | Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved | 68 | en | 0.940819 |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | heat/tests/test_support.py | 3,748 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under th... | 546 | en | 0.872906 |
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by David O'Brien
# Copyright (c) 2017 David O'Brien
#
# License: MIT
#
"""Exports the Vcom plugin class."""
from SublimeLinter.lint import Linter
class Vcom(Linter):
"""Provides an interface to vcom (Mentor Model... | linter.py | 2,064 | Provides an interface to vcom (Mentor Modelsim).
Override this method to prefix the error message with the lint binary name.
Exports the Vcom plugin class.
linter.py Linter for SublimeLinter3, a code checking framework for Sublime Text 3 Written by David O'Brien Copyright (c) 2017 David O'Brien License: MIT SAMPLE ER... | 923 | en | 0.496943 |
import paho.mqtt.client as mqtt
import time
import argparse
from tinydb import TinyDB, Query
from tinyrecord import transaction
import logging
import sys
import json
import threading
import ssl
from random import randint
CA_ROOT_CERT_FILE = "ag-certificate/AmazonRootCA1.pem"
THING_CERT_FILE = "ag-certificate/..."
THIN... | application/AWS-ag.py | 3,720 | init args parser init logger init opaque DB init clear measures DB on received message store in DB truncate because we will save it again? dont sent if pool is emptylogger.info(f"to_send: {to_send}") connecting to MQTT broker, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) client.enable_lo... | 570 | en | 0.728503 |
# -*- coding: utf-8 -*-
"""
Doors
AOE rider
"""
# Adding to the system path is needed
# because no longer in parent directory
# and I want to run this file as a script
import sys, os
sys.path.append(os.path.abspath('../'))
import farmbot as fb
class Farmer_Doors(fb.Farmbot):
def __init__(self):
fb.Farmbot.__ini... | nodes/doors.py | 2,671 | Doors
AOE rider
-*- coding: utf-8 -*- Adding to the system path is needed because no longer in parent directory and I want to run this file as a script Skills selection (may be empty) Attack Card selection (pick 3) Skills selection (may be empty) Attack Card selection (pick 3) Skills selection (may be empty) Attack ... | 702 | en | 0.829319 |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Modifier_stage2L1Trigger_cff import stage2L1Trigger
from Configuration.Eras.Modifier_stage2L1Trigger_2017_cff import stage2L1Trigger_2017
def L1TCaloStage2ParamsForHW(process):
process.load("L1Trigger.L1TCalorimeter.caloStage2Params_HWConfig_cfi")
... | L1Trigger/Configuration/python/customiseReEmul.py | 19,348 | As of 80X, this ES configuration is needed for *data* GTs (mc tags work w/o)process.CondDBSetup, When available, this will switch to TwinMux input Digis: quiet warning abouts missing Stage-2 payloads, since they won't reliably exist in 2015 data.cutlist=['simDtTriggerPrimitiveDigis','simCscTriggerPrimitiveDigis']for b ... | 900 | en | 0.564245 |
##################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019 #
##################################################
from os import path as osp
from typing import List, Text
import torch
__all__ = ['change_key', 'get_cell_based_tiny_net', 'get_search_spaces', 'get_cifar_models', 'ge... | nas201bench/models/__init__.py | 9,955 | Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019 useful modules Cell-based NAS Models to support the argument being a dict obtain the search space, i.e., a dict mapping the operation name into a python-function for this op The topology search space. The size search space. reload genotype by extra_path NAS searched archi... | 364 | en | 0.800347 |
# Tai Sakuma <tai.sakuma@gmail.com>
from __future__ import print_function
import os
import errno
import logging
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from alphatwirl import mkdir_p
##__________________________________________________________________||
@pytest.fixture... | tests/unit/misc/test_mkdir_p.py | 1,604 | Tai Sakuma <tai.sakuma@gmail.com>__________________________________________________________________||__________________________________________________________________||__________________________________________________________________|| | 237 | en | 0.254384 |
import os, sys, re
import importlib
try:
from PySide.QtGui import *
from PySide.QtCore import *
except:
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from multi_script_editor import scriptEditor
importlib.reload(scriptEditor)
import MaxPlus
q3dsmax = QApp... | python/pw_multiScriptEditor/managers/_3dsmax.py | 1,017 | se.installEventFilter(MaxDialogEvents())se.MaxEventFilter = MaxDialogEvents()se.installEventFilter(se.MaxEventFilter) | 117 | de | 0.173431 |
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | src/python/grpcio/tests/unit/framework/interfaces/face/_future_invocation_asynchronous_event_service.py | 20,358 | A test of the Face layer of RPC Framework.
Concrete subclasses must have an "implementation" attribute of type
test_interfaces.Implementation and an "invoker_constructor" attribute of type
_invocation.InvokerConstructor.
See unittest.TestCase.setUp for full specification.
Overriding implementations must call this imp... | 3,216 | en | 0.909141 |
"""
===========================================
Comparison of F-test and mutual information
===========================================
This example illustrates the differences between univariate F-test statistics
and mutual information.
We consider 3 features x_1, x_2, x_3 distributed uniformly over [0, 1], the
targ... | examples/feature_selection/plot_f_test_vs_mi.py | 1,647 | ===========================================
Comparison of F-test and mutual information
===========================================
This example illustrates the differences between univariate F-test statistics
and mutual information.
We consider 3 features x_1, x_2, x_3 distributed uniformly over [0, 1], the
target d... | 951 | en | 0.900123 |
"""
Tests utils for tagging.
"""
from django.template import Origin
from django.template.loaders.base import Loader
class VoidLoader(Loader):
"""
Template loader which is always returning
an empty template.
"""
is_usable = True
_accepts_engine_in_init = True
def get_template_sources(self,... | tagging/tests/utils.py | 636 | Template loader which is always returning
an empty template.
Tests utils for tagging. | 85 | en | 0.663968 |
from imdbclassifier.train_nn import KTrain
from imdbclassifier.parser_utils_nn import KParseArgs
from time import time
import sys
import os
# Hide warning messages
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
if __name__ == '__main__':
parser = KParseArgs()
args = parser.parse_args()
start_time = time()
... | tasks/natural-language-processing/sentiment-analysis/keras/imdbclassifier/main_nn.py | 827 | Hide warning messages | 21 | en | 0.117596 |
"""Unit tests for Tangent PCA."""
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.spd_matrices import SPDMatrices, SPDMetricAffine
from geomstats.geometry.special_euclidean import SpecialEuclidean
from geomstats.geometry.special_orthogonal import SpecialOrthogonal
from geomstats.learning.... | tests/tests_geomstats/test_pca.py | 4,685 | Unit tests for Tangent PCA. | 27 | en | 0.356922 |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import hashlib
import logging
import os
import re
import selectors
import threading
import time
from contextlib import closing
from pants.base.build_environment import get_buildroot
from ... | src/python/pants/java/nailgun_executor.py | 14,610 | Executes java programs by launching them in nailgun server.
If a nailgun is not available for a given set of jvm args and classpath, one is launched and re-
used for the given jvm args and classpath on subsequent runs.
Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun
stdout.
Matches o... | 2,587 | en | 0.807792 |
import abc
import configparser
import json
import os
from typing import Any, Dict, Optional
from pystratum_backend.RoutineWrapperGeneratorWorker import RoutineWrapperGeneratorWorker
from pystratum_backend.StratumStyle import StratumStyle
from pystratum_common.Util import Util
class CommonRoutineWrapperGeneratorWorke... | pystratum_common/backend/CommonRoutineWrapperGeneratorWorker.py | 6,523 | Class for generating a class with wrapper methods for calling stored routines in a MySQL database.
Generates the wrapper class.
Object constructor.
:param PyStratumStyle io: The output decorator.
Reads parameters from the configuration file.
Returns the metadata of stored routines.
:rtype: dict
Generate a class heade... | 1,885 | en | 0.253504 |
import sys
import psycopg2
import os
# Inicialização de parâmetros
database = os.environ['DATABASE_URL']
# Cria um banco de dados Postgres para armazenar informações, caso não exista.
def carregar_bd():
# Conecta ao banco de dados na URL especificada
connection = psycopg2.connect(database)
# Cria um curso... | database.py | 9,300 | Inicialização de parâmetros Cria um banco de dados Postgres para armazenar informações, caso não exista. Conecta ao banco de dados na URL especificada Cria um cursor do banco de dados, que é um iterador que permite navegar e manipular os registros do bd, e o atribui a uma variável. Carrega os comandos a partir do scrip... | 1,256 | pt | 0.998337 |
"""
neuropredict : easy and comprehensive predictive analysis.
"""
from __future__ import print_function
__all__ = ['run', 'cli', 'get_parser']
import argparse
import os
import sys
import textwrap
import traceback
import warnings
import matplotlib
import matplotlib.pyplot as plt
from sys import version_info
from os.... | neuropredict/run_workflow.py | 40,141 | Main entry point.
Parser to specify arguments and their defaults.
Imports all the specified feature sets and organizes them into datasets.
Parameters
----------
method_list : list of callables
Set of predefined methods returning a vector of features for a given sample id and location
out_dir : str
Path to the ... | 8,277 | en | 0.754626 |
from typing import Any, Callable, List, Optional, Tuple
import gym
import numpy as np
from tianshou.env.worker import EnvWorker
try:
import ray
except ImportError:
pass
class _SetAttrWrapper(gym.Wrapper):
def set_env_attr(self, key: str, value: Any) -> None:
setattr(self.env, key, value)
... | tianshou/env/worker/ray.py | 1,913 | Ray worker used in RayVectorEnv.
type: ignore self.action is actually a handle | 80 | en | 0.71121 |
"""
Base settings for jackergram 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 environ
ROOT_DIR = environ.Path(__file__) - 3 # (jackergram/confi... | config/settings/base.py | 10,200 | Base settings for jackergram 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/
(jackergram/config/settings/base.py - 3 = jackergram/) Load operating system env... | 5,207 | en | 0.535568 |
import numpy as np
import scipy.stats as scst
import scipy.special as scsp
import scipy.optimize as scopt
import tensorflow as tf
import tensorflow_probability as tfp
import pickle
import os
import sys
try:
import gpflow
except:
raise Exception("Requires gpflow!")
import utils
def fit_gp(
X,
Y,
... | functions.py | 26,122 | X: n x d
l: d
X: n x d
l: d
use gpflow to get the hyperparameters for the function concentration, rate = 1.1, 1./0.5 (in BoRisk) => shape, scale = 1.1, 0.5 shape, scale "Initialize likelihood variance at the mode of the prior (from BoRisk)" 1e-4 zmin, zmax only used for continuous z xs = np.random.rand(1000, xdim) * ... | 1,362 | en | 0.643888 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
from ..pipelineState import PipelineStateInterface
from ..data import BrewPipeDataFrame
__author__ = 'Dominik Meyer <meyerd@mytum.de>'
class NumpyNullPreprocessor(PipelineStateInterface):
"""
This is an example class of preprocessor,... | brewPipe/preprocess/numpy_null.py | 2,356 | This is an example class of preprocessor, that
takes numpy data from the data loader and outputs
numpy data again. Basically, it does nothing, and is
just a testcase to get some interface definitions going.
:param intermediate_directory: Directory, where the
intermediate pandas dataframe should be persisted
to.... | 414 | en | 0.857359 |
# -*- coding: utf-8 -*-
"""
mslib.msui._tests.test_mscolab_project
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module is used to test mscolab-project related gui.
This file is part of mss.
:copyright: Copyright 2019 Shivashis Padhi
:copyright: Copyright 2019-2021 by the mss team, see AUTHORS... | mslib/msui/_tests/test_mscolab_project.py | 7,329 | mslib.msui._tests.test_mscolab_project
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module is used to test mscolab-project related gui.
This file is part of mss.
:copyright: Copyright 2019 Shivashis Padhi
:copyright: Copyright 2019-2021 by the mss team, see AUTHORS.
:license: APACHE-2.0, see LICENSE for details.
Lic... | 917 | en | 0.796915 |
#!/usr/bin/python
# this script will update the versions in packages and innosetup installer files to match that in config.h
import plistlib, os, datetime, fileinput, glob, sys, string
scriptpath = os.path.dirname(os.path.realpath(__file__))
projectpath = os.path.abspath(os.path.join(scriptpath, os.pardir))
IPLUG2_R... | BigLittleGain/scripts/update_installer_version.py | 3,036 | !/usr/bin/python this script will update the versions in packages and innosetup installer files to match that in config.h MAC INSTALLER range = number of items in the installer (VST 2, VST 3, app, audiounit, aax) replacestrs(plistpath, "//Apple//", "//Apple Computer//"); WIN INSTALLER | 288 | en | 0.563511 |
#
# A general spatial method class
#
import pybamm
import numpy as np
from scipy.sparse import eye, kron, coo_matrix, csr_matrix
class SpatialMethod:
"""
A general spatial methods class, with default (trivial) behaviour for some spatial
operations.
All spatial methods will follow the general form of S... | pybamm/spatial_methods/spatial_method.py | 13,982 | A general spatial methods class, with default (trivial) behaviour for some spatial
operations.
All spatial methods will follow the general form of SpatialMethod in
that they contain a method for broadcasting variables onto a mesh,
a gradient operator, and a diverence operator.
Parameters
----------
mesh : :class: `pyb... | 8,010 | en | 0.664828 |
import os
import numpy as np
def save_gif(gif_fname, images, fps):
"""
To generate a gif from image files, first generate palette from images
and then generate the gif from the images and the palette.
ffmpeg -i input_%02d.jpg -vf palettegen -y palette.png
ffmpeg -i input_%02d.jpg -i palette.png -... | video_prediction/utils/ffmpeg_gif.py | 2,840 | To generate a gif from image files, first generate palette from images
and then generate the gif from the images and the palette.
ffmpeg -i input_%02d.jpg -vf palettegen -y palette.png
ffmpeg -i input_%02d.jpg -i palette.png -lavfi paletteuse -y output.gif
Alternatively, use a filter to map the input images to both th... | 618 | en | 0.391322 |
# -*- coding: utf-8 -*-
import datetime
import json
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
class DBEngine(object):
def __init__(self, db_uri):
"""
db_uri = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset=utf8mb4'
"""
... | httprunner/database/engine.py | 2,510 | db_uri = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset=utf8mb4'
Try to decode value of table
datetime.datetime-->string
datetime.date-->string
json str-->dict
:param row:
:return:
-*- coding: utf-8 -*- | 230 | en | 0.393777 |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import glob
import sys
class Binutils(AutotoolsPackage, GNUMirrorPackage):
"""GNU binutils, whic... | var/spack/repos/builtin/packages/binutils/package.py | 5,626 | GNU binutils, which contain the linker, assembler, objdump and others
Copyright 2013-2020 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) Prior to 2.30, gold did not distribute the generated files ... | 906 | en | 0.779936 |
#
# Copyright (c) 2021 Citrix Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | build/lib/nssrc/com/citrix/netscaler/nitro/resource/config/vpn/vpnvserver_vpnnexthopserver_binding.py | 7,327 | Binding class showing the vpnnexthopserver that can be bound to vpnvserver.
converts nitro response into object and returns the object array in case of get request.
Returns the value of object identifier argument
Use this API to count vpnvserver_vpnnexthopserver_binding resour... | 1,854 | en | 0.735865 |
import csv
import json
import random
import re
import socket
import string
import tempfile
from base64 import b64decode, b64encode
from pathlib import Path
import ipaddress
from subprocess import check_output, CalledProcessError, TimeoutExpired
from yaml import safe_load
from charmhelpers.core import hookenv
from char... | lib/charms/layer/kubernetes_master.py | 16,541 | Delete a given secret id.
In 1.19+, file-based authentication was deprecated in favor of webhook
auth. Write out generic files that inform the user of this.
Freeze the service CIDR. Once the apiserver has started, we can no
longer safely change this value.
Generate a random string compliant with RFC 1123.
https://kub... | 3,088 | en | 0.858765 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.