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 json
import kfp.dsl as _kfp_dsl
import kfp.components as _kfp_components
from collections import OrderedDict
from kubernetes import client as k8s_client
def step1():
from kale.common import mlmdutils as _kale_mlmdutils
_kale_mlmdutils.init_metadata()
from kale.marshal.decorator import marshal as... | backend/kale/tests/assets/kfp_dsl/simple_data_passing.py | 7,172 | Get or create an experiment and submit a pipeline run Submit a pipeline run | 75 | en | 0.69972 |
import numpy as np
import matplotlib.pyplot as plt
from UTILS.Calculus import Calculus
from UTILS.SetAxisLimit import SetAxisLimit
from UTILS.Tools import Tools
from UTILS.Errors import Errors
import sys
# Theoretical background https://arxiv.org/abs/1401.5176
# Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hyd... | CANUTO1997/LuminosityEquation.py | 11,870 | Plot mean total energy stratification in the model
Plot luminosity equation in the model
Theoretical background https://arxiv.org/abs/1401.5176 Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field Equations in Spherical Geometry and their Application to Turbulent Stellar Convection Data load ... | 1,624 | en | 0.68908 |
import numpy as np
class Graph():
""" The Graph to model the skeletons extracted by the openpose
Args:
strategy (string): must be one of the follow candidates
- uniform: Uniform Labeling
- distance: Distance Partitioning
- spatial: Spatial Configuration
For more informa... | action/pose_based/net/utils/graph.py | 7,104 | The Graph to model the skeletons extracted by the openpose
Args:
strategy (string): must be one of the follow candidates
- uniform: Uniform Labeling
- distance: Distance Partitioning
- spatial: Spatial Configuration
For more information, please refer to the section 'Partition Strategies'
in... | 1,264 | en | 0.566456 |
from selenium.webdriver.support.select import Select
def get_selected_option(browser, css_selector):
# Takes a css selector for a <select> element and returns the value of
# the selected option
select = Select(browser.find_element_by_css_selector(css_selector))
return select.first_selected_option.get_a... | tests/test_helpers/selenium_helper.py | 338 | Takes a css selector for a <select> element and returns the value of the selected option | 88 | en | 0.683958 |
import sys
import numpy as np
from contextlib import contextmanager
from qtpy.QtGui import QOpenGLBuffer
def setup_vertex_buffer(gl, data, shader, shader_variable):
'Setup a vertex buffer with `data` vertices as `shader_variable` on shader'
vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)
vbo.create()
... | caimageviewer/gl_util.py | 3,275 | Bind all objs (optionally with positional arguments); releases at cleanup
Allocate or update data stored in a pixel buffer object
Setup a vertex buffer with `data` vertices as `shader_variable` on shader
Update a texture associated with a PBO
Update a vertex buffer with `data` vertices
AreaDetector arrays are not str... | 554 | en | 0.687178 |
import base64 as _base64
import hashlib as _hashlib
import http.server as _BaseHTTPServer
import os as _os
import re as _re
import urllib.parse as _urlparse
import webbrowser as _webbrowser
from http import HTTPStatus as _StatusCodes
from multiprocessing import get_context as _mp_get_context
from urllib.parse import ur... | flytekit/clis/auth/auth.py | 11,325 | A simple wrapper around BaseHTTPServer.BaseHTTPRequestHandler that handles a callback URL that accepts an
authorization token.
A simple wrapper around the BaseHTTPServer.HTTPServer implementation that binds an authorization_client for handling
authorization code callbacks.
Adapted from https://github.com/openstack/deb-... | 2,087 | en | 0.758998 |
# Copyright (c) 2012-2016 Seafile Ltd.
import logging
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from seaserv import seafile_a... | seahub/api2/endpoints/admin/group_members.py | 8,391 | Delete an user from group
Permission checking:
1. only admin can perform this action.
List all group members
Permission checking:
1. only admin can perform this action.
Bulk add group members.
Permission checking:
1. only admin can perform this action.
update role of a group member
Permission checking:
1. only admi... | 573 | en | 0.874384 |
# Copyright 2013 Rackspace Hosting
#
# 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 ... | openstack_dashboard/contrib/trove/content/databases/workflows/create_instance.py | 16,647 | Initialize the database with users/databases. This tab will honor
the settings which should be a list of permissions required:
* TROVE_ADD_USER_PERMS = []
* TROVE_ADD_DATABASE_PERMS = []
Returns the initial databases for this instance.
Copyright 2013 Rackspace Hosting Licensed under the Apache License, Version 2.... | 1,012 | en | 0.817702 |
from tkinter import *
from time import *
## 전역 변수 선언 부분 ##
fnameList = ["jeju1.gif", "jeju2.gif", "jeju3.gif", "jeju4.gif", "jeju5.gif", "jeju6.gif", "jeju7.gif", "jeju8.gif", "jeju9.gif", "jeju10.gif"]
photoList = [None] * 9
num1,num2,num3 = 0,1,2
## 함수 선언 부분 ##
def clickNext() :
global num1,num2,num3
num1... | 4-1/WIndow Programing/20180502/p1.py | 3,809 | 전역 변수 선언 부분 함수 선언 부분 메인 코드 부분 | 33 | ko | 1.00007 |
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import pytest
import asyncio
from unittest.mock import patch, call, MagicMock
from foglamp.common import logger
from foglamp.common.storage_client.storage_client import ReadingsStorageClient, StorageClient
from foglamp.common.... | tests/unit/python/foglamp/tasks/purge/test_purge.py | 13,189 | Test the units of purge.py
Test that creating an instance of Purge calls init of FoglampProcess and creates loggers
Test that purge_data calls Storage's purge with defined configuration
Test that purge_data raises exception when called with invalid configuration
Test that purge_data logs message when no data was purged... | 1,042 | en | 0.720903 |
''' written by Emanuel Ramirez (emanuel2718@gmail.com) '''
class LanguageFlagNotFound(Exception):
pass
class AlgorithmFlagNotFound(Exception):
pass
| algocli/errors.py | 165 | written by Emanuel Ramirez (emanuel2718@gmail.com) | 50 | en | 0.727127 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Update handling."""
from __future__ import print_function, unicode_literals, absolute_import
import re, time, os, threading, zipfile, tarfile
try: # Python 2
# pylint:disable=import-error, no-name-in-module
from urllib import quote, unquote
from urlparse i... | core/update.py | 10,344 | Updater class for DFFD-hosted downloads.
Updater class which uses a JSON object to locate the version (and
optionally also the download URLs).
Updater class which uses regular expressions to locate the version (and
optionally also the download URLs).
General class for checking for updates.
Checks for updates using the ... | 1,628 | en | 0.742539 |
import lightgbm as lgb
import xgboost as xgb
from sklearn.metrics import mean_squared_error, mean_absolute_error, explained_variance_score, r2_score
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
def compile_model(network):
"""
:param network dict: dictionary with network parameter... | gb_rf_evolution/gb_train.py | 1,976 | :param network dict: dictionary with network parameters
:return: compiled model
:param network dict: dictionary with network parameters
:param x_train array: numpy array with features for traning
:param y_train array: numpy array with labels for traning
:param x_test array: numpy array with labels for test
:param y_tes... | 382 | en | 0.52218 |
from logging import getLogger
from mpi4py import MPI
logger = getLogger('om.mpi_ctrl')
WORKTAG = 0
DIETAG = 1
class MpiMaster(object):
def __init__(self, run_control, comm, rank, size):
self.run_control = run_control
self.comm = comm
self.rank = rank
self.size = size
log... | omnium/run_control/mpi_control.py | 4,547 | Launch all tasks initially. TODO: should handle exception in slave by consuming all data and issuing dies. Farm out rest of work when a worker reports back that it's done. There are tasks with unmet dependencies. Block until notified of completion. reconstituted via pickle. Clear backlog of waiting dests. We are done! ... | 409 | en | 0.92535 |
# needs mayavi2
# run with ipython -wthread
import networkx as nx
import numpy as np
from enthought.mayavi import mlab
# some graphs to try
#H=nx.krackhardt_kite_graph()
#H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')
#H=nx.grid_2d_graph(4,5)
H=nx.cycle_graph(20)
# reorder nodes from 0,len(... | examples/3d_drawing/mayavi2_spring.py | 1,103 | needs mayavi2 run with ipython -wthread some graphs to tryH=nx.krackhardt_kite_graph()H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')H=nx.grid_2d_graph(4,5) reorder nodes from 0,len(G)-1 3d spring layout numpy array of x,y,z positions in sorted node order scalar colors mlab.show() interactive... | 327 | en | 0.40865 |
#!/usr/bin/env python
import getopt
import sys
from coapthon.server.coap import CoAP
from exampleresources import BasicResource, Long, Separate, Storage, Big, voidResource, XMLResource, ETAGResource, \
Child, \
MultipleEncodingResource, AdvancedResource, AdvancedResourceSeparate, DynamicResource
__au... | coapserver.py | 2,220 | !/usr/bin/env python pragma: no cover pragma: no cover pragma: no cover | 71 | en | 0.402775 |
"""
Prime Developer Trial
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 re # noqa: F401
import sys # noqa: F401
from fds.sdk.Q... | code/python/QuotesAPIforDigitalPortals/v2/fds/sdk/QuotesAPIforDigitalPortals/model/prices_trading_schedule_event_list_data.py | 11,835 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the a... | 6,095 | en | 0.791051 |
#!/usr/bin/env python3
"""Define public exports."""
__all__ = ["OutputFileExists", "InvalidDomain", "FileWriteError", "NoDomains"]
class NoDomains(Exception):
"""Raise when no domains are passed to findcdn main."""
def __init__(self, error):
"""Instantiate super class with passed message."""
... | src/findcdn/findcdn_err.py | 1,458 | Raise when there is a problem writing to a file in findcnd.
Raise when an invalid domain is inputted in findcnd.main().
Raise when no domains are passed to findcdn main.
Raise when file already exists when writing in findcdn.
Instantiate super class with passed message.
Instantiate super class with passed message with ... | 517 | en | 0.729886 |
import pandas as pd
from utils.config import Config
import numpy as np
import pandas as pd
def fun_clean_categogy1(array, keyw1, index, BOW):
compty = 0
c = 0
for elm in array:
if elm == "oui" or elm == "parfois":
BOW[c].append(keyw1[index])
compty += 1
c += 1
#... | notebooks/template_preprocessing_columns.py | 4,073 | print(compty)Ajout des keywords de la catégorie 2 ATTENTION, ici j'ajoute tout le contenu des colonnes, donc il peut y avoir une grande variété de mots qui sugissent à cause d'ici. De plus, ce sont souvent des mots composés ou des séquences de mots. On peut envisager de ne sélectionner que le premier mot par exemple. p... | 993 | fr | 0.983012 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | docs/conf.py | 6,898 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions ... | 4,246 | en | 0.610065 |
import time
import scipy.io.wavfile as wavfile
import numpy as np
import speech_recognition as sr
import librosa
import argparse
import os
from glob import glob
from pydub import AudioSegment
from pydub.silence import split_on_silence, detect_nonsilent
from pydub.playback import play
import pysrt
import math
import sh... | src/subtitle.py | 6,237 | Normalize given audio chunk
finally: os.remove(wav_filename) Define a function to normalize a chunk to a target amplitude. Load your audio. song = AudioSegment.from_mp3("your_audio.mp3")song = AudioSegment.from_wav("vocals.wav") play(song) Nonsilence track start and end positions. for [start, end] in nonsi... | 803 | en | 0.610057 |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return... | Lintcode/Ladder_11_15_A/88. Lowest Common Ancestor of a Binary Tree.py | 734 | @param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None | 319 | en | 0.566927 |
import numpy as np
from yt.utilities.on_demand_imports import _h5py as h5py
from yt.funcs import \
mylog
from yt.geometry.selection_routines import GridSelector
from yt.utilities.io_handler import \
BaseIOHandler
def _grid_dname(grid_id):
return "/data/grid_%010i" % grid_id
def _field_dname(grid_id, fie... | yt/frontends/gdf/io.py | 3,452 | TODO all particle bits were removed check the dtype instead check the dtype instead check the dtype instead caches I don't get that part, only last nd is added | 159 | en | 0.890741 |
#######################
# Dennis MUD #
# telnet.py #
# Copyright 2018-2021 #
# Michael D. Reiley #
#######################
# **********
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal i... | lib/telnet.py | 4,782 | Dennis MUD telnet.py Copyright 2018-2021 Michael D. Reiley ********** 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 ... | 1,432 | en | 0.876923 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.INFO)
# Data sets
IRIS_TRAINING = os.path.join(os.path.dirname(__file__), "iris_training.csv")
IRIS_TEST = os.path.joi... | agents/tensorflow_iris.py | 2,393 | Data sets Load datasets. Specify that all features have real-value data Build 3 layer DNN with 10, 20, 10 units respectively. classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[10, 20, 10], n_... | 567 | en | 0.42139 |
# encoding: utf-8
"""
@author: sherlock
@contact: sherlockliao01@gmail.com
"""
import glob
import re
import os.path as osp
from .bases import BaseImageDataset
class Market1501(BaseImageDataset):
"""
Market1501
Reference:
Zheng et al. Scalable Person Re-identification: A Benchmark. ICCV 2015.
U... | data/datasets/market1501.py | 2,658 | Market1501
Reference:
Zheng et al. Scalable Person Re-identification: A Benchmark. ICCV 2015.
URL: http://www.liangzheng.org/Project/project_reid.html
Dataset statistics:
# identities: 1501 (+1 for background)
# images: 12936 (train) + 3368 (query) + 15913 (gallery)
@author: sherlock
@contact: sherlockliao01@gmail.co... | 443 | en | 0.716542 |
"""
Django settings for pets_forum project.
Generated by 'django-admin startproject' using Django 1.11.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
impor... | pets_forum/pets_forum/settings.py | 3,112 | Django settings for pets_forum project.
Generated by 'django-admin startproject' using Django 1.11.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
Build paths ... | 1,000 | en | 0.649352 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 30 03:08:17 2017
@author: aditya
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 12:46:25 2017
@author: aditya
"""
import math
import os
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow a... | FSL - Entire Project + Report/Final Project/Code/Exp1.py | 12,303 | bias_variable generates a bias variable of a given shape.
weight_variable generates a weight variable of a given shape.
Created on Thu Nov 30 03:08:17 2017
@author: aditya
!/usr/bin/env python3 -*- coding: utf-8 -*-!/usr/bin/env python3 -*- coding: utf-8 -*-Code boorrowed from https://github.com/tensorflow/tensorflow... | 970 | en | 0.692586 |
from os.path import join, dirname, abspath
here = lambda *paths: join(dirname(abspath(__file__)), *paths)
PROJECT_ROOT = here('..')
root = lambda *paths: join(PROJECT_ROOT, *paths)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
EMAIL_BACKEND = 'django.core.mail.bac... | tests/settings.py | 5,631 | ('Your Name', 'your_email@example.com'), Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. Or path to database file if using sqlite3. The following settings are not used with sqlite3: Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. Set to empty string for default. Hosts/dom... | 2,891 | en | 0.752139 |
# Copyright 2015 Red Hat, 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 agre... | neutron/tests/unit/agent/linux/openvswitch_firewall/test_firewall.py | 33,871 | Check that exception is not propagated outside.
Check that exception is not propagated outside.
Just make sure we doesn't crash
Check flows are applied right after _set_flows is called.
Just make sure it doesn't crash
Just make sure it doesn't crash
Just make sure it doesn't crash
Copyright 2015 Red Hat, Inc. Lice... | 1,032 | en | 0.930864 |
"""
Test Sermin config module
"""
from sermin.config.module import Registry, Namespace, Setting, settings
from sermin.config.utils import parse_args
from .utils import SafeTestCase
class SettingsTest(SafeTestCase):
def setUp(self):
self.old_settings = settings._namespaces
settings._clear()
d... | tests/test_config.py | 2,391 | Test Sermin config module | 25 | ru | 0.064592 |
import numpy as np
from rafiki.constants import TaskType
def ensemble_predictions(predictions_list, predict_label_mappings, task):
# TODO: Better ensembling of predictions based on `predict_label_mapping` & `task` of models
if len(predictions_list) == 0 or len(predictions_list[0]) == 0:
return []
... | rafiki/predictor/ensemble.py | 743 | TODO: Better ensembling of predictions based on `predict_label_mapping` & `task` of models By default, just return some trial's predictions Map probabilities to most probable label | 180 | en | 0.828244 |
"""Auto-generated file, do not edit by hand. EC metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_EC = PhoneMetadata(id='EC', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[19]\\d{2}', possible_number_pattern='\... | python/phonenumbers/shortdata/region_EC.py | 993 | Auto-generated file, do not edit by hand. EC metadata | 53 | en | 0.768489 |
import django_filters
from django_filters import DateFilter
from .models import Pet
class PetFilter(django_filters.FilterSet):
# name = django_filters.CharFilter(lookup_expr='iexact')
start_date = DateFilter(field_name = "age", lookup_expr='gte') #greater or equal to
end_date = DateFilter(field_name = "age... | pets/filters.py | 576 | name = django_filters.CharFilter(lookup_expr='iexact')greater or equal toless or equal to | 89 | en | 0.472622 |
# coding:utf-8
import sys
import codecs
from pathlib import Path
from collections import defaultdict
MAIN_PATH = Path(__file__).absolute().parent.parent.parent
sys.path.insert(0, str(MAIN_PATH))
from log import log_info as _info
from log import log_error as _error
from log import print_process as _process
class Vert... | Course_2/Week_01/3_SCC.py | 3,473 | coding:utf-8 for saving the nodes which have no outgoing arc reverse the graph sanity check reverse the graph sanity check find SCCs | 132 | en | 0.886687 |
from deadfroglib import *
import Image
import math
# set up the colors
BLACK = 0xff000000
WHITE = 0xffffffff
im = Image.open("willow.bmp")
imOut = Image.new(im.mode, im.size)
graph3d = CreateGraph3d()
minA = 1000
maxA = -1000
minB = 1000
maxB = -1000
minC = 1000
maxC = -1000
err = 0.0
for y in range(im.size[1]):
... | python/graph3d.py | 3,555 | set up the colors ya = round(0.299*r + 0.587*g + 0.114*b) cb = round(128 - 0.168736*r - 0.331264*g + 0.5*b) cr = round(128 + 0.5*r - 0.418688*g - 0.081312*b) ya = round( r + g + b) cb = round( r - g) cr = round( r + g - 2*b) {{0.61333, 0.58095, 0.53509}, {-0.32762,... | 1,089 | en | 0.431921 |
# Copyright (c) OpenMMLab. All rights reserved.
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=10)
evaluation = dict(interval=10, metric='mAP', key_indicator='AP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
op... | demo/hrnet_w32_coco_256x192.py | 5,013 | Copyright (c) OpenMMLab. All rights reserved. learning policy dict(type='TensorboardLoggerHook') model settings | 111 | en | 0.768964 |
import codecs
from xml.sax.saxutils import quoteattr, escape
__all__ = ['XMLWriter']
ESCAPE_ENTITIES = {
'\r': ' '
}
class XMLWriter(object):
def __init__(self, stream, namespace_manager, encoding=None,
decl=1, extra_ns=None):
encoding = encoding or 'utf-8'
encoder, deco... | lib/rdflib/plugins/serializers/xmlwriter.py | 3,396 | Utility method for adding a complete simple element
Compute qname for a uri using our extra namespaces,
or the given namespace manager
TODO: Allow user-provided namespace bindings to prevail | 192 | en | 0.358571 |
from tests.conftest import log_in
def test_logout_auth_user(test_client):
"""
GIVEN a flask app
WHEN an authorized user logs out
THEN check that the user was logged out successfully
"""
log_in(test_client)
response = test_client.get("auth/logout", follow_redirects=True)
assert response... | tests/test_auth/test_logout.py | 932 | GIVEN a flask app
WHEN an anon user attemps to log out
THEN check that a message flashes informing them that they are already logged out.
GIVEN a flask app
WHEN an authorized user logs out
THEN check that the user was logged out successfully
assert b"<!-- index.html -->" in response.data Removed -- COVID assert b"<!... | 373 | en | 0.837699 |
def demo():
"""Output:
---------⌝
----------
----?????-
----------
----------
--!!!-----
--!!!-----
----------
----------
⌞---------
"""
n = 10
# Construction is easy:
grid = {}
# Assignment is easy:
grid[(0, 0)] = "⌞"
grid[(n - 1, n - 1)] = "⌝"... | examples/grids/python/grid.py | 1,149 | Output:
---------⌝
----------
----?????-
----------
----------
--!!!-----
--!!!-----
----------
----------
⌞---------
Using product allows for flatter loops.
Stringify with (0, 0) in the lower-left corner.
Construction is easy: Assignment is easy: Helper functions that just work on the dictionary: | 300 | en | 0.518321 |
# coding: utf-8
"""
Apteco API
An API to allow access to Apteco Marketing Suite resources # noqa: E501
The version of the OpenAPI document: v2
Contact: support@apteco.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class Selection(object... | apteco_api/models/selection.py | 8,038 | 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
Selection - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Gets the ancestor_counts of this Selection. # n... | 2,689 | en | 0.735025 |
"""
mavDynamics
- this file implements the dynamic equations of motion for MAV
- use unit quaternion for the attitude state
part of mavPySim
- Beard & McLain, PUP, 2012
- Update history:
12/20/2018 - RWB
2/24/2020
"""
import sys
sys.path.append('..')
import numpy as np
# load m... | Lectures/MAV_Dynamics/mav_dynamics.py | 12,549 | for the dynamics xdot = f(x, u), returns fdot(x, u)
return the forces on the UAV based on the state, wind, and control surfaces
:param delta: np.matrix(delta_e, delta_a, delta_r, delta_t)
:return: Forces and Moments on the UAV np.matrix(Fx, Fy, Fz, Ml, Mn, Mm)
Integrate the differential equations defining dynamics, upd... | 2,904 | en | 0.766327 |
# 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://www.apache.org/licenses/LICENSE-2.0
#
# or in th... | mxfusion/components/distributions/gp/kernels/static.py | 7,240 | Bias kernel, which produces a constant value for every entries of the covariance matrix.
.. math::
k(x,y) = \sigma^2
:param input_dim: the number of dimensions of the kernel. (The total number of active dimensions).
:type input_dim: int
:param variance: the initial value for the variance parameter.
:type variance:... | 4,204 | en | 0.647778 |
from typing import Any
import tensorflow as tf
from .tf_util import scope_name as get_scope_name
def absolute_scope_name(relative_scope_name):
"""Appends parent scope name to `relative_scope_name`"""
base = get_scope_name()
if len(base) > 0:
base += '/'
return base + relative_scope_name
def _infer_scope_nam... | sandblox/util/scope.py | 1,650 | Appends parent scope name to `relative_scope_name`
noinspection PyMissingConstructor | 86 | en | 0.450069 |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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... | build/PureCloudPlatformClientV2/models/text_bot_flow_launch_response.py | 3,644 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
TextBotFlowLaunchResponse - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param d... | 1,651 | en | 0.808969 |
# Generated by Django 3.1.2 on 2020-10-29 20:54
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Quote',
fields=[
... | crawler/migrations/0001_initial.py | 992 | Generated by Django 3.1.2 on 2020-10-29 20:54 | 45 | en | 0.735655 |
from django.db import models
from django.utils.translation import gettext_lazy as _
from oscar.apps.offer.abstract_models import AbstractConditionalOffer, AbstractBenefit
from oscar.core.loading import get_class
class ConditionalOffer(AbstractConditionalOffer):
SITE, FLASH_SALE, VOUCHER, USER, SESSION = "Site", ... | sandbox/offer/models.py | 2,841 | noqa isort:skip noqa isort:skip | 31 | gu | 0.190627 |
"""Metadata State Manager."""
import asyncio
import logging
from typing import Dict, List, Optional, Set, Tuple, Type
from pydantic import ValidationError
from astoria.common.components import StateManager
from astoria.common.disks import DiskInfo, DiskType, DiskUUID
from astoria.common.ipc import (
MetadataMana... | astoria/astmetad/metadata_manager.py | 8,452 | Astoria Metadata State Manager.
Calculate the current metadata.
Takes the default, static metadata based on the config and system
information. It then overlays data from other sources in a priority order,
whereby each source has a set of permitted attributes in the metadata that
can be overridden.
Status to publish wh... | 860 | en | 0.816181 |
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2021 PyMeasure Developers
#
# 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 limit... | pymeasure/display/log.py | 2,097 | This file is part of the PyMeasure package. Copyright (c) 2013-2021 PyMeasure Developers 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... | 1,488 | en | 0.890806 |
import re
import setuptools
import setuptools.command.develop
import setuptools.command.install
import subprocess
import sys
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "show", "pkg_utils"],
check=True, capture_output=True)
match = re.search(r'\nVersion: (.*?)\n', result.stdout.d... | setup.py | 2,070 | get package metadata install package | 36 | en | 0.427415 |
"""
Top-level module of Jina.
The primary function of this module is to import all of the public Jina
interfaces into a single place. The interfaces themselves are located in
sub-modules, as described below.
"""
# DO SOME OS-WISE PATCHES
import datetime as _datetime
import os as _os
import platform as _platform
imp... | jina/__init__.py | 6,764 | sets nofile soft limit to at least 4096, useful for running matlplotlib/seaborn on
parallel executing plot generators vs. Ubuntu default ulimit -n 1024 or OS X El Captian 256
temporary setting extinguishing with Python session.
Top-level module of Jina.
The primary function of this module is to import all of the publi... | 1,430 | en | 0.822021 |
from niaaml.classifiers.classifier import Classifier
from niaaml.utilities import MinMax
from niaaml.utilities import ParameterDefinition
from sklearn.ensemble import RandomForestClassifier as RF
import numpy as np
import warnings
from sklearn.exceptions import ChangedBehaviorWarning, ConvergenceWarning, DataConversio... | niaaml/classifiers/random_forest.py | 3,040 | Implementation of random forest classifier.
Date:
2020
Author:
Luka Pečnik
License:
MIT
Reference:
Breiman, “Random Forests”, Machine Learning, 45(1), 5-32, 2001.
Documentation:
https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html
See Also:
* :clas... | 940 | en | 0.517208 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | sdk/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2020_03_01/operations/_private_endpoint_connections_operations.py | 22,860 | PrivateEndpointConnectionsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.iothub.models
:param ... | 6,337 | en | 0.546018 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/8/25 22:42
# @Author : Tom.lee
# @Site :
# @File : mysql_lock.py
# @Software: PyCharm
"""
通过MySQL实现分布式锁服务
"""
import MySQLdb
import logging
import time
FORMAT_STR = '%(asctime)s -%(module)s:%(filename)s-L%(lineno)d-%(levelname)s: %(message)s'
lo... | contributed_modules/mysql/mysqldb_/mysql_lock.py | 3,349 | !/usr/bin/env python -*- coding: utf-8 -*- @Time : 2017/8/25 22:42 @Author : Tom.lee @Site : @File : mysql_lock.py @Software: PyCharm 加锁操作 释放操作 模拟跨进程的同步操作! raise Exception('模拟操作异常,mysql会自动释放该进程持有的锁.') TODO something | 226 | zh | 0.328903 |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..arithmetic import AddScalarVolumes
def test_AddScalarVolumes_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True... | nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py | 1,182 | AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT | 51 | en | 0.653745 |
#coding:utf-8
# Chainer version 3.2 (use version 3.x)
#
# This is based on <https://raw.githubusercontent.com/chainer/chainer/v3/examples/mnist/train_mnist.py>
#
# This used mean_absolute_error as loss function.
# Check version
# Python 3.6.4 on win32 (Windows 10)
# Chainer 3.2.0
# numpy 1.14.0
# mat... | train.py | 9,050 | coding:utf-8 Chainer version 3.2 (use version 3.x) This is based on <https://raw.githubusercontent.com/chainer/chainer/v3/examples/mnist/train_mnist.py> This used mean_absolute_error as loss function. Check version Python 3.6.4 on win32 (Windows 10) Chainer 3.2.0 numpy 1.14.0 matplotlib 2.1.1 the size of the inpu... | 2,133 | en | 0.604918 |
"""
Forward Chaining, K-Fold and Group K-Fold algorithms to split a given training dataset into train (X, y) and validation (Xcv, ycv) sets
"""
import numpy as np
def split_train_val_forwardChaining(sequence, numInputs, numOutputs, numJumps):
""" Returns sets to train and cross-validate a model using forward chai... | tsxv/splitTrainVal.py | 8,290 | Returns sets to train and cross-validate a model using forward chaining technique
Parameters:
sequence (array) : Full training dataset
numInputs (int) : Number of inputs X and Xcv used at each training and validation
numOutputs (int) : Number of outputs y and ycv used at each training and validation
... | 3,321 | en | 0.798266 |
# Lint as: python3
# Copyright 2020 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 ... | official/vision/beta/modeling/backbones/spinenet.py | 16,368 | A container class that specifies the block configuration for SpineNet.
Class to build SpineNet models.
SpineNet model.
Creates one group of blocks for the SpineNet model.
Match filter size for endpoints before sharing conv layers.
Build scale-permuted network.
Build SpineNet stem.
Match resolution and feature dimension... | 1,860 | en | 0.765683 |
"""This module implements row model of Amazon.co.jp CSV."""
from dataclasses import dataclass
from datetime import datetime
from typing import ClassVar, Optional
from zaimcsvconverter import CONFIG
from zaimcsvconverter.file_csv_convert import FileCsvConvert
from zaimcsvconverter.inputcsvformats import InputItemRow, ... | zaimcsvconverter/inputcsvformats/amazon_201911.py | 9,135 | This class implements row model of Amazon.co.jp CSV.
This class implements row model of Amazon.co.jp CSV.
This class implements row model of Amazon.co.jp CSV.
This class implements data class for wrapping list of Amazon.co.jp CSV row model.
This class implements factory to create Amazon.co.jp CSV row instance.
Row mode... | 731 | en | 0.630207 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# flake8: noqa
#
# AppDaemon documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 11 14:36:18 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are pre... | docs/conf.py | 9,549 | !/usr/bin/env python3 -*- coding: utf-8 -*- flake8: noqa AppDaemon documentation build configuration file, created by sphinx-quickstart on Fri Aug 11 14:36:18 2017. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogene... | 8,018 | en | 0.661719 |
# -*- coding: utf-8 -*-
import pytest
from pyleecan.Classes.LamSlotMag import LamSlotMag
from pyleecan.Classes.SlotM14 import SlotM14
from numpy import pi, exp, sqrt, angle
from pyleecan.Methods.Slot.Slot.comp_height import comp_height
from pyleecan.Methods.Slot.Slot.comp_surface import comp_surface
from pyleecan.Met... | Tests/Methods/Slot/test_SlotM14_meth.py | 7,279 | unittest for MagnetType14 methods
Check that the computation of the average opening angle is correct
Check that the computation of the height is correct
Check that the computation of the active height is correct
Check that the computation of the mechanical radius is correct
Check that the point coordinates are correct
... | 1,016 | en | 0.846022 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | heat/tests/test_nokey.py | 2,798 | vim: tabstop=4 shiftwidth=4 softtabstop=4 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... | 630 | en | 0.829516 |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from six.moves import range
import numpy as np
import utool
from ibeis.control import SQLDatabaseControl as sqldbc
from ibeis.control._sql_helpers import _results_gen
from os.path import join
print, print_,... | _broken/test_sql_numpy.py | 3,008 | !/usr/bin/env python2.7 -*- coding: utf-8 -*- list of 10,000 chips with 3,000 features apeice.db.cur.commit()print('[TEST] result_list=%r' % result_list)with open('temp.dump.txt') as file_: print(file_.read()) For win32 | 222 | en | 0.603988 |
"""
Tests for Markov Autoregression models
Author: Chad Fulton
License: BSD-3
"""
import warnings
import os
import numpy as np
from numpy.testing import assert_equal, assert_allclose
import pandas as pd
import pytest
from statsmodels.tools import add_constant
from statsmodels.tsa.regime_switching import markov_auto... | statsmodels/tsa/regime_switching/tests/test_markov_autoregression.py | 41,400 | Tests for Markov Autoregression models
Author: Chad Fulton
License: BSD-3
AR(1) without mean, k_regimes=2 Resids when: S_{t} = 0 Resids when: S_{t} = 1 AR(1) with mean, k_regimes=2 Resids when: S_t = 0, S_{t-1} = 0 Resids when: S_t = 0, S_{t-1} = 1 Resids when: S_t = 1, S_{t-1} = 0 Resids when: S_t = 1, S_{t-1} = 1 ... | 2,324 | en | 0.752915 |
import tensorflow as tf
# DISCLAIMER:
# Parts of this code file were originally forked from
# https://github.com/tkipf/gcn
# which itself was very inspired by the keras package
def masked_logit_cross_entropy(preds, labels, mask):
"""Logit cross-entropy loss with masking."""
loss = tf.nn.sigmoid_cross_e... | graphsage/metrics.py | 1,683 | Accuracy with masking.
L2 loss with masking.
Logit cross-entropy loss with masking.
Softmax cross-entropy loss with masking.
DISCLAIMER: Parts of this code file were originally forked from https://github.com/tkipf/gcn which itself was very inspired by the keras package | 271 | en | 0.980907 |
import requests
import re
import random
import time
from bs4 import BeautifulSoup
import os
import lpmysql
import json
def getindex():
url = 'http://freeget.co'
headers = {'User-Agent': "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 S... | freeget.py | 1,983 | Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:zh-CN,zh;q=0.8 Connection:keep-alive这儿更改了一下(是不是发现 self 没见了?) "X - CSRFToken":"150416911445f7200f8dba99432cc422ed552b3bbf3baff85b", X - CSRFToken: 1504164180 fdbd5ae5ec0c76632937754c20e90c582f2f7c28 X - Requested - With: XMLHttpRequest Accept:*/* Accept-Encoding... | 546 | en | 0.259376 |
"""Python Interface for Residue-Residue Contact Predictions"""
import os
import sys
from distutils.command.build import build
from distutils.util import convert_path
from setuptools import setup, Extension
from Cython.Distutils import build_ext
import numpy as np
# ==================================================... | setup.py | 5,684 | Python Interface for Residue-Residue Contact Predictions
============================================================== Setup.py command extensions ============================================================== Credits to http://stackoverflow.com/a/33181352 ============================================================... | 871 | en | 0.48574 |
"""
Django settings for mymedicalassistant project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
fro... | mymedicalassistant/settings.py | 3,614 | Django settings for mymedicalassistant project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
Build path... | 1,140 | en | 0.684227 |
from deeplearning import logger, tf_util as U
import tensorflow as tf
from rl.runner import Runner
from rl.vec_env.subproc_vec_env import SubprocVecEnv
from collections import namedtuple
import os, time
class RLExperiment(U.Experiment):
def load_env_fn(self):
fname = os.path.join(self.logdir, 'checkpoints/... | rl/algorithms/core.py | 5,072 | returns a module for and the loss
returns a module for and the optimizer | 72 | en | 0.327079 |
import datetime
import logging
import time
import dataset
import discord
import privatebinapi
from discord.ext import commands
from discord.ext.commands import Cog, Bot
from discord_slash import cog_ext, SlashContext
from discord_slash.model import SlashCommandPermissionType
from discord_slash.utils.manage_commands im... | cogs/commands/moderation/mutes.py | 22,845 | Mute Cog
Load the Mute cog.
Enabling logs Open a connection to the database. Add the mute to the mod_log database. Occurs when the duration parameter in /mute is specified (tempmute). Commit the changes to the database. Removes "Muted" role from member. Open a connection to the database. Add the unmute to the mod_l... | 4,639 | en | 0.918496 |
# -*- coding: utf-8 -*-
### 기본 라이브러리 불러오기
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
'''
[Step 1] 데이터 준비 - read_csv() 함수로 자동차 연비 데이터셋 가져오기
'''
# CSV 파일을 데이터프레임으로 변환
df = pd.read_csv('./auto-mpg.csv', header=None)
# 열 이름 지정
df.columns = ['mpg','cylinders','displacemen... | 7.1_simple_linear_regression.py | 4,174 | -*- coding: utf-8 -*- 기본 라이브러리 불러오기 CSV 파일을 데이터프레임으로 변환 열 이름 지정 데이터 살펴보기 IPython 디스플레이 설정 - 출력할 열의 개수 한도 늘리기 데이터 자료형 확인 데이터 통계 요약정보 확인 horsepower 열의 자료형 변경 (문자열 ->숫자) horsepower 열의 고유값 확인 '?'을 np.nan으로 변경 누락데이터 행을 삭제 문자열을 실수형으로 변환 데이터 통계 요약정보 확인 분석에 활용할 열(속성)을 선택 (연비, 실린더, 출력, 중량) 종속 변수 Y인 "연비(mpg)"와 다른 변수 간의 선형관계를 그래... | 721 | ko | 1.000048 |
from datetime import datetime, timedelta as td
import json
import os
import re
from secrets import token_urlsafe
from urllib.parse import urlencode
from cron_descriptor import ExpressionDescriptor
from croniter import croniter
from django.conf import settings
from django.contrib import messages
from django.contrib.aut... | hc/front/views.py | 59,311 | Return specified channel if current user has access to it.
Return specified check if current user has access to it.
Check access, return (project, rw) tuple.
Check access, return (project, rw) tuple.
Update last_active_date if it is more than a day old.
Hide checks that don't match selected tags: Hide checks tha... | 2,106 | en | 0.90366 |
# Copyright 2020 MONAI Consortium
# 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, s... | monai/metrics/surface_distance.py | 2,371 | This function is used to compute the Average Surface Distance from `seg_pred` to `seg_gt`
under the default setting.
In addition, if sets ``symmetric = True``, the average symmetric surface distance between
these two inputs will be returned.
Args:
seg_pred: first binary or labelfield image.
seg_gt: second bina... | 1,291 | en | 0.781085 |
"""
This version considers task's datasets have equal number of labeled samples
"""
import os
import json
from collections import defaultdict
import numpy as np
from tensorboardX import SummaryWriter
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.aut... | MTL.py | 17,359 | "options for criterion is wasserstien, h_divergence
This version considers task's datasets have equal number of labeled samples
argument definition Constructing F -> H and F -> D if np.abs(np.mean(Total_loss[-5:-1]) - Total_loss[-1]) < 0.002 : print('Stop learning, reach to a stable point at epoch {:d} with tot... | 1,616 | en | 0.664247 |
from django.test import TestCase
class PollsViewsTestCase(TestCase):
fixtures = ['polls_views_testdata.json']
def test_index(self):
resp = self.client.get('/polls/')
self.assertEqual(resp.status_code, 200)
self.assertTrue('latest_poll_list' in resp.context)
self.assertEqual([p... | tdd/polls/tests/test_fixtures.py | 1,497 | Ensure that non-existent polls throw a 404. | 43 | en | 0.586318 |
"""
Support for a local MQTT broker.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/#use-the-embedded-broker
"""
import logging
import tempfile
from homeassistant.core import callback
from homeassistant.components.mqtt import PROTOCOL_311
from hom... | homeassistant/components/mqtt/server.py | 2,619 | Encrypt with what hbmqtt uses to verify | 39 | en | 0.898887 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/python/framework/test_util_test.py | 6,431 | Tests for tensorflow.ops.test_util.
Copyright 2015 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... | 1,074 | en | 0.850603 |
from baselines.deepq import models # noqa F401
from baselines.deepq.deepq_learner import DEEPQ # noqa F401
from baselines.deepq.deepq import learn # noqa F401
from baselines.deepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer # noqa F401
def wrap_atari_dqn(env):
from baselines.common.atari_wrapper... | baselines/deepq/__init__.py | 404 | noqa F401 noqa F401 noqa F401 noqa F401 | 39 | uz | 0.217007 |
# Generated by Django 3.1.4 on 2020-12-07 19:08
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... | leads/migrations/0001_initial.py | 3,792 | Generated by Django 3.1.4 on 2020-12-07 19:08 | 45 | en | 0.712127 |
# Generated from decafJavier.g4 by ANTLR 4.9.2
# encoding: utf-8
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7... | Python3/decafJavierParser.py | 78,103 | Generated from decafJavier.g4 by ANTLR 4.9.2 encoding: utf-8 Token type Token type Token type Token type Token type Token type Token type Token type Token type Token type Token type Token type Token type Token type Token type | 225 | en | 0.249348 |
import numpy as np
from dct_image_transform.dct import dct2
def reflection(image,axis=0):
'''
8x8のブロックごとに離散コサイン変換された画像(以下DCT画像)を鏡像変換する.
Parameters
----------
image:幅と高さが8の倍数である画像を表す2次元配列. 8の倍数でない場合の動作は未定義.
axis:変換する軸. defalutは`axis=0`
Returns
-------
`image`を鏡像変換したDCT画像を表す2次元... | dct_image_transform/reflection.py | 2,823 | 8x8のブロックごとに離散コサイン変換された画像(以下DCT画像)を鏡像変換する.
Parameters
----------
image:幅と高さが8の倍数である画像を表す2次元配列. 8の倍数でない場合の動作は未定義.
axis:変換する軸. defalutは`axis=0`
Returns
-------
`image`を鏡像変換したDCT画像を表す2次元配列を返す. `image`の値は変わらない.
Examples
--------
>>> import numpy as np
>>> a = np.arange(64).reshape((8,8))
>>> a
array([[ 0, 1, 2, 3, 4... | 1,967 | en | 0.316806 |
from __future__ import absolute_import
from django.conf import settings
import ujson
from zproject.backends import password_auth_enabled, dev_auth_enabled, google_auth_enabled, github_auth_enabled
def add_settings(request):
realm = request.user.realm if hasattr(request.user, "realm") else None
return {
... | zerver/context_processors.py | 1,874 | We use the not_voyager variable name so that templates will render even if the appropriate context is not provided to the template | 130 | en | 0.654967 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""The setup script."""
import sys
from setuptools import setup, find_p... | setup.py | 1,805 | The setup script.
!/usr/bin/env python -*- coding: utf-8 -*- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. | 254 | en | 0.887499 |
import taichi as ti
from mpl_toolkits.mplot3d import Axes3D
import os
import math
import numpy as np
import random
import cv2
import matplotlib.pyplot as plt
import time
import taichi as tc
real = ti.f32
ti.set_default_fp(real)
dim = 3
# this will be overwritten
n_particles = 0
n_solid_particles = 0
n_actuators = 0
n... | examples/difftaichi/liquid.py | 13,182 | this will be overwritten TODO: update ti.cfg.arch = ti.x86_64 ti.cfg.use_llvm = True ti.cfg.print_ir = True for all time steps and all particles fluid TODO: need pow(x, 1/3) r, s = ti.polar_decompose(new_F) ti.print(act) simulation Since we do not store the grid history (to save space), we redo p2g and grid op scene.se... | 525 | en | 0.389814 |
#!/usr/bin/env python
import sys
last_pkt_num = -1
daystart_pkt_num = -1
daystart_recv_time = -1
daystart_hwrecv_time = -1
dayend_pkt_num = -1
dayend_recv_time = -1
dayend_hwrecv_time = -1
def process_line(line):
global last_pkt_num
global daystart_pkt_num, daystart_recv_time, daystart_hwrecv_time
glob... | src/scripts/process-loss-rate-output.py | 2,039 | !/usr/bin/env python read in the first line skip through the day, looking for a gap we found a gap | 98 | en | 0.898472 |
# -*- coding: utf8 -*-
import json
from activity.womail.womail import WoMail
class DailySign(WoMail):
def __init__(self, mobile, openId):
super(DailySign, self).__init__(mobile, openId)
self.session.headers.update({
# 'Origin': 'https://nyan.mail.wo.cn',
'Referer': 'https:... | activity/womail/dailyTask.py | 4,340 | -*- coding: utf8 -*- 'Origin': 'https://nyan.mail.wo.cn', XMLHttpRequest data = { 'taskLevel': '1' } , "download" | 117 | en | 0.146124 |
'''
References:
- An Outline of Set Theory, Henle
'''
from . import fol
class ElementSymbol(fol.ImproperSymbol):
def __init__(self):
fol.PrimitiveSymbol.__init__('∈')
def symbol_type(self) -> str:
return 'element of'
@staticmethod
def new() -> "ElementSymbol":
return Elemen... | ddq_1/lang/set.py | 332 | References:
- An Outline of Set Theory, Henle | 46 | en | 0.720767 |
import structlog
from pathlib import Path
from typing import Any, Dict, Generator, Iterable, Optional, Tuple
from normality import normalize, WS
from followthemoney.schema import Schema
from followthemoney.types import registry
from opensanctions import settings
from nomenklatura.loader import Loader
from nomenklatura.... | opensanctions/core/index.py | 944 | Load the search index for the given dataset or generate one if it does
not exist. | 81 | en | 0.593916 |
# coding: utf-8
from __future__ import unicode_literals
import base64
import datetime
import hashlib
import json
import netrc
import os
import random
import re
import socket
import ssl
import sys
import time
import math
from ..compat import (
compat_cookiejar_Cookie,
compat_cookies,
compat_etree_Element,
... | youtube_dl/extractor/common.py | 143,548 | Information Extractor class.
Information extractors are the classes that, given a URL, extract
information about the video (or videos) the URL refers to. This
information includes the real video URL, the video title, author and
others. The information is stored in a dictionary which is then
passed to the YoutubeDL. Th... | 32,356 | en | 0.825456 |
from django import forms
from django.apps import apps
from django.core.exceptions import PermissionDenied
from django.urls import reverse, NoReverseMatch
from django.template.context_processors import csrf
from django.db.models.base import ModelBase
from django.forms.forms import DeclarativeFieldsMetaclass
from django.... | xadmin/views/dashboard.py | 23,641 | Normalize to strings. Call Field instead of ChoiceField __init__() because we don't need ChoiceField.__init__(). | 112 | en | 0.617005 |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | src/oci/dts/transfer_device_client_composite_operations.py | 3,520 | This class provides a wrapper around :py:class:`~oci.dts.TransferDeviceClient` and offers convenience methods
for operations that would otherwise need to be chained together. For example, instead of performing an action
on a resource (e.g. launching an instance, creating a load balancer) and then using a waiter to wait... | 2,013 | en | 0.739704 |
#!/usr/bin/env python
#
# Create daily QC HTML report
#
# USAGE : cbicqc_report.py <QA Directory>
#
# AUTHOR : Mike Tyszka
# PLACE : Caltech
# DATES : 09/25/2013 JMT From scratch
# 10/23/2013 JMT Add com external call
# 10/24/2013 JMT Move stats calcs to new cbicqc_stats.py
#
# This file is part of ... | cbicqclive_report.py | 5,891 | !/usr/bin/env python Create daily QC HTML report USAGE : cbicqc_report.py <QA Directory> AUTHOR : Mike Tyszka PLACE : Caltech DATES : 09/25/2013 JMT From scratch 10/23/2013 JMT Add com external call 10/24/2013 JMT Move stats calcs to new cbicqc_stats.py This file is part of CBICQC. CBICQC is free... | 1,332 | en | 0.75281 |
from typing import Callable
import unittest
# test
from .pipe import pipe
class TestPipe(unittest.TestCase):
def test_pipe_should_return_a_function(self) -> None:
# given
def echo(x: str) -> str:
return f"echo {x}"
# when
output = pipe(echo)
# then
s... | src/unshell/utils/test_pipe.py | 1,037 | test given when then type: ignore given when then given when then | 65 | en | 0.199673 |
# -*- coding: utf-8 -*-
# Author:Qiujie Yao
# Email: yaoqiujie@gscopetech.com
# @Time: 2019-06-26 14:15
| VehicleInspection/apps/appointment/permissions.py | 106 | -*- coding: utf-8 -*- Author:Qiujie Yao Email: yaoqiujie@gscopetech.com @Time: 2019-06-26 14:15 | 95 | en | 0.378837 |
default_ids = [
[0x0E8D, 0x0003, -1], # MTK Brom
[0x0E8D, 0x6000, 2], # MTK Preloader
[0x0E8D, 0x2000, -1], # MTK Preloader
[0x0E8D, 0x2001, -1], # MTK Preloader
[0x0E8D, 0x20FF, -1], # MTK Preloader
[0x1004, 0x6000, 2], # LG Preloader
[0x22d9, 0x0006, -1], # OPPO Preloader
[0x0FCE, 0xF2... | mtkclient/config/usb_ids.py | 343 | MTK Brom MTK Preloader MTK Preloader MTK Preloader MTK Preloader LG Preloader OPPO Preloader Sony Brom | 102 | en | 0.156257 |
########################################### Global Variables #################################
#sklearn pickled SGDClassifier where pre-trained clf.coef_ matrix is casted to a scipy.sparse.csr_matrix for efficiency and scalability
clf = None
#sklearn pickled TfidfVectorizer
vectorizer = None
#dictionary of labelid: (la... | WLM-WLMN/TextAnalyzer/TextAnalyzer/Pigeo/pigeo-master/params.py | 766 | Global Variables sklearn pickled SGDClassifier where pre-trained clf.coef_ matrix is casted to a scipy.sparse.csr_matrix for efficiency and scalabilitysklearn pickled TfidfVectorizerdictionary of labelid: (latitude, longitude) It is pre-computed as the median value of all training points in a region/clusterdictionary o... | 529 | en | 0.775621 |
"""
We recover the original divergence-free velocity field via
Ud,new = Ustar - Gphi
"""
import numpy
import pylab
import operator
def do_plots_c(Ud, Unew):
""" plot Ud,new and Ud with zoom on the bug """
pylab.clf()
pylab.cla()
f = pylab.figure()
f.text(.5, .95, r"$U_{\rm d}... | homework5_elliptic_PDES/part_c.py | 1,328 | coordinates of centers
plot Ud,new and Ud with zoom on the bug
We recover the original divergence-free velocity field via
Ud,new = Ustar - Gphi | 150 | en | 0.583578 |
"""Module containing sacred functions for handling ML models."""
import inspect
from sacred import Ingredient
from src import models
ingredient = Ingredient('model')
@ingredient.config
def cfg():
"""Model configuration."""
name = ''
parameters = {
}
@ingredient.named_config
def TopologicalSurroga... | exp/ingredients/model.py | 5,965 | TopologicalSurrogateAutoencoder.
Model configuration.
Get an instance of a model according to parameters in the configuration.
Also, check if the provided parameters fit to the signature of the model
class and log default values if not defined via the configuration.
Module containing sacred functions for handling ML m... | 707 | en | 0.483371 |
# -*- coding: utf-8 -*-
#
# 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
#... | airflow/contrib/hooks/gcp_translate_hook.py | 3,820 | Hook for Google Cloud translate APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
Retrieves connection to Cloud Translate
:return: Google Cloud Translate client object.
:rtype: Client
Translate a string or list of strings.
See https://cloud.googl... | 2,638 | en | 0.715029 |
from os import path as op
import numpy as np
from numpy.polynomial import legendre
from numpy.testing import (assert_allclose, assert_array_equal, assert_equal,
assert_array_almost_equal)
from scipy.interpolate import interp1d
import pytest
import mne
from mne.forward import _make_surface_... | mne/forward/tests/test_field_interpolation.py | 11,370 | Configure args for test_as_meg_type_evoked.
Test interpolation of data on to virtual channels.
Test that field mapping can be done with CTF data.
Test Legendre table calculation.
Test Legendre polynomial (derivative) equivalence.
Test interpolation of EEG field onto head.
Test making a M/EEG field map onto helmet & hea... | 1,368 | en | 0.815386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.