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 |
|---|---|---|---|---|---|---|
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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 ... | mysite/mysite/urls.py | 797 | mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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 vie... | 622 | en | 0.617633 |
# ReID Online Upload Service | upload/__init__.py | 28 | ReID Online Upload Service | 26 | en | 0.838573 |
# Author: F. Alex Wolf (http://falexwolf.de)
"""Differential Gene Expression Analysis
This is a Beta Version of a tool for differential gene expression testing
between sets detected in previous tools. Tools such as dpt, cluster,...
"""
import numpy as np
from scipy.sparse import issparse
from .. import utils
from .. ... | scanpy/tools/rank_genes_groups.py | 6,837 | Rank genes according to differential expression [Wolf17]_.
Rank genes by differential expression. By default, a t-test-like ranking is
used, in which means are normalized with variances. Soon, a Wilcoxon-rank
test and other alternatives will be provided.
Parameters
----------
adata : `AnnData`
Annotated data matr... | 2,013 | en | 0.750433 |
from __future__ import absolute_import
from django.dispatch import Signal
from functools import wraps
class BetterSignal(Signal):
def connect(self, receiver=None, **kwargs):
"""
Support decorator syntax:
>>> @signal.connect(sender=type)
>>> def my_receiver(**kwargs):
>>> ... | src/sentry/signals.py | 754 | Support decorator syntax:
>>> @signal.connect(sender=type)
>>> def my_receiver(**kwargs):
>>> pass | 103 | en | 0.632808 |
# Purpose: Calculate hydrological fluxes in the canopy, unsaturated and saturated sub-domains
# Record of revisions:
# Date Programmer Description of change
# ======== ============= =====================
# 09-2020 A. Elkouk Original code
# ------------------------------------------------... | flux_param.py | 7,501 | Calculate baseflow from the saturated zone
Parameters
----------
satStore : int or float
Storage in the saturated zone [mm]
k_sz : float
Runoff coefficient for the saturated zone [day^-1]
Returns
-------
baseflow : float
Baseflow from the saturated zone [mm day^-1]
Calculate the canopy drainage flux from ... | 4,735 | en | 0.447574 |
########################################################################
#
# Constants
#
########################################################################
RETURN_SUCCESS = 1234 # Requested command executed successfully
RETURN_FAIL = None # Requested command failed | libs/dev/consts.py | 277 | Constants Requested command executed successfully Requested command failed | 76 | en | 0.942536 |
#!/usr/bin/env python
#
# Copyright 2013 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
#... | src/etc/generate-deriving-span-tests.py | 4,072 | This script creates a pile of compile-fail tests check that all the
derives have spans that point to the fields, rather than the
#[derive(...)] line.
sample usage: src/etc/generate-deriving-span-tests.py
!/usr/bin/env python Copyright 2013 The Rust Project Developers. See the COPYRIGHT file at the top-level directory... | 843 | en | 0.730305 |
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgwidgetprogress"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osgDB
from osgpypp import osgWidget
# Translated from file 'osgwidgetprogress.cpp'
# -*-c++-*- osg... | examples/rough_translated1/osgwidgetprogress.py | 2,695 | !/bin/env python Automatically translated python version of OpenSceneGraph example program "osgwidgetprogress" !!! This program will need manual tuning before it will work. !!! Translated from file 'osgwidgetprogress.cpp' -*-c++-*- osgWidget - Code by: Jeremy Moles (cubicool) 2007-2008 $Id$include <osgDB/ReadFile>incl... | 399 | en | 0.725257 |
import numpy as np
import cv2
import matplotlib.pyplot as plt
#read image
img = np.array(cv2.imread('1.jpg'))
#this is mask
mask = np.zeros(img.shape[:2],np.uint8)
#this bgdModel and fgdModel is used in background
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
#This is a... | code/grab_foreground.py | 807 | read imagethis is maskthis bgdModel and fgdModel is used in backgroundThis is a rectangular cross section of given image where it will search for foregroundThis is a grabcut func from opencv which is used to detect foregroundhere we show our image | 247 | en | 0.908498 |
#!/usr/bin/env python3
"""
Convert data received from alfred (ffbi format) and serve them as prometheus python client
Typical call::
alfred -r 69 -u /var/run/alfred/alfred.sock > robin.txt
./robin_prometheus.py -m robin.txt
Dependencies:
prometheus_client -> pip3 install prometheus_client
License: CC BY... | roles/ffbsee-robin-exporter/files/robin_prometheus.py | 11,363 | A class providing static methods to parse and validate data reported by
nodes via alfred.
Data Collector for serving them in prometheus client
A node in the freifunk network, identified by its primary MAC.
Strip an escaped string which is enclosed in double quotes and
unescape.
collectors only function called collect. ... | 2,098 | en | 0.811136 |
"""
Aaron Harkrider
November 8th, 2018
Build a trojan horse that gains access to a file on cyber.anderson.edu.
The file under attack is the grade book for this assignment.
Sneaky sneaky
"""
import os
def test_mytest():
"""
When Dr. Tarplee run's py.test on the assignment this py file will run and insert my... | Trojan_Horse_Lab/awharkrider_test.py | 1,387 | When Dr. Tarplee run's py.test on the assignment this py file will run and insert my entry into the grade book.
Aaron Harkrider
November 8th, 2018
Build a trojan horse that gains access to a file on cyber.anderson.edu.
The file under attack is the grade book for this assignment.
Sneaky sneaky
the entry I want to in... | 855 | en | 0.841376 |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2021 Blue Cheetah Analog Design 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
#
# U... | tests/test_list.py | 3,114 | Check object is constructed properly.
Check object has correct doc string.
Check object errors when input has wrong data type.
Test inheritance behavior.
Test overriding virtual methods from python.
SPDX-License-Identifier: Apache-2.0 Copyright 2021 Blue Cheetah Analog Design Inc. Licensed under the Apache License, V... | 805 | en | 0.823169 |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | package/spack-xsetmode/package.py | 1,676 | Set the mode for an X Input device.
Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. This file is part of Spack. Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. LLNL-CODE-647188 For details, see https://github.com/spack/spack ... | 1,070 | en | 0.891682 |
# Copyright 2022, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | nuitka/utils/MemoryUsage.py | 4,269 | Memory usage of own process in bytes.
Tools for tracing memory usage at compiled time.
Copyright 2022, Kay Hayen, mailto:kay.hayen@gmail.com Part of "Nuitka", an optimizing Python compiler that is compatible and integrates with CPython, but also works on its own. Licensed under the Apache License, Ver... | 1,142 | en | 0.88551 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-04-30 17:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('codenerix_storages', '0025_auto_20180426_1035'),
]
... | codenerix_storages/migrations/0026_auto_20180430_1909.py | 1,104 | -*- coding: utf-8 -*- Generated by Django 1.10.8 on 2018-04-30 17:09 | 68 | en | 0.639366 |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Machine/Magnet.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Machine/Magnet
"""
from os import linesep
from sys import getsizeof
from loggin... | pyleecan/Classes/Magnet.py | 7,772 | Magnet class
Compare two objects (skip parent)
Constructor of the class. Can be use in three ways :
- __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
for pyleecan type, -1 will call the default constructor
- __init__ (init_dict = d) d must be a dictionary with property names as keys
- __... | 1,723 | en | 0.718916 |
"""Module containing a preprocessor that removes the outputs from code cells"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from textwrap import dedent
try:
from queue import Empty # Py 3
except ImportError:
from Queue import Empty # Py 2
... | env/lib/python2.7/site-packages/nbconvert/preprocessors/execute.py | 6,122 | Custom exception to propagate exceptions that are raised during
notebook execution to the caller. This is mostly useful when
using nbconvert as a library, since it allows to deal with
failures gracefully.
Executes all the cells in a notebook
Apply a transformation on each code cell. See base.py for details.
Module cont... | 619 | en | 0.89555 |
from rqalpha.interface import AbstractMod
from rqalpha.apis import *
from rqalpha.events import EVENT
from collections import defaultdict
import datetime
import os
class ForceClose(AbstractMod):
def __init__(self):
self._log_dir = None
self._log_file = defaultdict(lambda: None)
self._force... | rqalpha/mod/rqalpha_mod_force_close/mod.py | 3,233 | env.event_bus.add_listener(EVENT.BAR, self._check_force_close) order_to(contract, 0) return True print("call _calc_flow") if event.bar_dict._frequency != "1m": return if len(self._kline_bar) < self._kline_bar_cnt: self._kline_bar.append(event.) | 252 | en | 0.067347 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 damian <damian@C-DZ-E5500>
#
# Distributed under terms of the MIT license.
"""
"""
import subprocess
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import yaml
def read_file(filename):
with open(f... | bandit/insecureCode.py | 653 | ! /usr/bin/env python -*- coding: utf-8 -*- vim:fenc=utf-8 Copyright © 2018 damian <damian@C-DZ-E5500> Distributed under terms of the MIT license. | 146 | en | 0.500052 |
# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(1)
# Node Class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None # In python, None == null
class LinkedList:
# Constructor to initi... | Data_Structures/LinkedList/Reverse_List/reverse_LinkedList.py | 3,543 | Python program to reverse a linked list Time Complexity : O(n) Space Complexity : O(1) Node Class Constructor to initialize the node object In python, None == null Constructor to initialize the linked list Function to insert a new node at the beginning This is how you create an object in python Function to insert a new... | 860 | en | 0.775753 |
#
# PySNMP MIB module SENAO-ENTERPRISE-INDOOR-AP-CB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SENAO-ENTERPRISE-INDOOR-AP-CB-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:53:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | pysnmp/SENAO-ENTERPRISE-INDOOR-AP-CB-MIB.py | 26,422 | PySNMP MIB module SENAO-ENTERPRISE-INDOOR-AP-CB-MIB (http://snmplabs.com/pysmi) ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SENAO-ENTERPRISE-INDOOR-AP-CB-MIB Produced by pysmi-0.3.4 at Mon Apr 29 20:53:40 2019 On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 Using Python versio... | 360 | en | 0.372077 |
import asyncio
import dataclasses
import time
import traceback
from secrets import token_bytes
from typing import Dict, List, Optional, Tuple, Set
from blspy import AugSchemeMPL, G2Element
from chiabip158 import PyBIP158
import chia.server.ws_connection as ws
from chia.consensus.block_creation import create_unfinishe... | chia/full_node/full_node_api.py | 72,148 | this semaphore limits the number of tasks that can call new_peak() at the same time, since it can be expensive Ignore if syncing Ignore if already seen If there's current pending request just add this peer to the set of peers that have this tx Limit to asking to a few peers, it's possible that this tx got included on c... | 3,308 | en | 0.922043 |
"""
Provide a mock switch platform.
Call init before using it in your tests to ensure clean test data.
"""
from homeassistant.const import STATE_ON, STATE_OFF
from tests.common import MockToggleDevice
DEVICES = []
def init(empty=False):
"""Initialize the platform with devices."""
global DEVICES
DEVICE... | tests/testing_config/custom_components/switch/test.py | 685 | Initialize the platform with devices.
Provide a mock switch platform.
Call init before using it in your tests to ensure clean test data. | 137 | en | 0.759445 |
#AST transform that puts programs in SSA form
import collections
from translate import *
class SSAVisitor(Visitor):
def __init__(self):
# Number of static assignments to that variable seen so far.
self.definition_counter = collections.defaultdict(int)
# Name of the live definition of each v... | ssa.py | 5,949 | AST transform that puts programs in SSA form Number of static assignments to that variable seen so far. Name of the live definition of each variable before a node. Name of the last definition of each variable in a node. Node in SSA form. The if branches have their prev_definition set by the parent, so they don't redefi... | 331 | en | 0.908039 |
from __future__ import absolute_import
from __future__ import unicode_literals
import docker
import pytest
from docker.constants import DEFAULT_DOCKER_API_VERSION
from docker.errors import APIError
from docker.errors import NotFound
from .. import mock
from .. import unittest
from compose.config.errors import Depende... | tests/unit/service_test.py | 55,021 | This is aimed at simulating a race between the API call to list the containers, and the ones to inspect each of the listed containers. It can happen that a container has been removed after we listed it. containers() returns a container that is about to be removed inspect_container() will raise a NotFound when trying to... | 463 | en | 0.95192 |
import subprocess
import pymongo
class ReportsDataBase:
def __init__(self, url, db_name):
self.db_name = db_name
self.db = pymongo.MongoClient(url)[self.db_name]
self.db['reports'].create_index('group')
self.db['reports'].create_index('author')
self.db['reports'].create_i... | src/database/reports_data_base.py | 10,239 | words_intersections = [ (author_name, other_author_name, ['word1', 'word2', 'word3', ...]), .... ] | 98 | en | 0.393872 |
# coding: utf-8
"""
Velo Payments APIs
## Terms and Definitions Throughout this document and the Velo platform the following terms are used: * **Payor.** An entity (typically a corporation) which wishes to pay funds to one or more payees via a payout. * **Payee.** The recipient of funds paid out by a payor.... | velo_payments/models/name2.py | 10,846 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Returns true if both objects are equal
Name2 - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Gets the first_name of this Name2. # noqa: E501
:... | 6,110 | en | 0.805235 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'calculator2.ui'
#
# Created by: PyQt5 UI code generator 5.15.3
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... | gui_calculator.py | 16,968 | -*- coding: utf-8 -*- Form implementation generated from reading ui file 'calculator2.ui' Created by: PyQt5 UI code generator 5.15.3 WARNING: Any manual changes made to this file will be lost when pyuic5 is run again. Do not edit this file unless you know what you are doing. | 276 | en | 0.902723 |
"""
Seed-based connectivity on the surface
=======================================
The dataset that is a subset of the enhanced NKI Rockland sample
(http://fcon_1000.projects.nitrc.org/indi/enhanced/, Nooner et al, 2012)
Resting state fMRI scans (TR=645ms) of 102 subjects were preprocessed
(https://github.com/fliem/n... | examples/01_plotting/plot_surf_stat_map.py | 6,445 | Seed-based connectivity on the surface
=======================================
The dataset that is a subset of the enhanced NKI Rockland sample
(http://fcon_1000.projects.nitrc.org/indi/enhanced/, Nooner et al, 2012)
Resting state fMRI scans (TR=645ms) of 102 subjects were preprocessed
(https://github.com/fliem/nki_n... | 3,187 | en | 0.709076 |
import logging
import sys
from abc import abstractmethod
from typing import TextIO
import pandas as pd
from datapackage import Package
from pandas_datapackage_reader import read_datapackage
from sqlalchemy import create_engine
from otoole import read_packaged_file
logger = logging.getLogger(__name__)
class DataPac... | src/otoole/preprocess/narrow_to_datafile.py | 7,302 | Convert a data package to another format
Arguments
---------
datapackage: str
The path to the databackage
datafilepath: str
The path to the destination file or folder
sql: bool, default=False
Flag to set whether the source datapackage is in sqlite format
Converts data into wide format
Arguments
---------
... | 809 | en | 0.215723 |
# Data from https://www.kaggle.com/crawford/80-cereals/version/2
import pandas, matplotlib
data = pandas.read_csv('http://www.compassmentis.com/wp-content/uploads/2019/04/cereal.csv')
data = data.set_index('name')
data = data.calories.sort_values()[-10:]
ax = data.plot(kind='barh')
ax.set_xlabel('Calories per serving')... | read_csv_and_plot/read_and_plot.py | 458 | Data from https://www.kaggle.com/crawford/80-cereals/version/2 | 62 | en | 0.778167 |
#!/usr/bin/env python
# Copyright (c) 2012 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.
# Copyright (C) 2008 Evan Martin <martine@danga.com>
"""A git-command for integrating reviews on Rietveld and Gerrit."""
from __f... | git_cl.py | 190,006 | Contains a parsed form of the change description.
Changelist works with one changelist in local branch.
Supports two codereview backends: Rietveld or Gerrit, selected at object
creation.
Notes:
* Not safe for concurrent multi-{thread,process} use.
* Caches values from current branch. Therefore, re-use after branc... | 31,633 | en | 0.854541 |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# (c) Copyright 2013 Hewlett-Pa... | nova/virt/libvirt/driver.py | 244,846 | Manages information about the compute node through libvirt.
Checks if destination has enough disk for block migration.
Confirms existence of the tmpfile under CONF.instances_path.
Cannot confirm tmpfile return False.
Make sure that a failed migrate doesn't prevent us from rolling
back in a revert.
Delete all LVM disks... | 42,322 | en | 0.862784 |
# Copyright 2018 Braxton Mckee
#
# 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 t... | object_database/service_manager/ServiceBase.py | 1,936 | Subclasses should take the remaining args from the commandline and configure using them
Copyright 2018 Braxton Mckee 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.... | 697 | en | 0.871016 |
# Generated by Django 2.0.5 on 2018-12-04 13:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('branch', '0007_auto_20181204_2034'),
]
operations = [
migrations.AddField(
model_name='authentication',
name='sty',
... | Demo/branch/migrations/0008_authentication_sty.py | 434 | Generated by Django 2.0.5 on 2018-12-04 13:00 | 45 | en | 0.569114 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | aliyun-python-sdk-dyplsapi/aliyunsdkdyplsapi/request/v20170525/BindAxnRequest.py | 4,943 | 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... | 1,020 | en | 0.658176 |
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, LargeBinary, Float, UniqueConstraint
from sqlalchemy.orm import relationship, backref
from datetime import datetime
from conductor.app.db.base_class import Base
class DiscoveryResult(Base):
__tablename__ = "discovery_results"
__ta... | conductor/app/models/discovery.py | 732 | this can be db.PrimaryKeyConstraint if you want it to be a primary key | 70 | en | 0.746741 |
## @package attention
# Module caffe2.python.attention
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class AttentionType:
Regular, Recurrent = range(2)
def s(scope, name):
# We have to manually scope due t... | caffe2/python/attention.py | 7,839 | @package attention Module caffe2.python.attention We have to manually scope due to our internal/external blob relationships. c_i = \sum_j w_{ij}\textbf{s}_j [batch_size, encoder_output_dim, 1] TODO: somehow I cannot use Squeeze in-place op here [batch_size, encoder_output_dim] Calculate a softmax over the passed in att... | 1,144 | en | 0.628811 |
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String, Float
from sqlalchemy.ext.declarative import declarative_base
from zvt.contract import Mixin
from zvt.contract.register import register_schema
MoneyFlowBase = declarative_base()
# 板块资金流向
class BlockMoneyFlow(MoneyFlowBase, Mixin):
__tablename__ = '... | zvt/domain/misc/money_flow.py | 2,132 | -*- coding: utf-8 -*- 板块资金流向 收盘价 净流入 净流入率 主力=超大单+大单 超大单 大单 中单 小单 收盘价 净流入 净流入率 主力=超大单+大单 超大单 大单 中单 小单 the __all__ is generated | 125 | zh | 0.909419 |
# -*- coding: utf-8 -*-
"""Identity Services Engine getAllowedProtocolById data model.
Copyright (c) 2021 Cisco and/or its affiliates.
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 rest... | tests/models/validators/v3_0_0/jsd_e3ddfddd45e299f14ed194926f8de.py | 8,982 | getAllowedProtocolById request schema definition.
Identity Services Engine getAllowedProtocolById data model.
Copyright (c) 2021 Cisco and/or its affiliates.
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 th... | 1,206 | en | 0.860339 |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/10 7:44 PM
# @Author : xiaoliji
# @Email : yutian9527@gmail.com
"""
找出和为s的数字。
>>> nums = [1, 2, 4, 7, 11, 15]
>>> FindNumbersWithSum(nums, 15)
(4, 11)
"""
def FindNumbersWithSum(array: list, tsum: int) -> tuple:
l, r = 0, len(a... | Algorithm/coding_interviews/Python/sword-for-offer/57_find_num_with_sum.py | 542 | 找出和为s的数字。
>>> nums = [1, 2, 4, 7, 11, 15]
>>> FindNumbersWithSum(nums, 15)
(4, 11)
! /usr/bin/python3 -*- coding: utf-8 -*- @Time : 2019/3/10 7:44 PM @Author : xiaoliji @Email : yutian9527@gmail.com | 208 | en | 0.344489 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2017, 2018, 2019, 2020, 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA Job Controller models."""
from ... | reana_job_controller/schemas.py | 4,018 | Job model.
Job request model.
Set kubernetes_job_timeout to a default value if not provided and validate the value.
Method receives the whole data dictionary but operates *only* on kubernetes_job_timeout.
Updated dictionary is returned.
REANA Job Controller models.
!/usr/bin/env python3 -*- coding: utf-8 -*- This fil... | 530 | en | 0.72586 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vote_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that... | vote_project/manage.py | 810 | !/usr/bin/env python The above import may fail for some other reason. Ensure that the issue is really that Django is missing to avoid masking other exceptions on Python 2. | 171 | en | 0.863733 |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... | setup.py | 6,578 | A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
Always prefer setuptools over distutils To use a consistent encoding Get the long description from the README file Arguments marked as "Required" below must be included for upload to P... | 4,829 | en | 0.785089 |
# encoding: utf-8
#
# Copyright 2009-2020 Greg Neagle.
#
# 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 l... | code/client/munkilib/updatecheck/catalogs.py | 26,415 | Adds packageids from each catalogitem to two dictionaries.
One maps itemnames to receipt pkgids, the other maps receipt pkgids
to itemnames
Analyze catalog data and installed packages in an attempt to determine
what is installed.
Attempts to find the best match in item_dict for vers_num
Returns our internal _CATALOG di... | 7,416 | en | 0.831414 |
#--- Exercício 1 - Funções - 1
#--- Escreva uma função que imprima um cabeçalho
#--- O cabeçalho deve ser escrito usando a multiplicação de carácter
#--- resultado esperado: -------------- Cadastro Serasa --------------------------
#--- O cabeçalho deve conter o nome de uma empresa, que será uma variável
#--- Realize... | 01-Exercicios/Aula007/Ex1.py | 545 | --- Exercício 1 - Funções - 1--- Escreva uma função que imprima um cabeçalho--- O cabeçalho deve ser escrito usando a multiplicação de carácter --- resultado esperado: -------------- Cadastro Serasa ----------------------------- O cabeçalho deve conter o nome de uma empresa, que será uma variável--- Realize a chamada ... | 361 | pt | 0.992754 |
# coding=utf-8
from typing import Iterable
from .registry import registry
@registry.register("A000073")
def tribonacci() -> Iterable[int]:
"""Tribonacci numbers."""
yield 0
yield 0
yield 1
p3: int = 0 # tribonacci(0)
p2: int = 0 # tribonacci(1)
p1: int = 1 # tribonacci(2)
while Tru... | oeis/tribonacci.py | 409 | Tribonacci numbers.
coding=utf-8 tribonacci(0) tribonacci(1) tribonacci(2) | 76 | en | 0.538386 |
from dataclasses import dataclass
from enum import IntEnum
from typing import Optional, Dict
from blspy import G1Element
from wheat.protocols.pool_protocol import POOL_PROTOCOL_VERSION
from wheat.types.blockchain_format.coin import Coin
from wheat.types.blockchain_format.program import Program
from wheat.types.blockc... | wheat/pools/pool_wallet_info.py | 4,509 | From the user's point of view, a pool group can be in these states:
`SELF_POOLING`: The singleton exists on the blockchain, and we are farming
block rewards to a wallet address controlled by the user
`LEAVING_POOL`: The singleton exists, and we have entered the "escaping" state, which
means we are waiting for ... | 1,684 | en | 0.907008 |
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2022 Jeff Epler for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
# On an Adafruit Feather M4 or Adafruit Feather RP2040 with Floppy Featherwing,
# do some track-to-track seeking and flu... | examples/floppy_simpletest.py | 1,214 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries SPDX-FileCopyrightText: Copyright (c) 2022 Jeff Epler for Adafruit Industries SPDX-License-Identifier: Unlicense On an Adafruit Feather M4 or Adafruit Feather RP2040 with Floppy Featherwing, do some track-to-track seeking and flux reading. | 317 | en | 0.604935 |
"""Code and data structures for managing source directives."""
import bisect
import collections
import re
import sys
import tokenize
from pytype import utils
from six import moves
_DIRECTIVE_RE = re.compile(r"#\s*(pytype|type)\s*:\s?([^#]*)")
_CLOSING_BRACKETS_RE = re.compile(r"^(\s*[]})]\s*)+(#.*)?$")
_WHITESPACE_R... | pytype/directors.py | 11,290 | Holds all of the directive information for a source file.
Exception thrown if we encounter "pytype: skip-file" in the source code.
A set of line numbers.
The data structure is optimized to represent the union of a sparse set
of integers and ranges of non-negative integers. This supports the two styles
of directives: ... | 4,408 | en | 0.885741 |
import os
import time
import torch
import torch.nn as nn
import utils
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
def instance_bce_with_logits(logits, labels):
assert logits.dim() == 2
loss = nn.functional.binary_cross_entropy_with_logits(logits, labels)
loss *... | train.py | 3,564 | argmax Paper uses AdaDelta boxes not used true labels | 53 | en | 0.141878 |
from collections import defaultdict
from hashlib import md5
from typing import DefaultDict, Dict, List, Set, Union
import attr
from pyrdf2vec.graphs import KG, Vertex
from pyrdf2vec.typings import Entities, EntityWalks, SWalk
from pyrdf2vec.walkers import RandomWalker
@attr.s
class WLWalker(RandomWalker):
"""We... | pyrdf2vec/walkers/weisfeiler_lehman.py | 6,735 | Weisfeiler-Lehman walking strategy which relabels the nodes of the
extracted random walks, providing additional information about the entity
representations only when a maximum number of walks is not specified.
Attributes:
_inv_label_map: Stores the mapping of the inverse labels.
Defaults to defaultdict.
... | 2,986 | en | 0.854357 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import copy
import json
import requests
import pytz
import time
from inky.inky_uc8159 import Inky, DESATURATED_PALETTE
from datetime import datetime
from PIL import Image, ImageFont, ImageDraw
import io
import apikey
import os
import signal
import RPi.GPIO as GPIO
path = os.p... | weather.py | 10,557 | !/usr/bin/python3 -*- coding: utf-8 -*- 180 = flip displayBUTTONS = [5, 6, 16, 24]GPIO.setup(Buttons, GPIO.IN, pull_up_down=GPIO.PUD_UP)def handle_button(pin): label = LABELS[BUTTONS.index(pin)]pressure = int(day["pressure"])print(day["pressure"]) | 249 | en | 0.394866 |
"""
This module contains the cli functions.
Split them out into separate files if required.
"""
import sys
import os
import subprocess
import pickle
from cheapskate_bal import balance as bal
__collector__ = {'exe': "collect_3008", 'samp_rate': 2000}
def csbal_process():
"""
This method is run when the `csba... | cheapskate_bal/cheapskate_bal/cli.py | 4,806 | THis method performs the whole process for a dual plane balance
Three files are captured and the results are emitted
args are file stem, freq(Hz), shift angle of test mass (deg), test mass
This method performs an iteration of dual plane balance, once the
influence params are known. One file is captured and the result... | 1,100 | en | 0.917547 |
from __future__ import absolute_import
import os
# test_settings.py works differently from
# dev_settings.py/prod_settings.py; it actually is directly referenced
# by the test suite as DJANGO_SETTINGS_MODULE and imports settings.py
# directly and then hacks up the values that are different for the
# test suite. As wil... | zproject/test_settings.py | 4,961 | test_settings.py works differently from dev_settings.py/prod_settings.py; it actually is directly referenced by the test suite as DJANGO_SETTINGS_MODULE and imports settings.py directly and then hacks up the values that are different for the test suite. As will be explained, this is kinda messy and probably we'd be be... | 2,135 | en | 0.844574 |
import json
import os
import signal
import sys
from zipfile import BadZipfile
from zlib import error as zlib_error
from defusedxml.common import DefusedXmlException
import validator
from validator import decorator
from validator.chromemanifest import ChromeManifest
from validator.opensearch import detect_opensearch
f... | validator/submain.py | 15,382 | Loads the chrome.manifest if it's present
Prepares a file-based package for validation.
timeout is the number of seconds before validation is aborted.
If timeout is -1 then no timeout checking code will run.
Tests a package's inner content.
Begins tests for the package.
Tests the package to see if it is a search provi... | 2,570 | en | 0.84549 |
from flask import Flask, request, redirect, render_template, url_for, flash, jsonify
import gridfs, random, uuid, os
from flask_uploads import UploadSet, configure_uploads, IMAGES
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc
from datetime import datetime
app = Flask(__name__,
static_... | app.py | 3,986 | Database setup SQL form itemstime = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) Render webpages Get form data Check if the form is empty Save to database Save the photo in the upload folder Print test | 220 | en | 0.527687 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to parse BSM event auditing files."""
import argparse
import logging
import sys
from dtformats import bsm
from dtformats import output_writers
def Main():
"""The main program function.
Returns:
bool: True if successful or False if not.
"""
argumen... | scripts/bsm.py | 1,550 | The main program function.
Returns:
bool: True if successful or False if not.
Script to parse BSM event auditing files.
!/usr/bin/env python -*- coding: utf-8 -*- | 166 | en | 0.535807 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | CAAPR/CAAPR_AstroMagic/PTS/pts/magic/tools/masks.py | 4,809 | This function ...
:param region:
:param inner_factor:
:param outer_factor:
:param header:
:param x_size:
:param y_size:
:return:
This function ...
:param x_size:
:param y_size:
:param x_center:
:param y_center:
:param radius:
:return:
This function ...
:param args:
:return:
This function ...
:param region:
:param heade... | 2,337 | en | 0.534278 |
import sys, math
import numpy as np
import Box2D
from Box2D.b2 import (edgeShape, circleShape, fixtureDef, polygonShape, revoluteJointDef, contactListener)
import gym
from gym import spaces
from gym.utils import colorize, seeding
# This is simple 4-joints walker robot environment.
#
# There are two versions:
#
# - N... | mbbl_envs/env/gym_env/box2d/walker.py | 23,069 | This is simple 4-joints walker robot environment. There are two versions: - Normal, with slightly uneven terrain. - Hardcore with ladders, stumps, pitfalls. Reward is given for moving forward, total 300+ points up to the far end. If the robot falls, it gets -100. Applying motor torque costs a small amount of points, mo... | 2,009 | en | 0.917774 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | cinder/volume/api.py | 18,767 | API for interacting with the volume manager.
Check if the volume can be used.
Create a new image from the specified volume.
Delete the given metadata item from an volume.
Get all metadata associated with a volume.
Get value of particular metadata key.
Remove volume from specified compute host.
Updates or creates volume... | 2,082 | en | 0.797932 |
"""
See notebook 5 for example use of show_mri_sample()
"""
import glob
import os
import random
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
import cv2
import scipy.ndimage as ndimage
def make_bg_transparent(im, bg_th=0.0, set_to_color=None):... | src/seg_model_utils/visualization.py | 8,945 | Plot sample in three projections
See notebook 5 for example use of show_mri_sample()
create transparency alpha channel convert image to RGBA add batch dims if missing special case fix to get with correct with small bs Read additional meta from batch upsample seg back to original size if it has been downsampled Norma... | 601 | en | 0.806733 |
import glob
import pandas as pd
import os
import datetime
class DataMerge:
def __init__(self, directory):
self.directory = directory
self.__data = self.get_data_from(self.directory)
def date_to_int(self, dates):
"""
calculates number of days between 01/01/0001 and each date in... | backend/data_merge.py | 1,449 | calculates number of days between 01/01/0001 and each date in dates
date has format '%m/%d/%Y'
:param dates: Pandas Series
:return: list | 137 | en | 0.799051 |
import jax.numpy as np
import matplotlib.pyplot as plt
def plot(vi, X,
target='vanishing',
n=1000, scale=1.5, x_max=1.0, y_max=1.0,
z_func=lambda x_, y_: 0.0,
show=False, splitshow=False):
nvars = X.shape[-1]
if nvars == 2:
_plot2d(vi, X, target=target,
n=n, scale=s... | mavi/jax/util/plot.py | 3,803 | set plot range x = np.arange(-scale*x_max, scale*x_max, resolution) y = np.arange(-scale*y_max, scale*y_max, resolution) set plot setting npolys = sum([Gt.shape[-1] for Gt in vi.basis.vanishings()]) npolys = sum([len(Gt) for Gt in vi.basis.vanishings()]) plt.savefig('graph_Z.pdf') set plot range set plot setti... | 413 | en | 0.337409 |
"""Code generation utilities"""
from .utils import SchemaInfo, is_valid_identifier, indent_docstring, indent_arglist
import textwrap
import re
class CodeSnippet(object):
"""Object whose repr() is a string of code"""
def __init__(self, code):
self.code = code
def __repr__(self):
return se... | tools/schemapi/codegen.py | 7,247 | Object whose repr() is a string of code
Class that defines methods for generating code from schemas
Parameters
----------
classname : string
The name of the class to generate
schema : dict
The dictionary defining the schema class
rootschema : dict (optional)
The root schema for the class
basename : string ... | 1,555 | en | 0.560673 |
# 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, ... | jax/lib/__init__.py | 2,054 | 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, software distribut... | 779 | en | 0.850194 |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""
import sys
sys.path.append('..')
from nlpcommon import stopwords
if __name__ == '__main__':
print(len(stopwords), stopwords)
| examples/base_demo.py | 211 | @author:XuMing(xuming624@qq.com)
@description:
-*- coding: utf-8 -*- | 71 | en | 0.394133 |
import wmi
import speedtest_cli
import threading
import signal
import os
import json
def testSpeed(urls):
speedtest_cli.shutdown_event = threading.Event()
signal.signal(signal.SIGINT, speedtest_cli.ctrl_c)
print "Start to test download speed: "
dlspeed = speedtest_cli.downloadSpeed(urls)
dlspeed =... | network.py | 3,056 | ret = configuration.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask]) Query current gateway define gateways | 110 | en | 0.46891 |
#!/usr/bin/env python
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicabl... | keras_maskrcnn/bin/debug.py | 6,656 | Copyright 2017-2018 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... | 1,571 | en | 0.745693 |
"""
DataMeta
DataMeta # noqa: E501
The version of the OpenAPI document: 1.4.0
Contact: leon.kuchenbecker@uni-tuebingen.de
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from datameta_client_lib.model_utils import ( # noqa: F401
ApiTypeErr... | datameta_client_lib/model/staged_meta_data_sets.py | 6,553 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the a... | 3,576 | en | 0.777281 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/contrib/distributions/python/ops/gamma.py | 12,568 | The `Gamma` distribution with parameter alpha and beta.
The parameters are the shape and inverse scale parameters alpha, beta.
The PDF of this distribution is:
```pdf(x) = (beta^alpha)(x^(alpha-1))e^(-x*beta)/Gamma(alpha), x > 0```
and the CDF of this distribution is:
```cdf(x) = GammaInc(alpha, beta * x) / Gamma... | 5,651 | en | 0.729537 |
import logging
import sys
from abc import ABC, abstractmethod
logger = logging.getLogger(__name__)
class PaddownException(Exception):
pass
class Paddown(ABC):
@abstractmethod
def has_valid_padding(self, ciphertext: bytes) -> bool:
"""
Override this method and send off the ciphertext to ... | paddown.py | 3,558 | Override this method and send off the ciphertext to check for valid padding.
:param bytes ciphertext: The ciphertext to check, send this to your padding oracle.
:rtype: True for valid padding, False otherwise.
Replace ciphertext at index with a guessed byte Iterate blocks last to first Convert self.ciphertext to mut... | 400 | en | 0.621989 |
"""
WSGI config for CongressionalRecord project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_AP... | CongressionalRecord/wsgi.py | 1,458 | WSGI config for CongressionalRecord project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLIC... | 1,250 | en | 0.843154 |
"""Basic pyon logging (with or without container)
NOTE: the functionality of this module has moved to ooi.logging.config.
currently this module is maintained for API compatability, but is implemented using the new package.
"""
import logging
from ooi.logging import config
DEFAULT_LOGGING_PATHS = ['res/co... | pyon/core/log.py | 1,537 | direct warnings mechanism to loggers | 36 | en | 0.830046 |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Original C++ source file: boosted_trees_ops.cc
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context... | Keras_tensorflow_nightly/source2.7/tensorflow/python/ops/gen_boosted_trees_ops.py | 58,905 | Calculates gains for each feature and returns the best possible split information for the feature.
The split information is the best threshold (bucket id), gains and left/right node contributions per node for each feature.
It is possible that not all nodes can be split on each feature. Hence, the list of possible nod... | 17,000 | en | 0.656209 |
#!/usr/bin/env python
"""JIP module that handles job profiles.
A job profile contains all compute-cluster and execution related meta-data of a
job, such as the number of threads reserved for the job or the time limit.
Profiles can be named and stored in the user configuration.
In addition, hierarchical updates of pro... | jip/profiles.py | 23,630 | A Profile contains cluster and runtime specific information about
a job.
Apply this profile to the given job.
Apply the profile and overwrite all settings that are set
in this profile
Apply this profile to the pipeline
:param pipeline: the pipeline
:type pipeline: :class:`jip.pipeline.Pipeline`
Set the jobs working di... | 6,968 | en | 0.85788 |
#!/usr/bin/env python
# Copyright 2016 Intel
#
# 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 ... | scripts/readme.py | 2,623 | Concatinates files yielded by the generator `find_docs`.
Yields files as per the whitelist.
!/usr/bin/env python Copyright 2016 Intel 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.ap... | 655 | en | 0.844662 |
# -*- coding: utf-8 -*-
"""
Benchmark Results
Updated: 18.02.2022 (6618fa3c36b0c9f3a9d7a21bcdb00bf4fd258ee8))
------------------------------------------------------------------------------------------
| Model | Batch Size | Epochs | KNN Test Accuracy | Time | Peak GPU Usage |
--------------------------... | docs/source/getting_started/benchmarks/cifar10_benchmark.py | 27,350 | Helper method to create dataloaders for ssl, kNN train and kNN test
Args:
batch_size: Desired batch size for all dataloaders
Benchmark Results
Updated: 18.02.2022 (6618fa3c36b0c9f3a9d7a21bcdb00bf4fd258ee8))
------------------------------------------------------------------------------------------
| Model ... | 6,970 | en | 0.672573 |
from core.models import Item, Listing, PromoCode, Address, UserProfile
from core.zipcode import zipcodes
from datetime import datetime, timedelta
from decimal import *
from django import forms
from django.core.files.base import ContentFile
from django.core.files.images import get_image_dimensions
from io impor... | circa/core/forms.py | 8,688 | For image cropping purposes Make sure starting offer is at least $5.00 Make sure a category is chosen Make sure shipping zip code is one we deliver to Grabs current user Grabs listing Must be changed when we branch to different states! Information for Item Information for Listing Grabs current listing Make sure startin... | 555 | en | 0.953803 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.teachers import FbDeprecatedDialogTeacher
from .build import build
from parlai.utils.data impor... | doc/integrations/pytorch/parlai/tasks/cornell_movie/agents.py | 3,245 | This version creates text-label pairs from the perspective of both speakers.
Adds additional perspectives. For example, in the conversation:
x1 y1
x2 y2
x3
Creates the additional dialog:
y1 x2
y2 x3
!/usr/bin/env python3 Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT lic... | 506 | en | 0.834633 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from nose.tools import eq_, assert_raises
from socorrolib.lib import MissingArgumentError
from socorro.external.postgre... | socorro/unittest/external/postgresql/test_field.py | 2,184 | Test socorro.external.postgresql.field.Field class.
Clean up the database, delete tables and functions.
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. expect a result exp... | 366 | en | 0.85742 |
'''
Custom interpolation methods for representing approximations to functions.
It also includes wrapper classes to enforce standard methods across classes.
Each interpolation class must have a distance() method that compares itself to
another instance; this is used in HARK.core's solve() method to check for solution
co... | HARK/interpolation.py | 159,390 | Bilinear full (or tensor) grid interpolation of a function f(x,y).
A 3D interpolator that bilinearly interpolates among a list of lists of 1D
interpolators.
A 4D interpolation method that bilinearly interpolates among "layers" of
arbitrary 2D interpolations. Useful for models with two endogenous state
variables and tw... | 43,152 | en | 0.733564 |
from django import forms
from .models import Reclamacao,Login,Comentario
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CadastraReclamacaoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CadastraReclamacaoForm,self).__init__(*args,... | Application/ReclamaCaicoProject/ReclamaCaicoApp/forms.py | 1,619 | class CadastraForum(forms.ModelForm): class Meta: model = Forum fields = ('text',) | 99 | en | 0.343888 |
# coding: utf-8
from django.conf.urls import url
from api_v1 import views
urlpatterns = [
url(r'^register/$', views.register),
url(r'^login/$', views.login),
url(r'^images/$', views.images),
url(r'^reccomend/$', views.reccomend),
url(r'^user_post/$', views.get_user_post),
]
# api viewer (debug用)
fr... | server/project/api_v1/urls.py | 682 | coding: utf-8 api viewer (debug用) router.register(r'favorite', FavoriteViewSet) | 79 | en | 0.222626 |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6320, generator: {generator})
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# ---------------------------------------... | sdk/WebSearch/web_search_client/models/_models.py | 77,975 | Answer.
Variables are only populated by the server, and will be ignored when sending a request.
:param type:
:type type: str
:ivar id: A String identifier.
:vartype id: str
:ivar web_search_url: The URL To Bing's search result for this item.
:vartype web_search_url: str
:ivar follow_up_queries:
:vartype follow_up_que... | 35,836 | en | 0.642944 |
# 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 PyPytestRunner(PythonPackage):
"""Invoke py.test as distutils command with dependency reso... | var/spack/repos/builtin/packages/py-pytest-runner/package.py | 781 | Invoke py.test as distutils command with dependency resolution.
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) | 254 | en | 0.734105 |
"""
OpenSpace
Copyright (c) 2014-2018
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute... | support/coding/check_style_guide.py | 19,467 | OpenSpace
Copyright (c) 2014-2018
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, su... | 2,893 | en | 0.84651 |
"""
Training data and validation accuracy.
"""
# Author: Changyu Liu <Shiyipaisizuo@gmail.com>
# Last modified: 2018-07-06
# LICENSE: MIT
import os
import numpy as np
import tensorflow as tf
from PIL import Image
import train_test_split
import cnn
N_CLASSES = 2 # dogs and cats
IMG_W = 208 # resize the image,... | cats_dogs/base.py | 4,753 | Test one image against the saved models and parameters
Randomly pick one image from training data
====================
Args:
train: train data
====================
Return:
image
Training data and validation accuracy.
Author: Changyu Liu <Shiyipaisizuo@gmail.com> Last modified: 2018-07-06 LICENSE: MIT dogs... | 590 | en | 0.820136 |
import json
#Try with python3
try:
from urllib.request import urlopen, urlretrieve
from urllib.request import urlretrieve
#Else try python2
except:
from urllib2 import urlopen
from urllib import urlretrieve
from os import path
#User home folder
homeFolder = path.expanduser("~")
#... | Bing Wallpaper/GetWallpaper.py | 2,139 | Try with python3Else try python2User home folderSave pictures to a folderDefining variablesURL in json format for latest wallpaperManually change the resolution in the url to 1920x1200. Change to 0 if url breaks.Get json response from bing.comTrying python 3Else trying python2Get json outputForm image url from jsonForm... | 617 | en | 0.768031 |
import asyncio
from collections import defaultdict
from dataclasses import dataclass
import json
import logging
import os
import time
from typing import Dict, Set
from ray._private.utils import import_attr
from ray.core.generated import runtime_env_agent_pb2
from ray.core.generated import runtime_env_agent_pb2_grpc
fr... | dashboard/modules/runtime_env/runtime_env_agent.py | 11,735 | An RPC server to create and delete runtime envs.
Attributes:
dashboard_agent: The DashboardAgent object contains global config.
TODO(edoakes): this is used for unit tests. We should replace it with a better pluggability mechanism once available. Whether or not the env was installed correctly. If success is True,... | 1,351 | en | 0.838116 |
# Copyright 2018-2022 Streamlit 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 wr... | e2e/scripts/st_text.py | 640 | Copyright 2018-2022 Streamlit 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 di... | 555 | en | 0.853357 |
import os
import logging
import argparse
from collections import Counter
import pandas as pd
import inflect
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
_CATEGRORIES = [
'Mini Briefs',
'Advances & Business',
'Concerns & Hype',
'Analysis & Policy',
'Expert Opinions & Discussion within t... | scripts/csv2md.py | 3,270 | remove the last two empty lines | 31 | en | 0.559367 |
s = "Hey there! what should this string be?"
# Length should be 20
print("Length of s = %d" % len(s[0:20]))
# Index
print("The first occurrence of the letter a = %d" % s.index("!"))
# Count
print("t occurs %d times" % s.count("t"))
# Slicing the string into bits
s1 = "hello world"
print(s1[:1]) # splicing is exclusi... | python/python/basics/strings.py | 1,601 | Length should be 20 Index Count Slicing the string into bits splicing is exclusive splicing is exclusive splicing is exclusive splicing is exclusive Start to 5 5 to 10 Just number 12(0-based indexing) 5th-from-last to end string reversed reversed with odd index uppercase Convert everything to lowercase Check how a stri... | 372 | en | 0.773022 |
import os
import pkgutil
from pathlib import Path
import pytest
from click.testing import CliRunner
from slotscheck.cli import root as cli
from .conftest import EXAMPLES_DIR
@pytest.fixture()
def runner():
return CliRunner()
@pytest.fixture(autouse=True)
def set_cwd(request):
os.chdir(EXAMPLES_DIR)
y... | tests/src/test_cli.py | 15,847 | let's define the path indirectly to ensure it works type: ignore type: ignore[union-attr] | 89 | en | 0.500687 |
from keras.utils import to_categorical
import tensorflow as tf
import pygame
class pytennis:
def __init__(self, fps = 50):
self.net = Network(150,450,100,600)
self.updateRewardA = 0
self.updateRewardB = 0
self.updateIter = 0
self.lossA = 0
self.lossB = 0
... | pytennis/play.py | 15,682 | cmax: 450
cmin: 150
c definately will be between 150 and 450.
state0 - (150 - 179)
state1 - (180 - 209)
state2 - (210 - 239)
state3 - (240 - 269)
state4 - (270 - 299)
state5 - (300 - 329)
state6 - (330 - 359)
state7 - (360 - 389)
state8 - (390 - 419)
state9 - (420 - 450)
cmax: 450
cmin: 150
c definately will be betwe... | 2,506 | en | 0.648987 |
"""
Optuna example that optimizes a classifier configuration for cancer dataset
using XGBoost.
In this example, we optimize the validation accuracy of cancer detection
using XGBoost. We optimize both the choice of booster model and their hyper
parameters.
We have following two ways to execute this example:
(1) Execu... | examples/xgboost_simple.py | 2,599 | Optuna example that optimizes a classifier configuration for cancer dataset
using XGBoost.
In this example, we optimize the validation accuracy of cancer detection
using XGBoost. We optimize both the choice of booster model and their hyper
parameters.
We have following two ways to execute this example:
(1) Execute t... | 733 | en | 0.629075 |
import re,sys
class Instruction:
def __init__(self,defn):
m = re.match("^([A-Fa-f0-9\-\,]+)\s+\"(.*?)\"\s+(.*)$",defn)
assert m is not None,"Bad line "+defn
range = m.group(1)
range = range+"-"+range if len(range) == 2 else range
range = range+",1" if len(range) == 5 else range
self.first = int(range[:2],... | processor/generate.py | 3,489 | print(defn,range,self.first,self.last,self.step,self.getOpcodes())print(s,params)sys.exit(0) | 92 | en | 0.299679 |
"""Writes the given metrics in a csv."""
import numpy as np
import os
import pandas as pd
import sys
models_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(models_dir)
from baseline_constants import CLIENT_ID_KEY, NUM_ROUND_KEY, NUM_SAMPLES_KEY
COLUMN_NAMES = [
CLIENT_ID_KEY, ... | models/metrics/writer.py | 2,742 | Gets the names of the metrics.
Args:
metrics: Dict keyed by client id. Each element is a dict of metrics
for that client in the specified round. The dicts for all clients
are expected to have the same set of keys.
Writes the given dataframe in path as a csv
Prints or appends the given metrics in a ... | 1,182 | en | 0.884414 |
import numpy as np
import pandas as pd
import sys # can use sys to take command line arguments
class Recommender():
'''
What is this class all about - write a really good doc string here
'''
def __init__(self, ):
'''
what do we need to start out our recommender system
'''
... | lessons/Recommendations/2_Matrix_Factorization_for_Recommendations/recommender_template.py | 843 | can use sys to take command line arguments test different parts to make sure it works | 85 | en | 0.834695 |
import tensorflow as tf
import sys
sys.path.insert(0,'..')
import vtrace_popart as vtrace
nest = tf.contrib.framework.nest
from .flags import *
def compute_baseline_loss(advantages):
# Loss for the baseline, summed over the time dimension.
# Multiply by 0.5 to match the standard update rule:
# d(loss) / d(basel... | popart/build_learner.py | 5,645 | Builds the learner loop.
Args:
agent: A snt.RNNCore module outputting `AgentOutput` named tuples, with an
`unroll` call for computing the outputs for a whole trajectory.
agent_state: The initial agent state for each sequence in the batch.
env_outputs: A `StepOutput` namedtuple where each field is of shape
... | 1,660 | en | 0.860974 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.