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 |
|---|---|---|---|---|---|---|
###############################################################################
# 1) This is a test case to verify that the deposit case works fine.
# 2) It also checks whether duplicate requests are processed correctly.
###############################################################################
############... | config/config1_3_add_server_1.py | 2,428 | 1) This is a test case to verify that the deposit case works fine. 2) It also checks whether duplicate requests are processed correctly. Client Settings The client configuration is a dictionary where each key is a list of all the clients of a particular bank. Each entry in the list is a key:value pair of all th... | 849 | en | 0.853306 |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import operator
import os
import platform
import sys
from setup... | env/env/lib/python3.6/site-packages/setuptools/_vendor/packaging/markers.py | 9,837 | An invalid marker was found, users should refer to PEP 508.
An invalid operation was attempted on a value that doesn't support it.
A name was attempted to be used that does not exist inside of the
environment.
Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment i... | 1,750 | en | 0.80725 |
# --------------------- Telegram.py --------------------------------- #
# Allows the integration with Telegram Bot.
# ------------------------------------------------------------------- #
from numpy.core.fromnumeric import around, std
import requests
import Elo
from Models import Models
import Helper
import pandas as p... | NBABet/Telegram.py | 2,992 | Allows integration with the Telegram Bot.
--------------------- Telegram.py --------------------------------- Allows the integration with Telegram Bot. ------------------------------------------------------------------- Standardize the DataFrame | 249 | en | 0.263577 |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 09:47:07 2019
@author: student
"""
import numpy as np
import os
np.set_printoptions(precision=3, linewidth=200, suppress=True)
LINE_WIDTH = 60
N_SIMULATION = 4000 # number of time steps simulated
dt = 0.002 # controller time step
q0 ... | exercizes/ur5_conf.py | 1,860 | Created on Thu Apr 18 09:47:07 2019
@author: student
-*- coding: utf-8 -*- number of time steps simulated controller time step initial configuration REFERENCE SINUSOIDAL TRAJECTORY amplitude phase frequency (time 2 PI) weight of end-effector task weight of joint posture task weight of the torque bounds proportional ... | 543 | en | 0.683743 |
"""
Contains Catalyst DAO implementations.
"""
from django.conf import settings
from restclients.mock_http import MockHTTP
from restclients.dao_implementation import get_timeout
from restclients.dao_implementation.live import get_con_pool, get_live_url
from restclients.dao_implementation.mock import get_mockdata_url
i... | restclients/dao_implementation/catalyst.py | 2,679 | The File DAO implementation returns generally static content. Use this
DAO with this configuration:
RESTCLIENTS_CANVAS_DAO_CLASS =
'restclients.dao_implementation.catalyst.File'
This DAO provides real data. It requires further configuration, e.g.
For cert auth:
RESTCLIENTS_CATALYST_CERT_FILE='/path/to/an/authorized... | 779 | en | 0.61775 |
import hashlib
import math
from http import HTTPStatus
from quart import jsonify, url_for, request
from lnurl import LnurlPayResponse, LnurlPayActionResponse, LnurlErrorResponse # type: ignore
from lnbits.core.services import create_invoice
from lnbits.utils.exchange_rates import get_fiat_rate_satoshis
from . import... | lnbits/extensions/lnurlp/lnurl.py | 3,361 | type: ignore allow some fluctuation (as the fiat price may have changed between the calls) | 90 | en | 0.972904 |
# AMZ-Driverless
# Copyright (c) 2019 Authors:
# - Huub Hendrikx <hhendrik@ethz.ch>
#
# 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 ... | rbb_tools/src/rbb_tools/plugins/rviz_recorder.py | 8,669 | AMZ-Driverless Copyright (c) 2019 Authors: - Huub Hendrikx <hhendrik@ethz.ch> 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,... | 1,585 | en | 0.845342 |
"""
Min Stack
-----
A LIFO abstract data type that serves as a collection of elements.
Supports retrieving the min from the stack in constant time.
"""
class MinStack(object):
def __init__(self):
"""
Attributes:
data (arr): data stored in the stack
minimum (arr): minimum values of data stored
"""
self... | libalgs-py/data_structures/min_stack.py | 1,261 | Attributes:
data (arr): data stored in the stack
minimum (arr): minimum values of data stored
Returns whether or not the stack is empty.
Time Complexity: O(1)
Returns:
bool: whether or not the stack is empty
Returns the last item on the stack but doesn't remove it.
Time Complexity: O(1)
Retur... | 733 | en | 0.804399 |
# 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 ... | sdk/keyvault/azure-mgmt-keyvault/azure/mgmt/keyvault/v2021_04_01_preview/_key_vault_management_client.py | 6,327 | The Azure management API provides a RESTful set of web services that interact with Azure Key Vault.
:ivar vaults: VaultsOperations operations
:vartype vaults: azure.mgmt.keyvault.v2021_04_01_preview.operations.VaultsOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype... | 2,944 | en | 0.611251 |
import os
import time
import requests
from bs4 import BeautifulSoup
import datetime
from twilio.rest import Client
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import math
class Data():
def __init__(self,link): # Automatically stores the data from parsed link as the object's attribute
... | app.py | 11,219 | Automatically stores the data from parsed link as the object's attribute Parses the site's HTML code Automatically stores the data from parsed link as the object's attribute (Same constructor as Class Data) Creates SMS notification with the COVID data for each island Returns the data from today: Gathering all the data... | 2,268 | en | 0.77367 |
#!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.script import *
from test_framework.mininode import *
from test_framework.beerchain import *
from test_framework.beerchainconfig import *
from test_framework.blocktools import *
i... | test/functional/beerchain_gas_limit.py | 2,179 | !/usr/bin/env python3 Create a tx with 2000 outputs each with a gas stipend of 5*10^8 calling the contract. We may want to reject transactions which exceed the gas limit outright. | 179 | en | 0.794427 |
import QueueLinkedList as queue
"""
n1
/\
n2 n3
/\ /\
n4 n5 n6 n7
"""
class BinaryTree:
def __init__(self, size) -> None:
self.customList = size * [None]
self.lastUsedIndex = 0
self.maxSize = size
def inserNode(self, value):
if self.lastUsedIndex + 1 == self.m... | Trees/BinaryTreePL.py | 2,622 | root -> left -> right left -> root -> right left -> right -> root | 65 | en | 0.469026 |
"""hackernews URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
... | hackernews/hackernews/urls.py | 773 | hackernews URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... | 626 | en | 0.614812 |
import numpy as np
import cv2 as cv
import math
from server.cv_utils import *
def filterGaussian(img,size=(5,5),stdv=0):
"""Summary of filterGaussian
This will apply a noise reduction filter, we will use s 5x5 Gaussian filter to smooth
the image to lower the sensitivity to noise. (The smaller the size... | CarlaDriving/server/lane_detection/utils.py | 8,242 | Calculates the coordinates for a road lane
Combines line segments into one or two lanes
Note: By looking at the slop of a line we can see if it is on the left side (m<0) or right (m>0)
The Canny detector is a multi-stage algorithm optimized for fast real-time edge detection,
which will reduce complexity of the ima... | 2,940 | en | 0.856531 |
"""
A small utility aiming to create programatically sound.
"""
from __future__ import annotations
from importlib import metadata
__version__ = metadata.version("sarada")
| sarada/__init__.py | 173 | A small utility aiming to create programatically sound. | 55 | en | 0.821822 |
import imp
from tkinter import *
from sys import exit
from teste.testeCores.corFunc import formatar
conta2x2 = 'x2y=5\n3x-5y=4'
root = Tk()
text = Text(root, width=20, height=10)
text.config(font='arial 20 bold')
text.insert(END, conta2x2)
text.pack()
def q_evento(event):
exit()
root.bind('q', q_evento)
cs = cont... | 06-sistemaLinear/sistemaLinear_v11/teste/testeCores/cores2.py | 1,001 | text.tag_add("y1", p1, p2) text.tag_config("y1", background="black", foreground="green") | 88 | en | 0.152978 |
# 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 t... | cotyledon/_service.py | 8,126 | Base class for a service
This class will be executed in a new child process/worker
:py:class:`ServiceWorker` of a :py:class:`ServiceManager`. It registers
signals to manager the reloading and the ending of the process.
Methods :py:meth:`run`, :py:meth:`terminate` and :py:meth:`reload` are
optional.
Service Worker Wra... | 2,742 | en | 0.901223 |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
def GetPr... | tools/metrics/histograms/PRESUBMIT.py | 5,276 | Checks that histograms.xml is pretty-printed and well-formatted.
Validates all histograms in the file are obsolete.
Validates histogram prefixes in specified file.
Runs pretty-print command for specified file.
Validates histograms format and index file.
Does corresponding validations if histograms.xml or enums.xml is c... | 1,817 | en | 0.700777 |
import cv2
import pose_detection as pose_d
pose_model = pose_d.load_pose_model('pre_trained\AFLW2000.pkl')
def detect_face(img_PATH, model_PATH):
# Load the cascade
face_cascade = cv2.CascadeClassifier(model_PATH)
# Read the input image
img = cv2.imread(img_PATH)
# Convert into grayscale
gray = cv2.cvtCo... | face_detection_cv2.py | 2,040 | Load the cascade Read the input image Convert into grayscale Detect faces Draw rectangle around the faces Display the outputcv2_imshow(img) TO DO may want to return face at some point as well Load the cascade To capture video from webcam. To use a video file as input cap = cv2.VideoCapture('filename.mp4') Read the f... | 501 | en | 0.800323 |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the isBalanced function below.
def isBalanced(s):
left_symbol = [ '{', '[', '(']
right_symbol = [ '}', ']', ')']
# fast checking of symbol counting equality
for i in range(3):
left_count = s.count( left_symbo... | Data Structures/Stack/Balanced Bracket/balanced_bracket.py | 1,310 | !/bin/python3 Complete the isBalanced function below. fast checking of symbol counting equality push into stack pop from stack and compare with left symbol match of {}, [], or () | 178 | en | 0.798362 |
import unittest
import attr
import numpy as np
from robogym.randomization.env import (
EnvActionRandomizer,
EnvObservationRandomizer,
EnvParameterRandomizer,
EnvRandomization,
EnvSimulationRandomizer,
build_randomizable_param,
)
from robogym.randomization.observation import ObservationRandomiz... | robogym/randomization/tests/test_randomization.py | 4,093 | Test functionality of basic randomizer.
Non randomizable parameter. Make sure register duplicate parameter is not allowed. | 124 | en | 0.431535 |
# COMBINATION:
# combination is all the different ways that we can group something where the order does not matter.
# PERMUTATION:
# permutation is all the different ways that we can group something where the order does matter.
import itertools
my_list=[1,2,3]
my_combinations=itertools.combinations(my_list,2)# here fi... | term06 (permutation and combination).py | 1,174 | COMBINATION: combination is all the different ways that we can group something where the order does not matter. PERMUTATION: permutation is all the different ways that we can group something where the order does matter. here first arguement is a list and second arguement is how many items we want in a group. it is r of... | 501 | en | 0.900267 |
import logging
from flask import request, flash, abort, Response
from flask_admin import expose
from flask_admin.babel import gettext, ngettext, lazy_gettext
from flask_admin.model import BaseModelView
from flask_admin.model.form import wrap_fields_in_fieldlist
from flask_admin.model.fields import ListEditableFieldLi... | sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py | 20,150 | MongoEngine model scaffolding.
Constructor
:param model:
Model class
:param name:
Display name
:param category:
Display category
:param endpoint:
Endpoint
:param url:
Custom URL
:param menu_class_name:
Optional class name for the menu item.
:param menu_icon_type:
Optional icon. Possible ico... | 2,894 | en | 0.632425 |
import requests, json, os, time
from PIL import Image
from io import BytesIO
import img2pdf
class jumpplus_downloader:
def __init__(self):
self.file=0
self.h=1200
self.w=760
def auto_list_download(self, url, next=False, sleeptime=20,pdfConversion=True):
self.json_download(url)
... | py/lib/jumpplus_downloader.py | 3,931 | Counterfeit User agent for absolutely successfully connection.A simple Json Dumper for debugging. | 97 | en | 0.904576 |
import os
import sys
import numpy as np
from PIL import Image
import torch
#TODO - add save function, these functions can be used to check movement
def crop_image(image_array, bb):
image_array_copy = image_array.clone()
y_min = int(bb[0])
x_min = int(bb[1])
height = int(bb[2])
width = int(bb[3])
... | pneumoRL/image_util.py | 2,160 | TODO - add save function, these functions can be used to check movement Keep image size, set pixel value outside of bounding box as 0image_array_copy.unsqueeze_(0) | 163 | en | 0.776656 |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PRO... | tests/riscv/vector/vector_wide_operand_conflict_force.py | 4,580 | Copyright (C) [2020] Futurewei Technologies, Inc. FORCE-RISCV is 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 THIS SOFTWARE IS PROVIDED ON AN "AS IS" ... | 1,345 | en | 0.8459 |
import numpy as np
import matplotlib.pyplot as plt
def estimate(particles, weights):
"""returns mean and variance of the weighted particles"""
pos = particles
mean = np.average(pos, weights=weights, axis=0)
var = np.average((pos - mean)**2, weights=weights, axis=0)
return mean, var
def s... | 002_Particle_Filter/Particle_Filter.py | 1,939 | returns mean and variance of the weighted particles
avoid round-off error resample according to indexes初始真实状态系统过程噪声的协方差(由于是一维的,这里就是方差)测量的协方差共进行75次粒子数,越大效果越好,计算量也越大初始分布的方差plt.hist(x_P,N, normed=True)实际测量值测量值的输出向量估计值print(x_out)更新粒子print(z_update)计算权重估计重采样保存数据print(x_out) | 272 | zh | 0.333185 |
#
# PySNMP MIB module ADIC-INTELLIGENT-STORAGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADIC-INTELLIGENT-STORAGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:13:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | pysnmp-with-texts/ADIC-INTELLIGENT-STORAGE-MIB.py | 44,179 | PySNMP MIB module ADIC-INTELLIGENT-STORAGE-MIB (http://snmplabs.com/pysmi) ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADIC-INTELLIGENT-STORAGE-MIB Produced by pysmi-0.3.4 at Wed May 1 11:13:36 2019 On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 Using Python version 3.7.3 (d... | 350 | en | 0.435675 |
"""Tests to ensure that the html.parser tree builder generates good
trees."""
from pdb import set_trace
import pickle
from bs4.testing import SoupTest, HTMLTreeBuilderSmokeTest
from bs4.builder import HTMLParserTreeBuilder
from bs4.builder._htmlparser import BeautifulSoupHTMLParser
class HTMLParserTreeBuilderSmokeTes... | virtual/lib/python3.6/site-packages/bs4/tests/test_htmlparser.py | 1,688 | Unlike most tree builders, HTMLParserTreeBuilder and will
be restored after pickling.
Verify that our HTMLParser subclass implements error() in a way
that doesn't cause a crash.
Tests to ensure that the html.parser tree builder generates good
trees.
html.parser can't handle namespaced doctypes, so skip this one. html... | 469 | en | 0.867614 |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
import settings.base
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'profiles.views.index', name='index'),
url(r'^accou... | explorind_project/explorind_project/urls.py | 1,451 | Uncomment the next two lines to enable the admin: Examples: url(r'^$', 'explorind_project.views.home', name='home'), url(r'^explorind_project/', include('explorind_project.foo.urls')), Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), Uncomm... | 378 | en | 0.457299 |
"""GoodWe PV inverter numeric settings entities."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
import logging
from goodwe import Inverter, InverterError
from homeassistant.components.number import NumberEntity, NumberEntityDescription
from hom... | homeassistant/components/goodwe/number.py | 3,529 | Class describing Goodwe number entities.
Required values when describing Goodwe number entities.
Inverter numeric setting entity.
Initialize the number inverter setting entity.
GoodWe PV inverter numeric settings entities.
Inverter model does not support this setting | 269 | en | 0.700365 |
# -*- coding: utf-8 -*-
"""Configuration file for sniffer."""
# pylint: disable=superfluous-parens,bad-continuation
import time
import subprocess
from sniffer.api import select_runnable, file_validator, runnable
try:
from pync import Notifier
except ImportError:
notify = None
else:
notify = Notifier.notif... | scent.py | 2,255 | Run a command-line program and display the result.
Run targets for Python.
Launch the coverage report.
Show a user notification.
Configuration file for sniffer.
-*- coding: utf-8 -*- pylint: disable=superfluous-parens,bad-continuation unique per run | 251 | en | 0.730372 |
"""Provide useful functions for using PTLFlow."""
# =============================================================================
# Copyright 2021 Henrique Morimitsu
#
# 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... | ptlflow/__init__.py | 8,679 | Download the main scripts and configs to start working with PTLFlow.
Return an instance of a chosen model.
The instance can have configured by he arguments, and load some existing pretrained weights.
Note that this is different from get_model_reference(), which returns a reference to the model class. The instance,
re... | 2,819 | en | 0.771262 |
# _*_ coding: utf-8 _*_
"""
Created by Allen7D on 2018/5/12.
"""
from app import create_app
__author__ = 'Allen7D'
from app.models.base import db
from app.models.user import User
app = create_app()
with app.app_context():
with db.auto_commit():
# 创建一个超级管理员
user = User()
user.openid = '99... | fake.py | 757 | Created by Allen7D on 2018/5/12.
_*_ coding: utf-8 _*_ 创建一个超级管理员 创建一个普通管理员 | 76 | zh | 0.730702 |
import requests
import pprint
from config import API_KEY
base_url = f'https://api.telegram.org/bot{API_KEY}/'
api_response = requests.get(base_url + 'getUpdates').json()
for update in api_response['result']:
message = update['message']
chat_id = message['chat']['id']
text = message['text']
reply_... | telegramsLibs/api_telega_intro.py | 494 | pprint.pprint(api_response['result'][0]) | 40 | en | 0.238209 |
# Metafier V2: writes directly to output.mc
# Uses numpy and memoization to speed up a crap ton & compress data a bit
# ===REQUIRES metatemplate11.mc===
import golly as g
import numpy as np
from shutil import copyfile
#Get the selection
selection = g.getselrect()
if not selection: g.exit("No selection.")
... | MetafierV2.py | 3,190 | Metafier V2: writes directly to output.mc Uses numpy and memoization to speed up a crap ton & compress data a bit ===REQUIRES metatemplate11.mc===Get the selectionGet the cells in the selectionPseudo-convolution, to detect diagonal neighbors +1 +0 +2 +0 *16 +0 +4 +0 +8Remove all B/S cells5632 is starting point of ... | 676 | en | 0.796019 |
#!/bin/env
"""
Help new users configure the database for use with social networks.
"""
import os
from datetime import datetime
# Fix Python 2.x.
try:
input = raw_input
except NameError:
pass
import django
from django.conf import settings
from django.core.management.utils import get_random_secret_key
BASE_DI... | configure_new.py | 3,284 | Help new users configure the database for use with social networks.
!/bin/env Fix Python 2.x. DEBUG = True, for Django >= 1.7 must be < Django 1.7TODO: full list providers raw_input('Please enter a value.') | 207 | en | 0.456013 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to demonstrate vaspy.incar functionality.
"""
import argparse
import vaspy
import vaspy.incar
from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger
LOGLEVEL = DEBUG
logger = getLogger(__name__)
fmt = "%(asctime)s %(levelname)s %(name)s :%(messa... | scripts/vaspy-incar.py | 1,584 | Script to demonstrate vaspy.incar functionality.
!/usr/bin/env python3 -*- coding: utf-8 -*- if python 3.8 lint_msg:= incar.lint_all() can be used... | 150 | en | 0.516579 |
'''
blackbody.py - Color of thermal blackbodies.
Description:
Calculate the spectrum of a thermal blackbody at an arbitrary temperature.
Constants:
PLANCK_CONSTANT - Planck's constant, in J-sec
SPEED_OF_LIGHT - Speed of light, in m/sec
BOLTZMAN_CONSTANT - Boltzman's constant, in J/K
SUN_TEMPERATURE - Surface... | colorpy/colorpy-0.1.0/blackbody.py | 6,812 | Given a temperature (K), return the xyz color of a thermal blackbody.
Draw a color vs temperature plot for the given temperature range.
Draw a patch plot of blackbody colors for the given temperature range.
Get the monochromatic specific intensity for a blackbody -
wl_nm = wavelength [nm]
T_K = temperature [K... | 3,329 | en | 0.778121 |
import mugReader
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class readMugRFID(Resource):
def get(self):
return {'mugId': mugReader.readMug()}
api.add_resource(brewSettings, '/mugReader/')
if __name__ == "__main__":
#remove host for production... | endpoints/mugReader.py | 353 | remove host for production | 26 | en | 0.730339 |
#!/usr/bin/env python
#from .core import *
import numpy as np
import pandas as pd
import shutil
import urllib
import urlparse
from os.path import splitext, basename
import os
from os import sys, path
from pprint import pprint
import StringIO
import db
from gp import *
from core import *
from IPython.core.debugger impor... | database/task_class/annotation.py | 753 | !/usr/bin/env pythonfrom .core import * | 39 | en | 0.220965 |
# -*- coding: utf-8 -*-
import io
import json
import os
import sys
import shutil
from os import path
import django
from django.core.management.base import CommandError
from django.core.management.templates import TemplateCommand
from django.conf import settings
import blueapps
PY_VER = sys.version
class Command(Tem... | blueapps/contrib/bk_commands/management/commands/startweixin.py | 7,390 | -*- coding: utf-8 -*- 先获取原内容 if some directory is given, make sure it's nicely expanded Setup a stub settings environment for template rendering Ignore some files as they cause various breakages. Only rewrite once 修改文件 获取原先的 default 文件并对其进行追加和覆盖 打开覆盖前的文件和替换的 json 文件 获取 json 数据内容 根据 key 进行替换会追加内容 获得 key 值 寻找 key 值所在位置 获... | 471 | zh | 0.88107 |
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... | cryptoapis/model/coins_forwarding_success_data.py | 12,529 | 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... | 6,671 | en | 0.809589 |
#!usr/bin/env python3.7
#-*-coding:utf-8-*-
import json
import discord
PATH = "config.json"
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstan... | src/utils/config.py | 2,331 | !usr/bin/env python3.7-*-coding:utf-8-*- | 40 | en | 0.483934 |
from __future__ import unicode_literals
import pytest
import itertools
import boto
import boto3
from botocore.exceptions import ClientError
from boto.exception import EC2ResponseError
from boto.ec2.instance import Reservation
import sure # noqa
from moto import mock_ec2_deprecated, mock_ec2
import pytest
from tests... | tests/test_ec2/test_tags.py | 16,969 | noqa cm.value.request_id.should_not.be.none cm.value.request_id.should_not.be.none cm.value.request_id.should_not.be.none cm.value.request_id.should_not.be.none cm.value.request_id.should_not.be.none Cleanup of instance Check whether tag is present with correct value Fetch the volume again Check whether tag is present ... | 535 | en | 0.400904 |
'''define the config file for ade20k and resnet101os16'''
import os
from .base_cfg import *
# modify dataset config
DATASET_CFG = DATASET_CFG.copy()
DATASET_CFG.update({
'type': 'ade20k',
'rootdir': os.path.join(os.getcwd(), 'ADE20k'),
})
# modify dataloader config
DATALOADER_CFG = DATALOADER_CFG.copy()
# mod... | ssseg/cfgs/deeplabv3/cfgs_ade20k_resnet101os16.py | 1,192 | define the config file for ade20k and resnet101os16
modify dataset config modify dataloader config modify optimizer config modify losses config modify segmentor config modify inference config modify common config | 214 | en | 0.326299 |
# Generated by Django 2.1.2 on 2018-11-01 14:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("jbank", "0024_auto_20180425_1704"),
]
operations = [
migrations.AddField(
model_name="payout",
name="reference",
... | jbank/migrations/0025_auto_20181101_1430.py | 644 | Generated by Django 2.1.2 on 2018-11-01 14:30 | 45 | en | 0.609097 |
import os
import sys
import numpy as np
import caffe
import argparse
parser = argparse.ArgumentParser(description='Computes 5-fold cross-validation results over Twitter five-agrees dataset')
parser.add_argument('-ov', '--oversampling', help='Enables (1) or disables (0) oversampling')
args = parser.parse_args()
if ar... | compute_cross_validation_accuracy.py | 3,475 | Update paths for this subset Store images in a list Check if we have reached the end Add the line to the list Load network Loop through the ground truth file, predict each image's label and store the wrong ones Load image Make a forward pass and get the score Check if the prediction was correct or not Update label coun... | 401 | en | 0.851917 |
"""
Make sure that tiddler fields which are not strings
are stringified, otherwise, the text serialization will
assplode.
"""
from tiddlyweb.serializer import Serializer
from tiddlyweb.model.tiddler import Tiddler
def setup_module(module):
pass
def test_float_field():
tiddler = Tiddler('foo', 'bar')
t... | test/test_tiddler_fields_as_strings.py | 460 | Make sure that tiddler fields which are not strings
are stringified, otherwise, the text serialization will
assplode. | 118 | en | 0.848102 |
# a simple script to rename multiple files
import os
import re
path = 'myimages/'
files = os.listdir(path)
files.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])
for i, file in enumerate(files):
os.rename(path + file, path + "rename_{}".format(i)+".jpg")
print('do... | simple_task_python/rename.py | 326 | a simple script to rename multiple files | 40 | en | 0.616114 |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# vcdomainprovisioningconfig filter
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------------------------------... | vc/migrations/0010_vcdomainprobvisioningconfig_vcfilter.py | 860 | -*- coding: utf-8 -*- ---------------------------------------------------------------------- vcdomainprovisioningconfig filter ---------------------------------------------------------------------- Copyright (C) 2007-2019 The NOC Project See LICENSE for details ----------------------------------------------------------... | 364 | en | 0.249775 |
# Overloading Methods
class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.coords = (self.x, self.y)
def move(self, x, y):
self.x += x
self.y += y
# Overload __dunder__
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
... | ObjectOrientedProgramming/OOPpart4.py | 1,356 | Overloading Methods Overload __dunder__ this math does not alway work out correctly remeber float comparisionsreturn self.length() == p.length need to __str__ to represent the output of overloaded | 196 | en | 0.719853 |
# Copyright 2015 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... | examples/cifar10/cifar10.py | 14,656 | Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measures the sparsity of activations.
Args:
x: Tensor
Returns:
nothing
Add summaries for losses in CIFAR-10 model.
Generates moving average for all losses and associated summaries for
vi... | 5,566 | en | 0.792164 |
# Funcoes servem para quando tivermos coisas repetitivas poder simplificar o programa
def lin(): # para definir um afuncao ela tem que ter parenteses no finalk
print('=-'*30)
lin()
print('Bem Vindo')
lin()
nome = str(input('Qual seu nome? '))
lin()
print(f'Tenha um otimo dia {nome}!')
lin()
def mensagem(msg):... | modulo 3/aulas/4.0 - Funcoes.py | 490 | Funcoes servem para quando tivermos coisas repetitivas poder simplificar o programa para definir um afuncao ela tem que ter parenteses no finalk A mensagem que vai aparecer aqui o usuario vai digitar quando chamar a funcao | 222 | pt | 0.936325 |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
from .generation import (
TRANSFORM_FACTORIES,
colorspace_factory,
group_transform_factory,
look_factory,
named_transform_factory,
produce_transform,
transform_factory,
transform_factory_clf_tra... | opencolorio_config_aces/config/__init__.py | 1,959 | SPDX-License-Identifier: BSD-3-Clause Copyright Contributors to the OpenColorIO Project. | 88 | en | 0.556001 |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 15:49:49 2017
@author: tkoller
"""
import numpy as np
import numpy.linalg as nLa
from ..utils import unavailable
try:
import matplotlib.pyplot as plt
_has_matplotlib = True
except:
_has_matplotlib = False
@unavailable(not _has_matplotlib, "matplotlib")
... | safe_exploration/visualization/utils_visualization.py | 2,572 | Plot an ellipsoid in 2D
TODO: Untested!
Parameters
----------
p: 3x1 array[float]
Center of the ellipsoid
q: 3x3 array[float]
Shape matrix of the ellipsoid
ax: matplotlib.Axes object
Ax on which to plot the ellipsoid
Returns
-------
ax: matplotlib.Axes object
The Ax containing the ellipsoid
Plot an e... | 912 | en | 0.489268 |
# -*- coding: utf-8 -*-
"""
Created on 2013-2014
Author : Edouard Cuvelier
Affiliation : Université catholique de Louvain - ICTEAM - UCL Crypto Group
Address : Place du Levant 3, 1348 Louvain-la-Neuve, BELGIUM
email : firstname.lastname@uclouvain.be
"""
from numpy import *
import gmpy
from Crypto.Random.random import... | mathTools/field.py | 34,962 | This class defines extension fields and inherits field methods.
Depending on the degree of the extension field, we use
different algorithms to optimize the operations
Class for Field
This class represents a polynomial written P = c_nX**n+...c_1X+c_0
c_0,...,c_n are in the Field F (which can be an ExtensionField) so the... | 8,221 | en | 0.784241 |
# -*- coding: utf-8 -*-
# Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the
# University of Virginia, University of Heidelberg, and University
# of Connecticut School of Medicine.
# All rights reserved.
# Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
# Properties, Inc.,... | copasi/bindings/python/unittests/Test_CFunctionParameter.py | 2,766 | -*- coding: utf-8 -*- Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the University of Virginia, University of Heidelberg, and University of Connecticut School of Medicine. All rights reserved. Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual Properties, Inc., University of ... | 910 | en | 0.83115 |
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | generated/intermediate/ansible-module-rest/azure_rm_apimanagementapiexport_info.py | 7,615 | !/usr/bin/python Copyright (c) 2019 Zim Kalinowski, (@zikalino) GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) prepare url self.log('Response : {0}'.format(response)) | 210 | en | 0.430175 |
# TODO: By PySCF-1.5 release
# Copyright 2014-2020 The PySCF Developers. 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.... | pyscf/tools/Molpro2Pyscf/wmme.py | 22,035 | A generally contracted shell of spherical harmonic basis functions.
A FBasisShell which is placed on a concrete atom.
contains data describing how to evaluate quantum chemistry matrix
elements on electronic system as defined by the given atoms and basis
sets.
Note: Basis sets must either be basis set names (i.e., libr... | 6,445 | en | 0.784572 |
__author__ = 'aakilomar'
import requests, json, time
from timeit import default_timer as timer
requests.packages.urllib3.disable_warnings()
host = "https://localhost:8443"
def cancel_event(eventid):
post_url = host + "/api/event/cancel/" + str(eventid)
return requests.post(post_url,None, verify=False).json(... | docs/tests/adhoc_requests.py | 5,668 | print cancel_event(5166)user = add_user("0823333332")user = add_user("0821111111")print "user-->" + str(user)print rsvp(5167,user['id'],"no")print rsvpRequired(user['id'])print voteRequired(user['id'])print upcomingVotes(231)print votesPerGroupForEvent(194,5103)print addLogBook(1,85,"X must do Y")print addLogBook(1,88,... | 960 | en | 0.442137 |
#!---------------------------------------------------------------------!
#! Written by Madu Manathunga on 07/01/2021 !
#! !
#! Copyright (C) 2020-2021 Merz lab !
#! Copyright (C) 2020-2021 G... | src/oei/iclass/PFint.py | 12,254 | !---------------------------------------------------------------------!! Written by Madu Manathunga on 07/01/2021 !! !! Copyright (C) 2020-2021 Merz lab !! Copyright (C) 2020-2021 Götz lab ... | 2,345 | en | 0.700219 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('workshops', '0062_no_invoice_for_historic_events'),
('workshops', '0062_add_stalled_unresponsive_tags'),
]
operations = [
... | workshops/migrations/0063_merge.py | 324 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
"""
Django settings for project_name project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import ... | project_name/settings.py | 4,691 | Django settings for project_name project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
Build paths in... | 1,784 | en | 0.733871 |
#!/usr/bin/env python
# Copyright 2015 The Kubernetes 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 appli... | vendor/k8s.io/kubernetes/cluster/juju/layers/kubernetes-master/reactive/kubernetes_master.py | 37,137 | Test if the add ons got installed
Returns: True is the addons got applied
Check pod status in the kube-system namespace. Returns True if all
pods are running, False otherwise.
Return the package architecture as a string. Raise an exception if the
architecture is not supported by kubernetes.
Gather the relevant data f... | 9,219 | en | 0.87522 |
from ..api import rule
from ..api._endpoint import ApiEndpoint, maybe_login_required
from ..entities._entity import NotFound
from ..entities.commit import Commit, CommitSerializer
class CommitListAPI(ApiEndpoint):
serializer = CommitSerializer()
@maybe_login_required
def get(self):
"""
--... | conbench/api/commits.py | 1,612 | ---
description: Get a list of commits.
responses:
"200": "CommitList"
"401": "401"
tags:
- Commits
---
description: Get a commit.
responses:
"200": "CommitEntity"
"401": "401"
"404": "404"
parameters:
- name: commit_id
in: path
schema:
type: string
tags:
- Commits | 307 | en | 0.707107 |
############################################################################
# examples/multi_webcamera/host/test_module/__init__.py
#
# Copyright 2019, 2020 Sony Semiconductor Solutions Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... | examples/multi_webcamera/host/test_module/__init__.py | 1,792 | examples/multi_webcamera/host/test_module/__init__.py Copyright 2019, 2020 Sony Semiconductor Solutions Corporation 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 cop... | 1,540 | en | 0.866986 |
import io
import logging
import os
import json
import time
import boto3
import botocore
from markov.utils import log_and_exit, Logger, get_boto_config, \
SIMAPP_EVENT_ERROR_CODE_500, SIMAPP_EVENT_ERROR_CODE_400, \
SIMAPP_S3_DATA_STORE_EXCEPTION
LOG = Logger(__name__, l... | src/rl_coach_2020_v2/src/markov/s3_client.py | 5,975 | The amount of time for the sim app to wait for sagemaker to produce the ip 20 minutes Wait for sagemaker to produce the redis ip Download the ip file It is possible that the file isn't there in which case we should return fasle and let the client decide the next action | 269 | en | 0.922674 |
"""Components for use in `CycleGroup`. For details, see `CycleGroup`."""
from __future__ import division, print_function
from six.moves import range
import numpy as np
import scipy.sparse as sparse
import unittest
from openmdao.core.explicitcomponent import ExplicitComponent
PSI = 1.
_vec_terms = {}
def _compu... | openmdao/test_suite/components/cycle_comps.py | 17,390 | Components for use in `CycleGroup`. For details, see `CycleGroup`.
Try/Except pattern is much faster than if key in ... if the key is present (which it will be outside of the first invocation). Setup partials if our subjacs are not dense, we must assign values here that match their type (data values don't matter, onl... | 552 | en | 0.922667 |
import tensorflow as tf
from TransformerNet.layers import Encoder, Decoder
def Decoder_test(*args, **kwargs):
inputs = tf.random.uniform((64, 62), dtype=tf.int64, minval=0, maxval=200) # (batch_size, input_seq_len)
enc_output = Encoder(num_layers=2, d_model=512, num_heads=8,
d... | TransformerNet/layers/Decoder_test.py | 1,218 | (batch_size, input_seq_len) (batch_size, target_seq_len) (batch_size, target_seq_len, d_model) (batch_size, target_seq_len, input_seq_len) | 138 | en | 0.191667 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# vim: expandtab:tabstop=4:shiftwidth=4
'''
oo_option lookup plugin for openshift-ansible
Usage:
- debug:
msg: "{{ lookup('oo_option', '<key>') | default('<default_value>', True) }}"
This returns, by order of priority:
* if it exists, the `cli_<key>` ansible... | lookup_plugins/oo_option.py | 2,604 | oo_option lookup plugin main class
Constructor
Main execution path
oo_option lookup plugin for openshift-ansible
Usage:
- debug:
msg: "{{ lookup('oo_option', '<key>') | default('<default_value>', True) }}"
This returns, by order of priority:
* if it exists, the `cli_<key>` ansible variable. This variab... | 1,517 | en | 0.64799 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import os
import itertools
from datetime import datetime
from dateutil.relativedelta import relativedelta
import subprocess
from ..train_utils import TSCVSplitter
class ParameterSweeper:
"""
The function of this class i... | contrib/tsperf/cross_validation/cross_validation.py | 7,638 | The function of this class is currently replaced by HyperDrive.
But let's keep it to preserve the work already done, and also
in case we need more flexibility than what HyperDrive provides.
Copyright (c) Microsoft Corporation. Licensed under the MIT License. In default mode, simply iterate through each feature set in... | 1,283 | en | 0.7129 |
# coding: utf-8
# In[ ]:
import os
import re
import tarfile
import requests
from pugnlp.futil import path_status, find_files
# In[ ]:
# From the nlpia package for downloading data too big for the repo
BIG_URLS = {
'w2v': (
'https://www.dropbox.com/s/965dir4dje0hfi4/GoogleNews-vectors-negative300.... | nlpia/book/examples/ch09.py | 17,875 | We truncate to maxlen or add in PAD tokens
Shift to lower case, replace unknowns with UNK, and listify
Peel of the target values from the dataset
Modified from Keras LSTM example
Uses stream=True and a reasonable chunk size to be able to download large (GB) files over https
One hot encode the tokens
Args:
datas... | 2,357 | en | 0.713907 |
from dataloaders.datasets import cityscapes, coco, combine_dbs, pascal, sbd, rip
from torch.utils.data import DataLoader
def make_data_loader(args, **kwargs):
if args.dataset == 'pascal':
train_set = pascal.VOCSegmentation(args, split='train')
val_set = pascal.VOCSegmentation(args, split='val')
... | dataloaders/__init__.py | 3,423 | patches = 'COCOJSONPatches' if patches == 'patches' else 'COCOJSONs' NOTE: drop_last=True here to avoid situation when batch_size=1 which causes BatchNorm2d errors | 163 | en | 0.762145 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consist... | Packages/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/output.py | 31,267 | Defines a number of commonly used DOCTYPE declarations as constants.
A filter that inserts the DOCTYPE declaration in the correct location,
after the XML declaration.
Combines `START` and `STOP` events into `EMPTY` events for elements that
have no contents.
Produces HTML text from an event stream.
>>> from genshi.buil... | 7,469 | en | 0.659052 |
# -*- coding: utf-8 -*-
# Begin CVS Header
# $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/bindings/python/unittests/Test_CMoiety.py,v $
# $Revision: 1.11 $
# $Name: $
# $Author: shoops $
# $Date: 2010/07/16 18:55:59 $
# End CVS Header
# Copyright (C) 2010 by Pedro Mendes, Virginia Tech I... | copasi/bindings/python/unittests/Test_CMoiety.py | 2,530 | -*- coding: utf-8 -*- Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/bindings/python/unittests/Test_CMoiety.py,v $ $Revision: 1.11 $ $Name: $ $Author: shoops $ $Date: 2010/07/16 18:55:59 $ End CVS Header Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual Proper... | 601 | en | 0.670641 |
# build_features.py
# This module holds utility classes and functions that creates and manipulates input features
# This module also holds the various input transformers
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
def correlation_columns(dataset: pd.DataFrame, targe... | credit-card-fraud/src/features/build_features.py | 1,572 | Columns Extractor based on correlation to the output label
Columns that are correlated to the target point
Parameters
----------
dataset: pd.DataFrame
The pandas dataframe
target_column: str
The target column to calculate correlation against
k: float
The correlation cuttoff point; defaults to -0.5 and 0... | 680 | en | 0.725502 |
# Generated by Django 3.0 on 2019-12-12 08:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('team', '0002_auto_20191210_2330'),
('members', '0001_initial'),
]
operations = [
migrations.AddField(... | backend/members/migrations/0002_member_team.py | 496 | Generated by Django 3.0 on 2019-12-12 08:54 | 43 | en | 0.765422 |
#
# 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 us... | python/pyspark/pandas/generic.py | 104,770 | The base class for both DataFrame and Series.
Return a Series/DataFrame with absolute numeric value of each element.
Returns
-------
abs : Series/DataFrame containing the absolute value of each element.
Examples
--------
Absolute numeric values in a Series.
>>> s = ps.Series([-1.10, 2, -3.33, 4])
>>> s.abs()
0 1... | 56,549 | en | 0.536522 |
import importlib
import sys
import argparse
from multi_sample_factory.algorithms.utils.algo_utils import ExperimentStatus
from multi_sample_factory.runner.run_ngc import add_ngc_args
from multi_sample_factory.runner.run_slurm import add_slurm_args
from multi_sample_factory.utils.utils import log
def runner_argparser... | multi_sample_factory/runner/run.py | 2,676 | assuming we're given the full name of the module | 48 | en | 0.735049 |
"""
Showcases *LLAB(l:c)* colour appearance model computations.
"""
import numpy as np
import colour
from colour.appearance.llab import CAM_ReferenceSpecification_LLAB
from colour.utilities import message_box
message_box('"LLAB(l:c)" Colour Appearance Model Computations')
XYZ = np.array([19.01, 20.00, 21.78])
XYZ_0... | colour/examples/appearance/examples_llab.py | 1,331 | Showcases *LLAB(l:c)* colour appearance model computations. | 59 | en | 0.718263 |
import random
import math
import os.path
import numpy as np
import pandas as pd
from pysc2.agents import base_agent
from pysc2.lib import actions
from pysc2.lib import features
_NO_OP = actions.FUNCTIONS.no_op.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_BUILD_SUPPLY_DEPOT = actions.FUNCTIONS.Build_SupplyDe... | 7. Using Reward for Agent/reward_agent.py | 10,878 | Stolen from https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow a list choose best action some actions have the same value choose random action next state is terminal update append new state to q table | 218 | en | 0.766727 |
"""
# Sheets Account
Read a Google Sheet as if it were are realtime source of transactions
for a GL account. Columns are mapped to attributes. The
assumption is that the sheet maps to a single account, and the
rows are the credit/debits to that account.
Can be used as a plugin, which will write new entries (for ref... | src/coolbeans/plugins/sheetsaccount.py | 9,782 | This is a bit of a hack. But using get_all_records doesn't leave many
options
Clean a possible Slug string to remove dashes and lower case.
Given a set of entries, pull out any slugs and add them to the context
Try to Load Entries from URL into Account.
options include:
- document_name -- the Actual Google Doc na... | 1,998 | en | 0.838002 |
"""
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
from test.unit.rules import BaseRuleTestCase
from cfnlint.rules.resources.properties.OnlyOne import OnlyOne # pylint: disable=E0401
class TestPropertyOnlyOne(BaseRuleTestCase):
"""Test OnlyOne Property ... | test/unit/rules/resources/properties/test_onlyone.py | 748 | Test OnlyOne Property Configuration
Setup
Test failure
Test Positive
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
pylint: disable=E0401 | 195 | en | 0.62839 |
import unittest
from unittest.mock import patch, call, Mock, MagicMock, mock_open
from botocore.exceptions import ClientError
from ground_truth.src import ground_truth
from common import _utils
required_args = [
'--region', 'us-west-2',
'--role', 'arn:aws:iam::123456789012:user/Development/product_1234/*',
'-... | components/aws/sagemaker/tests/unit_tests/tests/test_ground_truth.py | 9,211 | Mock out all of utils except parser Set some static returns Check if correct requests were created and triggered Check the file outputs | 135 | en | 0.896853 |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | tests/lax_control_flow_test.py | 87,629 | Test typing error messages for cond.
Test typing error messages for while.
Test typing error messages for scan.
Test typing error messages for switch.
Test typing error messages for while.
Test custom linear solve with inputs and outputs that are pytrees.
Apply a Python list of lists of scalars to a list of scalars.
S... | 4,534 | en | 0.873079 |
# from flask import Flask, Blueprint
# from flask_sqlalchemy import SQLAlchemy
# from flask_login import LoginManager
# import os
from flask import Flask, jsonify, request, make_response, redirect, url_for
import jwt
import datetime
import os
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
import u... | .vscode-server/data/User/History/-1f47d17c/IWlp.py | 16,514 | from flask import Flask, Blueprint from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager import os Modelsid = db.Column(db.Integer, primary_key=True )Column('timestamp', TIMESTAMP(timezone=False), nullable=False, default=datetime.now())id = db.Sequence('id', start=1, increment=1)Column('timestam... | 2,292 | es | 0.158281 |
"""A setuptools based setup module.
"""
# Always prefer setuptools over distutils
from setuptools import setup
setup(
name='ooinstall',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en... | oct/ansible/openshift-ansible/utils/setup.py | 2,656 | A setuptools based setup module.
Always prefer setuptools over distutils Versions should comply with PEP440. For a discussion on single-sourcing the version across setup.py and the project code, see https://packaging.python.org/en/latest/single_source_version.html The project's main homepage. Author details Choose y... | 1,458 | en | 0.808607 |
import pytest
from . import specparser
def test_load() -> None:
spec = specparser.Spec.loads(
"""
[meta]
version = 0
[enum]
user_level = ["beginner", "intermediate", "advanced"]
[directive._parent]
content_type = "block"
options.foo = ["path", "uri"]
[directive.child]
... | .myenv/Lib/site-packages/snooty/test_specparser.py | 3,280 | Test these in the opposite order of the definition to ensure that each "type" of definition has a separate inheritance namespace | 128 | en | 0.88391 |
# dagutil.py - dag utilities for mercurial
#
# Copyright 2010 Benoit Boissinot <bboissin@gmail.com>
# and Peter Arrenbrecht <peter@arrenbrecht.ch>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from node import nullrev
from i18n ... | LocalMercurial/mercurial/dagutil.py | 8,249 | generic interface for DAGs
terms:
"ix" (short for index) identifies a nodes internally,
"id" identifies one externally.
All params are ixs unless explicitly suffixed otherwise.
Pluralized params are lists or sets.
generic implementations for DAGs
inverse of an existing revlog dag; see revlogdag.inverse()
generic dag ... | 1,698 | en | 0.824613 |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient
from recipe_app.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe_app... | app/recipe_app/tests/test_ingredients_api.py | 3,090 | Test endpoints that require authentication.
Test endpoints that don't require authentication.
Test that creating a new ingredient is successful.
Test that ingredients is not created with invalid details
Test that authentication is needed to view the ingredients.
Test retrieve ingredients
Tests that only the user's ingr... | 341 | en | 0.895907 |
#
# Copyright (c) 2008-2015 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 l... | nitro/resource/config/lb/lbvserver_appfwpolicy_binding.py | 13,671 | Binding class showing the appfwpolicy that can be bound to lbvserver.
converts nitro response into object and returns the object array in case of get request.
:param service:
:param response:
Returns the value of object identifier argument
:param client:
:param resource:
The bindpoint to which the policy is bound.... | 3,575 | en | 0.728292 |
#
# Autogenerated by Frugal Compiler (3.4.2)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
import asyncio
from datetime import timedelta
import inspect
from frugal.aio.processor import FBaseProcessor
from frugal.aio.processor import FProcessorFunction
from frugal.exceptions import TApplicat... | test/expected/python.asyncio/service_extension_same_file/f_Pinger.py | 7,173 | Create a new Client with an FServiceProvider containing a transport
and protocol factory.
Args:
provider: FServiceProvider
middleware: ServiceMiddleware or list of ServiceMiddleware
Create a new Processor.
Args:
handler: Iface
Autogenerated by Frugal Compiler (3.4.2) DO NOT EDIT UNLESS YOU ARE SURE THAT... | 459 | en | 0.862852 |
from __future__ import annotations
import argparse
import atexit
import itertools
import shlex
import shutil
import signal
import subprocess
import sys
import traceback
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from pyoomph import ast, ast2ir, ast_transformer, c_output, ir, parser
pytho... | pyoomph/__main__.py | 8,281 | Another instance of oomph compiler running in parallel make mypy feel good Pop the next source file to parse Create a compilation unit out of it and parse it into an untyped ast Calculate its dependencies and add them to the dependencies dictionary, including builtins if necessary, and add those dependencies to the que... | 666 | en | 0.867526 |
import logging
from typing import List, Union
from cactus.consensus.block_record import BlockRecord
from cactus.consensus.blockchain_interface import BlockchainInterface
from cactus.consensus.constants import ConsensusConstants
from cactus.types.blockchain_format.sized_bytes import bytes32
from cactus.types.full_block... | cactus/consensus/get_block_challenge.py | 4,794 | Args:
header_block: An overflow block, with potentially missing information about the new sub slot
blocks: all blocks that have been included before header_block
sub_slot_iters: sub_slot_iters at the header_block
Returns: True iff the missing sub slot was already included in a previous block. Returns False... | 1,261 | en | 0.943783 |
# -*- coding: utf-8 -*-
from functools import lru_cache
import requests
from requests.packages.urllib3.util.retry import Retry
# https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#module-urllib3.util.retry
DEFAULT_RETRIES = 5
DEFAULT_BACKOFF_FACTOR = 0.1
DEFAULT_STATUS_FORCELIST = [500, 502, 503, 50... | mozci/util/req.py | 1,031 | -*- coding: utf-8 -*- https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.htmlmodule-urllib3.util.retry Default HTTPAdapter uses 10 connections. Mount custom adapter to increase that limit. Connections are established as needed, so using a large value should not negatively impact performance. | 305 | en | 0.754774 |
from werkzeug.wrappers import Request
from flask import Flask, redirect, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
import os
import requests
import random
from contact_form import ContactForm
from flask_dance.contrib.github import make_github_blueprint, github
from flask_dance.contrib.gitl... | app.py | 7,828 | Various environmental variables Github blueprint Database model & connection gitlab_hash = db.Column(db.String(80), unique=True, nullable=True) Routing and repository parsing if repo['fork'] == False: parsedRepos.append(parsedRepo) @app.route("/signup_gitlab") def signup_gitlab(): resp = gitlab.get("/user") if ... | 1,699 | en | 0.18758 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'secure_auth_rest.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
rai... | manage.py | 636 | Django's command-line utility for administrative tasks.
!/usr/bin/env python | 77 | en | 0.656913 |
ownerclass = 'AppDelegate'
ownerimport = 'AppDelegate.h'
# Init
result = Window(330, 110, "Tell me your name!")
nameLabel = Label(result, text="Name:")
nameLabel.width = 45
nameField = TextField(result, text="")
helloLabel = Label(result, text="")
button = Button(result, title="Say Hello", action=Action(owner, 'sayHel... | demos/localized/MainWindow.py | 820 | Init Owner Assignments Layout | 29 | en | 0.897204 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Tickfont(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scatterternary.marker.colorbar"
_path_str = "scatterternary.marker.colorbar.tickfont"
_val... | packages/python/plotly/plotly/graph_objs/scatterternary/marker/colorbar/_tickfont.py | 8,543 | Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterternary
.marker.colorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by... | 4,490 | en | 0.569698 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.