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 |
|---|---|---|---|---|---|---|
import unittest
from robot.parsing import TestCaseFile
from robot.parsing.model import TestCaseTable
from robot.utils import ET, ETSource, StringIO
from robot.utils.asserts import assert_equal
def create_test_case_file():
data = TestCaseFile(source='foo.txt')
table = TestCaseTable(data)
data.testcase_tab... | utest/writer/test_filewriters.py | 2,631 | csv not available on IronPython 2.7 | 35 | en | 0.515641 |
import cv2.cv2 as cv2
import skimage.io as io
from skimage.transform import downscale_local_mean
import numpy as np
from model import *
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklear... | main.py | 33,843 | Create a mesh of points to plot in
Parameters
----------
x: data to base x-axis meshgrid on
y: data to base y-axis meshgrid on
h: stepsize for meshgrid, optional
Returns
-------
xx, yy : ndarray
Plot the decision boundaries for a classifier.
Parameters
----------
ax: matplotlib axes object
clf: a classifier
xx: mesh... | 3,146 | en | 0.443463 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import pickle
import pandas as pd
from cgp import *
from cgp_config import *
from cnn_train import CNN_train
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Evolving CAE structures')
parser.add_argument('--gpu_num', '-g',... | exp_main.py | 3,730 | !/usr/bin/env python -*- coding: utf-8 -*- --- Optimization of the CNN architecture --- Create CGP configuration and save network information Evaluation function for CGP (training CNN and return validation accuracy) Execute evolution --- Retraining evolved architecture --- In the case of existing log_cgp.txt Load CGP c... | 841 | en | 0.618722 |
#!/usr/bin/env python3
import os
import shutil
import threading
from selfdrive.swaglog import cloudlog
from selfdrive.loggerd.config import ROOT, get_available_bytes, get_available_percent
from selfdrive.loggerd.uploader import listdir_by_creation
from selfdrive.dragonpilot.dashcam import DASHCAM_FREESPACE_LIMIT
MIN_B... | selfdrive/loggerd/deleter.py | 1,285 | !/usr/bin/env python3 remove the earliest directory we can | 58 | en | 0.405588 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
from future.utils import iteritems
from collections import defaultdict
from copy import deepcopy
from itertools import product
import re
from sqlal... | snorkel/candidates.py | 13,432 | An operator to extract Candidate objects from a Context.
:param candidate_class: The type of relation to extract, defined using
:func:`snorkel.models.candidate_subclass <snorkel.models.candidate.candidate_subclass>`
:param cspaces: one or list of :class:`CandidateSpace` objects, one for each re... | 3,074 | en | 0.821501 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 15 10:38:14 2021
@author: kunal001
"""
import logging
logger = logging.getLogger(__name__)
class CreateDatabase:
def __init__(self,hier_graph,const_parse):
self.hier_graph_dict = {}
self.const_parse = const_parse
self.G ... | align/compiler/create_database.py | 2,918 | Recusively reads all hierachies in the graph and convert them to dictionary
read circuit graphs
Created on Fri Jan 15 10:38:14 2021
@author: kunal001
!/usr/bin/env python3 -*- coding: utf-8 -*- | 195 | en | 0.749925 |
def main():
# Open a file for writing and create it if it doesn't exist
# myfile = open("textfile.txt", "w+")
# # Open the file for appending text to the end
# myfile = open("textfile.txt", "a+")
# # write some lines of data to the file
# for i in range(10):
# myfile... | Chapter03/file_start.py | 772 | Open a file for writing and create it if it doesn't exist myfile = open("textfile.txt", "w+") Open the file for appending text to the end myfile = open("textfile.txt", "a+") write some lines of data to the file for i in range(10): myfile.write("This is some new text\n") close the file when done myfile.close() Op... | 402 | en | 0.800717 |
from robotMap import XboxMap
from components.Actuators.LowLevel.shooterMotors import ShooterMotors
from components.Actuators.LowLevel.intakeMotor import IntakeMotor
from components.Actuators.HighLevel.hopperMotor import HopperMotor
from utils.DirectionEnums import Direction
from enum import Enum, auto
from magicbot imp... | components/Actuators/HighLevel/feederMap.py | 2,584 | Simple map that holds the logic for running elements of the feeder.
Enumeration for the two types within the feeder.
Called when execution of a feeder element is desired.
log.setLevel(logging.DEBUG) | 200 | en | 0.875602 |
# NOTICE
#
# This software was produced for the U.S. Government under
# contract SB-1341-14-CQ-0010, and is subject to the Rights
# in Data-General Clause 52.227-14, Alt. IV (DEC 2007)
#
# (c) 2018 The MITRE Corporation. All Rights Reserved.
#====================================================
# CASE API
#!/usr/bin... | example/case_example.py | 11,982 | Implements a generic node in the graph.
Wrapper for checking if triple is contained in the graph.
Initializes the CASE document.
Args:
graph: The graph to populate (instance of rdflib.Graph)
If not provided, a graph in memory will be used.
Initializes and adds a node to the graph.
NOTE: At least the typ... | 5,537 | en | 0.754369 |
#
# Copyright 2018 PyWren Team
# (C) Copyright IBM Corp. 2020
# (C) Copyright Cloudlab URV 2020
#
# 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-... | lithops/job/job.py | 12,417 | :param func: the function to map over the data
:param iterdata: An iterable of input data
:param extra_env: Additional environment variables for CF environment. Default None.
:param extra_meta: Additional metadata to pass to CF. Default None.
:param remote_invocation: Enable remote invocation. Default False.
:param inv... | 1,670 | en | 0.742161 |
import sys
import time
import os
import os.path as osp
import requests
import shutil
import tqdm
import pickle
import numpy as np
import torch
from cogdl.data import Data, Dataset, download_url
from . import register_dataset
def untar(path, fname, deleteTar=True):
"""
Unpacks the given archive file to the ... | cogdl/datasets/gtn_data.py | 6,101 | The network datasets "ACM", "DBLP" and "IMDB" from the
`"Graph Transformer Networks"
<https://arxiv.org/abs/1911.06455>`_ paper.
Args:
root (string): Root directory where the dataset should be saved.
name (string): The name of the dataset (:obj:`"gtn-acm"`,
:obj:`"gtn-dblp"`, :obj:`"gtn-imdb"`).
Unpack... | 411 | en | 0.715103 |
#!/usr/bin/env python3
#
# Convert full firmware binary to rwd patch.
# Supported models:
# CR-V 5g (part num: 39990-TLA), tested
# Civic 2016 sedan (part num: 39990-TBA), tested
# Civic 2016 hatchback Australia (part num: 39990-TEA), tested
# Civic 2016 hatchback (part num: 39990-TGG), tested
#
import os
impor... | tools/bin_to_rwd.py | 8,871 | !/usr/bin/env python3 Convert full firmware binary to rwd patch. Supported models: CR-V 5g (part num: 39990-TLA), tested Civic 2016 sedan (part num: 39990-TBA), tested Civic 2016 hatchback Australia (part num: 39990-TEA), tested Civic 2016 hatchback (part num: 39990-TGG), tested Decryption lookup table built fr... | 1,409 | en | 0.682646 |
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from ManagementStudents.jinja2 import Environment
# This enables us to use Django template tags like {% url ‘index’ %} or {% static ‘path/to/static/file.js’ %} in our Jinja2 templates.
def environment(**options):
en... | 14_Tran_An_Thien/ManagementStudents/ManagementStudents/customsettings.py | 469 | This enables us to use Django template tags like {% url ‘index’ %} or {% static ‘path/to/static/file.js’ %} in our Jinja2 templates. | 132 | en | 0.144252 |
"""
This module used for serializing data
CategorySchema - data from Category model
VacancySchema - data from Vacancy model
"""
# pylint: disable=too-many-ancestors
# pylint: disable=missing-class-docstring
# pylint: disable=too-few-public-methods
from app import ma
from app.models.model import Category, Vacancy
cl... | app/rest/serializers.py | 798 | Used for serialize Category data
Used for serialize Vacancy data
This module used for serializing data
CategorySchema - data from Category model
VacancySchema - data from Vacancy model
pylint: disable=too-many-ancestors pylint: disable=missing-class-docstring pylint: disable=too-few-public-methods | 301 | en | 0.562361 |
# 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/communication/azure-communication-networktraversal/azure/communication/networktraversal/_generated/models/_communication_network_traversal_client_enums.py | 999 | The routing methodology to where the ICE server will be located from the client. "any" will
have higher reliability while "nearest" will have lower latency. It is recommended to default
to use the "any" routing method unless there are specific scenarios which minimizing latency is
critical.
coding=utf-8 -------------... | 746 | en | 0.805632 |
# -*- coding: utf-8 -*-
"""Class that defines the abstract interface for an object repository.
The scope of this class is intentionally very narrow. Any backend implementation should merely provide the methods to
store binary blobs, or "objects", and return a string-based key that unique identifies the object that was... | aiida/repository/backend/abstract.py | 8,766 | Class that defines the abstract interface for an object repository.
The repository backend only deals with raw bytes, both when creating new objects as well as when returning a stream
or the content of an existing object. The encoding and decoding of the byte content should be done by the client
upstream. The file rep... | 5,153 | en | 0.847417 |
"""personal_gallery URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')... | personal_gallery/urls.py | 819 | personal_gallery URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... | 642 | en | 0.681664 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft and contributors. 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 ... | azure-mgmt-resource/azure/mgmt/resource/features/__init__.py | 1,049 | coding=utf-8 -------------------------------------------------------------------------- Copyright (c) Microsoft and contributors. 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... | 883 | en | 0.767341 |
import sqlite3
import os
MSG_HELP = """List of commands:
!help
List commands
!listAll
List all animals
!show <animal>
Give description
!getFlag
Give flag (Admin only)
!serverInfo
Give server info (Dragonite only)
!addAdmin <id>
Make user an admin (Dragonite only)
!hint
Give you a hint.
Sou... | botCmd.py | 4,322 | Log userId and their msg here CREATE TABLE MsgLog (user TEXT, msg TEXT); Show animal description CREATE TABLE Animals (animal TEXT UNIQUE, description TEXT); List every animals CREATE TABLE Animals (animal TEXT UNIQUE, description TEXT); My own reminder CREATE TABLE ServerInfo (info TEXT); You should ask Dragonite to a... | 482 | en | 0.402912 |
import unittest
import xmlrunner
# from selenium import webdriver
import pagemodels.headerpage
import tests.pickledlogin
import browserconfig
# VIDEO OF EXECUTION
# https://gyazo.com/b20fd223076bf34c1f2c9b94a4f1fe0a
# 2020-04-20 All tests passing, refactor complete
# All tests passed 5 executions in a row. v1 ready... | tests/test_headerpage.py | 5,022 | Test cases for the use of the header features atop most netflix pages.
Return to the home page, netflix.com/browse, the staging place for header tests.
Launch the webdriver of choice with selected options(see browserconfig.py).
Then login using pickled cookies(see tests/pickledlogin.py).
Closes the browser and shuts do... | 2,270 | en | 0.866819 |
import os
import sys
import copy as copy
from tensor_view_1d import TensorView1D
from tensor_view_2d import TensorView2D
from tensor_view_act import TensorViewAct
from tensor_view_filter import TensorViewFilter
from tensor_data import TensorData
import inspect
from PyQt4 import QtGui, QtCore
from pyqt_env i... | TensorMonitor/control_panel.py | 26,784 | self.tensor_input_list = args['tensor_input_list']self.data_source = TensorData(start_step=ControlPanel.step_count)TypeError: fix for python3self.pyqt_window_id = Noneself.view = None global control tensor select panel tensor watch panel add_input testfor test/alexnetself.__add_input('img_input')for test/basic_testself... | 410 | en | 0.175219 |
"""TensorFlow ops for deep neural networks."""
# Copyright 2015-present The Scikit Flow 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.apac... | tensorflow/contrib/learn/python/learn/ops/dnn_ops.py | 1,844 | Creates fully connected deep neural network subgraph.
Args:
tensor_in: tensor or placeholder for input features.
hidden_units: list of counts of hidden units in each layer.
activation: activation function between layers. Can be None.
dropout: if not None, will add a dropout layer with given probability.
Retur... | 1,013 | en | 0.857006 |
"""
This code was created by Tyler Adam Martinez for the BMEN3310 Final
#This are the varibles and what they stand for.
Hemodynamic Parameter Analysis
CS // Cross-Sectional Area of the heart valve
vR // Radius of Valve
DR // Disk Radius
TiA // Area of the Titanium wire
TiV // Volume of the Titanium wire... | Hemodynamic_Parameter_Analysis.py | 2,707 | This code was created by Tyler Adam Martinez for the BMEN3310 Final
#This are the varibles and what they stand for.
Hemodynamic Parameter Analysis
CS // Cross-Sectional Area of the heart valve
vR // Radius of Valve
DR // Disk Radius
TiA // Area of the Titanium wire
TiV // Volume of the Titanium wire
IRV // Inner ... | 1,205 | en | 0.374302 |
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from .GraphicsView import GraphicsView
from ..graphicsItems.GradientEditorItem import GradientEditorItem
import weakref
import numpy as np
__all__ = ['GradientWidget']
class GradientWidget(GraphicsView):
"""
Widget displaying an editable colo... | scripts/pyqtgraph-develop/pyqtgraph/widgets/GradientWidget.py | 2,975 | Widget displaying an editable color gradient. The user may add, move, recolor,
or remove colors from the gradient. Additionally, a context menu allows the
user to select from pre-defined gradients.
The *orientation* argument may be 'bottom', 'top', 'left', or 'right'
indicating whether the gradient is displayed horiz... | 1,051 | en | 0.450397 |
from typing_extensions import Final # noqa: F401
CONTAINER_CLIENT_PACKAGES = 'compressedpackages' # type: Final
CONTAINER_EMAILS = 'emails' # type: Final
CONTAINER_MAILBOX = 'mailbox' # type: Final
CONTAINER_SENDGRID_MIME = 'sendgridinboundemails' # type: Final
TABLE_DOMAIN_X_DELIVERED = 'emaildomainxdelivered' ... | opwen_email_server/constants/azure.py | 554 | noqa: F401 type: Final type: Final type: Final type: Final type: Final type: Final type: Final type: Final type: Final | 118 | en | 0.473341 |
#
#
# Copyright 2020-21 British Broadcasting Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | aiocypher/aioneo4j/graph.py | 2,387 | A conceptual wrapper for a neo4j query which will return a neo4j.graph.Graph object.
To execute the query and return the underlying object await this object. But the
returned neo4j.graph.Graph is unlikely to be very useful outside of the context managers
in which it was created.
A better way to use this object is to ... | 930 | en | 0.905433 |
# -*- coding: utf-8 -*-
__version__ = "0.1.0"
| resources_crawler/__init__.py | 48 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Copyright 2014 Google 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 agreed to in writing, ... | storage/tests/unit/test_blob.py | 91,732 | Copyright 2014 Google 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 agreed to in writing, software distribut... | 3,974 | en | 0.89547 |
class Hero:
def __init__(self,name,health,attackPower):
self.__name = name
self.__health = health
self.__attPower = attackPower
# getter
def getName(self):
return self.__name
def getHealth(self):
return self.__health
# setter
def diserang(self,serangPower):
self.__health -= serangPower
def setA... | Python OOP/test.py | 565 | getter setter awal dari game game berjalan | 42 | id | 0.559041 |
import argparse
import datasets
import matplotlib.pyplot as plt
import numpy as np
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, required=True, help='Path to the directory with input dataset')
return parser.parse_args()
if __name__ == '__main__... | src/cluster/sort_dataset_by_column/test.py | 1,069 | plt.xlabel('len') plt.ylabel('tse / len') plt.scatter(xs, ys) plt.hist(ys, bins=5000) | 85 | hu | 0.06424 |
# coding: utf-8
"""
API's OpenData do Open Banking Brasil
As API's descritas neste documento são referentes as API's da fase OpenData do Open Banking Brasil. # noqa: E501
OpenAPI spec version: 1.0.0-rc5.2
Contact: apiteam@swagger.io
Generated by: https://github.com/swagger-api/swagger-codegen.gi... | products_and_services_client/api/invoice_financings_api.py | 8,940 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501
Obtém a lista de Adiantamento de Recebíveis de Pessoa Jurídica. # noqa: E501
This... | 3,572 | pt | 0.503537 |
# -*- coding: utf-8 -*-
from __future__ import print_function
from warnings import catch_warnings
from datetime import datetime
import itertools
import pytest
from numpy.random import randn
from numpy import nan
import numpy as np
from pandas.compat import u
from pandas import (DataFrame, Index, Series, MultiIndex... | pandas/tests/frame/test_reshape.py | 36,111 | -*- coding: utf-8 -*- name tracking don't specify values pivot multiple columns gh-3962 omit values GH 18310 flat columns: MultiIndex columns: as above, but used labels in level are actually of homogeneous type GH 9746: fill_value keyword argument for Series and DataFrame unstack From a series From a series with incorr... | 1,987 | en | 0.6918 |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
all_raw = open(sys.argv[1], 'r')
# init empty lists
cell0v = []
cell1v = []
cell2v = []
cell3v = []
totalv = []
# Process data into lists
for line in all_raw:
if 'voltage cell 0: ' in line:
try:
... | plot_battery.py | 1,626 | !/usr/bin/env python init empty lists Process data into lists Write images Total voltage of pack Cells | 102 | en | 0.529774 |
import time
from messaging_pyx import Context, Poller, SubSocket, PubSocket # pylint: disable=no-name-in-module, import-error
MSGS = 1e5
if __name__ == "__main__":
c = Context()
sub_sock = SubSocket()
pub_sock = PubSocket()
sub_sock.connect(c, "controlsState")
pub_sock.connect(c, "controlsState")
poll... | selfdrive/messaging/demo.py | 652 | pylint: disable=no-name-in-module, import-error | 47 | en | 0.234269 |
###########################
#
# #21 Amicable numbers - Project Euler
# https://projecteuler.net/problem=21
#
# Code by Kevin Marciniak
#
###########################
def sumproperdivisors(num):
sum = 0
for x in range(1, int((num / 2)) + 1):
if num % x == 0:
sum += x
return sum
amicabl... | problem0021.py | 712 | 21 Amicable numbers - Project Euler https://projecteuler.net/problem=21 Code by Kevin Marciniak | 95 | en | 0.362048 |
import threading
from typing import Callable, List, MutableMapping, NamedTuple
from dagster import check
from dagster.core.events.log import EventLogEntry
from .sql_event_log import SqlEventLogStorage
POLLING_CADENCE = 0.1 # 100 ms
class CallbackAfterCursor(NamedTuple):
"""Callback passed from Observer class ... | python_modules/dagster/dagster/core/storage/event_log/polling_event_watcher.py | 7,354 | Callback passed from Observer class in event polling
start_cursor (int): Only process EventLogEntrys with an id >= start_cursor
(earlier ones have presumably already been processed)
callback (Callable[[EventLogEntry], None]): callback passed from Observer
to call on new EventLogEntrys
Event Log Watcher that us... | 2,177 | en | 0.793207 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | docs/source/conf.py | 6,179 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/stable/config -- Path setup -------------------------------------------------------------- If extensions ... | 4,454 | en | 0.565657 |
from typing import Optional, Type
from pydantic import UUID4
from tortoise import fields, models
from tortoise.exceptions import DoesNotExist
from fastapi_users.db.base import BaseUserDatabase
from fastapi_users.models import UD
class TortoiseBaseUserModel(models.Model):
id = fields.UUIDField(pk=True, generated... | fastapi_users/db/tortoise.py | 4,952 | Database adapter for Tortoise ORM.
:param user_db_model: Pydantic model of a DB representation of a user.
:param model: Tortoise ORM model.
:param oauth_account_model: Optional Tortoise ORM model of a OAuth account.
Tortoise complains if we pass the PK again | 261 | en | 0.465863 |
from datetime import datetime
from typing import List, Optional
from uuid import getnode
from .ballot import (
CiphertextBallot,
CiphertextBallotContest,
CiphertextBallotSelection,
PlaintextBallot,
PlaintextBallotContest,
PlaintextBallotSelection,
make_ciphertext_ballot_contest,
make_ci... | src/electionguard/encrypt.py | 19,691 | Metadata for encryption device
An object for caching election and encryption state.
It composes Elections and Ballots.
Construct a `BallotContest` from a specific `ContestDescription` with all false fields.
This function is useful for filling contests and selections when a voter undervotes a ballot.
:param descriptio... | 6,647 | en | 0.812783 |
import argparse
import logging
import sys
import pyphen
import nltk
pyphen.language_fallback("en_US")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
console_out = logging.StreamHandler(sys.stdout)
console_out.setLevel(logging.DEBUG)
logger.addHandler(console_out)
def parse_arguments():
"""
Simp... | ml_editor/ml_editor.py | 8,408 | Text sanitization function
:param text: User input text
:return: Sanitized text, without non ascii characters
Calculate word length for a sentence
:param tokens: a list of words
:return: The average length of words in this list
Computes readability score from summary statistics
:param total_syllables: number of syllabl... | 2,751 | en | 0.827244 |
# -*- coding: utf-8 -*-
import six
from flask import Blueprint, jsonify, current_app
from ..utils import MountTree
from .utils import is_testing
api_bp = Blueprint('api', __name__.rsplit('.')[1])
if is_testing():
@api_bp.route('/_hello/')
def api_hello():
return jsonify('api hello')
@api_bp.route(... | mlcomp/board/views/api.py | 1,114 | Get all storage in JSON.
-*- coding: utf-8 -*- get a compressed representation of the tree | 92 | en | 0.848112 |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
from copy import deepcopy
import torch
from cvpods.checkpoint import DefaultCheckpointer
from cvpods.data import build_transform_gens
__all__ = ["DefaultPredictor"]
class DefaultPredictor:
"""
Create a simple end-to-end predictor with the given config that runs on
... | cvpods/engine/predictor.py | 2,871 | Create a simple end-to-end predictor with the given config that runs on
single device for a single input image.
Compared to using the model directly, this class does the following additions:
1. Load checkpoint from `cfg.MODEL.WEIGHTS`.
2. Always take BGR image as the input and apply conversion defined by `cfg.INPUT.FO... | 1,235 | en | 0.738415 |
# coding: utf-8
from pytdx.hq import TdxHq_API
from pytdx.params import TDXParams
import pandas as pd
import numpy as np
import re
import csv
import io
import time
import traceback
if __name__ == '__main__':
with io.open(r'..\all_other_data\symbol.txt', 'r', encoding='utf-8') as f:
symbol = [s.strip() fo... | get_data/get_last_price.py | 1,672 | coding: utf-8symbol = symbol[0:5]quote_info = TDXHQ.get_security_quotes([(market, code)]) string_columns = ['代码'] quote_df[string_columns] = quote_df[string_columns].applymap( lambda x: '=""' if type(x) is float else '="' + str(x) + '"') | 241 | en | 0.234239 |
#! /usr/bin/env python3
from ssedata import FunctionType
from google.protobuf.json_format import MessageToDict
import grpc
import argparse
import json
import logging
import logging.config
import os
import sys
import inspect
import time
from websocket import create_connection
import socket
import re
from concurrent imp... | gcp/__main__.py | 26,947 | ! /usr/bin/env python3 import helper .py filesself.ScriptEval = ScriptEval() Retrieve string value of parameter and append to the params variable Length of param is 1 since one column is received, the [0] collects the first value in the list Join with current timedate stamp Create an iterable of dual with the result Yi... | 3,407 | en | 0.698575 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read functionality for OGR EDIGEO driver.
# Author: Even Rouault <even dot rouault at mines dash paris dot org>
#
####################... | autotest/ogr/ogr_edigeo.py | 5,249 | !/usr/bin/env python -*- coding: utf-8 -*- $Id$ Project: GDAL/OGR Test Suite Purpose: Test read functionality for OGR EDIGEO driver. Author: Even Rouault <even dot rouault at mines dash paris dot org> Copyright (c) 2011, Even Rouault <even dot rouault at mines-paris dot org> Permission is hereby granted, free of ch... | 1,425 | en | 0.803166 |
from datetime import datetime
import itertools
import os
import random
import string
from _signal import SIGINT
from contextlib import contextmanager
from functools import partial
from itertools import permutations, combinations
from shutil import copyfile
from sys import executable
from time import sleep, perf_counter... | plenum/test/helper.py | 57,035 | Advance time to next scheduled callback and run that callback
Advance time in steps until required value running scheduled callbacks in process
the client must get at least :math:`f+1` responses
Checks if all the given nodes have the expected view no
:param nodes: The nodes to check for
:param expectedViewNo: the view... | 3,434 | en | 0.820913 |
# !/usr/bin/env python2
from math import pi, cos, sin, atan2, acos, sqrt, pow, radians, asin
from math_calc import *
from service_router import readPos
class LegConsts(object):
''' Class object to store characteristics of each leg '''
def __init__(self, x_off, y_off, z_off, ang_off, leg_nr):
self.x_of... | dns_main/src/kinematics.py | 15,667 | !/usr/bin/env python2 X offset from body origin to first servo (mm) Y offset from body origin to first servo (mm) Z offset from body origin to first servo (mm) Angular offset from body origin to first servo (mm) Angular offset of Femur Angular offset of Tibia Link length of Coxa (mm) Link length of Femur (mm) Link len... | 733 | en | 0.597333 |
'''
Module containing python objects matching the ESGF database tables.
'''
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey
from sqlalchemy.orm import relationship
Base = declarative_base()
ROLE_USER = 'user'
ROLE_PUBLISHER = 'publisher'
ROL... | cog/plugins/esgf/objects.py | 2,461 | Class that represents the 'esgf_secitity.group' table in the ESGF database.
Class that represents the 'esgf_security.permission' table in the ESGF database.
Class that represents the 'esgf_security.role' table in the ESGF database.
Class that represents the 'esgf_security.user' table in the ESGF database.
Module contai... | 438 | en | 0.456772 |
import logging
from typing import Iterable, Mapping, Optional, Union
import gym
import numpy as np
import torch as th
from stable_baselines3.common import on_policy_algorithm, vec_env
from imitation.data import types
from imitation.rewards import discrim_nets
from imitation.algorithms.adversarial import AdversarialT... | cnn_modules/cnn_gail.py | 1,593 | Generative Adversarial Imitation Learning that accepts Image Obs
Most parameters are described in and passed to `AdversarialTrainer.__init__`.
Additional parameters that `CNNGAIL` adds on top of its superclass initializer are
as follows:
Args:
discrim_kwargs: Optional keyword arguments to use while constructing t... | 346 | en | 0.688433 |
# -*- coding: utf-8 -*-
#
# Review Heatmap Add-on for Anki
# Copyright (C) 2016-2019 Glutanimate <https://glutanimate.com>
#
# This file was automatically generated by Anki Add-on Builder v0.1.4
# It is subject to the same licensing terms as the rest of the program
# (see the LICENSE file which accompanies this progra... | review_heatmap/gui/forms/anki21/__init__.py | 520 | Initializes generated Qt forms/resources
-*- coding: utf-8 -*- Review Heatmap Add-on for Anki Copyright (C) 2016-2019 Glutanimate <https://glutanimate.com> This file was automatically generated by Anki Add-on Builder v0.1.4 It is subject to the same licensing terms as the rest of the program (see the LICENSE file wh... | 403 | en | 0.877376 |
""" Orlov Module : workspace module fixture. """
import os
import logging
import pytest
from orlov.libs.workspace import Workspace
logger = logging.getLogger(__name__)
@pytest.fixture(scope='session')
def workspace(request) -> Workspace:
""" Workspace Factory Fixture.
Yields:
directory(Workspace): ... | orlov/libs/workspace/fixture.py | 822 | Workspace Factory Fixture.
Yields:
directory(Workspace): Workspace Created.
Orlov Module : workspace module fixture.
create screenshot directory | 152 | en | 0.596795 |
import dask
import dask.array as da
import numpy as np
import numpy.testing as npt
import pytest
import sklearn
import sklearn.linear_model
import sklearn.metrics
from dask.array.utils import assert_eq
import dask_ml.metrics
import dask_ml.wrappers
def test_pairwise_distances(X_blobs):
centers = X_blobs[::100].c... | tests/metrics/test_metrics.py | 5,512 | X_blobs has 500 rows per block. Ensure 500 rows in the scikit-learn version too. a_scorer = sklearn.metrics.get_scorer('neg_log_loss') b_scorer = dask_ml.metrics.get_scorer('neg_log_loss') | 188 | en | 0.610655 |
# coding=utf-8
# Copyright (c) 2019 Uber 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 ... | ludwig/models/modules/recurrent_modules.py | 22,124 | coding=utf-8 Copyright (c) 2019 Uber 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 applicable law or agreed to i... | 2,092 | en | 0.696033 |
# 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 *
class RCheckmate(RPackage):
"""Tests and assertions to perform frequent argument checks.
A s... | var/spack/repos/builtin/packages/r-checkmate/package.py | 953 | Tests and assertions to perform frequent argument checks.
A substantial part of the package was written in C to
minimize any worries about execution time overhead.
Copyright 2013-2020 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-Licen... | 354 | en | 0.871747 |
import os
import torch
import os
import random
from torch.nn import(
Module,Linear,LayerNorm
)
import math
from .AutoEncoder import Encoder
class DeltaT(Module):
def __init__(self):
super().__init__()
self.reset_seed()
self.elem = math.prod(Encoder().output_size)
self.input_size... | _Sensation0/DeltaTime.py | 1,254 | Model layersx1,x2 = x1.unsqueeze(1),x2.unsqueeze(1)x = torch.cat([x1,x2],dim=1) | 79 | en | 0.330356 |
# Time: O(k * log(min(n, m, k))), where n is the size of num1, and m is the size of num2.
# Space: O(min(n, m, k))
# You are given two integer arrays nums1
# and nums2 sorted in ascending order and an integer k.
#
# Define a pair (u,v) which consists of one element
# from the first array and one element from the seco... | Python/find-k-pairs-with-smallest-sums.py | 2,231 | :type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
Time: O(k * log(min(n, m, k))), where n is the size of num1, and m is the size of num2. Space: O(min(n, m, k)) You are given two integer arrays nums1 a... | 1,121 | en | 0.579595 |
"""
Gets concordance for keywords and groups by word.
"""
from defoe import query_utils
from defoe.alto.query_utils import get_page_matches
def do_query(archives, config_file=None, logger=None, context=None):
"""
Gets concordance for keywords and groups by word.
config_file must be the path to a configu... | defoe/alto/queries/keyword_concordance_by_word.py | 2,852 | Gets concordance for keywords and groups by word.
config_file must be the path to a configuration file with a list
of the keywords to search for, one per line.
Both keywords and words in documents are normalized, by removing
all non-'a-z|A-Z' characters.
Returns result of form:
{
<WORD>:
[
... | 1,375 | en | 0.727846 |
"""
Demonstrate differences between __str__() and __reper__().
"""
class neither:
pass
class stronly:
def __str__(self):
return "STR"
class repronly:
def __repr__(self):
return "REPR"
class both(stronly, repronly):
pass
class Person:
def __init__(self, name, age):
... | Python3/Python3_Lesson09/src/reprmagic.py | 493 | Demonstrate differences between __str__() and __reper__(). | 58 | en | 0.732133 |
#!/usr/bin/env python3
"""
"""
import socket
device_ca_server_prefix = f'{socket.gethostname()}_dio_controller:'
from caproto.threading.client import Context
ctx = Context()
ca_name = device_ca_server_prefix
pv_names = ['dio',
'bit0_indicator',
'bit0',
'b... | icarus_nmr/scripts/digital_controller_terminal_client.py | 734 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
from flask import Flask, render_template, request, redirect
from flask import render_template
app = Flask(__name__)
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
from flask import Flask,request,render_template,redirect
# 绑定访问地址127.0.0.1... | demo_flask.py | 836 | 绑定访问地址127.0.0.1:5000/user | 25 | en | 0.165828 |
#
# io_fits.py -- Module wrapper for loading FITS files.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
"""
There are two possible choices for a python FITS file readi... | ginga/util/io_fits.py | 8,569 | io_fits.py -- Module wrapper for loading FITS files. Eric Jeschke (eric@naoj.org) Copyright (c) Eric R. Jeschke. All rights reserved. This is open-source software licensed under a BSD license. Please see the file LICENSE.txt for details. maybe they have a standalone version of pyfits?newer astropy.io.fits don't have a... | 869 | en | 0.82313 |
#!/usr/bin/python
#
# Copyright: Ansible Project
# 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
DOCUMENTATION = '''
---
module: onyx_qos
author: "Anas Badaha (@anasb)"
short_description:... | venv/lib/python3.7/site-packages/ansible_collections/mellanox/onyx/plugins/modules/onyx_qos.py | 9,244 | initialize module
main entry point for module execution
!/usr/bin/python Copyright: Ansible Project GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) | 205 | en | 0.469944 |
from abstractclasses import solver, solver_model
"""
The Nash equilibrium solver takes a payoff matrix from game theory,
then it solves for a nash equilibrium, if one exists.
"""
# ————————————————————————————————————————————————
# NASH EQUILIBRIUM SOLVER CLASS
# ————————————————————————————————————————————————
cl... | modules/nashequilibrium.py | 10,956 | This is a helper function that turns a payoff matrix and available
strategies into ASCII art of a payoff matrix
Takes a payoff matrix from game theory and the available strategies for
both players. Solves for the Nash equilibrium
———————————————————————————————————————————————— NASH EQUILIBRIUM SOLVER CLASS —————————... | 497 | en | 0.376387 |
"""Describe overall framework configuration."""
import os
import pytest
from kubernetes.config.kube_config import KUBE_CONFIG_DEFAULT_LOCATION
from settings import (
DEFAULT_IMAGE,
DEFAULT_PULL_POLICY,
DEFAULT_IC_TYPE,
DEFAULT_SERVICE,
DEFAULT_DEPLOYMENT_TYPE,
NUM_REPLICAS,
BATCH_START,
... | tests/conftest.py | 5,263 | Get cli-arguments.
:param parser: pytest parser
:return:
Skip tests marked with '@pytest.mark.skip_for_nginx_oss' for Nginx OSS runs.
Skip tests marked with '@pytest.mark.appprotect' for non AP images.
:param config: pytest config
:param items: pytest collected test-items
:return:
Print out IC Pod logs on test failur... | 685 | en | 0.649976 |
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from dailymed.models import Set, Spl, InactiveIngredient
from dailymed.serializers import SplSerializer
import json
from pathlib import Path
SPL_URL = reverse('spl-list')
PR... | api/dailymed/tests/test_api.py | 5,524 | Test public daily med API
Test retrieving spls
Test retrieving spls filtered by set & inactive ingredient
Test retrieving spls by drug name filter
Test retrieving a spl by inactive ingredient filter
Test retrieving spls by schedule filter
Test retrieving a spl by set filter | 274 | en | 0.761861 |
import os
os.chdir("./export")
from reader.csv_mod import CsvReader
from reader.sarif_mod import SarifReader
from reader.server_mod import RestfulReader
from export.export import Exporter
def generate(args):
project_name = args.name
sarif_list = args.sarif
if sarif_list == None:
sarif_list = ... | codql-report/generator.py | 1,320 | r = SarifReader()r.read('/home/heersin/blackhole/codeql/result.sarif')print(os.getcwd())project_name = "socat"pdf_factory = Exporter()pdf_factory.setData(r.get_data())pdf_factory.build(project_name) | 198 | en | 0.4546 |
# Copyright (c) 2020 PaddlePaddle 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 app... | python/paddle/nn/functional/extension.py | 5,990 | This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2)
are filled by ``input``. By default, a 2D plane formed by the last two dimensions
of the returned tensor will be selected.
The argument ``offset`` determines which diagonal is generated:
- If offset = 0, it is the main diagon... | 3,496 | en | 0.694547 |
# -*- coding: utf-8 -*-
# @Time : 2021/6/10
# @Author : kaka
import argparse
import logging
import os
from config import Params
from datasets import load_dataset
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer
impor... | simcse/train_unsup.py | 4,614 | 句子进行重复
-*- coding: utf-8 -*- @Time : 2021/6/10 @Author : kaka parser.add_argument("train_file", type=str, help="train text file") parser.add_argument("--pretrained", type=str, default="hfl/chinese-bert-wwm-ext", help="huggingface pretrained model") parser.add_argument("--model_out", type=str, default="./finder_mo... | 351 | en | 0.111723 |
#---------------------------------------------------------------
# ALGORITHM DEMO : TOPLOGICAL SORT
#---------------------------------------------------------------
# Topological Sort is a algorithm can find "ordering" on an "order dependency" graph
# Concept
# https://blog.techbridge.cc/2020/05/10/leetcode-topologica... | algorithm/python/topological_sort.py | 10,916 | Perform topological sort on a directed acyclic graph.
--------------------------------------------------------------- ALGORITHM DEMO : TOPLOGICAL SORT--------------------------------------------------------------- Topological Sort is a algorithm can find "ordering" on an "order dependency" graph Concept https://blog.t... | 4,549 | en | 0.716686 |
#
# CSS
#
PIPELINE_CSS = {
'search': {
'source_filenames': (
'crashstats/css/lib/flatpickr.dark.min.css',
'supersearch/css/search.less',
),
'output_filename': 'css/search.min.css',
},
'select2': {
'source_filenames': (
'crashstats/js/lib/s... | webapp-django/crashstats/settings/bundles.py | 13,620 | CSS JavaScript This is sanity checks, primarily for developers. It checks that you haven't haven't accidentally make a string a tuple with an excess comma, no underscores in the bundle name and that the bundle file extension is either .js or .css. We also check, but only warn, if a file is re-used in a different bundle... | 506 | en | 0.940092 |
# Copyright (C) 2021, Mindee.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import pytest
import numpy as np
from scipy.optimize import linear_sum_assignment
from doctr.utils.metrics import box_iou
@p... | api/tests/routes/test_detection.py | 1,184 | Copyright (C) 2021, Mindee. This program is licensed under the Apache License version 2. See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. Check that IoU with GT if reasonable | 222 | en | 0.851742 |
from .eLABJournalObject import *
import json
import pandas as pd
import numbers
class SampleSerie(eLABJournalObject):
def __init__(self, api, data):
"""
Internal use only: initialize sample serie
"""
if ((data is not None) & (type(data) == dict) &
("name" in ... | elabjournal/elabjournal/SampleSerie.py | 1,480 | Internal use only: initialize sample serie
Get the barcode.
Get a dict with the samples for this sample serie.
The sampleID is used as a key, the value is a sample object. | 171 | en | 0.851228 |
#!/usr/bin/env python
"""
Axis camera video driver. Inspired by:
https://code.ros.org/svn/wg-ros-pkg/branches/trunk_cturtle/sandbox/axis_camera/axis.py
Communication with the camera is done using the Axis VAPIX API described at
http://www.axis.com/global/en/support/developer-support/vapix
.. note::
This is a ma... | nodes/axis.py | 27,430 | The ROS-VAPIX interface for video streaming.
A class representing a CIF standard resolution.
A class representing a video resolution.
Create the ROS-VAPIX interface.
:param hostname: Hostname of the camera (without http://, can be an IP address).
:type hostname: basestring
:param username: If login is needed, provide ... | 9,734 | en | 0.698402 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'CakeGallery.created'
db.add_column(u'cakegallery_cakegallery', 'created',
... | povary/apps/cakegallery/migrations/0014_auto__add_field_cakegallery_created__add_field_cakegallery_updated.py | 9,566 | -*- coding: utf-8 -*- Adding field 'CakeGallery.created' Adding field 'CakeGallery.updated' Deleting field 'CakeGallery.created' Deleting field 'CakeGallery.updated' | 165 | en | 0.529426 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-24 05:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('utils', '0011_auto_20160822_1127'),
]
operations = ... | apps/utils/migrations/0012_auto_20160824_0543.py | 921 | -*- coding: utf-8 -*- Generated by Django 1.9.7 on 2016-08-24 05:43 | 67 | en | 0.658825 |
import time
import pytest
from tools import utils, constants
PARAMS = ['--connections', '500']
# TODO parameterize test
@pytest.mark.baker
@pytest.mark.multinode
@pytest.mark.slow
@pytest.mark.incremental
class TestManyBakers:
"""Run 5 bakers and num nodes, wait and check logs"""
def test_init(self, sandb... | tests_python/tests/test_many_bakers.py | 869 | Run 5 bakers and num nodes, wait and check logs
TODO parameterize test | 72 | en | 0.514597 |
"""
Telnet server.
Example usage::
class MyTelnetApplication(TelnetApplication):
def client_connected(self, telnet_connection):
# Set CLI with simple prompt.
telnet_connection.set_application(
telnet_connection.create_prompt_application(...))
def... | oscar/lib/python2.7/site-packages/prompt_toolkit/contrib/telnet/server.py | 13,300 | Class that represents one Telnet connection.
Telnet server implementation.
Wrapper around socket which provides `write` and `flush` methods for the
Vt100_Output output.
Eventloop object to be assigned to `CommandLineInterface`.
Accept new incoming connection.
Handle command. This will run in a separate thread, in order... | 3,063 | en | 0.812384 |
# model settings
model = dict(
type='CenterNet',
pretrained='modelzoo://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_eval=False,
add_summay_every_n_step=200,
style='pytorch'),
... | configs/centernext/paper_cxt18_Ro16_3lr_wd4e4_hm2wh1_s123_nos_2x.py | 4,037 | model settings training and testing settings dataset settings optimizer learning policy yapf:disable yapf:enable runtime settings | 129 | en | 0.778863 |
#!/usr/bin/env python
"""
This now uses the imshow command instead of pcolor which *is much
faster*
"""
from __future__ import division, print_function
import numpy as np
from matplotlib.pyplot import *
from matplotlib.collections import LineCollection
import matplotlib.cbook as cbook
# I use if 1 to break up the di... | examples/pylab_examples/mri_with_eeg.py | 2,057 | This now uses the imshow command instead of pcolor which *is much
faster*
!/usr/bin/env python I use if 1 to break up the different regions of code visually load the data data are 256x256 16 bit integers plot the MRI in pcolor plot the histogram of MRI intensity ignore the background normalize plot the EEG load the da... | 388 | en | 0.69962 |
import pandas as pd
kraken_rank_dictionary = {
'P': 'phylum',
'C': 'class',
'O': 'order',
'F': 'family',
'G': 'genus',
'S': 'species'
}
greengenes_rank_dict = {
'k__': 'kingdom',
'p__': 'phylum',
'c__': 'class',
'o__': 'order',
'f__': 'family',
'g__': 'genus',
's__'... | benchutils/transformers.py | 2,472 | Converts a summary of all ranks from kraken into rank-wise profiles
similar to the CAMI-SIM output
Parameters
----------
all_rank_summary
output_rank_summaries
ranks
Returns
-------
TODO finsih docs TODO COULD be split into two format functions: one to reformat, and one to split on rank TODO give error for invalid... | 404 | en | 0.669179 |
"""empty message
Revision ID: f6d196dc5629
Revises: fd5076041bff
Create Date: 2019-04-06 22:25:32.133764
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f6d196dc5629'
down_revision = 'fd5076041bff'
branch_labels = None
depends_on = None
def upgrade():
# ... | services/backend/migrations/versions/f6d196dc5629_.py | 749 | empty message
Revision ID: f6d196dc5629
Revises: fd5076041bff
Create Date: 2019-04-06 22:25:32.133764
revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands | 296 | en | 0.579339 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
TODO:
* needs to check if required modules are installed (or prefereably developed)
* needs to be able to ignore plugins that the user doesnt care about
Super Setup
PREREQ:
git config --global push.default current
export CODE_DIR=~/code
mkdir $CODE_DIR
cd $CODE... | super_setup.py | 48,428 | todo, find a way to use this effectively
export THEANO_FLAGS="device=cpu,print_active_device=True,enable_initial_driver_test=True"
set THEANO_FLAGS=device=cpu,print_active_device=True,enable_initial_driver_test=True,print_test_value=True
python -c "import pydot; print(pydot.__file__)"
python -c "import pydot; print(p... | 8,999 | en | 0.35084 |
#!/usr/bin/env python3
# Software Name: ngsildclient
# SPDX-FileCopyrightText: Copyright (c) 2021 Orange
# SPDX-License-Identifier: Apache 2.0
#
# This software is distributed under the Apache 2.0;
# see the NOTICE file for more details.
#
# Author: Fabien BATTELLO <fabien.battello@orange.com> et al.
# SPDX-License-Id... | tests/test_client.py | 1,040 | !/usr/bin/env python3 Software Name: ngsildclient SPDX-FileCopyrightText: Copyright (c) 2021 Orange SPDX-License-Identifier: Apache 2.0 This software is distributed under the Apache 2.0; see the NOTICE file for more details. Author: Fabien BATTELLO <fabien.battello@orange.com> et al. SPDX-License-Identifier: Apache-2.0 | 320 | en | 0.45636 |
from django import template
from django.db import models
register = template.Library()
try:
''.rsplit
def rsplit(s, delim, maxsplit):
return s.rsplit(delim, maxsplit)
except AttributeError:
def rsplit(s, delim, maxsplit):
"""
Return a list of the words of the string s, scanning s
... | satchmo/apps/satchmo_store/shop/templatetags/satchmo_adminapplist.py | 2,769 | the following lines perform the function, but inefficiently. This may be adequate for compatibility purposes | 109 | en | 0.930966 |
# Copyright (c) 2010-2019 openpyxl
import pytest
from io import BytesIO
from zipfile import ZipFile
from openpyxl.packaging.manifest import Manifest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
from .test_fields import (
Index,
Number,
Text,
)
@py... | openpyxl/pivot/tests/test_record.py | 2,691 | Copyright (c) 2010-2019 openpyxl | 32 | en | 0.506525 |
## Calculate feature importance, but focus on "meta-features" which are categorized by
## rules from different perspectives: orders, directions, powers.
## for "comprehensive methods"
from util_relaimpo import *
from util_ca import *
from util import loadNpy
def mainCA(x_name, y_name, divided_by = "", feature_names... | feature_importance_v4.py | 2,403 | Calculate feature importance, but focus on "meta-features" which are categorized by rules from different perspectives: orders, directions, powers. for "comprehensive methods" INFO make dataframe divide X if power, only use the first four terms INFO make dataframe divide X if power, only use the first four terms da or c... | 321 | en | 0.822249 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_params.py | 17,588 | -------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. ----------------------------------------------------------------------------... | 630 | en | 0.257626 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | docs/conf.py | 1,857 | Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- If extensions (or mod... | 1,546 | en | 0.664142 |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from blueapps.account import views
app_name = 'account'
urlpatterns = [
url(r'^login_success/$', views.login_success, name="login_success"),
url(r'^login_page/$', views.login_page, name="login_page"),
url(r'^send_code/$', views.send_code_view, name... | blueapps/account/urls.py | 336 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# -*- coding: utf-8 -*-
# Copyright 2010 Dirk Holtwick, holtwick.it
#
# 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 ... | xhtml2pdf/turbogears.py | 1,458 | -*- coding: utf-8 -*- Copyright 2010 Dirk Holtwick, holtwick.it 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 agr... | 585 | en | 0.857206 |
#!/usr/bin/env python
# Copyright 2015 Coursera
#
# 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 ag... | courseraprogramming/commands/config.py | 3,985 | Checks courseraprogramming's connectivity to the coursera.org API servers
Writes to the screen the state of the authentication cache. (For debugging
authentication issues.) BEWARE: DO NOT email the output of this command!!!
You must keep the tokens secure. Treat them as passwords.
Build an argparse argument parser to p... | 1,120 | en | 0.818649 |
import torch
import torch.nn.functional as F
def spatial_argmax(logit):
weights = F.softmax(logit.view(logit.size(0), -1), dim=-1).view_as(logit)
return torch.stack(((weights.sum(1) * torch.linspace(-1, 1, logit.size(2)).to(logit.device)[None]).sum(1),
(weights.sum(2) * torch.linspace(-... | planner/regressor/models.py | 5,248 | Your code here
Predict the aim point in image coordinate, given the supertuxkart image
@img: (B,3,96,128)
return (B,2)
self.classifier = torch.nn.Linear(h, 2) self.classifier = torch.nn.Conv2d(h, 1, 1) Add all the information required for skip connections Fix the padding Add the skip connection | 297 | en | 0.520751 |
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
# Empty for now (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpa... | chat_app/routing.py | 346 | Empty for now (http->django views is added by default) | 54 | en | 0.931003 |
#
# 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... | tests/providers/amazon/aws/hooks/test_cloud_formation.py | 3,387 | 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... | 752 | en | 0.883564 |
"""sls.py
An implementation of the robust adaptive controller.
Both FIR SLS version with CVXPY and the common
Lyapunov relaxation.
"""
import numpy as np
import cvxpy as cvx
import utils
import logging
import math
import scipy.linalg
from abc import ABC, abstractmethod
from adaptive import AdaptiveMethod
class ... | python/sls.py | 22,553 | Adaptive control based on common Lyapunov relaxation
of robust control problem
Adaptive control based on FIR truncated SLS
Gets the squared infinite horizon LQR cost for system
(A,B) in feedback with the controller defined by Phi_x
and Phi_u.
Converts FIR transfer functions to a state
space realization of the dy... | 3,609 | en | 0.77174 |
# partesanato/__init__.py
| src/partesanato/__init__.py | 27 | partesanato/__init__.py | 23 | es | 0.257923 |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... | contrib/seeds/generate-seeds.py | 4,382 | Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory that is passed as an
argument:
nodes_main.txt
nodes_test.txt
These files must consist of lines in the format
<ip>
<ip>:<port>
[<ipv6>]
[<ipv6>]:<port>
<onion>.onion
0xDDBBCC... | 989 | en | 0.603813 |
"""
Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents.
"""
from __future__ import division
import math
import random
from itertools import count
from neat.config import ConfigParameter, DefaultClassConfig
from neat.math_util import mean
from neat.six_util import iterit... | neat_local/reproduction.py | 8,371 | Implements the default NEAT-python reproduction scheme:
explicit fitness sharing with fixed-time species stagnation.
Compute the proper number of offspring per species (proportional to fitness).
Handles creation of genomes, either from scratch or by sexual or
asexual reproduction from parents.
Handles creation of genom... | 2,862 | en | 0.905464 |
import logging
from functools import reduce
from typing import Text, Set, Dict, Optional, List, Union, Any
import os
import rasa.shared.data
import rasa.shared.utils.io
from rasa.shared.core.domain import Domain
from rasa.shared.importers.importer import TrainingDataImporter
from rasa.shared.importers import utils
fro... | rasa/shared/importers/multi_project.py | 7,787 | Retrieves model config (see parent class for full docstring).
Returns config file path for auto-config only if there is a single one.
Retrieves conversation test stories (see parent class for full docstring).
Retrieves model domain (see parent class for full docstring).
Retrieves NLU training data (see parent class for... | 861 | en | 0.840131 |
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
from __future__ import absolute_import, division... | jsonpickle/pickler.py | 26,149 | Recursively call flatten() and return json-friendly dict
Special case file objects
Flatten a key/value pair into the passed-in dictionary.
Return a json-friendly dict for new-style objects with __slots__.
Flatten only non-string key/value pairs
Recursively flatten an instance and return a json-friendly dict
Return a js... | 8,530 | en | 0.769188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.