content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
import math
import warnings
from functools import reduce
import numpy as np
import torch
from backpack import backpack, extend
from backpack.extensions import BatchGrad
from gym.utils import seeding
from torchvision import datasets, transforms
from dacbench import AbstractEnv
warnings.filterwarnings("ignore")
clas... | dacbench/envs/sgd.py | 14,795 | Environment to control the learning rate of adam
Initialize SGD Env
Parameters
-------
config : objdict
Environment configuration
No additional cleanup necessary
Returns
-------
bool
Cleanup flag
Gather state description
Returns
-------
dict
Environment state
Render env in human mode
Parameters
--------... | 924 | en | 0.297289 |
from __future__ import print_function
import sys
import os
import subprocess
from .simsalabim import __version__, __copyright__
from . import add_quant_info as quant
from . import helpers
def main(argv):
print('dinosaur-adapter version %s\n%s' % (__version__, __copyright__))
print('Issued command:', os.path.base... | simsalabim/dinosaur_adapter.py | 5,225 | ------------------------------------------------ | 48 | en | 0.115767 |
# _*_ coding: utf-8 _*_
"""
util_urlfilter.py by xianhu
"""
import re
import pybloom_live
from .util_config import CONFIG_URLPATTERN_ALL
class UrlFilter(object):
"""
class of UrlFilter, to filter url by regexs and (bloomfilter or set)
"""
def __init__(self, black_patterns=(CONFIG_URLPATTERN_ALL,), ... | spider/utilities/util_urlfilter.py | 2,125 | class of UrlFilter, to filter url by regexs and (bloomfilter or set)
constructor, use variable of BloomFilter if capacity else variable of set
check the url based on self._re_black_list and self._re_white_list
check the url to make sure that the url hasn't been fetched, and add url to urlfilter
update this urlfilter us... | 453 | en | 0.764258 |
#!/usr/bin/env python
'''command long'''
import threading
import time, os
import math
from pymavlink import mavutil
from MAVProxy.modules.lib import mp_module
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from threading import Thread
import mpl_toolkits.mplot3d.axes3d as... | pycalc/MAVProxy/modules/mavproxy_cmdlong.py | 30,985 | !/usr/bin/env pythonthread_obj = Thread(target = self.show_svo_2d)thread_obj = Thread(target = self.show_svo)thread_obj.setDaemon(True)thread_obj.start() target_system target_component command confirmation param1 param2 param3 param4 param5 param6 param7 target_system target_component target_system target_component com... | 5,499 | en | 0.260864 |
""" This module is intended to extend functionality of the code provided by original authors.
The process is as follows:
1. User has to provide source root path containing (possibly nested) folders with dicom files
2. The program will recreate the structure in the destination root path and anonymize all
... | dicomanonymizer/batch_anonymizer.py | 8,067 | Anonymize dicom files in `in_path`, if `in_path` doesn't
contain dicom files, will do nothing. Debug == True will do
sort of dry run to check if all good for the large data storages
Args:
in_path (Path_Str): path to the folder containing dicom files
out_path (Path_Str): path to the folder there anonymized copi... | 1,922 | en | 0.802947 |
import pickle
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
df = pd.read_csv('Train.csv')
# check for categorical attributes
cat_col = []
for x in df.dtypes.index:
if df.dtypes[x] == 'object':
ca... | bigmart.py | 2,911 | check for categorical attributes replace zeros with mean combine item fat contentCreation of New Attributes create small values for establishment yearInput SplitModel Training train the model predict the training set perform cross-validationdump information to that file | 270 | en | 0.748699 |
"""State-Split Transformation
-----------------------------
(C) Frank-Rene Schaefer
The 'State-Split' is a procedure transforms a state machine that triggers on
some 'pure' values (e.g. Unicode Characters) into a state machine that triggers
on the code unit sequences (e.g. UTF8 Code Units) that correspond to the
origi... | quex/engine/state_machine/transformation/state_split.py | 17,246 | Check whether a modification is necessary 'UnchangedRange' => No change to numerical values. 'number_set' solely contains forbidden elements. Second, enter the new transitions. Absorb new transitions into the target map of the 'from state'. A single code element can only produce a single interval sequence! Find the sta... | 1,696 | en | 0.857725 |
# small demo for listmode TOF MLEM without subsets
import os
import matplotlib.pyplot as py
import pyparallelproj as ppp
from pyparallelproj.wrapper import joseph3d_fwd, joseph3d_fwd_tof, joseph3d_back, joseph3d_back_tof
import numpy as np
import argparse
import ctypes
from time import time
#------------------------... | examples/projector_order_test.py | 4,951 | small demo for listmode TOF MLEM without subsets--------------------------------------------------------------------------------- parse the command line------------------------------------------------------------------------------------------------------------------------------------------------------------------ setup... | 766 | en | 0.375549 |
import asyncio
import random
import re
import textwrap
import discord
from .. import utils, errors, cmd
from ..servermodule import ServerModule, registered
from ..enums import PrivilegeLevel
@registered
class TruthGame(ServerModule):
MODULE_NAME = "Truth Game"
MODULE_SHORT_DESCRIPTION = "Tools to play *Truth*... | mentionbot/servermodules/truthgame.py | 9,114 | TODO: Edit this to use the topic string abstraction methods. Currently, it only consideres user mentions to be participants! TOPIC STRING ABSTRACTION PRECONDITION: participant_str contains printable characters. PRECONDITION: participant_str does not contain the delimiter. PRECONDITION: participant_str in self._g... | 361 | en | 0.683052 |
"""
Module for all Form Tests.
"""
import pytest
from django.utils.translation import gettext_lazy as _
from my_blog.users.forms import UserCreationForm
from my_blog.users.models import User
pytestmark = pytest.mark.django_db
class TestUserCreationForm:
"""
Test class for all tests related to the UserCreati... | my_blog/users/tests/test_forms.py | 1,163 | Test class for all tests related to the UserCreationForm
Tests UserCreation Form's unique validator functions correctly by testing:
1) A new user with an existing username cannot be added.
2) Only 1 error is raised by the UserCreation Form
3) The desired error message is raised
Module for all Form Tests.
... | 369 | en | 0.84332 |
#
# 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/google/cloud/operators/sql_to_gcs.py | 11,474 | :param sql: The SQL to execute.
:type sql: str
:param bucket: The bucket to upload to.
:type bucket: str
:param filename: The filename to use as the object name when uploading
to Google Cloud Storage. A {} should be specified in the filename
to allow the operator to inject file numbers in cases where the
fi... | 4,336 | en | 0.782952 |
from shallowflow.api.source import AbstractListOutputSource
from shallowflow.api.config import Option
class ForLoop(AbstractListOutputSource):
"""
Outputs an integer from the specified range.
"""
def description(self):
"""
Returns a description for the actor.
:return: the act... | base/src/shallowflow/base/sources/_ForLoop.py | 2,016 | Outputs an integer from the specified range.
For configuring the options.
Performs the actual execution.
:return: None if successful, otherwise error message
:rtype: str
Returns the type of the individual items that get generated, when not outputting a list.
:return: the type that gets generated
Returns a description... | 473 | en | 0.52556 |
# -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | google/cloud/vision/v1p3beta1/vision-v1p3beta1-py/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py | 14,205 | gRPC backend transport for ImageAnnotator.
Service that performs Google Cloud Vision API detection tasks
over client images, such as face, landmark, logo, label, and
text detection. The ImageAnnotator service returns detected
entities from the images.
This class defines the same methods as the primary client, so the
... | 6,927 | en | 0.804054 |
import io
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
def resize_axis(tensor, axis, new_size, fill_value=0, random_sampling=False):
"""Truncates or pads a tensor to new_size on on a given axis.
Truncate or extend tensor s... | utils.py | 2,222 | Truncates or pads a tensor to new_size on on a given axis.
Truncate or extend tensor such that tensor.shape[axis] == new_size. If the
size increases, the padding will be performed at the end, using fill_value.
Args:
tensor: The tensor to be resized.
axis: An integer representing the dimension to be sliced.
new_si... | 575 | en | 0.672781 |
from .infinity import INFINITY
import json
from typing import List, Tuple, Any, Type, Union, TypeVar, Generic, Optional, Dict, cast, Callable
T = TypeVar('T')
class PageProperty(Generic[T]):
"""
A class to represent a property that varies depending on the pages of a spectral sequence.
This... | chart/chart/python/spectralsequence_chart/page_property.py | 5,040 | A class to represent a property that varies depending on the pages of a spectral sequence.
This is the main helper class that encapsulates any property of a class, edge, or chart
that varies depending on the page.
Examples:
>>> p = PageProperty(1)
>>> p[4] = 7
>>> p[2]
1
>>> p[4]
7
Initialize... | 436 | en | 0.815055 |
# Generated by Django 2.1.3 on 2018-12-08 05:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('staf', '0008_auto_20181207_1525'),
]
operations = [
migrations.AddField(
model_name='dataset',
... | src/staf/migrations/0009_dataset_process.py | 489 | Generated by Django 2.1.3 on 2018-12-08 05:56 | 45 | en | 0.597899 |
"""about command for osxphotos CLI"""
from textwrap import dedent
import click
from osxphotos._constants import OSXPHOTOS_URL
from osxphotos._version import __version__
MIT_LICENSE = """
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documen... | osxphotos/cli/about.py | 15,763 | Print information about osxphotos including license.
about command for osxphotos CLI | 84 | en | 0.840753 |
# -*- coding: utf-8 -*-
"""
Logging for the hubble daemon
"""
import logging
import time
import hubblestack.splunklogging
# These patterns will not be logged by "conf_publisher" and "emit_to_splunk"
PATTERNS_TO_FILTER = ["password", "token", "passphrase", "privkey",
"keyid", "s3.key", "splun... | hubblestack/log.py | 6,628 | Fake record that mimicks a logging record
Filter known sensitive info
Remove temporary handler if it exists
Emit a single message to splunk
Filters out keys containing certain patterns to avoid sensitive information being sent to logs
Works on dictionaries and lists
This function was located at extmods/modules/conf_pu... | 1,139 | en | 0.846832 |
import os
class ConfigParams:
def __init__(self,configPath):
self.env_dist = os.environ
#权限验证
self.api_key = ""
# userID = ""
# ip = "0.0.0.0"
#模型相关存放根目录
self.modelPath = os.path.join(os.getcwd(),"model")
cpuCores = 0
threads = 2
por... | common/configParams.py | 1,622 | 权限验证 userID = "" ip = "0.0.0.0"模型相关存放根目录每个算法使用的GPU数量 self.helmet_ids = [1,1,1] self.pose_ids = [] self.track_coal_ids = [] self.smoke_phone_ids = [] | 148 | en | 0.271399 |
import sys, gzip, logging
from .in_util import TimeReport, detectFileChrom, extendFileList, dumpReader
#========================================
# Schema for AStorage
#========================================
_TRASCRIPT_PROPERTIES = [
{"name": "Ensembl_geneid", "tp": "str", "opt": "repeat"},
{"name":... | a_storage/ingest/in_dbnsfp4.py | 12,656 | ======================================== Schema for AStorage============================================================================================================================================================================================================================= Ingest logic==========================... | 734 | en | 0.292612 |
# Source: https://gist.github.com/redknightlois/c4023d393eb8f92bb44b2ab582d7ec20
from torch.optim.optimizer import Optimizer
import torch
import math
class Ralamb(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-4):
defaults = dict(lr=lr, betas=betas, eps=eps... | pywick/optimizers/ralamb.py | 3,979 | Source: https://gist.github.com/redknightlois/c4023d393eb8f92bb44b2ab582d7ec20 Decay the first and second moment running average coefficient m_t v_t more conservative since it's an approximated value more conservative since it's an approximated value | 250 | en | 0.919329 |
import sys
import json
import hashlib
import gc
from operator import *
import shlex
from pyspark import StorageLevel
from pyspark.sql import SQLContext
from pyspark.sql.functions import *
from pyspark.sql.types import *
import numpy as np
from subjectivity_clues import clues
def expect(name, var, expected, op=eq):... | step_2/scripts/sample_subjectivity_tweets.py | 12,231 | Make sure Python uses UTF-8 as tweets contains emoticon and unicode Use SQLContext for better support Define storage level Read GNIP's JSON file Check checksum count Check post count Check share count Check dataset count Remove post authored by @ChipotleTweet and news agencies Remove share retweet of tweet by @Chipotle... | 863 | en | 0.750845 |
import os
import sys
from setuptools import find_packages, setup
IS_RTD = os.environ.get("READTHEDOCS", None)
version = "0.4.0b14.dev0"
long_description = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
install_requires = [
"morepath==0.19",
"alembic",
"rulez>=0.1.4,<0.2.0",
"inv... | setup.py | 2,620 | Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers | 71 | en | 0.40275 |
# 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 ... | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2018_11_01/models/update_history_property.py | 2,805 | An update history of the ImmutabilityPolicy of a blob container.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar update: The ImmutabilityPolicy update type of a blob container,
possible values include: put, lock and extend. Possible values include:
'put', 'lock', 'exten... | 1,551 | en | 0.650908 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/resources/paid_organic_search_term_view.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.proto... | google/ads/google_ads/v6/proto/resources/paid_organic_search_term_view_pb2.py | 5,490 | Generated protocol buffer code.
-*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: google/ads/googleads/v6/resources/paid_organic_search_term_view.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:google.ads.googleads.v6.resources.PaidOrganicSearchTermVie... | 361 | en | 0.580453 |
from itertools import product
from json import dumps
import logging
import nox # noqa
from pathlib import Path # noqa
import sys
# add parent folder to python path so that we can import noxfile_utils.py
# note that you need to "pip install -r noxfile-requiterements.txt" for this file to work.
sys.path.append(str(P... | noxfile.py | 12,326 | Generates the doc and serves it on a local http server. Pass '-- build' to build statically instead.
Launch flake8 qualimetry.
(mandatory arg: <base_session_name>) Prints all sessions available for <base_session_name>, for GithubActions.
Deploy the docs+reports on github pages. Note: this rebuilds the docs
Create a rel... | 4,454 | en | 0.764985 |
#!usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'yanqiong'
import random
import secrets
from bisect import bisect_right
from sgqlc.operation import Operation
from pandas.core.internals import BlockManager
from tqsdk.ins_schema import ins_schema, _add_all_frags
RD = random.Random(secrets.randbits(128)) #... | tqsdk/utils.py | 5,470 | mock BlockManager for unconsolidated, 不会因为自动合并同类型的 blocks 而导致 k 线数据不更新
返回 bisect_right() 取得下标对应的值,当插入点距离前后元素距离相等,priority 表示优先返回右边的值还是左边的值
a: 必须是已经排序好(升序排列)的 list
bisect_right : Return the index where to insert item x in list a, assuming a is sorted.
返回某些类型合约的 query
todo: 为了兼容旧版提供给用户的 api._data["quote"].items() 类似用法,应该... | 620 | zh | 0.842235 |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... | qiskit_aqua/algorithms/components/optimizers/nlopts/esch.py | 2,367 | ESCH (evolutionary algorithm)
NLopt global optimizer, derivative-free
http://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/#esch-evolutionary-algorithm
-*- coding: utf-8 -*- Copyright 2018 IBM. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the L... | 798 | en | 0.76759 |
# Generated by Django 3.2.11 on 2022-02-10 16:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("cabins", "0020_auto_20211111_1825"),
("cabins", "0021_booking_is_declined"),
]
operations = []
| backend/apps/cabins/migrations/0022_merge_20220210_1705.py | 268 | Generated by Django 3.2.11 on 2022-02-10 16:05 | 46 | en | 0.64043 |
#! /usr/bin/env python3
"""Unit tests for smartcard.readers.ReaderGroups
This test case can be executed individually, or with all other test cases
thru testsuite_framework.py.
__author__ = "http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
This fil... | cacreader/pyscard-2.0.2/smartcard/test/framework/testcase_readergroups.py | 5,702 | Test smartcard framework readersgroups.
tests groups=groups+[newgroups]
test groups.append(newgroups)
test groups+=[newgroups]
test groups.insert(i,newgroups)
test groups=[newgroups]+groups
Unit tests for smartcard.readers.ReaderGroups
This test case can be executed individually, or with all other test cases
thru test... | 1,719 | en | 0.742088 |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
from io import IOBase
import networkx as nx
import numpy as np
from openvino.tools.mo.ops.elementwise import Mul
from openvino.tools.mo.ops.split import AttributedVariadicSplit
from openvino.tools.mo.front.common.... | tools/mo/openvino/tools/mo/front/kaldi/loader/loader.py | 25,367 | Structure of the file is the following:
magic-number(16896)<Nnet> <Next Layer Name> weights etc.
:param nnet_path:
:return:
Load ParallelComponent of the Kaldi model.
ParallelComponent contains parallel nested networks.
VariadicSplit is inserted before nested networks.
Outputs of nested networks concatenate with layer ... | 2,758 | en | 0.856036 |
#!/usr/bin/env python
"""
SHUTDOWN.PY
Shutdown Plugin
(C) 2015, rGunti
"""
import dot3k.lcd as lcd
import dot3k.backlight as backlight
import time, datetime, copy, math, psutil
import sys
import os
from dot3k.menu import Menu, MenuOption
class Shutdown(MenuOption):
def __init__(self):
self.last = self.millis... | display/plugins/Shutdown.py | 1,171 | SHUTDOWN.PY
Shutdown Plugin
(C) 2015, rGunti
!/usr/bin/env python | 68 | en | 0.581802 |
from collections import Iterable
from itertools import combinations
from math import log, ceil
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_make... | benchmarks/ltl_timed_transition_system/token_ring/f3/token_ring_0024.py | 13,536 | Synchronous component
Station module
TokenManager module
init: tot_transm_time = 0 invar: delta >= 0 only 1 station moves sync stations and mgr (mgr.counting & mgr.idle') -> total_transm_time' = total_transm_time + mgr.c !(mgr.counting & mgr.idle') -> total_transm_time' = total_transm_time (G F (mgr.counting & mgr.id... | 802 | en | 0.524222 |
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : tota... | src/utils/console_functions.py | 1,193 | Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : pos... | 716 | en | 0.357814 |
"""Julia set generator without optional PIL-based image drawing"""
import time
#from memory_profiler import profile
# area of complex space to investigate
x1, x2, y1, y2 = -1.8, 1.8, -1.8, 1.8
c_real, c_imag = -0.62772, -.42193
@profile
def calculate_z_serial_purepython(maxiter, zs, cs):
"""Calculate output list... | codes/01_profiling/memory_profiler/julia1_memoryprofiler2.py | 2,580 | from memory_profiler import profile area of complex space to investigate set width and height to the generated pixel counts, rather than the pre-rounding desired width and height build a list of co-ordinates and the initial condition for each cell. Note that our initial condition is a constant and could easily be remov... | 676 | en | 0.854869 |
import os
import csv
# File path
election_dataCSV = os.path.join('.', 'election_data.csv')
# The total number of votes cast
# A complete list of candidates who received votes
# The percentage of votes each candidate won
# The total number of votes each candidate won
# The winner of the election based on popular vote... | PyPoll/main.py | 2,695 | File path The total number of votes cast A complete list of candidates who received votes The percentage of votes each candidate won The total number of votes each candidate won The winner of the election based on popular vote. Declaring my variables percent_votes = 0 total_votes_candidate = 0 winner = 0 Open file as ... | 725 | en | 0.938027 |
'''
A collection of functions to perform portfolio analysis.
Max Gosselin, 2019
'''
import numpy as np
import pandas as pd
from scipy import optimize
def portfolio_metrics(weights, avg_xs_returns, covariance_matrix):
''' Compute basic portfolio metrics: return, stdv, sharpe ratio '''
por... | portfolio_functions.py | 4,837 | Anonymous function to check equality with the target return
Anonymous function to compute sharpe ratio, note that since scipy only minimizes we go negative.
Anonymous function to compute stdv
Anonymous function to compute stdv
Compute basic portfolio metrics: return, stdv, sharpe ratio
What we want here is to rand... | 1,217 | en | 0.854758 |
## @example pyfast_and_pyside2_custom_window.py
# This example demonstrates how to use FAST in an existing PySide2 application.
#
# @m_class{m-block m-warning} @par PySide2 Qt Version
# @parblock
# For this example you <b>must</b> use the same Qt version of PySide2 as used in FAST (5.14.0)
# Do this with: <b>pi... | source/FAST/Examples/Python/pyfast_and_pyside2_custom_window.py | 2,566 | @example pyfast_and_pyside2_custom_window.py This example demonstrates how to use FAST in an existing PySide2 application. @m_class{m-block m-warning} @par PySide2 Qt Version @parblock For this example you <b>must</b> use the same Qt version of PySide2 as used in FAST (5.14.0) Do this with: <b>pip install pysid... | 962 | en | 0.588513 |
# Project Quex (http://quex.sourceforge.net); License: MIT;
# (C) 2005-2020 Frank-Rene Schaefer;
#_______________________________________________________________________________
from quex.input.setup import NotificationDB
from quex.input.regular_expression.pattern import Patt... | quex/input/files/specifier/counter.py | 21,323 | Line/column number count specification.
___________________________________________________________________________
The main result of the parsing the the Base's .count_command_map which is
an instance of CountActionMap_Builder.
____________________________________________________________________________
Indentation c... | 3,868 | en | 0.695558 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=2
# total number=20
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for... | data/p2DJ/New/program/cirq/startCirq347.py | 2,182 | !/usr/bin/env python -*- coding: utf-8 -*- @Time : 5/15/20 4:49 PM @File : grover.py qubit number=2 total number=20thatsNoCode Symbols for the rotation angles in the QAOA circuit. circuit begin number=1 number=17 number=18 number=19 number=2 number=4 number=3 number=13 number=14 number=15 number=8 number=9 number... | 355 | en | 0.318577 |
import requests
import urllib.parse
import posixpath
import pandas as pd
def get_enrollment_dates(course):
'''Takes a course object and returns student dates of enrollment.
Useful for handling late registrations and modified deadlines.
Example:
course.get_enrollment_date()'''
url_path = posixpath.... | scripts/canvas.py | 7,108 | Takes a course object and the name of a Canvas assignment and returns the due date. Returns None if no due date assigned.
Example:
course.get_assignment_due_date('worksheet_01')
Takes a course object and the name of a Canvas assignment and returns the Canvas ID.
Example:
course.get_assignment_id('worksheet_01')
Takes... | 1,496 | en | 0.731063 |
# -*- coding: utf-8 -*-
"""
pygments.lexers.graphics
~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for computer graphics and plotting related languages.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexe... | env/lib/python3.7/site-packages/pygments/lexers/graphics.py | 39,040 | For `Asymptote <http://asymptote.sf.net/>`_ source code.
.. versionadded:: 1.2
GLSL (OpenGL Shader) lexer.
.. versionadded:: 1.1
For `Gnuplot <http://gnuplot.info/>`_ plotting scripts.
.. versionadded:: 0.11
HLSL (Microsoft Direct3D Shader) lexer.
.. versionadded:: 2.3
Lexer for PostScript files.
The PostScript La... | 2,958 | en | 0.726236 |
import os
import sys
from typing import Dict
from typing import List
from typing import Optional
import pkg_resources
from setuptools import find_packages
from setuptools import setup
def get_version() -> str:
version_filepath = os.path.join(os.path.dirname(__file__), "optuna", "version.py")
with open(versi... | setup.py | 7,862 | TODO(hvy): Unpin `sphinx` version after: https://github.com/sphinx-doc/sphinx/issues/8105. As reported in: https://github.com/readthedocs/sphinx_rtd_theme/issues/949, `sphinx_rtd_theme` 0.5.0 is still not compatible with `sphinx` >= 3.0. optuna/visualization/param_importances.py. TODO(toshihikoyanase): Remove the versi... | 705 | en | 0.700849 |
from ..coefficient_array import PwCoeffs
from scipy.sparse import dia_matrix
import numpy as np
def make_kinetic_precond(kpointset, c0, eps=0.1, asPwCoeffs=True):
"""
Preconditioner
P = 1 / (||k|| + ε)
Keyword Arguments:
kpointset --
"""
nk = len(kpointset)
nc = kpointset.ctx().num_s... | python_module/sirius/ot/ot_precondition.py | 3,716 | Apply diagonal preconditioner and project resulting gradient to satisfy the constraint.
Preconditioner
P = 1 / (||k|| + ε)
Keyword Arguments:
kpointset --
return as np.matrix | 204 | en | 0.618913 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2011 Cisco Systems, 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... | quantum/plugins/cisco/nexus/cisco_nexus_configuration.py | 1,407 | Configuration consolidation for the Nexus Driver
This module will export the configuration parameters
from the nexus.ini file
vim: tabstop=4 shiftwidth=4 softtabstop=4 Copyright 2011 Cisco Systems, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this fi... | 865 | en | 0.7657 |
'''
Neuron simulator export for:
Components:
net1 (Type: network)
sim1 (Type: Simulation: length=1.0 (SI time) step=5.0E-5 (SI time))
hhcell (Type: cell)
passive (Type: ionChannelPassive: conductance=1.0E-11 (SI conductance))
na (Type: ionChannelHH: conductance=1.0E-11 (SI conductance))
k (T... | src/test/resources/expected/neuron/hhcell/main_script.py | 5,456 | Neuron simulator export for:
Components:
net1 (Type: network)
sim1 (Type: Simulation: length=1.0 (SI time) step=5.0E-5 (SI time))
hhcell (Type: cell)
passive (Type: ionChannelPassive: conductance=1.0E-11 (SI conductance))
na (Type: ionChannelHH: conductance=1.0E-11 (SI conductance))
k (Type:... | 1,534 | en | 0.585608 |
# Character field ID when accessed: 100000201
# ParentID: 32226
# ObjectID: 0
| scripts/quest/autogen_q32226s.py | 78 | Character field ID when accessed: 100000201 ParentID: 32226 ObjectID: 0 | 71 | en | 0.433372 |
# Josh Aaron Miller 2021
# VenntDB methods for Characters
import venntdb
from constants import *
# VenntDB Methods
def character_exists(self, username, char_id):
return self.get_character(username, char_id) is not None
def get_character(self, username, char_id):
self.assert_valid("accounts",... | db_characters.py | 1,239 | Josh Aaron Miller 2021 VenntDB methods for Characters VenntDB Methods | 69 | en | 0.472623 |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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/lice... | nnunet/utilities/file_endings.py | 1,058 | Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 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... | 628 | en | 0.858488 |
from dataclasses import dataclass
from apple.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class BackupInitialized(Streamable):
"""
Stores user decision regarding import of backup info
"""
user_initialized: bool # Stores if user made a selection in UI. (Skip vs I... | apple/wallet/settings/settings_objects.py | 577 | Stores user decision regarding import of backup info
Stores if user made a selection in UI. (Skip vs Import backup) Stores if user decided to skip import of backup info Stores if backup info has been imported Stores if this wallet is newly created / not restored from backup | 276 | en | 0.904552 |
""" This file holds all the chapter 2 areas of the game. """
from time import sleep
# from classes import Player, Difficulty
from chapters.chapter import Chapter
from chapters.chapter3 import Chapter3
from other.sounds_effects import GameSounds
from game import player1, sounds, Difficulty
from choices import _player_c... | chapters/chapter2.py | 3,800 | Contains all the main chapter 2 areas of the game.
runs movement to levels -- checkpoint when leaving area
start of ch2
Simply plays the good ending scene and then drops the player into chapter 2.
Checkpoint save 3
This file holds all the chapter 2 areas of the game.
from classes import Player, Difficulty | 309 | en | 0.919212 |
import numpy
from fframework import asfunction, OpFunction
__all__ = ['Angle']
class Angle(OpFunction):
"""Transforms a mesh into the angle of the mesh to the x axis."""
def __init__(self, mesh):
"""*mesh* is the mesh Function."""
self.mesh = asfunction(mesh)
def __call__(self, ps):
... | moviemaker3/math/angle.py | 494 | Transforms a mesh into the angle of the mesh to the x axis.
Returns the arctan2. The (y, x) coordinate is in the last
dimension.
*mesh* is the mesh Function. | 159 | en | 0.776611 |
from pathlib import Path
import numba
import numpy as np
from det3d.core.bbox.geometry import (
points_count_convex_polygon_3d_jit,
points_in_convex_polygon_3d_jit,
)
try:
from spconv.utils import rbbox_intersection, rbbox_iou
except:
print("Import spconv fail, no support for sparse convolut... | det3d/core/bbox/box_np_ops.py | 29,715 | assign a 0/1 label to each voxel based on whether
the center of voxel is in gt_box. LIDAR.
assign a 0/1 label to each voxel based on whether
the center of voxel is in gt_box. LIDAR.
convert kitti locations, dimensions and angles to corners.
format: center(xy), dims(xy), angles(clockwise when positive)
Args:
center... | 5,087 | en | 0.722076 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HContractUnitR03_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HContractUnitR03_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_compil... | UML2ER/contracts/unit/HContractUnitR03_ConnectedLHS.py | 1,298 | Creates the himesis graph representing the AToM3 model HContractUnitR03_ConnectedLHS
Flag this instance as compiled now Add the edges Set the graph attributes Set the node attributes match class Class(Class) node Add the edges define evaluation methods for each match class. define evaluation methods for each match as... | 330 | en | 0.706277 |
import numpy as np
import networkx as nx
if __name__ == '__main__':
from ged4py.algorithm import graph_edit_dist
else:
from .ged4py.algorithm import graph_edit_dist
def rearrange_adj_matrix(matrix, ordering):
assert matrix.ndim == 2
# Check that matrix is square
assert matrix.shape[0] == matrix.sh... | utils/graph_utils.py | 3,483 | Calculate the graph edit distance between two graphs
Calculate the graph edit distance between two graphs using the ged4py implementation
Calculate the graph edit distance between two graphs using the networkx implementation
Checks whether two graphs are isomorphic taking adjacency matrices as inputs
Randomly permute t... | 536 | en | 0.888002 |
import time
from typing import Optional, Dict
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torch.nn.utils.rnn import pack_padded_sequence
from utils import TensorboardWriter, AverageMeter, save_checkpoint, accuracy, \
clip_gradient, adjust_learning_rate
from metrics import ... | trainer/trainer.py | 14,308 | Encoder-decoder pipeline. Tearcher Forcing is used during training and validation.
Parameters
----------
caption_model : str
Type of the caption model
epochs : int
We should train the model for __ epochs
device : torch.device
Use GPU or not
word_map : Dict[str, int]
Word2id map
rev_word_map : Dict[... | 3,449 | en | 0.748056 |
# Get substring using 'start' and 'end' position.
def get_substring_or_empty(data, start, end=''):
if start in data:
if '' == start:
f = 0
else:
f = len(start)
f = data.find(start) + f
data = data[f:]
else:
return ''
if end in data:
... | utils.py | 501 | Get substring using 'start' and 'end' position. | 47 | en | 0.441224 |
import cmath
import math
cv =150
cvconv = 736
t1 =440
t2 = 254
polos = 10
freq = 60
r1 = 0.012
R2L = 0.018
X1 = 0.08
X2L = X1
Rp = 58
Xm = 54
print("\nConsidere que o motor é alimentado com tensão de fase igual a 254 V, conexão Y e atinge escorregamento igual a 1,8%")
print("\nA - Corrente no estator\n")
s = 0.018
p... | P5/Brasilia/Q7 - BR.py | 1,667 | professor ultiliza dados polares | 32 | pt | 0.887097 |
# +
import numpy as np
import holoviews as hv
from holoviews import opts
import matplotlib.pyplot as plt
from plotsun import plot_sun
hv.extension('bokeh', 'matplotlib')
# -
# # Load data
data = np.load('npz_timeseries/subset.npz')
arr = data['arr']
stack = data['stack']
sun = data['sun']
print(arr.shape, stack.sha... | datashader_nb.py | 1,401 | + - Load data + - View | 24 | en | 0.390463 |
# -*- coding: utf-8 -*-
from django.conf.urls import include
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from .views import *
# register的可选参数 base_name: 用来生成urls名字,如果viewset中没有包含queryset, base_name一定要有
router = DefaultRouter()
router.register(r'idcs', IdcViewSet)
router.register... | backend/category/urls.py | 758 | -*- coding: utf-8 -*- register的可选参数 base_name: 用来生成urls名字,如果viewset中没有包含queryset, base_name一定要有 | 95 | zh | 0.737162 |
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from djangocms_versioning.constants import PUBLISHED, VERSION_STATES
from djangocms_versioning.versionables import _cms_exte... | djangocms_content_expiry/filters.py | 7,876 | An author filter limited to those users who have added expiration dates
If there's a default value set the all parameter needs to be provided
however, if a default is not set the all parameter is not required.
Only add references to the inherited concrete model i.e. not referenced polymorphic models Create an entry O... | 591 | en | 0.657196 |
import keras
from sklearn.metrics import roc_auc_score
from src.predictionAlgorithms.machineLearning.helpers.validation import Validation
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import glob
class Callbacks(keras.callbacks.Callback):
validationSequences =... | src/predictionAlgorithms/machineLearning/helpers/callbacks.py | 2,828 | Initialize the lists for holding the logs, losses and accuracies | 64 | en | 0.871922 |
# 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 u... | hacking/checks/dictlist.py | 1,533 | Do not use locals() or self.__dict__ for string formatting.
Okay: 'locals()'
Okay: 'locals'
Okay: locals()
Okay: print(locals())
H501: print("%(something)" % locals())
H501: LOG.info(_("%(something)") % self.__dict__)
Okay: print("%(something)" % locals()) # noqa
Licensed under the Apache License, Version 2.0 (the... | 799 | en | 0.807915 |
# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4
"""
第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码
(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
"""
import uuid
def generate_key():
key_list = []
for i in range(200):
uuid_key = uuid.... | renzongxian/0001/0001.py | 606 | 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码
(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
Source:https://github.com/Show-Me-the-Code/show-me-the-code Author:renzongxian Date:2014-11-30 Python 3.4 | 200 | zh | 0.811679 |
from art import logo_blackjack
from replit import clear
import random
def deal_card():
"""Return random card"""
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
def calculate_score(cards):
"""Take a list of cards and return the score"""
if sum(cards)... | Programs/day_11_blackjack.py | 2,637 | Take a list of cards and return the score
Return random card | 60 | en | 0.761562 |
# Copyright 2021 The Flax 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 or agreed to in wri... | tests/linen/linen_linear_test.py | 10,432 | Tests for flax.nn.linear.
Copyright 2021 The Flax 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 or agreed... | 628 | en | 0.838535 |
import os, sys, shutil, glob, math
import regex as re
from doconce import globals
from .doconce import read_file, write_file, doconce2format, handle_index_and_bib, preprocess
from .misc import option, help_print_options, check_command_line_options, system, _abort, \
find_file_with_extensions, folder_checker, doconc... | lib/doconce/jupyterbook.py | 33,648 | Helper function to allow doconce jupyterbook to automatically assign titles in the TOC
If a chunk of text starts with the section specified in sep, lift it up
to a chapter section. This allows doconce jupyterbook to automatically use the
section's text as title in the TOC on the left
:param str chunk: text string
:pa... | 12,176 | en | 0.702952 |
from collections import defaultdict
from hsst.utility import search
from hsst.utility.graph import SemanticGraph
class SubgraphEnumeration(object):
def __init__(self, graph, node_set_size_limit=0):
self.full_node_set = graph.nodes
self.full_edge_set = graph.edges
self.current_node_set =... | hsst/utility/dfs_subgraph_enumeration.py | 4,590 | Create fast lookup structures Generate all possible moves Each move consists of a single node and the set of edges that connect that node to the nodes in the currentNodeSet E.g. ( node, { (label1, node, node1), (label2, node2, node) ... } ) Moves are temporarily stored as a dictionary so that the full set of edges asso... | 1,043 | en | 0.895089 |
import os
import h5py
import numpy as np
from keras import backend as K
from keras.layers import Activation, BatchNormalization, Conv2D, Dense, Dot, \
Dropout, Flatten, Input, MaxPooling2D, GlobalAveragePooling2D
from keras import regularizers
from keras.layers import Average as KerasAverage
from keras.models imp... | raynet/models.py | 12,739 | Implementation of Mean average error
Set the type of the reducer to be used Set the type of optimizer to be used Make sure that we have a proper input shape TODO: Maybe change this to 3, because we finally need only the patch_shape? Unpack the input shape to make the code more readable If there is a weight file ... | 1,106 | en | 0.900662 |
"""
module init
"""
from flask import Flask
<<<<<<< HEAD
from config import config_options
from flask_sqlalchemy import SQLAlchemy
import os
=======
from config import DevelopmentConfig
from .views import orders_blue_print
>>>>>>> ba86ec7ade79a936b81e04ee8b80a97cf8f97770
def create_app(DevelopmentConfig):
"""
... | app/__init__.py | 1,246 | set the configurations initialiaze the database register your blueprints here | 77 | en | 0.567025 |
# DO NOT EDIT THIS FILE!
#
# All configuration must be done in the `configuration.py` file.
# This file is part of the Peering Manager code and it will be overwritten with
# every code releases.
from __future__ import unicode_literals
import os
import socket
from django.contrib.messages import constants as messages
... | peering_manager/settings.py | 6,626 | DO NOT EDIT THIS FILE! All configuration must be done in the `configuration.py` file. This file is part of the Peering Manager code and it will be overwritten with every code releases. Enforce trailing slash only PeeringDB URLs Build paths inside the project like this: os.path.join(BASE_DIR, ...) If LDAP is configured,... | 554 | en | 0.602535 |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the 'license' file acc... | src/sagemaker_training/_entry_point_type.py | 1,664 | Enumerated type consisting of valid types of training entry points.
Args:
path (string): Directory where the entry point is located.
name (string): Name of the entry point file.
Returns:
(_EntryPointType): The type of the entry point.
This module contains an enumerated type and helper functions related
to ... | 990 | en | 0.860681 |
# Lint as: python2, python3
# 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
#
... | research/object_detection/builders/calibration_builder_test.py | 10,338 | Adds a function approximation to calibration proto for a class id.
Helper performing 1d linear interpolation using SciPy.
Helper performing 1d linear interpolation using Tensorflow.
Tests that calibration produces correct class-agnostic values.
Tests that calibration produces correct multiclass values.
Tests that graph... | 2,216 | en | 0.765115 |
"""
Leetcode 70.
Climbing Stairs.
DP.
类似斐波那契数列:
转移方程: f(n) = f(n-1) + f(n-2).
时间复杂度:O(n)
还是没看明白这跟DP有啥关系,就是递归而已。
"""
class Solution:
def climbStairs(self, n: int) -> int:
res = [-1] * (n)
def dfs(n):
if n == 1:
return 1
if n == 2:
return 2
... | dp/climbing_stairs.py | 597 | Leetcode 70.
Climbing Stairs.
DP.
类似斐波那契数列:
转移方程: f(n) = f(n-1) + f(n-2).
时间复杂度:O(n)
还是没看明白这跟DP有啥关系,就是递归而已。 | 108 | zh | 0.811985 |
import logging
from collections import Counter
from itertools import chain
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import pairwise_distances
from pysrc.papers.analysis.text import get_frequent_tokens
logger = logging.getLogger(__name__)
def compute_topics_similar... | pysrc/papers/analysis/topics.py | 6,272 | Select words with the frequency vector that is the closest to the 'ideal' frequency vector
([0, ..., 0, 1, 0, ..., 0]) in tokens of cosine distance
:param x: object representations (X x Features)
:param max_clusters:
:param min_cluster_size:
:return: List[cluster], Hierarchical dendrogram of splits.
Get words from abst... | 1,128 | en | 0.860382 |
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu).
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, ... | examples/minkunet.py | 12,318 | Copyright (c) Chris Choy (chrischoy@ai.stanford.edu). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publi... | 2,315 | en | 0.6971 |
#! /usr/bin/env python
#############################################################################
##
## Copyright (C) 2015 The Qt Company Ltd.
## Contact: http://www.qt.io/licensing/
##
## This file is part of the build configuration tools of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:LGPL21$
## Commercial License Usag... | qtmultimedia/tests/auto/runautotests.py | 7,028 | ! /usr/bin/env python Copyright (C) 2015 The Qt Company Ltd. Contact: http://www.qt.io/licensing/ This file is part of the build configuration tools of the Qt Toolkit. $QT_BEGIN_LICENSE:LGPL21$ Commercial License Usage Licensees holding valid commercial Qt licenses may use this file in accordance with the commercial li... | 1,811 | en | 0.825608 |
import warnings
import numpy as np
from nilearn.plotting import cm
from nilearn.plotting.js_plotting_utils import decode
from nilearn.plotting import html_connectome
from .test_js_plotting_utils import check_html
def test_prepare_line():
e = np.asarray([0, 1, 2, 3], dtype=int)
n = np.asarray([[0, 1], [0, 2... | nilearn/plotting/tests/test_html_connectome.py | 8,330 | Tests whether use of deprecated keyword parameters of view_markers
raise corrrect warnings. | 91 | en | 0.368531 |
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
dataset = load_boston()
X = dataset.data
y = dataset.target
mean = X.mean(axis=0)
std = X.std(axis=0)
X = (X-mean)/std
# print(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
n_tr... | 1_boston.py | 1,285 | print(X) 权重初始化 偏置项不做正则化处理 | 25 | zh | 0.863565 |
# Name:
# Date:
# proj02: sum
# Write a program that prompts the user to enter numbers, one per line,
# ending with a line containing 0, and keep a running sum of the numbers.
# Only print out the sum after all the numbers are entered
# (at least in your final version). Each time you read in a number,
# you can immed... | proj02_loops/proj02_01.py | 1,019 | Name: Date: proj02: sum Write a program that prompts the user to enter numbers, one per line, ending with a line containing 0, and keep a running sum of the numbers. Only print out the sum after all the numbers are entered (at least in your final version). Each time you read in a number, you can immediately use it for ... | 717 | en | 0.918151 |
#!/usr/bin/env python
"""
convert corpus to annotated corpus
This script uses nltk for dependency parsing, which is based on stanford corenlp.
"""
import os
from nltk.parse.stanford import *
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('corenlp_path',
help='Dir... | vsmlib/embeddings/bofang/annotate_corpus_nltk.py | 4,466 | convert corpus to annotated corpus
This script uses nltk for dependency parsing, which is based on stanford corenlp.
!/usr/bin/env python /home/lbf/Documents/stanford-corenlp-full-2017-06-09/StanfordNeuralDependencyParser , corenlp_options='-model modelOutputFile.txt.gz' hack for nltk hack for output format print(text... | 690 | en | 0.541785 |
#!/usr/bin/python
#
# Copyright JS Foundation and other contributors, http://js.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
# Unles... | packages/node_modules/@node-red/nodes/core/hardware/nrgpio.py | 7,702 | !/usr/bin/python Copyright JS Foundation and other contributors, http://js.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 app... | 1,402 | en | 0.812733 |
# Import Basic modules
import numpy as np
import os
# Import everything needed to edit video clips
from moviepy.editor import *
from moviepy.Clip import *
from moviepy.video.VideoClip import *
from moviepy.config import get_setting # ffmpeg, ffmpeg.exe, etc...
class AudioProcessing:
# documentation stri... | livius/audio/audioProcessing.py | 2,407 | Import Basic modules Import everything needed to edit video clips ffmpeg, ffmpeg.exe, etc... documentation string, which can be accessed via ClassName.__doc__ (slide_detection.__doc__ )def template_matching(self): | 213 | en | 0.382885 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from collections import defaultdict
from collections import OrderedDict
import itertools
import os
from pathlib import Path
from colcon_core.package_selection import add_arguments \
as add_packages_arguments
from colcon_core.packag... | colcon_package_information/verb/graph.py | 13,514 | Generate a visual representation of the dependency graph.
Copyright 2016-2018 Dirk Thomas Licensed under the Apache License, Version 2.0 noqa: D107 noqa: D102 only added so that package selection arguments can be used which use the build directory to store state information noqa: D102 draw dependency graph in ASCII p... | 1,371 | en | 0.74871 |
#!/usr/bin/env python
# encoding: utf-8
'''
@project : MSRGCN
@file : cmu_runner.py
@author : Droliven
@contact : droliven@163.com
@ide : PyCharm
@time : 2021-07-28 13:29
'''
from datas import CMUMotionDataset, get_dct_matrix, reverse_dct_torch, define_actions_cmu, draw_pic_gt_pred
from nets import MSRGCN,... | run/cmu_runner.py | 12,529 | gt: B, 66, 25
# (batch size,feature dim, seq len)
等同于 mpjpe_error_p3d()
@project : MSRGCN
@file : cmu_runner.py
@author : Droliven
@contact : droliven@163.com
@ide : PyCharm
@time : 2021-07-28 13:29
!/usr/bin/env python encoding: utf-8 (batch size,feature dim, seq len) B, 25, 22, 3 B, 25, 22, 3 参数 模型 数据 ski... | 443 | en | 0.269446 |
#!/usr/bin/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 tha... | contrib/seeds/generate-seeds.py | 4,364 | 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... | 980 | en | 0.615454 |
class Type:
def __init__(self):
pass
def get_repr(self):
return self
def __repr__(self):
return self.get_repr().stringify()
def stringify(self):
return ""
def put_on_stack(self, stack):
stack.put(self.get_repr())
def take_from_stack(self, stack):
... | utils/parsxv2/typesystem.py | 5,924 | Takes a sequence of types, produces a signle type matching the sequence | 71 | en | 0.74475 |
"""
logan.runner
~~~~~~~~~~~~
:copyright: (c) 2012 David Cramer.
:license: Apache License 2.0, see NOTICE for more details.
"""
import argparse
import os
import re
import sys
from django.core import management
from nautobot import __version__
from . import importer
from .settings import create_default_settings
__... | nautobot/core/runner/runner.py | 7,969 | Argparse Formatter that includes newlines and shows argument defaults.
:param project: should represent the canonical name for the project, generally
the same name it assigned in distutils.
:param default_config_path: the default location for the configuration file.
:param default_settings: default settings to load... | 2,224 | en | 0.737274 |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... | nemo/collections/nlp/data/text_normalization/utils.py | 2,453 | The function is used to do some basic tokenization
Args:
input_str: The input string
lang: Language of the input string
Return: a list of tokens of the input string
Normalize an input string
Reading the raw data from a file of NeMo format
For more info about the data format, refer to the
`text_normalization d... | 1,056 | en | 0.755212 |
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "... | gcloud/google-cloud-sdk/.install/.backup/lib/third_party/dns/rdata.py | 14,998 | Generate Rdata Class
This class is used for rdata types for which we have no better
implementation. It implements the DNS "unknown RRs" scheme.
Base class for all DNS rdata types.
Initialize an rdata.
@param rdclass: The rdata class
@type rdclass: int
@param rdtype: The rdata type
@type rdtype: int
Convert a bin... | 6,067 | en | 0.625867 |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 23 15:54:01 2018
@author: shinyonsei2
"""
import numpy as np
import imageio
def read_pfm(fpath, expected_identifier="Pf"):
# PFM format definition: http://netpbm.sourceforge.net/doc/pfm.html
def _get_next_line(f):
next_line = f.readline().decode('... | epinet_fun/util.py | 3,690 | Created on Fri Dec 23 15:54:01 2018
@author: shinyonsei2
-*- coding: utf-8 -*- PFM format definition: http://netpbm.sourceforge.net/doc/pfm.html ignore comments header load LF images(9x9) load LF disparity map try: 0%.2d.png load LF disparity map except: print(hci_root + dir_LFi... | 368 | en | 0.3444 |
# Copyright 2020 University of New South Wales, University of Sydney
# 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... | platipy/dicom/io/crawl.py | 44,900 | Fixes missing points in contouring using simple linear interpolation
Args:
contour_data_list (list): The contour data for each slice
Returns:
contour_data (numpy array): Interpolated contour data
Attempts to return some information from a DICOM
This is typically used for naming converted NIFTI files
Args:
... | 6,212 | en | 0.819219 |
"""
Conjuntos são chamados de set's
- Set não possui duplicidade
- Set não possui valor ordenado
- Não são acessados via indice, ou seja, não são indexados
Bons para armazenar elementos são ordenação, sem se preocupar com chaves, valores e itens duplicados.
Set's são referenciados por {}
Diferença de set e dict
- Dic... | Secao7_ColecoesPython/Conjutos.py | 4,683 | Conjuntos são chamados de set's
- Set não possui duplicidade
- Set não possui valor ordenado
- Não são acessados via indice, ou seja, não são indexados
Bons para armazenar elementos são ordenação, sem se preocupar com chaves, valores e itens duplicados.
Set's são referenciados por {}
Diferença de set e dict
- Dict te... | 4,643 | pt | 0.755896 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import click
import builderutils.parser as parser
import builderutils.renderer as renderer
import builderutils.dom as dom
@click.group()
def cli():
pass
@click.command()
@click.option("--configfile", type=click.Path(), help="Builder config", required=True)
def crea... | builder/builder.py | 1,108 | !/usr/bin/env python -*- coding: utf-8 -*- parserObj = parser.BuilderParser(configfile) renderObj = renderer.Renderer() renderObj.build_staging_environment(parserObj.parsedData) userConfig = parserObj.parsedData["user_config"] htmlTemplate = parserObj.parsedData["html_template"] flaskTemplate = parserObj.parsedData["fl... | 444 | en | 0.077154 |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template_file: python-cli-command.j2
# justice-platform-service (4.10.0)
# pylint: disable=duplicate-co... | samples/cli/accelbyte_py_sdk_cli/platform/_download.py | 2,224 | Copyright (c) 2021 AccelByte Inc. All Rights Reserved. This is licensed software from AccelByte Inc, for limitations and restrictions contact your company contract manager. Code generated. DO NOT EDIT! template_file: python-cli-command.j2 justice-platform-service (4.10.0) pylint: disable=duplicate-code pylint: disable=... | 743 | en | 0.674467 |
"""
Credentials used when making CLIs.
"""
from pathlib import Path
from dcos_e2e.cluster import Cluster
DEFAULT_SUPERUSER_USERNAME = 'bootstrapuser'
DEFAULT_SUPERUSER_PASSWORD = 'deleteme'
def add_authorized_key(cluster: Cluster, public_key_path: Path) -> None:
"""
Add an authorized key to all nodes in th... | src/dcos_e2e_cli/common/credentials.py | 814 | Add an authorized key to all nodes in the given cluster.
Credentials used when making CLIs. | 91 | en | 0.697547 |
"""Some miscellaneous utility functions."""
from contextlib import contextmanager
import os
import re
import sys
import warnings
import unittest
from fnmatch import fnmatchcase
from io import StringIO
from numbers import Number
# note: this is a Python 3.3 change, clean this up for OpenMDAO 3.x
try:
from collectio... | openmdao/utils/general_utils.py | 34,574 | A fake dictionary that always reports __contains__(name) to be True.
Iterable object yielding local indices while iterating over local or distributed vars.
The number of iterations for a distributed variable will be the full distributed size of the
variable but None will be returned for any indices that are not local ... | 15,046 | en | 0.650161 |
import json
import os
srt_path = '/home/lyp/桌面/MAE_论文逐段精读【论文精读】.457423264.zh-CN.srt'
json_path = '/home/lyp/桌面/caption.json'
txt_path = '/home/lyp/桌面'
def srt2txt(path):
out_path= os.path.join(txt_path,path.split('.')[0]+'.txt')
with open(path,'r+') as f:
with open(out_path, 'w+') as out:
fo... | test_model/utils/caption2txt.py | 945 | print(len(caption_dict['body'])) | 32 | en | 0.177847 |
# coding: utf-8
"""
Pure Storage FlashBlade REST 1.3 Python SDK
Pure Storage FlashBlade REST 1.3 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.3
Contact: i... | purity_fb/purity_fb_1dot3/apis/network_interfaces_api.py | 20,545 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
Create a new network interface
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
... | 7,639 | en | 0.678387 |
"""
This project demonstrates NESTED LOOPS (i.e., loops within loops)
in the context of SEQUENCES OF SUB-SEQUENCES.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues,
and Lucas D'Alesio.
""" # DONE: 1. PUT YOUR NAME IN THE AB... | src/m3_more_nested_loops_in_sequences.py | 15,919 | Given a sequence of subsequences:
-- Returns True if any element of the first (initial) subsequence
appears in any of the other subsequences.
-- Returns False otherwise.
For example, if the given argument is:
[(3, 1, 4),
(13, 10, 11, 7, 10),
[11, 12, 3, 10]]
then this function returns True bec... | 5,888 | en | 0.70708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.