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 |
|---|---|---|---|---|---|---|
# terrascript/data/onelogin.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:23:37 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.data.onelogin
#
# instead of
#
# >>> import terrascript.data.onelogin.onelogin
#
# This is only available for 'official' and 'partner' providers... | terrascript/data/onelogin.py | 372 | terrascript/data/onelogin.py Automatically generated by tools/makecode.py (24-Sep-2021 15:23:37 UTC) For imports without namespace, e.g. >>> import terrascript.data.onelogin instead of >>> import terrascript.data.onelogin.onelogin This is only available for 'official' and 'partner' providers. | 297 | en | 0.352139 |
# -*- coding: utf-8 -*-
"""Common collection classes."""
from __future__ import print_function, division, absolute_import
from functools import reduce
from collections import Mapping, Set
from .compat import isiterable, iteritems, odict, text_type
def make_immutable(value):
# this function is recursive, and if n... | lib/python3.7/site-packages/conda/_vendor/auxlib/collection.py | 3,582 | Sub-classes dict, and further allows attribute-like access to dictionary items.
Examples:
>>> d = AttrDict({'a': 1})
>>> d.a, d['a'], d.get('a')
(1, 1, 1)
>>> d.b = 2
>>> d.b, d['b']
(2, 2)
Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None
Give the first v... | 1,415 | en | 0.602026 |
def event_handler(source,evt):
if evt == lv.EVENT.CLICKED:
if source == btn1:
# treat "clicked" events only for btn1
print("Clicked")
elif evt == lv.EVENT.VALUE_CHANGED:
print("Toggled")
# create a simple button
btn1 = lv.btn(lv.scr_act(),None)
# attach the call... | ArduinoProject/DAC_CONTROLLER/lib/lv_demos/src/lv_ex_widgets/lv_ex_btn/lv_ex_btn_1.py | 733 | treat "clicked" events only for btn1 create a simple button attach the callback create a toggle button attach the callbackbtn2.set_fit2(lv.FIT.NONE,lv.FIT.TIGHT) | 161 | en | 0.307387 |
"""List options for creating Placement Groups"""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.vs_placement import PlacementManager as PlacementManager
@click.command()
@environment.pass_env
def cli(env)... | SoftLayer/CLI/virt/placementgroup/create_options.py | 1,186 | List options for creating a placement group.
Formats output from _get_routers and returns a table.
Formats output from get_all_rules and returns a table.
List options for creating Placement Groups
:license: MIT, see LICENSE for more details. | 245 | en | 0.635537 |
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | open-hackathon-server/src/hackathon/registration/register_mgr.py | 8,728 | -*- coding: utf-8 -*- ----------------------------------------------------------------------------------- Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved. The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated... | 1,434 | en | 0.79494 |
"""
Takes the gradients of the solution to the screen mapping potential problem and
reconstructs the perpendicular deflection field.
"""
import numpy as np
import scipy as sp
import scipy.interpolate
import scipy.misc
import scipy.ndimage
from .constants import M_PROTON_G, ESU, C_CMS
def reconstruct(ri, li, rs, v, x... | problem/deflect.py | 8,167 | Creates a flux image out of a perpendicular deflection field.
Args:
ri:
li:
rs:
v:
x (array): Perpendicular deflection field x-coordinates.
y (array): Perpendicular deflection field y-coordinates.
wBx (array): Perpendicular deflection field x-component.
wBy (array): Perpendicular defle... | 3,666 | en | 0.651139 |
# coding: utf-8
try:
from lxml import etree
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
except ImportError:
try:
#... | maxipago/utils/xml.py | 788 | coding: utf-8 Python 2.5 Python 2.5 normal cElementTree install raises ImportError | 82 | en | 0.503888 |
# 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/fluid/contrib/slim/quantization/imperative/qat.py | 24,682 | Applying quantization aware training (QAT) to the dgraph model.
Based on the input params, add the quant_dequant computational
logic both for activation inputs and weight inputs.
Calculate the output scales for target layers.
The constructor for ImperativeQuantAware.
Args:
quantizable_layer_type(list[str | layer])... | 9,981 | en | 0.726064 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# refer to `https://bitbucket.org/akorn/wheezy.captcha`
import random
import string
import os.path
from io import BytesIO
from PIL import Image
from PIL import ImageFilter
from PIL.ImageDraw import Draw
from PIL.ImageFont import truetype
class Bezier:
def __init__(... | info/utils/captcha/captcha.py | 8,171 | Create a captcha.
Args:
path: save path, default None.
fmt: image format, PNG / JPEG.
Returns:
A tuple, (name, text, StringIO.value).
For example:
('fXZJN4AFxHGoU5mIlcsdOypa', 'JGW9', 'PNG
...')
Bezier curves:
http://en.w... | 729 | en | 0.314408 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pipreqs - Generate pip requirements.txt file based on imports
Usage:
pipreqs [options] <path>
Options:
--use-local Use ONLY local package info instead of querying PyPI
--pypi-server <url> Use custom PyPi server
--proxy <url> Use Prox... | pipenv/vendor/pipreqs/pipreqs.py | 13,981 | Remove modules that aren't imported in project from file.
Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
tuple: The modules not imported in the project, but do exist i... | 2,456 | en | 0.704045 |
#!/usr/bin/env python3
# Copyright (c) 2017-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test getblockstats rpc call
#
from test_framework.blocktools import COINBASE_MATURITY
from test_fram... | test/functional/rpc_getblockstats.py | 7,042 | !/usr/bin/env python3 Copyright (c) 2017-2021 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Test getblockstats rpc call Set the timestamps from the file so that the nodes can get out of Initial Block Downl... | 782 | en | 0.852191 |
"""Training run script"""
import argparse
import json
from pathlib import Path
from bisect import bisect_left
import torch
import torch_geometric as tg
import matplotlib.pyplot as plt
import local2global as l2g
from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio... | local2global_embedding/run.py | 21,912 | Class for keeping track of results
initialise empty ResultsDict
Args:
replace: set the replace attribute (default: ``False``)
insert new data at index
Args:
index: integer index into data lists
dim: data dimension for index
aucs: new auc values
args: new args data (optional)
update data for a given... | 4,523 | en | 0.480563 |
# Copyright 2021 The Cirq Developers
#
# 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 ... | cirq-core/cirq/transformers/transformer_primitives_test.py | 12,512 | Artificial example where a CZ will absorb any merge-able operation.
Copyright 2021 The Cirq Developers 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.... | 720 | en | 0.846596 |
import collections
import operator
import bytewax
FIRST_ITERATION = 0
def read_edges(filename):
with open(filename) as lines:
for line in lines:
line = line.strip()
if line:
parent, child = tuple(x.strip() for x in line.split(","))
yield FIRST_ITE... | examples/pagerank.py | 2,074 | (parent, {child}) per edge (parent, children) per parent TODO: Some sort of state capture here. This will be tricky because we don't have a way of building state per-worker generically yet. Timely uses Rust closures, but we're outside that context here. (parent, weight, children) per parent (child, contrib) per child *... | 819 | en | 0.890428 |
from abc import ABCMeta
from abc import abstractproperty
# The base class for all BMI Exceptions
# Made abstract since it is recommended to raise the specific subclass
class BMIException(Exception):
__metaclass__ = ABCMeta
@abstractproperty
def status_code(self):
pass
# The base class for all e... | m2-modified/ims/exception/exception.py | 1,753 | The Base Class for all exceptions related to Shell
The base class for all BMI Exceptions Made abstract since it is recommended to raise the specific subclass The base class for all exceptions related to the file system like ceph The base class for all exceptions related to HIL The base class for all exceptions relat... | 597 | en | 0.816377 |
import requests
import json
import os
requests.packages.urllib3.disable_warnings()
from cmlApiCalls import CML as cml
#edit the following variables
server = "cml.server.com"
username = "admin"
password = "CMLpassword123"
lab = "53b3fe"
user = os.getlogin()
auth = cml.auth(server, username, password)
N = True
n_id =... | scripts/breakout-to-secureCRT-session/main.py | 1,635 | edit the following variablesexit if end of list dont count external_connector as usable get label turn port number into hex strip "0x2233" and make it only 4 charators add by 1 if wan_emulator | 195 | en | 0.796368 |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | ooobuild/lo/form/x_positioning_listener.py | 1,981 | allows to receive notifications about cursor movements into a database form.
Please do not use anymore, this interface is deprecated, and superseded by functionality from the com.sun.star.form.component.DataForm service, as well as the com.sun.star.sdbc.XRowSetListener.
.. deprecated::
Class is deprecated.
See ... | 1,238 | en | 0.811592 |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 16:39:59 2020
@author: nicholls
"""
import os
import numpy as np
import matplotlib.pyplot as plt
#%%
class AngularSpreadCalc():
""" class for calculating how angular spread changes with iterations:
Inputs:
iterations: maxinum number of iterat... | model/algorithms/legacy/angular_spread_lorentzian.py | 8,998 | class for calculating how angular spread changes with iterations:
Inputs:
iterations: maxinum number of iterations to calculate for (e.g. 500)
acceptance angle: acceptance angle of analyser
energy: initial energy of scattered electrons (eV)
Calculate the change in area ratio between iteration n and n-... | 2,033 | en | 0.737041 |
# =======================================================================================
# \ | | __ __| _ \ | / __| \ \ / __|
# _ \ | | | ( | . < _| \ / \__ \
# @autor: Luis Monteiro _/ _\ \__/ _| \___/ _|\_\ ___| _| ____/
# ============... | autokeys/credentials.py | 1,531 | ======================================================================================= \ | | __ __| _ \ | / __| \ \ / __| _ \ | | | ( | . < _| \ / \__ \ @autor: Luis Monteiro _/ _\ \__/ _| \___/ _|\_\ ___| _| ____/ ======================... | 618 | en | 0.347466 |
"""Install funsies."""
import setuptools
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setuptools.setup(
name="funsies",
version="0.8.1",
author="Cyrille Lavigne",
auth... | setup.py | 1,838 | Install funsies.
mypy exports Dependencies | 44 | en | 0.563046 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.CloudbusTransitResultItem import CloudbusTransitResultItem
class AlipayDataAiserviceCloudbusTransitorridorQueryResponse(AlipayResponse):
def __init__(self):
... | alipay/aop/api/response/AlipayDataAiserviceCloudbusTransitorridorQueryResponse.py | 989 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
class Domain(Enum,IComparable,IFormattable,IConvertible):
"""
Enumeration of connector domain types
enum Domain,values: DomainCableTrayConduit (4),DomainElectrical (2),DomainHvac (1),DomainPiping (3),DomainUndefined (0)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq... | release/stubs.min/Autodesk/Revit/DB/__init___parts/Domain.py | 1,085 | Enumeration of connector domain types
enum Domain,values: DomainCableTrayConduit (4),DomainElectrical (2),DomainHvac (1),DomainPiping (3),DomainUndefined (0)
x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y
__format__(formattable: IFormattable,format: str) -> str
x.__init__(...) initializes x; see x... | 488 | en | 0.303184 |
"""
This is the custom function interface.
You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y),... | 1237-Find Positive Integer Solution for a Given Equation.py | 893 | This is the custom function interface.
You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
d... | 373 | en | 0.825372 |
# This code implementents a variational autoencoder using importance weighted
# sampling as described in Burda et al. 2015 "Importance Weighted Autoencoders"
# and the planar normalizing flow described in Rezende et al. 2015
# "Variational Inference with Normalizing Flows"
import theano
theano.config.floatX = 'float32'... | examples/iw_vae_normflow.py | 23,210 | This code implementents a variational autoencoder using importance weighted sampling as described in Burda et al. 2015 "Importance Weighted Autoencoders" and the planar normalizing flow described in Rezende et al. 2015 "Variational Inference with Normalizing Flows"number of importance weighted samplesnumber of samples ... | 2,817 | en | 0.691223 |
from . import base
from grow.common import utils as common_utils
from boto.s3 import connection
from boto.s3 import key
from grow.pods import env
from protorpc import messages
import boto
import cStringIO
import logging
import os
import mimetypes
class Config(messages.Message):
bucket = messages.StringField(1)
... | grow/deployments/destinations/amazon_s3.py | 3,392 | TODO: Allow configurable headers. | 33 | en | 0.192868 |
# Copyright 2020 QuantumBlack Visual Analytics Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THE SOFTWARE IS PROVIDED "AS IS",... | tests/pipeline/test_node.py | 17,245 | Copyright 2020 QuantumBlack Visual Analytics Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY ... | 1,582 | en | 0.809877 |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | aiida/work/launch.py | 3,873 | Run the process with the supplied inputs in a local runner that will block until the process is completed.
The return value will be the results of the completed process
:param process: the process class or workfunction to run
:param inputs: the inputs to be passed to the process
:return: the outputs of the process
Run... | 2,082 | en | 0.895066 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: See license.txt
import frappe
from frappe.model.document import Document
class Note(Document):
def autoname(self):
# replace forbidden characters
import re
self.name = re.sub("[%'\"#*?`]", "", self.title.strip())
def validate(sel... | frappe/desk/doctype/note/note.py | 1,206 | Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors License: See license.txt replace forbidden characters expire this notification in a week (default) | 165 | en | 0.636349 |
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... | core/setup.py | 5,699 | Setup for YDK
---------------------------------------------------------------- Copyright 2016 Cisco Systems 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/LICENS... | 809 | en | 0.747648 |
from ..utils import Object
class PageBlockRelatedArticle(Object):
"""
Contains information about a related article
Attributes:
ID (:obj:`str`): ``PageBlockRelatedArticle``
Args:
url (:obj:`str`):
Related article URL
title (:obj:`str`):
Article titl... | pytglib/api/types/page_block_related_article.py | 1,558 | Contains information about a related article
Attributes:
ID (:obj:`str`): ``PageBlockRelatedArticle``
Args:
url (:obj:`str`):
Related article URL
title (:obj:`str`):
Article title; may be empty
description (:obj:`str`):
Article description; may be empty
photo (:class:`te... | 662 | en | 0.606091 |
from django.db import models
from django.core.validators import URLValidator
from django.contrib.auth.models import User
from tinymce.models import HTMLField
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length = 50)
image = models.ImageField(upload_to = 'projects/')
... | upload/models.py | 1,837 | Create your models here. | 24 | en | 0.920486 |
n = int(input())
x = int(input())
# n = 5 : 101 => x ** 4 * x ** 1
ans = 1
while n > 0:
if n & 1:
ans *= x
n >>= 1
x *= x
continue
n >>= 1
x *= x
print(ans)
| src/2sem/pow.py | 204 | n = 5 : 101 => x ** 4 * x ** 1 | 30 | en | 0.26868 |
##
# Copyright (c) 2007-2016 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | caldavclientlibrary/protocol/webdav/tests/test_head.py | 1,788 | Copyright (c) 2007-2016 Apple Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr... | 573 | en | 0.865893 |
import random
from typing import List, Optional, Tuple
import numpy as np
import gym
import wandb
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import Sequential, Input, Model
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Concatenate
from tensorflow.keras.optimizers impor... | RL/Snake-DQN/model/dqn_engineered.py | 8,901 | Construct a new 'Deep Q-Network' object.
:param env: The environment of the game
:param lr: The learning rate of the agent
:param gamma: The amount of weight it gives to future rewards in the value function
:param epsilon: The probability where we do not go with the “greedy” action with the highest Q-value but rather ... | 1,842 | en | 0.851243 |
#!/usr/bin/env python
# coding: utf-8
from saenopy import Solver
# initialize the object
M = Solver()
from saenopy.materials import SemiAffineFiberMaterial
# provide a material model
material = SemiAffineFiberMaterial(1645, 0.0008, 1.0075, 0.033)
M.setMaterialModel(material)
import numpy as np
... | docs/regularization.py | 1,621 | !/usr/bin/env python coding: utf-8 initialize the object provide a material model define the coordinates of the nodes of the mesh the array has to have the shape N_v x 3 0 1 2 3 4 5 6 7 define the tetrahedra of the mesh the array has to have the shape N_t x 4 every entry is an index referencing a verces in R (indices s... | 541 | en | 0.846205 |
"""
This module stores global variables that must be shared between all modules of
envprobe.
Please do not introduce a too large global state in this module.
Please do not add dependencies of other modules to this module because almost
all parts of envprobe refers this module.
"""
# This list contains the valid subco... | configuration/global_config.py | 456 | This module stores global variables that must be shared between all modules of
envprobe.
Please do not introduce a too large global state in this module.
Please do not add dependencies of other modules to this module because almost
all parts of envprobe refers this module.
This list contains the valid subcommands th... | 419 | en | 0.778089 |
# -*- coding: utf-8 -*-
# __ __ __ ___ __ __ __ __ ____
# | ' \ \/ / | | \ \ \ / \
# | _ \ /__| | , , |/ /\__|
# | (_) ) / _ | | | | ( __
# | ___/ ( (_) | | | |\ \/ |
# |__| \___/ \___,__;__/__/__/ \____/
"""
Digital Messaging Center API Client
~~~~~~~~~~~~~~~~~~~~~~~~~... | pydmc/__init__.py | 592 | Digital Messaging Center API Client
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PyDmc is an API client library, written in Python, for Teradata's Digital
Messaging Center.
-*- coding: utf-8 -*- __ __ __ ___ __ __ __ __ ____ | ' \ \/ / | | \ \ \ / \ | _ \ /__| | , , |/ /\__| | (_) ) / _ | | ... | 405 | en | 0.466717 |
# -*- coding: utf-8 -*-
import keras.engine.training
from typing import Callable
from typing import Tuple
from typing import List
from typing import Union
from util_types import types_of_loco
from network_model.distillation.distillation_model_builder import DistllationModelIncubator
from keras.optimizers import Optimiz... | network_model/model_builder.py | 5,867 | モデル生成をする関数を返す
交差検証をかける際のラッパーとして使う
:param img_size:
:param channels:
:param model_name:
:param optimizer:
:return:
Ganのgenerator部を作成する
:param class_num
:param channels:色の出力変数(白黒画像なら1)
:param optimizer: 2次元の畳み込みウィンドウの幅と高さ 整数なら縦横比同じに
:return: discriminator部のモデル
-*- coding: utf-8 -*- | 282 | ja | 0.925456 |
# @ayushk780
# Big Thanks To Spechide and @TechnoAyanBoT
"""Counth: Avaible commands: .bstats
"""
import asyncio
from telethon import events
from uniborg.util import admin_cmd, humanbytes,get_readable_time
import shutil
import time
from userbot import botStartTime
@borg.on(admin_cmd(pattern=r"bstats"))
async def _(e... | userbot/plugins/bot_stats.py | 777 | Counth: Avaible commands: .bstats
@ayushk780 Big Thanks To Spechide and @TechnoAyanBoT | 88 | en | 0.690385 |
import six
from django.shortcuts import render, resolve_url
from django.utils.functional import Promise
from rest_framework.renderers import BaseRenderer, JSONRenderer, TemplateHTMLRenderer
from rest_framework.utils import json
from .app_settings import redoc_settings, swagger_settings
from .codecs import VALIDATORS,... | src/drf_yasg/renderers.py | 7,274 | Renders the schema as a JSON document with the ``application/openapi+json`` specific mime type.
Renders a ReDoc 1.x.x web interface for schema browisng.
Renders a ReDoc web interface for schema browisng.
Renders the schema as a JSON document with the generic ``application/json`` mime type.
Renders a swagger-ui web inte... | 1,042 | en | 0.762817 |
"""
Grabs data from the "FAQ Content" CSV and turns it into nice JSON: a main faq object containing an array of themed Section objects, each Section Object in turn holding an array of Question objects consisting of question, answer and related link/s, as follows:
[
{
"Q": "What are the symptoms of... | data/jsonic1_commit.py | 3,098 | Grabs data from the "FAQ Content" CSV and turns it into nice JSON: a main faq object containing an array of themed Section objects, each Section Object in turn holding an array of Question objects consisting of question, answer and related link/s, as follows:
[
{
"Q": "What are the symptoms of COV... | 1,900 | en | 0.827042 |
#!/usr/bin/env python
import mdtraj as md
import numpy as np
from LLC_Membranes.llclib import physical, topology
r = 1
t = md.load('initial.gro')
keep = [a.index for a in t.topology.atoms if a.residue.name == 'HOH']
res_start = keep[0]
com = physical.center_of_mass(t.xyz[:, keep, :], [18., 1., 1.])
membrane = top... | Ben_Manuscripts/stochastic_transport/figures/pore_water_tcl.py | 1,625 | !/usr/bin/env python object w/ attributes of LC making up membrane have to use double equals sign. Using is doesn't work with np.where | 134 | en | 0.891371 |
#!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""BitcoinSN P2... | test/functional/test_framework/mininode.py | 22,983 | A low-level connection object to a node's P2P interface.
This class is responsible for:
- opening and closing the TCP connection to the node
- reading bytes from and writing bytes to the socket
- deserializing and serializing the P2P message header
- logging messages as they are sent and received
This class contains... | 6,523 | en | 0.872284 |
from tool.runners.python import SubmissionPy
class CocoSubmission(SubmissionPy):
def run(self, s):
"""
:param s: input in string format
:return: solution flag
"""
# Your code goes here
# suppositions: all numbers are co-prime (it seems to be the case in the input ??... | day-13/part-2/coco.py | 1,083 | :param s: input in string format
:return: solution flag
Your code goes here suppositions: all numbers are co-prime (it seems to be the case in the input ??) | 158 | en | 0.80808 |
import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('./demo/'))
from autorch_sphinx_theme import __version__
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# document... | docs/conf.py | 7,900 | If extensions (or modules to document with autodoc) are in another directory, add these directories to sys.path here. If the directory is relative to the documentation root, use os.path.abspath to make it absolute, like shown here.sys.path.insert(0, os.path.abspath('.')) -- General configuration -----------------------... | 6,241 | en | 0.647201 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | jax/experimental/jax2tf/tests/tf_test_util.py | 1,945 | Compares jax_func(*args) with convert(jax_func)(*args).
Compares dtypes across JAX and TF dtypes. Overrides super method.
Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ... | 693 | en | 0.811265 |
# coding: utf-8
#
# Copyright 2017 The Oppia 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 requi... | core/domain/activity_jobs_one_off_test.py | 83,226 | Mock CollectionCommitLogEntryModel so that it allows to set username.
Mock CollectionRightsModel so that it uses old version of
_trusted_commit.
Mock ExplorationRightsModel so that it uses old version of
_trusted_commit.
Mock TopicRightsModel so that it uses old version of _trusted_commit.
Runs the one-off MapReduce jo... | 4,403 | en | 0.831264 |
import tensorflow as tf
import numpy as np
import hyperchamber as hc
import inspect
from hypergan.trainers.base_trainer import BaseTrainer
TINY = 1e-12
class EvolutionTrainer(BaseTrainer):
def _create(self):
gan = self.gan
generator = self.gan.generator
config = self.config
d_var... | hypergan/trainers/experimental/evolution_trainer.py | 4,063 | TODO more than one g_losswinner = np.random.choice(range(len(gan.generator.children))) | 86 | en | 0.331653 |
import csv
import numpy as np
import re
import itertools
from collections import Counter
from collections import namedtuple
DataPoint = namedtuple('DataPoint', ['PhraseId', 'SentenceId', 'Phrase', 'Sentiment'])
def load_datapoints(data_file):
datapoints = []
with open(data_file) as f:
reader = csv.... | data_helpers.py | 2,886 | Generates a batch iterator for a dataset.
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
Load d... | 365 | en | 0.765678 |
import numpy as np
import pytest
import random
from mujoco_py import (MjSim, load_model_from_xml, cymj)
MODEL_XML = """
<mujoco model="inverted pendulum">
<size nuserdata="100"/>
<compiler inertiafromgeom="true"/>
<default>
<joint armature="0" damping="1" limited="true"/>
<geom contype="0" friction="1 0.1 0.1" ... | mujoco-py/mujoco_py/tests/test_pid.py | 2,773 | pertubation of pole to be unbalanced | 36 | en | 0.843477 |
import nanome
from nanome.util import Logs
from nanome._internal._network import PluginNetwork, _Packet
from nanome._internal._process import ProcessManagerInstance
from nanome._internal._network._commands._callbacks import _Messages
from nanome._internal._network._commands._callbacks._commands_enums import _Hashes
im... | nanome/_internal/_plugin_instance.py | 4,598 | Give log a little time to reach destination before closing pipe | 63 | en | 0.829587 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
import os
from io import BytesIO
from subprocess import PIPE, Popen
... | thumbor/engines/pil.py | 14,494 | !/usr/bin/python -*- coding: utf-8 -*- thumbor imaging service https://github.com/thumbor/thumbor/wiki Licensed under the MIT license: http://www.opensource.org/licenses/mit-license Copyright (c) 2011 globo.com thumbor@googlegroups.com serve tif as png invalid type n/a for this file Nasty retry if the image is loaded f... | 1,528 | en | 0.827816 |
# Subplots Function
subplots_doc = """It creates a matrix of subplots. It requires two integers (different from 0) where the first sets the number of rows and the second the number of columns of the subplots matrix."""
subplot_doc = """It sets the subplot to use to plot data: further commands will refer to the subp... | plotext/docstrings.py | 10,234 | Subplots Function Clear Functions Set Functions Plotting Functions Show Other Functions | 102 | en | 0.368898 |
from __future__ import absolute_import
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from ..w_transform import HaarTransform, InvHaarTransform
def _zeros_like(obj):
zeros = [np.zeros_like(lev, dtype=float) for lev in obj]
return zeros
__all__ = ['_f... | kwakpriv/plotting/plottingtools.py | 3,525 | Small numbercolors = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] RGBcolors = [(0.172, 0.521, 0.729), (0.870, 0.325, 0.129)] | 113 | en | 0.500087 |
##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | python/GafferUI/WidgetAlgo.py | 3,628 | Copyright (c) 2017, Image Engine Design Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions... | 1,714 | en | 0.892763 |
from dyc.utils import (
get_leading_whitespace,
read_yaml,
get_indent_forward,
get_indent_backward,
get_extension,
is_comment,
)
class TestGetLeadingWhitespace:
def test_tabs(self):
"""Test tabs functionality"""
text = '\t\tHello'
expected = '\t\t'
got = get... | tests/test_utils.py | 3,798 | Testing invalid comments
Test tabs functionality
Testing valid comments
Test whitespace functionality | 101 | en | 0.430651 |
import pickle
from kitti_functions import *
class DataLoader:
def __init__(self, args):
self.dataset_path = args.dataset_path
self.batch_size = args.batch_size
self.batch_size_valid = 1
self.seq_length = args.seq_length
self.scale_factor = args.data_scale
self.soci... | kitti_utils.py | 13,137 | raw_data is a list that has three components
component1) trajectory data for training
component2) trajectory data for validation and visualization
Read a batch randomly
:x_batch: <batch size x seq_length x input_dim>
:y_batch: <batch size x seq_length x input_dim>
:d_batch: <batch size x seq_length>
Read a batch random... | 1,990 | en | 0.521316 |
import argparse, json
import simpleamt
import MySQLdb
if __name__ == '__main__':
parser = argparse.ArgumentParser(parents=[simpleamt.get_parent_parser()])
parser.add_argument('-f', action='store_true', default=False)
args = parser.parse_args()
mtc = simpleamt.get_mturk_connection_from_args(args)
approve_ids... | check_and_approve_hits.py | 2,597 | Try to parse the output from the assignment. If it isn't valid JSON then we reject the assignment. Check if HIT assignment properly completed! | 142 | en | 0.835323 |
import logging
import pickle
import os
import sys
import json
import cv2
import numpy as np
import glob
import tqdm
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
import src
from src.__init__ import *
def image_reader(image_path_list):
image = cv2.imread(image_path_list[0], 0)
image... | src/dataset_creator.py | 4,359 | PAY ATTENTION HERE: YOU CAN ALSO ADD DEV-SET :) | 47 | en | 0.857099 |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | python/pyspark/taskcontext.py | 7,299 | .. note:: Experimental
A :class:`TaskContext` with extra contextual info and tooling for tasks in a barrier stage.
Use :func:`BarrierTaskContext.get` to obtain the barrier context for a running barrier task.
.. versionadded:: 2.4.0
.. note:: Experimental
Carries all task infos of a barrier task.
:var address: The I... | 3,817 | en | 0.844723 |
from unittest import TestCase
import pandas as pd
from pytz import UTC
from trading_calendars.exchange_calendar_xshg import XSHGExchangeCalendar
from .test_trading_calendar import ExchangeCalendarTestBase
from .test_utils import T
class XSHGCalendarTestCase(ExchangeCalendarTestBase, TestCase):
answer_key_file... | trading_calendars/tests/test_xshg_calendar.py | 2,090 | Shanghai stock exchange is open from 9:30 am to 3pm (for now, ignoring lunch break) the XSHG calendar currently goes from 1999 to 2025, inclusive. | 146 | en | 0.950947 |
import os
from sb3_contrib.ppo_mask import MaskablePPO
from sb3_contrib.qrdqn import QRDQN
from sb3_contrib.tqc import TQC
from sb3_contrib.trpo import TRPO
# Read version from file
version_file = os.path.join(os.path.dirname(__file__), "version.txt")
with open(version_file, "r") as file_handler:
__version__ = fi... | sb3_contrib/__init__.py | 346 | Read version from file | 22 | en | 0.974045 |
import logging
import os
import pickle
import sys
from pathlib import Path
import click
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import zsampler
from dotenv import load_dotenv, find_dotenv
from scipy.special import logsumexp, softmax
from src.inference.context_geo import GridContextGeo, ... | src/models/block_mixture_gp_softmax.py | 17,915 | do a random assignment to mixtures Create an (N x 1) vector which gives the corresponding block for each cell. a single block read in block centroid coordinates Create the cell <-> block mapping (mind the ordering of the blocks) Priors build a J x K matrix build a J x K matrix build a J x K matrix GP contribution nabla... | 537 | en | 0.833794 |
#!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deepcoin-cli"""
from test_framework.test_framework import DeepcoinTestFramework
from test_framewor... | test/functional/interface_deepcoin_cli.py | 4,210 | Main test logic
Test deepcoin-cli
!/usr/bin/env python3 Copyright (c) 2017-2018 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. unlocked_until is not tested because the wallet is not encrypted | 306 | en | 0.655136 |
# coding: utf-8
"""
Flat API
The Flat API allows you to easily extend the abilities of the [Flat Platform](https://flat.io), with a wide range of use cases including the following: * Creating and importing new music scores using MusicXML, MIDI, Guitar Pro (GP3, GP4, GP5, GPX, GP), PowerTab, TuxGuitar and Mus... | flat_api/models/flat_locales.py | 4,145 | 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
FlatLocales - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Returns the model properties as a dict
Returns... | 2,203 | en | 0.737312 |
from io import BytesIO
from unittest import TestCase
from ecc import G, N, PrivateKey, S256Point
from helper import (
big_endian_to_int,
byte_to_int,
encode_base58_checksum,
hmac_sha512,
hmac_sha512_kdf,
int_to_big_endian,
int_to_byte,
raw_decode_base58,
sha256,
)
from mnemonic impo... | session6/hd.py | 45,286 | Returns the proper address among purposes 44', 49' and 84'.
p2pkh for 44', p2sh-p2wpkh for 49' and p2wpkh for 84'.
Returns the base58-encoded x/y/z prv.
Expects a 4-byte version.
Returns the base58-encoded x/y/z pub.
Expects a 4-byte version.
Returns the child HDPrivateKey at a particular index.
Hardened children retur... | 5,787 | en | 0.745905 |
# Copyright 2017-present Open Networking Foundation
#
# 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... | ofagent/loxi/of11/instruction.py | 11,337 | Copyright 2017-present Open Networking Foundation 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,... | 1,126 | en | 0.842372 |
import os
import numpy as np
import copy
import colorsys
from timeit import default_timer as timer
from keras import backend as K
from keras.models import load_model
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw
from nets.yolo4 import yolo_body,yolo_eval
from utils.utils import letterbox_im... | yolo.py | 7,016 | -------------------------------------------- 使用自己训练好的模型预测需要修改2个参数 model_path和classes_path都需要修改!-------------------------------------------- 显存比较小可以使用416x416 显存比较大可以使用608x608--------------------------------------------------- 初始化yolo----------------------------------------------------------------------------------... | 849 | zh | 0.472434 |
import holoviews as hv
import geoviews as gv
import cartopy.crs as ccrs
import cartopy.feature as cf
from holoviews.operation.datashader import regrid
from holoviews.streams import FreehandDraw
import panel as pn
pn.extension()
hv.extension('bokeh', logo=False)
import sys
# Suppress warnings
if not sys.warnoptions:
... | 2.1 Weather/opscentretools/plotting.py | 2,637 | Suppress warnings Generate an interactive Bokeh image of a cube with various plotting options Convert cube to GeoViews dataset Generate an image object which will dynamically render as the interactive view changes Options for plotting Include coastlines if needed Generate a Panel dashboard from a list of interactive pl... | 701 | en | 0.72143 |
import re
### parse_text(text)
# takes a string, return a list of strings with the matching groups
def parse_text_regex(text, regex):
try:
compiled_regex = re.compile(regex)
if compiled_regex is None:
raise Exception(f"String {text} doesn't match {regex}")
except TypeError as te:
... | TPS_dice_roller_bot/core/parse.py | 616 | parse_text(text) takes a string, return a list of strings with the matching groups | 82 | en | 0.69591 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime
from django.contrib import messages
from django.db.models import Count
from django.views.generic import (
DetailView,
TemplateView,
)
from .models import (
AggregateHourlySongChart,
HourlySo... | kchart/charts/views.py | 2,177 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#
# LeetCode
#
# Problem - 581
# URL - https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
#
class Solution:
def findUnsortedSubarray(self, arr: List[int]) -> int:
if (not arr):
0
index1 = -1
index2 = -1
for i in range(1, len(arr)):
if (arr[i] < arr[i-1]):
index... | LeetCode/581.py | 840 | LeetCode Problem - 581 URL - https://leetcode.com/problems/shortest-unsorted-continuous-subarray/ | 97 | en | 0.621298 |
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... | cryptoapis/model/list_assets_details_e400.py | 14,861 | 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... | 7,184 | en | 0.796611 |
#!/usr/bin/env python
# mypy: ignore-errors
# depdive documentation build configuration file
#
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, li... | docs/conf.py | 4,732 | !/usr/bin/env python mypy: ignore-errors depdive documentation build configuration file If extensions (or modules to document with autodoc) are in another directory, add these directories to sys.path here. If the directory is relative to the documentation root, use os.path.abspath to make it absolute, like shown here. ... | 3,231 | en | 0.704918 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HMM10_then1_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HMM10_then1_IsolatedLHS.
"""
# Flag this insta... | UMLRT2Kiltera_MM/Properties/from_thesis/HMM10_then1_IsolatedLHS.py | 2,498 | Creates the himesis graph representing the AToM3 model HMM10_then1_IsolatedLHS.
Executable constraint code.
@param PreNode: Function taking an integer as parameter
and returns the node corresponding to that label.
Flag this instance as compiled now Add the edges Set the graph attribut... | 882 | en | 0.709727 |
#!/usr/bin/env python
# Copyright (c) 2014 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.
'''
A script to check that the (Linux) executables produced by gitian only contain
allowed gcxc, glibc and libstdc+... | contrib/devtools/symbol-check.py | 6,195 | Demangle C++ symbol names.
Use a pipe to the 'c++filt' command.
Parse an ELF executable and return a list of (symbol,version) tuples
for dynamic, imported symbols.
A script to check that the (Linux) executables produced by gitian only contain
allowed gcxc, glibc and libstdc++ version symbols. This makes sure they are... | 2,286 | en | 0.559826 |
#!/usr/bin/env python3
import cgi, cgitb, os, storage, shutil, time, sys, atexit
def deltemp():
os.remove("_/3dsthemes/tmp.zip")
from libs import zip
cgitb.enable()
from libs.session import Session
from libs import smdh
session=Session()
if not session.isLoggedIn():
raise ValueError("Must be logged in to upload... | 3dsthemes/do_upload.py | 2,007 | !/usr/bin/env python3Check if an upload is in progressOK, we're onto somethingWill throw an exception if the file doesn't exist or isn't valid.Put theme into database. This is done last to prevent 'ghost themes'Write | 216 | en | 0.89958 |
# Generated by Django 4.0.2 on 2022-02-19 19:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='HierarchicalModelMixin',
f... | common/migrations/0001_initial.py | 654 | Generated by Django 4.0.2 on 2022-02-19 19:48 | 45 | en | 0.755005 |
import pickle
from time import time
from sklearn.cross_validation import train_test_split as tts
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import classification_report as clsr
from sklearn.neural_network._base import identity
from sk... | analyzer/build.py | 1,996 | Inner build function that builds a single model.
@timeit @timeit Label encode the targets Begin evaluation | 108 | en | 0.634141 |
class FlumineException(Exception):
"""Base class for Flumine Errors"""
pass
class RunError(FlumineException):
"""Exception raised if error
in `Flumine.run()``
"""
def __init__(self, message):
super(RunError, self).__init__(message)
class ListenerError(FlumineException):
"""Erro... | flumine/exceptions.py | 1,331 | Exception raised on client
error.
Exception raised if order voilates
a control.
Base class for Flumine Errors
Error raised if error in Listener
Exception raised if incorrect
order/order_type requested.
Exception raised error in package during
execution.
Exception raised if order update
incorrect.
Exception raised if er... | 343 | en | 0.646146 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import sys
import os
sys.path.append(os.getc... | test/test_all.py | 3,326 | Try each toolchain with a pcf
Try seeding, where possible
Try each toolchain
!/usr/bin/env python3 -*- coding: utf-8 -*- Copyright (C) 2020 The SymbiFlow Authors. Use of this source code is governed by a ISC-style license that can be found in the LICENSE file or at https://opensource.org/licenses/ISC SPDX-License-Ide... | 372 | en | 0.764929 |
import os
import freesasa
from .extract_residues import extract_residue
# Defaults
_DEFAULT_OPTIONS = {
'hetatm': True,
'hydrogen': True,
# 'halt-at-unknown': True,
# 'separate-chains' : False,
'separate-models': True
}
_DEFAULT_PARAMETERS = {
'algorithm': freesasa.LeeRichards,
'probe-r... | bac/analyse/wsas/freesasa_utils.py | 7,648 | Wrapper to help run freesasa on a single PDB file
Freesasa has a nice Python interface but some things don't work quite as
needed for BAC, at least in Python 3. This wrapper is intended to handle
these issues:
1. File names need conversion to bytes when passed to freesasa
2. By default should include HETATMS and hydro... | 3,000 | en | 0.622681 |
import sys
from telethon import events, functions, __version__
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="helpme", allow_sudo=True)) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
help_string = """@UniBorg
Python {}
Telethon {}
UserBot Forked from https://git... | stdplugins/_help.py | 1,484 | pylint:disable=E0602 pylint:disable=E0602 pylint:disable=E0602 pylint:disable=E0602 pylint:disable=E0602 pylint:disable=E0602 pylint:disable=E0602 pylint:disable=E0602 | 167 | de | 0.444287 |
import pytest
from briefcase.integrations.subprocess import CommandOutputParseError, ParseError
def splitlines_parser(data):
"""A test parser that returns the input data, split by line."""
return data.splitlines()
def second_line_parser(data):
"""A test parser that returns the second line of input."""
... | tests/integrations/subprocess/test_Subprocess__parse_output.py | 3,252 | A test parser that returns the second line of input.
A test parser that returns the input data, split by line.
A simple call to check_output will be invoked.
Any extra keyword arguments are passed through as-is to check_output.
Parser errors on output from check_output.
Parser returns expected portion of check_output's... | 475 | en | 0.513475 |
"""This module contains the detection code for predictable variable
dependence."""
import logging
from copy import copy
from mythril.analysis.module.base import DetectionModule, EntryPoint
from mythril.analysis.report import Issue
from mythril.exceptions import UnsatError
from mythril.analysis import solver
from mythr... | mythril/analysis/module/modules/dependence_on_predictable_vars.py | 9,011 | State annotation set in blockhash prehook if the input value is lower than the current block number.
State annotation used when a path is chosen based on a predictable variable.
Symbol annotation used if a variable is initialized from a predictable environment variable.
This module detects whether control flow decision... | 886 | en | 0.805085 |
# -*- coding: utf-8 -*-
from helper import unittest, PillowTestCase
from PIL import Image, ImageDraw, ImageFont, features
FONT_SIZE = 20
FONT_PATH = "Tests/fonts/DejaVuSans.ttf"
@unittest.skipUnless(features.check('raqm'), "Raqm Library is not installed.")
class TestImagecomplextext(PillowTestCase):
def test_en... | Pillow-4.3.0/Tests/test_imagefontctl.py | 4,540 | -*- coding: utf-8 -*-smoke test, this should not fail End of file | 65 | en | 0.892932 |
# Standard Library
import asyncio
import logging
import math
# Third Party
import numpy as np
import pandas as pd
from fastapi import FastAPI, HTTPException, Request
from nats.aio.client import Client as NATS
from nats_wrapper import NatsWrapper
app = FastAPI()
logging.basicConfig(level=logging.INFO, format="%(asctim... | src/payload-receiver-service/app/main.py | 2,860 | Standard Library Third Party compute window process every chunk TODO logs without timestamp (e.g. control plane logs) Bad Request | 129 | en | 0.829768 |
# Copyright (c) 2019 - now, Eggroll 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 ... | python/eggroll/core/aspects.py | 1,905 | Copyright (c) 2019 - now, Eggroll 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 applicable law o... | 594 | en | 0.876211 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Lbann(CMakePackage, CudaPackage, ROCmPackage):
"""LBANN: Livermore Big Artificia... | var/spack/repos/builtin/packages/lbann/package.py | 18,618 | LBANN: Livermore Big Artificial Neural Network Toolkit. A distributed
memory, HPC-optimized, model and data parallel training toolkit for deep
neural networks.
Copyright 2013-2021 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-... | 1,373 | en | 0.774047 |
# coding=utf-8
"""sksurgerytextoverlay tests"""
from sksurgeryutils.ui.sksurgerytextoverlay_demo import TextOverlayDemo
import pytest
import sys
def test_sksurgerytextoverlay():
""" Basic test to run the widget and make sure everything loads OK."""
if sys.platform == "darwin":
pytest.skip("Test not ... | tests/test_sksurgerytextoverlay.py | 502 | Basic test to run the widget and make sure everything loads OK.
sksurgerytextoverlay tests
coding=utf-8 Use input video rather than camera to test | 148 | en | 0.781194 |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Bill)
| bills/admin.py | 113 | Register your models here. | 26 | en | 0.957485 |
# stdlib
import time
from unittest import skipIf
# 3p
import psycopg2
from psycopg2 import extensions
from psycopg2 import extras
from ddtrace import Pin
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.contrib.psycopg.patch import PSYCOPG2_VERSION
from ddtrace.contrib.psycopg.patch import patch
f... | tests/contrib/psycopg/test_psycopg.py | 13,928 | Checks whether execution of composed SQL string is traced
Checks whether execution of composed SQL string is traced
Checks whether execution of composed SQL string is traced
When a user specifies a service for the app
The psycopg integration should not use it.
stdlib 3p default service Test patch idempotence Test... | 1,656 | en | 0.798489 |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os,json,glob,re
import numpy as np
import pandas as pd
import nibabel as nb
from nilearn.input_data import NiftiMasker
def dcan2fmriprep(dcandir,outdir,sub_id=None):
dcandir = os.path.abspath(... | xcp_abcd/utils/dcan2fmriprep.py | 11,044 | Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
dcan2fmriprep(dcan_dir,out_dir)
emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- vi: set ft=python sts=4 ts=4 sw=4 et: get session id if available ... | 902 | en | 0.388423 |
from __future__ import absolute_import
import os
from collections import namedtuple
import time
from torch.nn import functional as F
from baseline.fast_rcnn.model.utils.creator_tool import AnchorTargetCreator, ProposalTargetCreator
from torch import nn
import torch as t
from baseline.fast_rcnn.utils import array_tool ... | baseline/fast_rcnn/trainer.py | 9,694 | wrapper for conveniently training. return losses
The losses include:
* :obj:`rpn_loc_loss`: The localization loss for Region Proposal Network (RPN).
* :obj:`rpn_cls_loss`: The classification loss for RPN.
* :obj:`roi_loc_loss`: The localization loss for the head module.
* :obj:`roi_cls_loss`: The classificati... | 2,454 | en | 0.828916 |
import math
import random
import time
def average_density(rdr):
countZeros = 0
length = 0
for i in rdr:
length = length + 1
if (i == 0):
countZeros = countZeros + 1
return [length - countZeros, length]
def check_rdr(rdr):
for i in range (0, len(rdr)-1):
... | Python/IFRA.py | 8,792 | convert bin_k to an array to allow change of one bit easily If k is empty, Then carry needs to be added last. If LSB is 0, we just add carry to make it one. If it's 1, we make it 0 and carry is set to 1 index is set to the second LSB if k was only 1 bit, we just append the carry if we reached the MSB and it's 1, then w... | 3,210 | en | 0.704313 |
"""
WSGI config for djangoCMS project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SET... | step3ComprehensiveProject/django-vue-cms/djangoCMS/djangoCMS/wsgi.py | 395 | WSGI config for djangoCMS project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ | 215 | en | 0.77306 |
from django.contrib import auth
from django.shortcuts import render
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from user.serializers import UserSerializer, AuthTokenSerializer
class Cre... | app/user/views.py | 1,008 | create a new auth token for user
create a new user in the system
Manage the authenticated user
retrieve auhtenticated user | 122 | en | 0.776886 |
# 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 ... | src/aks-preview/azext_aks_preview/vendored_sdks/azure_mgmt_preview_aks/v2022_03_02_preview/operations/_managed_cluster_snapshots_operations.py | 26,959 | ManagedClusterSnapshotsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.containerservice.v2022_0... | 5,761 | en | 0.555299 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-03-10 12:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gram', '0004_auto_20190310_1510'),
]
operations = [
migrations.AlterField(
... | gram/migrations/0005_auto_20190310_1523.py | 454 | -*- coding: utf-8 -*- Generated by Django 1.11 on 2019-03-10 12:23 | 66 | en | 0.666302 |
#
# 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... | airflow/providers/databricks/hooks/databricks.py | 13,450 | Interact with Databricks.
:param databricks_conn_id: Reference to the :ref:`Databricks connection <howto/connection:databricks>`.
:param timeout_seconds: The amount of time in seconds the requests library
will wait before timing-out.
:param retry_limit: The number of times to retry the connection in case of
se... | 5,031 | en | 0.770608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.