content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
'''
feature: v1, 2, 3, 4, 10, 11
feature: v1, 2, 3, 4, 11, 13, 14, 17, 18, 19, 22, 23
model: v10
'''
import itertools
import json
import gc
import glob
import os
import time
import cv2
import re
import nltk
import torch
import imagehash
import lightgbm as lgb
import xgboost as xgb
import matplot... | code/exp/v18.py | 110,820 | Parameters
----------
use_idf : boolean, optional (default=True)
k1 : float, optional (default=2.0)
b : float, optional (default=0.75)
References
----------
Okapi BM25: a non-binary model - Introduction to Information Retrieval
http://nlp.stanford.edu/IR-book/html/htmledition/okapi-bm25-a-non-binary-model-1.html
Param... | 2,748 | en | 0.301235 |
class NeuralNet():
def __init__(self, game):
pass
def train(self, examples):
"""
This function trains the neural network with examples obtained from
self-play.
Input:
examples: a list of training examples, where each example is of form
... | pommerman/NN/neural_net.py | 1,206 | Loads parameters of the neural network from folder/filename
Input:
board: current board in its canonical form.
Returns:
pi: a policy vector for the current board- a numpy array of length
game.getActionSize
v: a float in [-1,1] that gives the value of the current board
Saves the current neural networ... | 704 | en | 0.917271 |
"""
File name: utils
Author: rameshpr
Date: 11/5/18
"""
import numpy as np
from ctypes import *
from typing import List, Tuple
import cv2
from pyyolo.darknet import c_array, IMAGE, METADATA, predict_image, get_network_boxes, \
do_nms_obj, do_nms_sort, free_image, free_detections, ndarray_image
import ... | pyyolo/utils.py | 4,110 | Given image with numpy array will be converted to
darkent image
Remember to call free_image(im) function after using this image
:rtype: IMAGE
:param arr: numpy array
:return: darknet image
Detect the objects in the given image. free_image function is called inside this function.
Therefore the input darkent image is no... | 1,642 | en | 0.684751 |
# coding: utf-8
"""
Cloudsmith API
The API to the Cloudsmith Service
OpenAPI spec version: v1
Contact: support@cloudsmith.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import cloudsmith_api
f... | bindings/python/src/test/test_rates_api.py | 835 | RatesApi unit test stubs
Test case for rates_limits_list
Endpoint to check rate limits for current user.
Cloudsmith API
The API to the Cloudsmith Service
OpenAPI spec version: v1
Contact: support@cloudsmith.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 | 294 | en | 0.612023 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.recovery` module.
"""
import numpy as np
import unittest
from colour.colorimetry import (
MSDS_CMFS,
SDS_ILLUMINANTS,
SpectralShape,
reshape_msds,
reshape_sd,
sd_to_XYZ_integration,
)
from colour.rec... | colour/recovery/tests/test__init__.py | 2,463 | Defines :func:`colour.recovery.XYZ_to_sd` definition unit tests
methods.
Initialises common tests attributes.
Tests :func:`colour.recovery.XYZ_to_sd` definition domain
and range scale support.
Defines the unit tests for the :mod:`colour.recovery` module.
!/usr/bin/env python -*- coding: utf-8 -*- pylint: disable=E110... | 321 | en | 0.576392 |
#!/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.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory... | contrib/seeds/generate-seeds.py | 4,386 | Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory that is passed as an
argument:
nodes_main.txt
nodes_test.txt
These files must consist of lines in the format
<ip>
<ip>:<port>
[<ipv6>]
[<ipv6>]:<port>
<onion>.onion
0xDDBBC... | 984 | en | 0.611035 |
"""Test UniFi config flow."""
from unittest.mock import patch
import aiounifi
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.components.unifi.const import (
CONF_ALLOW_BANDWIDTH_SENSORS,
CONF_ALLOW_UPTIME_SENSORS,
CONF_BLOCK_CLIENT,
CONF_CONTROLLER,
CONF_DETECT... | tests/components/unifi/test_config_flow.py | 19,098 | Test UniFi config flow. | 23 | en | 0.677914 |
import math
import random
import time
import argparse
from sklearn import preprocessing
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_curve, auc
import pandas as pd
import numpy as np
import torch.nn as nn
import torch
from LR import... | JIT_Baseline/baseline.py | 10,342 | f1 = 2 * prc * rc / (prc + rc) return the features of yasu data return the labels of yasu data number of training examples Step 1: No shuffle (X, Y) Step 2: Randomly pick mini_batch_size / 2 from each of positive and negative labels number of training examples Step 1: No shuffle (X, Y) Step 2: Partition (X, Y). Minus t... | 870 | en | 0.595423 |
"""
Support the sensor of a BloomSky weather station.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/sensor.bloomsky/
"""
import logging
from homeassistant.const import TEMP_FAHRENHEIT
from homeassistant.helpers.entity import Entity
from homeassistant.... | homeassistant/components/sensor/bloomsky.py | 2,914 | Representation of a single sensor in a BloomSky device.
Initialize a bloomsky sensor.
The name of the BloomSky device and this sensor.
Setup the available BloomSky weather sensors.
The current state, eg. value, of this sensor.
Return the unique ID for this sensor.
Return the sensor units.
Request an update from the Blo... | 684 | en | 0.773687 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | tests/kafkatest/tests/client/message_format_change_test.py | 5,717 | This tests performs the following checks:
The workload is a mix of 0.9.x, 0.10.x and 0.11.x producers and consumers
that produce to and consume from a DEV_BRANCH cluster
1. initially the topic is using message format 0.9.0
2. change the message format version for topic to 0.10.0 on the fly.
3. change the message format... | 1,695 | en | 0.861949 |
# -*- coding: utf-8 -*-
"""
[googleSearch.py]
Google Search Plugin
[Author]
Justin Walker
[About]
Returns the first three links from a google search.
[Commands]
>>> .google <<search term>>
returns search links
"""
try:
from googlesearch import search
except ImportError:
print("No modu... | honeybot/plugins/google.py | 1,435 | [googleSearch.py]
Google Search Plugin
[Author]
Justin Walker
[About]
Returns the first three links from a google search.
[Commands]
>>> .google <<search term>>
returns search links
-*- coding: utf-8 -*- start is what link to start with, stop is how many links to get only_standard limits it to normal links instea... | 410 | en | 0.882485 |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | lite/examples/model_personalization/converter/tfltransfer/model_correctness_test.py | 15,985 | Test consumer of models generated by the converter.
Creates a wrapper for a set of models and a data set.
Applies the optimizer to the model parameters.
Consumes a generator and converts all images to bottlenecks.
Args:
image_gen: A Keras data generator for images to process
Returns:
Two NumPy arrays: (bottleneck... | 2,629 | en | 0.828722 |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""
spyderlib.widgets
=================
Widgets defined in this module may be used in any other Qt-based application
They are also used in Spyder throug... | spyderlib/widgets/__init__.py | 375 | spyderlib.widgets
=================
Widgets defined in this module may be used in any other Qt-based application
They are also used in Spyder through the Plugin interface
(see spyderlib.plugins)
-*- coding: utf-8 -*- Copyright © 2009-2010 Pierre Raybaut Licensed under the terms of the MIT License (see spyderlib/__i... | 341 | en | 0.668104 |
from math import ceil
from time import sleep
from config import *
from servo import *
from camera import *
from pid import *
# Init
servo1 = Servo(2)
servo2 = Servo(3)
servo_count = 0
#servo1.setAngle(90)
#sleep(1)
#servo2.setAngle(90)
#sleep(1)
camera = Camera()
PID = PID()
# Loop
while True:
data = ca... | run.py | 1,489 | Initservo1.setAngle(90)sleep(1)servo2.setAngle(90)sleep(1) Loopdata = None Calculate PID Print resultprint("x", round(move[0]), "y", round(move[1]), round(move[2]*600)) Move servosmove_x = ( (move[0] - conf.cam_x_min) / (conf.cam_x_max - conf.cam_x_min) ) * (conf.servo_max - conf.servo_min) + conf.servo_minmove_y = ( (... | 494 | en | 0.204446 |
# -*- coding: utf-8 -*-
# @Author: Jie
# @Date: 2017-06-15 14:11:08
# @Last Modified by: Jie Yang, Contact: jieynlp@gmail.com
# @Last Modified time: 2019-02-13 12:41:44
from __future__ import print_function
import time
import sys
import argparse
import random
import torch
import gc
import torch.nn as nn
import... | main.py | 39,647 | input: list of words, chars and labels, various length. [[words, features, chars, labels],[words, features, chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
features: features ids for one sentence. (batch_size, feature_num), each sentence has one set of feature
chars: char ids for... | 6,436 | en | 0.696813 |
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from pymongo import MongoClient
import json
import os
client = MongoClient(os.environ.get("DATABASE"))
db = client.politics.brexit
external_stylesheets = ['https://codepen.io/chriddy... | brexit-word-freq/app.py | 1,979 | Set up plot in milliseconds | 27 | en | 0.708825 |
import pytest
from nbformat import notebooknode
from nb2hugo.preprocessors import FixLatexPreprocessor
@pytest.fixture
def preprocessor():
"""Return an instance of FixLatexPreprocessor."""
return FixLatexPreprocessor()
source = (
'Some text with an inline equality $escaped\_0 = lower_0$.\n'
'And a d... | tests/preprocessors/test_fixlatex.py | 2,073 | Return an instance of FixLatexPreprocessor. | 43 | en | 0.339552 |
"""WARNING: This code is not recommanded. It is not finished, it is
slower then the version in sandbox/neighbours.py, and it do not work
on the GPU.
We only keep this version here as it is a little bit more generic, so
it cover more cases. But thoses cases aren't needed frequently, so you
probably don't want to use th... | theano/sandbox/neighbourhoods.py | 10,953 | This extracts neighbourhoods from "images", but in a
dimension-generic manner.
In the 2D case, this is similar to downsampling, but instead of reducing
a group of 2x2 pixels (for example) to a single new pixel in the output,
you place those 4 pixels in a row.
For example, say you have this 2x4 image::
[ [ 0.5, 0... | 3,158 | en | 0.928996 |
# ======🙋🙋🙋实现了 1个函数fn 映射 为1个URL处理函数!!!
import asyncio, os, inspect, logging, functools
from urllib import parse
from aiohttp import web
from apis import APIError
def get(path):
'''
Define decorator @get('/path')
'''
def decorator(func):
@functools.wraps(func)
def wrapper(*args, *... | qiushaoyi/programs/qsy_program_codes/python3-webapp/www/coroweb.py | 6,296 | Define decorator @get('/path')
Define decorator @post('/path')
======🙋🙋🙋实现了 1个函数fn 映射 为1个URL处理函数!!! remove all unamed kw: check named arg: check required kw: | 159 | zh | 0.148113 |
import torch.nn as nn
import torch
import torch.nn.functional as F
class CombinationModule(nn.Module):
def __init__(self, c_low, c_up, batch_norm=False, group_norm=False, instance_norm=False):
super(CombinationModule, self).__init__()
if batch_norm:
self.up = nn.Sequential(nn.Conv2d(c_... | models/layers.py | 2,401 | track_running_stats=True), track_running_stats=True), if self.up[1].running_mean is not None: print(self.up[1].running_mean.shape) | 134 | en | 0.373936 |
# encoding: utf-8
# module Autodesk.Civil.Settings calls itself Settings
# from AeccDbMgd, Version=13.3.854.0, Culture=neutral, PublicKeyToken=null, AeccPressurePipesMgd, Version=13.3.854.0, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class Abbrev... | release/stubs/Autodesk/Civil/Settings.py | 142,260 | encoding: utf-8 module Autodesk.Civil.Settings calls itself Settings from AeccDbMgd, Version=13.3.854.0, Culture=neutral, PublicKeyToken=null, AeccPressurePipesMgd, Version=13.3.854.0, Culture=neutral, PublicKeyToken=null by generator 1.145 no doc no imports no functions classes no doc default default default default d... | 4,899 | gl | 0.07066 |
"""
Utilities for training, testing and caching results
for HICO-DET and V-COCO evaluations.
Fred Zhang <frederic.zhang@anu.edu.au>
The Australian National University
Australian Centre for Robotic Vision
"""
import os
import sys
import torch
import random
import warnings
import argparse
import numpy as np
import tor... | main.py | 7,916 | Utilities for training, testing and caching results
for HICO-DET and V-COCO evaluations.
Fred Zhang <frederic.zhang@anu.edu.au>
The Australian National University
Australian Centre for Robotic Vision
Fix seed Fetch indices for rare and non-rare classes Override optimiser and learning rate scheduler training paramet... | 323 | en | 0.729596 |
#!/usr/bin/python
import os, sys # low level handling, such as command line stuff
import string # string methods available
import re # regular expressions
import getopt # comand line argument handling
import math # match functions
from low import * # custom functions, written by myself
... | python/fasta/seqlength.py | 3,734 | !/usr/bin/python low level handling, such as command line stuff string methods available regular expressions comand line argument handling match functions custom functions, written by myself ============================================================================= =================================================... | 924 | en | 0.404267 |
# -*- coding: utf-8 -*-
"""
Tests the speed of image updates for an ImageItem and RawImageWidget.
The speed will generally depend on the type of data being shown, whether
it is being scaled and/or converted by lookup table, and whether OpenGL
is used by the view widget
"""
## Add path to library (just for examples; yo... | examples/VideoSpeedTest.py | 9,663 | Tests the speed of image updates for an ImageItem and RawImageWidget.
The speed will generally depend on the type of data being shown, whether
it is being scaled and/or converted by lookup table, and whether OpenGL
is used by the view widget
-*- coding: utf-8 -*- Add path to library (just for examples; you do not nee... | 708 | en | 0.826579 |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from wagtail.tests.testapp.models import SingleEventPage
from wagtail.tests.testapp.rich_text import C... | wagtail/wagtailadmin/tests/test_rich_text.py | 8,267 | These tests generate new EditHandlers with different settings. The
cached edit handlers should be cleared before and after each test run
to ensure that no changes leak through to other tests.
Simulate the absence of a setting Find root page Simulate the absence of a setting Check status code Check that hallo (default... | 780 | en | 0.905053 |
#!/usr/bin/env python
# Copyright (c) 2018, The Regents of the University of California
# 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 cop... | cogrob_ros/cogrob_pololu_lidar/scripts/cogrob_pololu_lidar.py | 5,645 | !/usr/bin/env python Copyright (c) 2018, The Regents of the University of California 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 noti... | 1,636 | en | 0.876664 |
"""
The main purpose of this module is to expose LinkCollector.collect_links().
"""
import cgi
import functools
import itertools
import logging
import mimetypes
import os
import re
from collections import OrderedDict
from pip._vendor import html5lib, requests
from pip._vendor.distlib.compat import unescape
from pip._... | src/pip/_internal/index/collector.py | 21,609 | Encapsulates the return value of a call to LinkCollector.collect_links().
The return value includes both URLs to project pages containing package
links, as well as individual package Link objects collected from other
sources.
This info is stored separately as:
(1) links from the configured file locations,
(2) links ... | 7,696 | en | 0.812124 |
import tarfile
import re
import logging
from dipper.sources.Source import Source
from dipper.models.assoc.OrthologyAssoc import OrthologyAssoc
from dipper.models.Model import Model
from dipper.models.Dataset import Dataset
from dipper import config
from dipper import curie_map
__author__ = 'nicole'
logger = logging.... | dipper/sources/Panther.py | 15,667 | The pairwise orthology calls from Panther DB:
http://pantherdb.org/ encompass 22 species,
from the RefGenome and HCOP projects.
Here, we map the orthology classes to RO homology relationships
This resource may be extended in the future with additional species.
This currently makes a graph of orthologous relationships ... | 5,020 | en | 0.807061 |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# Vulkan CTS
# ----------
#
# Copyright (c) 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | external/vulkancts/scripts/gen_framework.py | 54,066 | -*- coding: utf-8 -*-------------------------------------------------------------------------- Vulkan CTS ---------- Copyright (c) 2015 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at ... | 1,760 | en | 0.794761 |
# -*- coding: utf-8 -*-
"""Title translate module."""
#
# (C) Rob W.W. Hooft, 2003
# (C) Yuri Astrakhan, 2005
# (C) Pywikibot team, 2003-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id: 790e17e8c0da2027ad0cb511c168c353056583aa $'
#... | pywikibot/titletranslate.py | 4,120 | Return a list of links to pages on other sites based on hints.
Entries for single page titles list those pages. Page titles for entries
such as "all:" or "xyz:" or "20:" are first built from the page title of
'page' and then listed. When 'removebrackets' is True, a trailing pair of
brackets and the text between them i... | 1,030 | en | 0.875285 |
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... | tfx/components/pusher/executor_test.py | 3,769 | Tests for tfx.components.pusher.executor.
Lint as: python2, python3 Copyright 2019 Google LLC. 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/license... | 639 | en | 0.849412 |
"""
Create a flat plate of length 1.0 with aspect ratio 2.0 and a 30-degree
inclination.
The plate is discretized with spacing 0.04 in the x-y plane and with spacing
0.04 along the z-direction.
"""
import math
import pathlib
import numpy
# Flat-plate's parameters.
L = 1.0 # chord length
AR = 2.0 # aspect ratio
xc,... | examples/decoupledibpm/flatplate3dRe100AoA30_GPU/scripts/createBody.py | 1,084 | Create a flat plate of length 1.0 with aspect ratio 2.0 and a 30-degree
inclination.
The plate is discretized with spacing 0.04 in the x-y plane and with spacing
0.04 along the z-direction.
Flat-plate's parameters. chord length aspect ratio center's coordinates angle of inclination in degrees mesh spacing Generate co... | 377 | en | 0.808031 |
# coding=utf-8
# Copyright 2018 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | tf_agents/environments/random_py_environment_test.py | 6,224 | Tests for utils.random_py_environment.
coding=utf-8 Copyright 2018 The TF-Agents Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless requi... | 764 | en | 0.83363 |
# Copyright 2017 OpenStack Foundation
# 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 requ... | apmec/conductor/conductor_server.py | 3,183 | Copyright 2017 OpenStack Foundation 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... | 682 | en | 0.858606 |
# -*- coding: utf-8 -*-
import argparse
from GoogleScraper.version import __version__
def get_command_line(only_print_help=False):
"""
Parse command line arguments when GoogleScraper is used as a CLI application.
Returns:
The configuration as a dictionary that determines the behaviour of the app... | GoogleScraper/commandline.py | 8,687 | Parse command line arguments when GoogleScraper is used as a CLI application.
Returns:
The configuration as a dictionary that determines the behaviour of the app.
-*- coding: utf-8 -*-custom arguments | 207 | en | 0.740134 |
# -*- coding: utf-8 -*-
"""
auto rule template
~~~~
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
from utils.api import *
class CVI_300... | rules/javascript/CVI_3003.py | 1,098 | rule class
regex string input
:regex_string: regex match string
:return:
auto rule template
~~~~
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
-*- coding: utf-8 -*- ... | 369 | en | 0.487063 |
'''
Exercise 5: Vectors
A vector of dimension 𝑛𝑛 can be represented by a list in Python. For example, a vector of
dimension 3 could represent a point in space, and a vector of dimension 4 could represent a
point in space and time (the fourth dimension being the time). In mathematical notation, a
vector of dimension 3... | week4/week4_additionalexercice_5.py | 1,864 | Exercise 5: Vectors
A vector of dimension 𝑛𝑛 can be represented by a list in Python. For example, a vector of
dimension 3 could represent a point in space, and a vector of dimension 4 could represent a
point in space and time (the fourth dimension being the time). In mathematical notation, a
vector of dimension 3 is ... | 1,108 | en | 0.893014 |
# 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 Stc(AutotoolsPackage):
"""STC: The Swift-Turbine Compiler"""
homepage = 'http://swif... | var/spack/repos/builtin/packages/stc/package.py | 1,367 | STC: The Swift-Turbine Compiler
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) | 222 | en | 0.660524 |
#!/usr/bin/env python
"""
Add docstring
"""
from datetime import datetime
from protorpc import messages
from google.appengine.ext import ndb
# Define game objects
class Game(ndb.Model):
"""Game object"""
deck = ndb.StringProperty(repeated=True)
disp_deck = ndb.StringProperty(repeated=True)
attemp... | models/game.py | 7,756 | Game object
Used for outbound game information
Used for outbound information on the state of a
user's active game
Outbound container for a list of GameFormUserGame forms
Used for outbound information on each guess made
and the outcome of a game
Inbound form used to make a move
Inbound form used to create a new game
Use... | 1,057 | en | 0.847822 |
'''Tests about the gzippy top-level functions.'''
import unittest
from test import scratch_file
import gzippy
class GzippyTest(unittest.TestCase):
'''Tests about the gzippy top-level functions.'''
def test_open_with_plus(self):
'''Opening with r+ is not allowed.'''
with scratch_file('exam... | test/test_gzippy.py | 873 | Tests about the gzippy top-level functions.
Opening in append mode is not allowed.
Opening with r+ is not allowed.
Tests about the gzippy top-level functions. | 158 | en | 0.948362 |
import copy
import json
import logging
import warnings
import requests
from elastalert.alerter import Alerter
from elastalert.exceptions import EAException
from elastalert.utils.time import DateTimeEncoder
from elastalert.utils.util import lookup_es_key
from requests import RequestException
log = logging.getLogger(__... | elastalert/alerter/slack_alerter.py | 6,294 | Creates a Slack room message for each alert
https://api.slack.com/docs/formatting Reduced maximum width for prettier Slack display. post to slack set https proxy, if it was provided if we have defined fields, populate noteable fields for the alert | 250 | en | 0.831138 |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 11:46:26 2022
@author: Pedro
"""
def search(lista, target) -> int:
for i in range(len(lista)):
if lista [i] == target:
return i
return -1
def search2(lista, target) -> int:
for i, element in enumerate(lista):
if element == targ... | teoria/clase 29-03/algoritmos.py | 358 | Created on Tue Mar 29 11:46:26 2022
@author: Pedro
-*- coding: utf-8 -*- | 75 | en | 0.78809 |
"""Constants used to ensure topic consistantancy."""
STANDARD_RECEIVED = "standard_received"
EXTENDED_RECEIVED = "extended_received"
X10_RECEIVED = "x10_received"
ALL_LINKING_COMPLETED = "all_linking_completed"
BUTTON_EVENT_REPORT = "button_event_report"
USER_RESET_DETECTED = "user_reset_detected"
ALL_LINK_CLEANUP_FAI... | pyinsteon/topics.py | 9,033 | Constants used to ensure topic consistantancy.
Command Topics | 63 | en | 0.707449 |
"""Interfaces for interactively entering guesses."""
import curses
import time
import click
from wordle_cheater.interface_base import WordleCheaterUI
class CursesInterface(WordleCheaterUI):
"""Interface for using the curses library to enter guesses and display solutions.
Attributes
----------
guess... | src/wordle_cheater/interface.py | 15,589 | Interface for using Click alone to enter letters and see solutions.
Parameters
----------
max_rows : int, optional
The maximum rows of possible solutions to print.
max_cols : int, optional
The maximum columns of possible solutions to print.
x0 : int, optional
The leftmost position where guesses will be ent... | 6,429 | en | 0.566548 |
import asyncio
import functools
import operator
from typing import (
cast,
Iterable,
NamedTuple,
Sequence,
Type,
Tuple,
)
from cached_property import cached_property
from eth_utils import (
ExtendedDebugLogger,
to_tuple,
)
from eth_utils.toolz import groupby, valmap
from eth_keys impo... | p2p/handshake.py | 14,929 | Base class that handles the handshake for a given protocol. The primary
justification for this class's existence is to house parameters that are
needed for the protocol handshake.
Select the appropriate shared capabilities between local and remote.
https://github.com/ethereum/devp2p/blob/master/rlpx.md#capability-mes... | 3,818 | en | 0.876432 |
"""
A module that contains utility functions to load the 'classical' workspace configuration.
This configuration may have three meaningful files:
.remote (required) - information about the connection options
.remoteindex (optional) - information about which connection from options above to use
.remoteignore (optional) ... | src/remote/configuration/classic.py | 8,574 | A medium class that knows how to load and save the 'classical' workspace configuration.
This configuration may have three meaningful files:
.remote (required) - information about the connection options
.remoteindex (optional) - information about which connection from options above to use
.remoteignore (optional) - inf... | 1,106 | en | 0.800592 |
import csv
import logging
import os
import copy
import re
import random
from functools import reduce
import ast
import pandas
import pexpect
import avi.migrationtools.netscaler_converter.ns_constants as ns_constants
from pkg_resources import parse_version
from xlsxwriter import Workbook
from openpyxl import load_workb... | python/avi/migrationtools/netscaler_converter/ns_util.py | 88,542 | Adds as status row in conversion status csv
:param ns_config: NS config dict
:param output_dir: output directory
:param avi_config: AVI config dict
:param report_name: name of report
:param vs_level_status: add vs level details in XL sheet
Adds as status row in conversion status csv
:param line_no: line number of comma... | 13,041 | en | 0.682791 |
"""BitMEX API Connector."""
from __future__ import absolute_import
import requests
import time
import datetime
import json
import base64
import uuid
from market_maker.auth import APIKeyAuthWithExpires
from market_maker.utils import constants, errors, log
from market_maker.ws.ws_thread import BitMEXWebsocket
from thread... | market_maker/bitmex.py | 14,504 | BitMEX API Connector.
Init connector.
Send a request to BitMEX Servers.
Amend multiple orders.
Annotation for methods that require auth.
Place a buy order.
Returns order object. ID: orderID
Cancel an existing order.
Create multiple orders.
Get your current balance.
Get open orders via HTTP. Used on close to ensure we ... | 2,187 | en | 0.820916 |
"""
Django settings for activitytracker project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR,... | activitytracker/settings.py | 3,494 | Django settings for activitytracker project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
Build paths inside the project like this: os.path.join(BASE_DIR, ...) imp... | 1,262 | en | 0.558583 |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, 2015 Mitch Garnaat
#
# 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 appl... | kappa/__init__.py | 634 | -*- coding: utf-8 -*- Copyright (c) 2014, 2015 Mitch Garnaat 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... | 582 | en | 0.853719 |
import io
import json
import logging
from pathlib import Path
import boto3
from ..api import API
from ..exceptions import (
SABaseException, SAExistingAnnotationClassNameException,
SANonExistingAnnotationClassNameException
)
from .project import get_project_metadata
logger = logging.getLogger("superannotate-... | superannotate/db/annotation_classes.py | 15,033 | Create annotation class in project
:param project: project name or metadata of the project
:type project: str or dict
:param name: name for the class
:type name: str
:param color: RGB hex color value, e.g., "#FFFFAA"
:type color: str
:param attribute_groups: example:
[ { "name": "tall", "is_multiselect": 0, "attribut... | 2,093 | en | 0.58653 |
from cmstack.hdfg import hdfgutils
from cmstack.hdfg.hdfg_pb2 import Component, ValueInfo
import logging
from . import is_literal, is_number
def flatten_graph(output_graph, graph, templates, context,edge_node_ids, arg_map):
components = {}
for e in graph.edge_info:
copy_edge = ValueInfo()
if... | cmstack/hdfg/passes/flatten.py | 8,338 | inputs.append(carg_map[i]) outputs.append(carg_map[out]) states.append(carg_map[s]) parameters.append(carg_map[p]) | 114 | zh | 0.345299 |
"""FastAPI Project for CodeSpace.
https://csdot.ml
"""
| src/__init__.py | 55 | FastAPI Project for CodeSpace.
https://csdot.ml | 47 | en | 0.676718 |
import cv2
import os,shutil
import numpy as np
from Adb import Adb
import time
class Photo():
'''
提取图片信息,比较图片
'''
def __init__(self,img_path) -> None:
'''
读取图片
'''
self.img = cv2.imread(img_path)
class sourceData():
'''
获取测试数据
'''
def ... | Photo.py | 2,128 | 提取图片信息,比较图片
获取测试数据
读取图片
计算938:1035,1935:2247区域间图片的方差,用于比较图片见相似程度
计算过程,对图像每一行像素求平均,对所有行像素平均值求方差
return (int)
chazhi = (abs(static_num**2-img_num**2))**0.5 '''截图 400s''' sourceData.getScreenPhoto() | 197 | zh | 0.801257 |
#!/usr/bin/env python
# this node will be implemented on the master node
# this is a test script for drive motor
# in function of stop and front lights detection
# this script will be implemented in another node
# import libraries
import rospy,sys,time,atexit,numpy
from std_msgs.msg import String,Int16MultiArray
... | deprecated/led_control.py | 1,383 | !/usr/bin/env python this node will be implemented on the master node this is a test script for drive motor in function of stop and front lights detection this script will be implemented in another node import libraries define variables | 238 | en | 0.716825 |
from dataclasses import dataclass, field
from typing import List
from bindings.wfs.range import Range
__NAMESPACE__ = "http://www.opengis.net/ows/1.1"
@dataclass
class AllowedValues:
"""List of all the valid values and/or ranges of values for this quantity.
For numeric quantities, signed values should be or... | catalog/bindings/wfs/allowed_values.py | 768 | List of all the valid values and/or ranges of values for this quantity.
For numeric quantities, signed values should be ordered from
negative infinity to positive infinity. | 173 | en | 0.784709 |
import importlib
import inspect
import os
import sys
import warnings
from abc import ABCMeta, abstractmethod
from collections import namedtuple
import six
from dagster import check
from dagster.core.errors import DagsterInvariantViolationError
from dagster.serdes import whitelist_for_serdes
from dagster.seven import ... | python_modules/dagster/dagster/core/code_pointer.py | 12,685 | Same as FileCodePointer, but with an additional field `working_directory` to help resolve
modules that are resolved from the python invocation directory. Required so other processes
that need to resolve modules (e.g. cron scheduler) can do so. This could be merged with the
`FileCodePointer` with `working_directory` a... | 2,104 | en | 0.912665 |
# -*- coding: utf-8 -*-
import torch
from supar.utils.common import MIN
from supar.utils.fn import pad
from torch.autograd import Function
def tarjan(sequence):
r"""
Tarjan algorithm for finding Strongly Connected Components (SCCs) of a graph.
Args:
sequence (list):
List of head indi... | supar/structs/fn.py | 8,916 | ChuLiu/Edmonds algorithm for non-projective decoding :cite:`mcdonald-etal-2005-non`.
Some code is borrowed from `tdozat's implementation`_.
Descriptions of notations and formulas can be found in :cite:`mcdonald-etal-2005-non`.
Notes:
The algorithm does not guarantee to parse a single-root tree.
Args:
s (~tor... | 3,925 | en | 0.785072 |
# -*- coding: latin-1 -*-
# -----------------------------------------------------------------------------
# Copyright 2009-2011 Stephen Tiedemann <stephen.tiedemann@googlemail.com>
#
# Licensed under the EUPL, Version 1.1 or - as soon they
# will be approved by the European Commission - subsequent
# versions of the EU... | src/nfc/llcp/llc.py | 23,871 | -*- coding: latin-1 -*- ----------------------------------------------------------------------------- Copyright 2009-2011 Stephen Tiedemann <stephen.tiedemann@googlemail.com> Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licen... | 1,356 | en | 0.754881 |
import os
import cv2
import numpy as np
import time
cap = cv2.VideoCapture(0)
file_index = 0
if not os.path.exists("calibration_data/calibration_frames/"):
os.makedirs("calibration_data/calibration_frames/")
while True:
ret, frame = cap.read()
# display the resulting frame
cv2.imshow("frame", frame... | grab_calibration_frames.py | 672 | display the resulting frame | 27 | en | 0.298512 |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QGIS plugin 'Graphium'
/***************************************************************************
*
* Copyright 2020 Simon Gröchenig @ Salzburg Research
* eMail graphium@salzburgresearch.at
*
* Licensed... | graphium/graph_management/model/osm_highway_types.py | 1,680 | /***************************************************************************
QGIS plugin 'Graphium'
/***************************************************************************
*
* Copyright 2020 Simon Gröchenig @ Salzburg Research
* eMail graphium@salzburgresearch.at
*
* Licensed under the Apache License, Ve... | 939 | en | 0.634923 |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | make_train_test_split.py | 19,538 | Validates experiment setup for given lists of inchikeys.
A function to combine lists of inchikeys that are values from a dict.
Args:
dataset_subdivision_list: List of keys in dataset_split_dict to combine
into one list
dataset_split_dict: dict containing keys in dataset_subdivision_list, with
lists of ... | 6,484 | en | 0.802454 |
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def recurhelper(nums,res,path,target,start):
if target==0:
res.append(path)
... | 39-Combination-Sum/solution.py | 677 | :type candidates: List[int]
:type target: int
:rtype: List[List[int]] | 69 | en | 0.162415 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v3/proto/services/campaign_criterion_simulation_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
fro... | google/ads/google_ads/v3/proto/services/campaign_criterion_simulation_service_pb2.py | 6,415 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: google/ads/googleads_v3/proto/services/campaign_criterion_simulation_service.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:google.ads.googleads.v3.services.GetCampaignCriterionSimulationRequest) @@proto... | 351 | en | 0.620199 |
import numpy as np
from env import Env
from models import PolicyNet, Critic
from utils import one_hot
import torch
from torch.optim import Adam
import time
import os
from datetime import datetime
import math
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
#------------------------SET PARAMETE... | infer.py | 3,533 | ------------------------SET PARAMETERS--------------------------------------------INITIALIZE ENVIROMENT AND POLICIES----------------------------------LOAD TRAINDEL MODEL--------------------------------------------RUN TRAINED POLICY------------------------- GREEDY POLICY ------------ [ batch size ][batch_size, n_agents]... | 428 | en | 0.271101 |
"""File Converter
.nfc """
import asyncio
import os
import time
from datetime import datetime
from userbot.utils import admin_cmd, progress
@borg.on(admin_cmd(pattern="nfc (.*)")) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
input_str = event.pattern_match.group(1)
reply_... | userbot/plugins/fconvert.py | 4,048 | File Converter
.nfc
pylint:disable=E0602 pylint:disable=C0103,W0703 TODO: re-write create_subprocess_exec 😉 stdout must a pipe to be accessible as process.stdout Wait for the subprocess to finish | 198 | en | 0.642456 |
#!/usr/bin/env python3
import pwncat
from pwncat.commands import CommandDefinition
class Command(CommandDefinition):
"""
Exit the interactive prompt. If sessions are active, you will
be prompted to confirm. This shouldn't be run from a configuration
script.
"""
PROG = "exit"
ARGS = {}
... | pwncat/commands/exit.py | 414 | Exit the interactive prompt. If sessions are active, you will
be prompted to confirm. This shouldn't be run from a configuration
script.
!/usr/bin/env python3 | 159 | en | 0.763605 |
from __future__ import absolute_import
#SymPy is a non-commercial alternative to Mathematica and Maple
# SymPy can map variable to a value or a matrix.
# SymPy's Symbolic Statistical Modelling uses scintific computing.
import sys
import numpy as np
import sympy as sp
import pandas as pd
from pathlib import Path
from .... | src/equation_parser/equations.py | 2,298 | SymPy is a non-commercial alternative to Mathematica and Maple SymPy can map variable to a value or a matrix. SymPy's Symbolic Statistical Modelling uses scintific computing. | 174 | en | 0.673223 |
from win32com import storagecon
import pythoncom, os, win32api
import win32com.test.util
import unittest
class TestEnum(win32com.test.util.TestCase):
def testit(self):
fname, tmp = win32api.GetTempFileName(win32api.GetTempPath(),'stg')
m=storagecon.STGM_READWRITE | storagecon.STGM_SHARE_E... | python35/Lib/site-packages/win32com/test/testStorage.py | 3,406 | file, mode, format, attrs (always 0), IID (IStorage or IPropertySetStorage, storage options(only used with STGFMT_DOCFILE) {"Version":2,"reserved":0,"SectorSize":512,"TemplateFile":u'somefilename'}) FMTID_SummaryInformation FMTID_DocSummaryInformation FMTID_UserDefinedProperties its very ... | 630 | en | 0.884109 |
"""A simple CLI app to practice grammatical genders of German nouns."""
import argparse
import json
import pathlib
import pandas as pd
class WordList:
"""Data structure to store a pandas dataframe and some structural details.
Args:
path (pathlib.Path or None): The path (without suffix) to a wor... | deutscheflash.py | 13,628 | Data structure to store a pandas dataframe and some structural details.
Args:
path (pathlib.Path or None): The path (without suffix) to a wordlist.
If there is no current list at the path, will create a new list.
If no path is provided the WordList will not be fully initialized and will
req... | 2,937 | en | 0.840575 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return None
odd, even = ... | 328-odd-even-linked-list/328-odd-even-linked-list.py | 786 | Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next | 140 | en | 0.542756 |
# services/resource/project/utils/enums.py
from enum import Enum
class Status(Enum):
normal = 0
delete = 1
other = 2
class Scope(Enum):
user = 'UserScope'
admin = 'AdminScope'
| services/resource/project/utils/enums.py | 202 | services/resource/project/utils/enums.py | 40 | en | 0.693682 |
import os
import shutil
#for i in range(8050,8051):
# old=str(i) + '.bin'
# new="../new/"+'%06d.bin' % i
# shutil.move(old,new)
file1 = open('a.txt', 'r')
Lines = file1.readlines()
file2 = open('b.txt', 'r')
Lines2 = file2.readlines()
calib_DIR='./calib/'
img_DIR='./image_2/'
label_DIR='./label_2/'
pcl_... | useful_scripts/split.py | 792 | for i in range(8050,8051): old=str(i) + '.bin' new="../new/"+'%06d.bin' % i shutil.move(old,new) Strips the newline character shutil.move(label_DIR+txt_fname, "../testing/"+label_DIR+txt_fname)shutil.move(img_DIR+img_fname, "../testing/"+img_DIR+img_fname)shutil.move(pcl_DIR+pcl_fname, "../testing/"+pcl_DIR+pc... | 328 | en | 0.319028 |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_warren_bors_teraud.iff"
result.attribute_template_id = 9
resu... | data/scripts/templates/object/mobile/shared_warren_bors_teraud.py | 446 | NOTICE: THIS FILE IS AUTOGENERATED MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES BEGIN MODIFICATIONS END MODIFICATIONS | 168 | en | 0.698026 |
#
# Copyright (c) 2015 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... | tests/extractcode/extractcode_assert_utils.py | 8,837 | This assertion accepts an instance instead of a class for refined
exception testing.
Run the extraction `test_function` on `test_file` checking that a map of
expected paths --> size exist in the extracted target directory.
Does not test the presence of all files unless `check_all` is True.
Walk test_dir.
Check that all... | 2,708 | en | 0.835561 |
import os
import unittest
from tests.base import (
HPSS_ARCHIVE,
TOP_LEVEL,
ZSTASH_PATH,
TestZstash,
compare,
print_starred,
run_cmd,
write_file,
)
class TestUpdate(TestZstash):
"""
Test `zstash --update`.
"""
# x = on, no mark = off, b = both on and off tested
# ... | tests/test_update.py | 5,648 | Test `zstash --update`.
Test `zstash update`.
Test `zstash update --cache`.
Test `zstash update --dry-run`.
Test `zstash update --keep`.
x = on, no mark = off, b = both on and off tested option | Update | UpdateDryRun | UpdateKeep | UpdateCache | TestZstash.add_files (used in multiple tests)| --hpss |x|x|x|x|x| --... | 498 | en | 0.357905 |
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 14:25:47 2018
@author: Steven
"""
import sys
import argparse
from radioxenon_ml.read_in import ml_matrix_composition as mlmc
from radioxenon_ml.solve import iterate
import numpy as np
"""
import radioxenon_ml.read_in.ml_matrix_composition
import radioxenon_ml.solve.it... | ml_rxe.py | 1,678 | Created on Wed May 9 14:25:47 2018
@author: Steven
-*- coding: utf-8 -*-acceptable error in normalized activityShould have elements equal to the number of isotopesscale_array = np.array([0.561,0.584,0.9,0.372,0.489,0.489,1]) scaling factor for each simulation filecurrently taken from (Czyz, 2017)number of simulat... | 450 | en | 0.82127 |
""" A class for testing a SSD model on a video file or webcam """
import cv2
import keras
from keras.applications.imagenet_utils import preprocess_input
from keras.backend.tensorflow_backend import set_session
from keras.models import Model
from keras.preprocessing import image
import pickle
import numpy as np
from r... | testing_utils/videotest.py | 7,659 | Class for testing a trained SSD model on a video file and show the
result in a window. Class is designed so that one VideoTest object
can be created for a model, and the same object can then be used on
multiple videos and webcams.
Arguments:
class_names: A list of strings, each containing the name of a class.
... | 2,213 | en | 0.895895 |
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | jax_cfd/base/time_stepping.py | 4,171 | Spatially discretized version of Navier-Stokes.
The equation is given by:
∂u/∂t = explicit_terms(u)
0 = incompressibility_constraint(u)
Explicitly evaluate the ODE.
Create a forward Runge-Kutta time-stepper for incompressible Navier-Stokes.
This function implements the reference method (equations 16-21), rather ... | 1,369 | en | 0.789377 |
# Copyright (c) 2015 Huawei Technologies Co., Ltd.
# 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
#
# ... | Cinder/Mitaka/extend/fc_zone_helper.py | 11,598 | FC zone helper for Huawei driver.
Check FC port on array and wwn on host is connected to switch.
If no FC port on array is connected to switch or no ini on host is
connected to switch, raise a error.
Get on FC port per one controller.
task flow:
1. Get all the FC port from the array.
2. Filter out ports belonged to t... | 1,313 | en | 0.874841 |
# This code is licensed under the MIT License (see LICENSE file for details)
import concurrent.futures as futures
import contextlib
import inspect
import json
import logging
import pathlib
import platform
import sys
import time
from zplib import datafile
from zplib.image import threaded_io
from elegant import load_da... | scope/timecourse/base_handler.py | 15,595 | Setup the basic code to take a single timepoint from a timecourse experiment.
Parameters:
data_dir: directory where the data and metadata-files should be read/written.
io_threads: number of threads to use to save image data out.
loglevel: level from logging library at which to log information to the
... | 5,901 | en | 0.845554 |
from logging import warning
from os import path
from typing import Optional, List
from lxml.html import HtmlElement
from manga_py.http import Http
from .params import ProviderParams
class Base(ProviderParams):
_storage = None
_params = None
_image_params = None
_http_kwargs = None
__http = None
... | manga_py/base_classes/base.py | 4,492 | 'crop': (left, upper, right, lower) 'auto_crop': True, manga_name, url, directory type: str, str | 96 | en | 0.283531 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the... | myProject/settings.py | 2,858 | Build paths inside the project like this: os.path.join(BASE_DIR, ...) Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECURITY WARNING: don't run with debug turned on in pr... | 687 | en | 0.614913 |
# coding: utf-8
"""
Genomic Data Store Service
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
imp... | libica/openapi/libgds/models/folder_update_request.py | 4,304 | 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
FolderUpdateRequest - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Gets the acl of this FolderUpdateReque... | 1,436 | en | 0.618859 |
import numpy as np
from mendeleev import element as md_element
from basisopt import api, data
from basisopt.exceptions import PropertyNotAvailable
from basisopt.basis import even_temper_expansion
from basisopt.basis.guesses import null_guess
from .preconditioners import unit
from .strategies import Strategy
_INITIAL_... | basisopt/opt/eventemper.py | 4,682 | Implements a strategy for an even tempered basis set, where each angular
momentum shell is described by three parameters: (c, x, n)
Each exponent in that shell is then given by
y_k = c*(x**k) for k=0,...,n
--------------------------- ALGORITHM ----------------------------
Evaluate: energy (can change to any RMSE-c... | 1,562 | en | 0.671868 |
# Copyright 2019 TerraPower, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | armi/utils/directoryChangers.py | 8,543 | Utility to change directory.
Parameters
----------
destination : str
Path of directory to change into
filesToMove : list of str, optional
Filenames to bring from the CWD into the destination
filesToRetrieve : list of str, optional
Filenames to bring back from the destination to the cwd
dumpOnException : bo... | 2,545 | en | 0.839628 |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import os
import zipfile
from dataclasses import dataclass
from io import BytesIO
from typing import Iterable
from pants.backend.python.... | src/python/pants/backend/python/util_rules/local_dists.py | 6,968 | A PEX file containing locally-built dists.
Can be consumed from another PEX, e.g., by adding to PEX_PATH.
Lists the files provided by the dists on sys.path, so they can be subtracted from
sources digests, to prevent the same file ending up on sys.path twice.
Request to build the local dists from the dependency closur... | 1,448 | en | 0.950167 |
from fastai.data.all import IntToFloatTensor
from fastai.vision.learner import *
from fastai.vision.augment import *
from fastai.vision.core import PILImageBW, PILImage
from fastai.vision.data import *
from preprocessing.transforms import *
# from preprocessing.dicom import *
from preprocessing.misc import *
def ge... | train/tfms.py | 4,394 | from preprocessing.dicom import * if run_params['HIST_CLIPPING']: item_tfms.append(XRayPreprocess(PIL_cls=PILImageBW, cut_min=run_params['HIST_CLIPPING_CUT_MIN'], cut_max=run_params['HIST_CLIPPING_CUT_MAX'], np_input=len(item_tfms) > 0, np_output=True)) item_tfms.append(RandomResizedCrop(RANDOM_RESIZE_CROP)) Histog... | 543 | en | 0.212789 |
import sys,os
try:
import argparse
except ImportError:
print("""ERROR: Could not import argparse
Either use python2.7 or later (perhaps in a strange location such as
/bgsys/tools/python2.7.5-gnu-20130730/bin/hostpython) or install from
PyPI (https://pypi.python.org/pypi/argparse/).""")
sys.exit(1)
def mkd... | examples/hpgmg/hpgmgconf.py | 6,022 | ALCF locationdefines.append('STENCIL_FUSE_DINV') generally only good on compute-intensive architectures with good compilersdefines.append('STENCIL_FUSE_BC') | 157 | en | 0.518122 |
from typing import Any
from typing import Mapping
from pandas.core.frame import DataFrame
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType
from cishouseholds.pipeline.config import get_config
sessions = {
"s": (
SparkSession.builder.config("spark.executor.memory", "1g")
... | cishouseholds/pyspark_utils.py | 4,202 | Fast collection of all records in a column to a standard list.
Convert a cerberus validation schema to a pyspark schema.
Assumes that schema is not nested.
The following are required in spark schema:
* `nullable` is False by default
* `metadata` is an empty dict by default
* `name` is the name of the field
Create a sp... | 439 | en | 0.711515 |
from panda3d.core import *
from direct.distributed.PyDatagram import PyDatagram
from OTPInternalRepository import OTPInternalRepository
from direct.directnotify import DirectNotifyGlobal
from game.OtpDoGlobals import *
from realtime.types import *
from direct.distributed.AIZoneData import AIZoneDataStore
from game.Time... | game/AIRepository.py | 3,237 | register the AI on the state server... add a post remove to remove the shard from the state server when we disconnect from the message director... create the AI globals... | 171 | en | 0.528779 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
import collections
import hashlib
import os
import pickle
import sys
import numpy
import yaml
from six import iteritems
from tqdm import tqdm
from dcase_util.datasets import AcousticSceneDataset, SyntheticSoundEve... | dcase_util/datasets/tut.py | 113,777 | TUT Acoustic scenes 2016 development dataset
This dataset is used in DCASE2016 - Task 1, Acoustic scene classification
TUT Acoustic scenes 2016 evaluation dataset
This dataset is used in DCASE2016 - Task 1, Acoustic scene classification
TUT Acoustic scenes 2017 development dataset
This dataset is used in DCASE2017 -... | 17,279 | en | 0.392894 |
# Generated by Django 2.1.4 on 2018-12-22 04:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
... | XD/mysite/polls/migrations/0001_initial.py | 1,165 | Generated by Django 2.1.4 on 2018-12-22 04:01 | 45 | en | 0.617404 |
import numpy as np
from keras.callbacks import Callback
from keras import backend as K
class SGDR(Callback):
"""This callback implements the learning rate schedule for
Stochastic Gradient Descent with warm Restarts (SGDR),
as proposed by Loshchilov & Hutter (https://arxiv.org/abs/1608.03983).
The... | sgdr_callback.py | 3,172 | This callback implements the learning rate schedule for
Stochastic Gradient Descent with warm Restarts (SGDR),
as proposed by Loshchilov & Hutter (https://arxiv.org/abs/1608.03983).
The learning rate at each epoch is computed as:
lr(i) = min_lr + 0.5 * (max_lr - min_lr) * (1 + cos(pi * i/num_epochs))
Here, num_epochs... | 1,081 | en | 0.806327 |
from synbioweaver.core import *
from synbioweaver.aspects.designRulesAspect import *
from synbioweaver.aspects.printStackAspect import *
from synbioweaver.aspects.pigeonOutputAspect import *
declareNewMolecule('A')
declareNewMolecule('B')
declareNewMolecule('C')
declareNewMolecule('In')
declareNewPart('t1',Terminator... | examples/drawing-circuits/designIFFL2.py | 1,408 | compiledDesign = Weaver(constGFP, DesignRules, PrintStack, PigeonOutput).output() | 81 | en | 0.328622 |
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
import uuid
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['txt', 'csv'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000
app.co... | backend/app.py | 2,548 | TODO Pass the message through the model If anything goes wrong, return an error TODO REMOVE GET @app.route('/start', methods=['POST']) check if the post request has the file part If the user does not select a file, error Check if allowed and secure Create a unique filename and save it locally TODO Train our model Tempo... | 356 | en | 0.724419 |
# Copyright (c) 2014 Mirantis 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, so... | cloudferrylib/os/actions/detach_used_volumes.py | 1,090 | Copyright (c) 2014 Mirantis Inc. Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distribut... | 546 | en | 0.887232 |
import random
import string
import time
import os
try:
import telepot
from telepot.loop import MessageLoop
except:
os.system('pip install telepot --user')
try:
import requests
except:
os.system('pip install requests --user')
class host:
def __init__(self, host):
h = ho... | bot.py | 10,880 | print(host('https://vodafone.com.eg').links('asd')) | 51 | en | 0.208542 |
"""Pytest plugin entry point. Used for any fixtures needed."""
import pytest
from .pytest_selenium_enhancer import add_custom_commands
@pytest.fixture(scope='session')
def selenium_patcher():
"""Add custom ."""
add_custom_commands()
| pytest_selenium_enhancer/plugin.py | 243 | Add custom .
Pytest plugin entry point. Used for any fixtures needed. | 69 | en | 0.666162 |
from django.shortcuts import render
# Create your views here.
from .models import BallotText, Candidate, District
def index(request):
districts = District.objects.all
context = {'districts': districts}
return render(request, 'vote/index.html', context)
def ballot(request, district_num):
ballot_lis... | nc_vote/vote/views.py | 1,258 | Create your views here. | 23 | en | 0.928092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.