max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
pkgs/ops-pkg/src/genie/libs/ops/dot1x/ios/tests/test_dot1x.py
jbronikowski/genielibs
94
9900
# Python import unittest from copy import deepcopy from unittest.mock import Mock # ATS from pyats.topology import Device # Genie from genie.libs.ops.dot1x.ios.dot1x import Dot1X from genie.libs.ops.dot1x.ios.tests.dot1x_output import Dot1xOutput # Parser from genie.libs.parser.ios.show_dot1x import ShowDot1xAllDeta...
# Python import unittest from copy import deepcopy from unittest.mock import Mock # ATS from pyats.topology import Device # Genie from genie.libs.ops.dot1x.ios.dot1x import Dot1X from genie.libs.ops.dot1x.ios.tests.dot1x_output import Dot1xOutput # Parser from genie.libs.parser.ios.show_dot1x import ShowDot1xAllDeta...
en
0.867709
# Python # ATS # Genie # Parser # Give the device as a connection type # This is done in order to call the parser on the output provided # Get outputs # Learn the feature # Verify Ops was created successfully # Check Selected Attributes # info - mdot1x default # Learn the feature # Check no attribute not found # Get ou...
2.401625
2
script/analysis/check_transformation_matrices.py
lanl/nubhlight
16
9901
# ====================================================================== # copyright 2020. Triad National Security, LLC. All rights # reserved. This program was produced under U.S. Government contract # 89233218CNA000001 for Los Alamos National Laboratory (LANL), which # is operated by Triad National Security, LLC for ...
# ====================================================================== # copyright 2020. Triad National Security, LLC. All rights # reserved. This program was produced under U.S. Government contract # 89233218CNA000001 for Los Alamos National Laboratory (LANL), which # is operated by Triad National Security, LLC for ...
en
0.697238
# ====================================================================== # copyright 2020. Triad National Security, LLC. All rights # reserved. This program was produced under U.S. Government contract # 89233218CNA000001 for Los Alamos National Laboratory (LANL), which # is operated by Triad National Security, LLC for ...
2.221071
2
holobot/discord/sdk/models/channel.py
rexor12/holobot
1
9902
<gh_stars>1-10 from dataclasses import dataclass @dataclass class Channel: id: str
from dataclasses import dataclass @dataclass class Channel: id: str
none
1
1.620115
2
pynet/models/braingengan.py
claireguichon/pynet
8
9903
<reponame>claireguichon/pynet # -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2020 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences...
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2020 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
en
0.569243
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2020 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
2.232651
2
research/object_detection/core/freezable_batch_norm_test.py
baranshad/models
3
9904
<filename>research/object_detection/core/freezable_batch_norm_test.py # Copyright 2018 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 # # htt...
<filename>research/object_detection/core/freezable_batch_norm_test.py # Copyright 2018 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 # # htt...
en
0.847373
# Copyright 2018 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...
2.34755
2
offspect/gui/VWidgets/message.py
translationalneurosurgery/tool-offspect
1
9905
<reponame>translationalneurosurgery/tool-offspect # from PyQt5.QtWidgets import QMessageBox # def raise_error(message: str = "DEFAULT:Error Description:More Information"): # box = QMessageBox() # kind, msg, info = message.split(":") # box.setIcon(QMessageBox.Critical) # box.setWindowTitle(kind + " Err...
# from PyQt5.QtWidgets import QMessageBox # def raise_error(message: str = "DEFAULT:Error Description:More Information"): # box = QMessageBox() # kind, msg, info = message.split(":") # box.setIcon(QMessageBox.Critical) # box.setWindowTitle(kind + " Error") # box.setText(msg) # box.setInformati...
en
0.254341
# from PyQt5.QtWidgets import QMessageBox # def raise_error(message: str = "DEFAULT:Error Description:More Information"): # box = QMessageBox() # kind, msg, info = message.split(":") # box.setIcon(QMessageBox.Critical) # box.setWindowTitle(kind + " Error") # box.setText(msg) # box.setInformative...
2.630445
3
Widen/LC759_Employee_Free_Time.py
crazywiden/Leetcode_daily_submit
0
9906
<filename>Widen/LC759_Employee_Free_Time.py """ 759. Employee Free Time We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing commo...
<filename>Widen/LC759_Employee_Free_Time.py """ 759. Employee Free Time We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing commo...
en
0.858313
759. Employee Free Time We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, ...
3.612826
4
storitch/config.py
thomaserlang/storitch
0
9907
<reponame>thomaserlang/storitch<filename>storitch/config.py import os, yaml config = { 'debug': False, 'port': 5000, 'store_path': '/var/storitch', 'pool_size': 5, 'logging': { 'level': 'warning', 'path': None, 'max_size': 100 * 1000 * 1000,# ~ 95 mb 'num_backups': 1...
import os, yaml config = { 'debug': False, 'port': 5000, 'store_path': '/var/storitch', 'pool_size': 5, 'logging': { 'level': 'warning', 'path': None, 'max_size': 100 * 1000 * 1000,# ~ 95 mb 'num_backups': 10, }, 'image_exts': [ '.jpg', '.jpeg', '.png...
none
1
2.140211
2
keras/lstm-securitai/model/pipeline_invoke_python.py
PipelineAI/models
44
9908
import io import os import numpy as np import pandas import json import logging #<== Optional. Log to console, file, kafka from pipeline_monitor import prometheus_monitor as monitor #<== Optional. Monitor runtime metrics from pipeline_logger import log import tenso...
import io import os import numpy as np import pandas import json import logging #<== Optional. Log to console, file, kafka from pipeline_monitor import prometheus_monitor as monitor #<== Optional. Monitor runtime metrics from pipeline_logger import log import tenso...
en
0.603857
#<== Optional. Log to console, file, kafka #<== Optional. Monitor runtime metrics #<== Optional. Being a good Python citizen. #<== Optional. Used for metrics/labels #<== Optional. Called once upon server startup Initialize / Restore Model Object. # This is called unconditionally at *module import time*... #@log(la...
2.265293
2
src/act/common/aCTReport.py
ATLASControlTower/aCT
0
9909
<reponame>ATLASControlTower/aCT import argparse import importlib import os import re import signal import subprocess import sys import time import logging from act.common import aCTLogger from act.common.aCTConfig import aCTConfigAPP from act.arc import aCTDBArc class aCTReport: '''Print summary info on jobs in D...
import argparse import importlib import os import re import signal import subprocess import sys import time import logging from act.common import aCTLogger from act.common.aCTConfig import aCTConfigAPP from act.arc import aCTDBArc class aCTReport: '''Print summary info on jobs in DB. Use --web to print html that ...
en
0.827053
Print summary info on jobs in DB. Use --web to print html that is automatically refreshed. Add filenames to query more than one aCT DB # empty string for default behaviour # don't print processes for combined report # Group processes by cluster # ignore Main and this process # Check for overrunning processes # Kill...
2.198004
2
unittests/test_apiv2_user.py
mtcolman/django-DefectDojo
249
9910
<reponame>mtcolman/django-DefectDojo from rest_framework.test import APITestCase, APIClient from django.urls import reverse from rest_framework.authtoken.models import Token class UserTest(APITestCase): """ Test the User APIv2 endpoint. """ fixtures = ['dojo_testdata.json'] def setUp(self): ...
from rest_framework.test import APITestCase, APIClient from django.urls import reverse from rest_framework.authtoken.models import Token class UserTest(APITestCase): """ Test the User APIv2 endpoint. """ fixtures = ['dojo_testdata.json'] def setUp(self): token = Token.objects.get(user__us...
en
0.85167
Test the User APIv2 endpoint. # simple user without password # user with good password #$' # test password by fetching API key # user with weak password # some user #$" #$"
2.7547
3
src/init.py
ankit-kushwaha-51/RESTful_API
0
9911
<reponame>ankit-kushwaha-51/RESTful_API from flask import Flask from src.models import db from . import config def create_app(): flask_app = Flask(__name__) flask_app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_CONNECTION_URI flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False flask_ap...
from flask import Flask from src.models import db from . import config def create_app(): flask_app = Flask(__name__) flask_app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_CONNECTION_URI flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False flask_app.app_context().push() db.init_app(f...
none
1
2.248958
2
tests/helpers/examples/order/tasks.py
nicoddemus/dependencies
0
9912
<filename>tests/helpers/examples/order/tasks.py<gh_stars>0 from dependencies import Injector from dependencies import this from dependencies.contrib.celery import shared_task from examples.order.commands import ProcessOrder @shared_task class ProcessOrderTask(Injector): name = "process_order" run = ProcessOr...
<filename>tests/helpers/examples/order/tasks.py<gh_stars>0 from dependencies import Injector from dependencies import this from dependencies.contrib.celery import shared_task from examples.order.commands import ProcessOrder @shared_task class ProcessOrderTask(Injector): name = "process_order" run = ProcessOr...
none
1
1.64534
2
001 - 050/ex032.py
SocrammBR/Desafios-Python-CursoEmVideo
0
9913
ano = int(input('Digite o ano: ')) if (ano%4) == 0: print ('Ele é bissexto') else: print ('Ele não é bissexto')
ano = int(input('Digite o ano: ')) if (ano%4) == 0: print ('Ele é bissexto') else: print ('Ele não é bissexto')
none
1
3.734377
4
rn/__init__.py
vikneswaran20/rn
0
9914
<reponame>vikneswaran20/rn __version__ = '0.0.1' __license__ = 'BSD'
__version__ = '0.0.1' __license__ = 'BSD'
none
1
0.975119
1
flexmeasures/cli/data_edit.py
FlexMeasures/flexmeasures
12
9915
from datetime import timedelta from typing import Union, List, Optional import click import pandas as pd from flask import current_app as app from flask.cli import with_appcontext from flexmeasures import Sensor from flexmeasures.data import db from flexmeasures.data.schemas.generic_assets import GenericAssetIdField ...
from datetime import timedelta from typing import Union, List, Optional import click import pandas as pd from flask import current_app as app from flask.cli import with_appcontext from flexmeasures import Sensor from flexmeasures.data import db from flexmeasures.data.schemas.generic_assets import GenericAssetIdField ...
en
0.757261
FlexMeasures: Edit data. Edit (or add) an asset attribute or sensor attribute. # Parse attribute value # Set attribute Assign a new event resolution to an existing sensor and resample its data accordingly. # note that "" or None becomes NaT # Update sensor # Update sensor data Parse attribute value.
2.274544
2
semana2/mail_settings.py
ArseniumGX/bluemer-modulo2
0
9916
mail_settings = { "MAIL_SERVER": 'smtp.gmail.com', "MAIL_PORT": 465, "MAIL_USE_TLS": False, "MAIL_USE_SSL": True, "MAIL_USERNAME": '<EMAIL>', "MAIL_PASSWORD": '<PASSWORD>' }
mail_settings = { "MAIL_SERVER": 'smtp.gmail.com', "MAIL_PORT": 465, "MAIL_USE_TLS": False, "MAIL_USE_SSL": True, "MAIL_USERNAME": '<EMAIL>', "MAIL_PASSWORD": '<PASSWORD>' }
none
1
1.204269
1
frame/base/parser.py
dingjingmaster/blog_spider
0
9917
#!/usr/bin/env python3.6 # -*- encoding=utf8 -*- import pyquery """ 需求字段: 標題、發表日期、分類、標籤、內容、圖片 需要的字段信息 1. 网站根URL 2. 解析器名字 3. 解析器类型 1. PARSER_PASSAGE_URL 文章URL 2. PARSER_PASSAGE_TITLE 文章标题 3. PARSER_PASSAGE_DATE ...
#!/usr/bin/env python3.6 # -*- encoding=utf8 -*- import pyquery """ 需求字段: 標題、發表日期、分類、標籤、內容、圖片 需要的字段信息 1. 网站根URL 2. 解析器名字 3. 解析器类型 1. PARSER_PASSAGE_URL 文章URL 2. PARSER_PASSAGE_TITLE 文章标题 3. PARSER_PASSAGE_DATE ...
zh
0.734618
#!/usr/bin/env python3.6 # -*- encoding=utf8 -*- 需求字段: 標題、發表日期、分類、標籤、內容、圖片 需要的字段信息 1. 网站根URL 2. 解析器名字 3. 解析器类型 1. PARSER_PASSAGE_URL 文章URL 2. PARSER_PASSAGE_TITLE 文章标题 3. PARSER_PASSAGE_DATE 发表日期 ...
2.791188
3
tools/mkblocks.py
Commodore-Bench/u5remastered
14
9918
<filename>tools/mkblocks.py #!/usr/bin/env python3 # ---------------------------------------------------------------------------- # Copyright 2019 Drunella # # 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 t...
<filename>tools/mkblocks.py #!/usr/bin/env python3 # ---------------------------------------------------------------------------- # Copyright 2019 Drunella # # 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 t...
en
0.561158
#!/usr/bin/env python3 # ---------------------------------------------------------------------------- # Copyright 2019 Drunella # # 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://...
2.424695
2
src/apetest/decode.py
boxingbeetle/apetest
6
9919
<gh_stars>1-10 # SPDX-License-Identifier: BSD-3-Clause """ Text decode functions. These functions can be used to get Unicode strings from a series of bytes. """ from codecs import ( BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE, CodecInfo, lookup as lookup_codec, ) from...
# SPDX-License-Identifier: BSD-3-Clause """ Text decode functions. These functions can be used to get Unicode strings from a series of bytes. """ from codecs import ( BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE, CodecInfo, lookup as lookup_codec, ) from collections im...
en
0.810754
# SPDX-License-Identifier: BSD-3-Clause Text decode functions. These functions can be used to get Unicode strings from a series of bytes. Look for a byte-order-marker at the start of the given C{bytes}. If found, return the encoding matching that BOM, otherwise return C{None}. Map a codec name to the preferred sta...
3.152421
3
utils.py
jiangycTarheel/Compositional-Auxseq
8
9920
import os import json import gzip from copy import deepcopy, copy import numpy as np import csv import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler from transformers.tokenization_utils import trim_batch class LabelSmoothingLoss(nn.Module)...
import os import json import gzip from copy import deepcopy, copy import numpy as np import csv import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader, RandomSampler from transformers.tokenization_utils import trim_batch class LabelSmoothingLoss(nn.Module)...
en
0.447558
Args: pred: [bsz, seq_len, vocab_size] target: [bsz, seq_len] Returns: # [bsz, seq_len, vocab_size] #return F.kl_div(pred_prob, model_prob, reduction='mean') # Special symbols # start of sentence # end of sentence # padding symbol # ACTION_TO_TEXT = {'I_TURN_RIGHT': 'right', 'I_JUMP': '...
2.324399
2
bridger/serializers/fields/related.py
intellineers/django-bridger
2
9921
from typing import Dict from rest_framework import serializers from rest_framework.fields import empty from rest_framework.relations import ManyRelatedField from rest_framework.request import Request from .mixins import BridgerSerializerFieldMixin from .types import BridgerType, ReturnContentType class BridgerManyR...
from typing import Dict from rest_framework import serializers from rest_framework.fields import empty from rest_framework.relations import ManyRelatedField from rest_framework.request import Request from .mixins import BridgerSerializerFieldMixin from .types import BridgerType, ReturnContentType class BridgerManyR...
en
0.831966
# If the data is send through form data, we need to convert the data into a proper list of ids # If the data is a list of an empty string we need to convert it (FORM DATA) # If the data is a list and contains the string null, then we need to convert it (FORM DATA) # If the data is None and null is an allowed value, dat...
2.31075
2
python/graphscope/experimental/nx/tests/algorithms/forward/operators/test_product.py
wenyuanyu/GraphScope
2
9922
<filename>python/graphscope/experimental/nx/tests/algorithms/forward/operators/test_product.py import networkx.algorithms.operators.tests.test_product import pytest from graphscope.experimental.nx.utils.compat import import_as_graphscope_nx import_as_graphscope_nx(networkx.algorithms.operators.tests.test_product, ...
<filename>python/graphscope/experimental/nx/tests/algorithms/forward/operators/test_product.py import networkx.algorithms.operators.tests.test_product import pytest from graphscope.experimental.nx.utils.compat import import_as_graphscope_nx import_as_graphscope_nx(networkx.algorithms.operators.tests.test_product, ...
en
0.921513
# basic smoke test, more realistic tests would be useful
2.36023
2
Footy/UnsupportedBantzStrings.py
schleising/banter-bot
0
9923
<reponame>schleising/banter-bot # {team} -> Name of team # {name} -> Name of person who supports team teamMatchStarted: list[str] = [ "{team} are shit", "{team} cunts", "Dirty {team}", "Dirty {team}, dirty {name}", ] drawing: list[str] = [ "{team} level, this is a shit match", "Boring old {tea...
# {team} -> Name of team # {name} -> Name of person who supports team teamMatchStarted: list[str] = [ "{team} are shit", "{team} cunts", "Dirty {team}", "Dirty {team}, dirty {name}", ] drawing: list[str] = [ "{team} level, this is a shit match", "Boring old {team}", "Happy with how it's go...
en
0.885788
# {team} -> Name of team # {name} -> Name of person who supports team
3.405827
3
bench/fibrec.py
codr7/alisp
8
9924
from bench import bench print(bench(100, ''' def fib(n): return n if n < 2 else fib(n-1) + fib(n-2) ''', ''' fib(20) '''))
from bench import bench print(bench(100, ''' def fib(n): return n if n < 2 else fib(n-1) + fib(n-2) ''', ''' fib(20) '''))
en
0.141179
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2) fib(20)
2.888842
3
nlpir/native/classifier.py
NLPIR-team/nlpir-python
18
9925
# coding=utf-8 from nlpir.native.nlpir_base import NLPIRBase from ctypes import c_bool, c_char_p, c_int, POINTER, Structure, c_float class StDoc(Structure): __fields__ = [ ("sTitle", c_char_p), ("sContent", c_char_p), ("sAuthor", c_char_p), ("sBoard", c_char_p), ("sDatatype...
# coding=utf-8 from nlpir.native.nlpir_base import NLPIRBase from ctypes import c_bool, c_char_p, c_int, POINTER, Structure, c_float class StDoc(Structure): __fields__ = [ ("sTitle", c_char_p), ("sContent", c_char_p), ("sAuthor", c_char_p), ("sBoard", c_char_p), ("sDatatype...
zh
0.614864
# coding=utf-8 Call **classifier_init** :param data_path: :param encode: :param license_code: :return: 1 success 0 fail Call **classifier_exit** :return: exit success or not Call **classifier_exec1** 对输入的文章结构进行分类 :param data: 文章结构 :param out_type: 输出是否...
2.313889
2
tests/param/get_param_type_spec_test.py
nickgaya/bravado-core
122
9926
# -*- coding: utf-8 -*- import pytest from mock import Mock from bravado_core.exception import SwaggerMappingError from bravado_core.operation import Operation from bravado_core.param import get_param_type_spec from bravado_core.param import Param from bravado_core.spec import Spec @pytest.fixture def body_param_spe...
# -*- coding: utf-8 -*- import pytest from mock import Mock from bravado_core.exception import SwaggerMappingError from bravado_core.operation import Operation from bravado_core.param import get_param_type_spec from bravado_core.param import Param from bravado_core.spec import Spec @pytest.fixture def body_param_spe...
en
0.769321
# -*- coding: utf-8 -*-
2.073619
2
functions/markdown-to-html/markdown2html.py
truls/faas-profiler
0
9927
# Copyright (c) 2019 Princeton University # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from markdown import markdown import base64 import json import base64 def main(params): try: md = json.loads(base64.decodebytes(params["__...
# Copyright (c) 2019 Princeton University # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from markdown import markdown import base64 import json import base64 def main(params): try: md = json.loads(base64.decodebytes(params["__...
en
0.89182
# Copyright (c) 2019 Princeton University # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
2.832717
3
Python Files/Dataset_Formating/Audio_splicing.py
brennanMosher/Music-Genre-Recognition-using-a-Machine-Learning-Appraoch
1
9928
from pydub import AudioSegment import os import math from pathlib import Path ''' Splice wav files into multiple segments. ''' LENGTH = 3 # Set splice length in seconds def splice(audioPath, outputPath): # try: # os.mkdir('Spliced Spectrogram training') # Need to figure out where to put this # excep...
from pydub import AudioSegment import os import math from pathlib import Path ''' Splice wav files into multiple segments. ''' LENGTH = 3 # Set splice length in seconds def splice(audioPath, outputPath): # try: # os.mkdir('Spliced Spectrogram training') # Need to figure out where to put this # excep...
en
0.822219
Splice wav files into multiple segments. # Set splice length in seconds # try: # os.mkdir('Spliced Spectrogram training') # Need to figure out where to put this # except OSError: # print("Creation of the directory failed") # Do we want the last part of audio?
3.445538
3
manpages.py
mba811/dash-manpages-zh
1
9929
<reponame>mba811/dash-manpages-zh #!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: <NAME> @contact: @date: 2014/06/23 """ import os import sqlite3 import urllib2 import shutil import tarfile import hashlib import codecs from mako.template import Template from pyquery import PyQuery currentPath = os.path.j...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: <NAME> @contact: @date: 2014/06/23 """ import os import sqlite3 import urllib2 import shutil import tarfile import hashlib import codecs from mako.template import Template from pyquery import PyQuery currentPath = os.path.join(os.path.dirname(os.path.realpa...
en
0.252843
#!/usr/bin/env python # -*- coding: utf-8 -*- @author: <NAME> @contact: @date: 2014/06/23 # Step 2: Copy the HTML Documentation # Step 3: create the Info.plist file <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <key>CFBundleIdentifier</key> <string>${name}</string> <key>CFBundleName</key> <string...
2.285386
2
docs/conf.py
alexweav/nisystemlink-clients-python
0
9930
<reponame>alexweav/nisystemlink-clients-python import os import sys sys.path.insert(0, os.path.abspath("..")) # -------------------------------------------------------------------------------------- project = "nisystemlink" copyright = "2020, National Instruments" author = "National Instruments" # The short X.Y ver...
import os import sys sys.path.insert(0, os.path.abspath("..")) # -------------------------------------------------------------------------------------- project = "nisystemlink" copyright = "2020, National Instruments" author = "National Instruments" # The short X.Y version version = "0.1" # The full version, includ...
en
0.520518
# -------------------------------------------------------------------------------------- # The short X.Y version # The full version, including alpha/beta/rc tags # -------------------------------------------------------------------------------------- # Don't let napoleon force methods to be included in the docs; use au...
1.724703
2
multinet/api/views/common.py
multinet-app/multinet-api
0
9931
from typing import Dict, List from arango.cursor import Cursor from django.http.response import Http404 from django.shortcuts import get_object_or_404 from rest_framework.pagination import LimitOffsetPagination from rest_framework.request import Request from rest_framework_extensions.mixins import NestedViewSetMixin ...
from typing import Dict, List from arango.cursor import Cursor from django.http.response import Http404 from django.shortcuts import get_object_or_404 from rest_framework.pagination import LimitOffsetPagination from rest_framework.request import Request from rest_framework_extensions.mixins import NestedViewSetMixin ...
en
0.842123
Override the LimitOffsetPagination class to allow for use with arango cursors. Get the queryset for workspace child enpoints. Check that the requeting user has appropriate permissions for the associated workspace. # prevent warning for schema generation incompatibility # No user or user permission required for...
1.976589
2
scripts/tests/generate_host_files.py
NDevTK/cel
0
9932
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import logging import os import sys def ParseArgs(): parser = argparse.ArgumentParser( description='Host file generator for CELab E...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import logging import os import sys def ParseArgs(): parser = argparse.ArgumentParser( description='Host file generator for CELab E...
en
0.903939
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Generate all the host files based off the arguments passed.
2.436458
2
users/models.py
moshthepitt/probsc
0
9933
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from django.urls import reverse from django_extensions.db.models import TimeStampedModel from mptt.models import MPTTModel, TreeForeignKey ...
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from django.urls import reverse from django_extensions.db.models import TimeStampedModel from mptt.models import MPTTModel, TreeForeignKey ...
en
0.822206
Departments in an organisation Job positions in an organisation Model used to store more information on users Returns a queryset of UserProfile objects which report to this userprofile # get job positions of subs # get any position that may report to these positions # list of position ids of Positions that repo...
2.158536
2
azure-devops/azure/devops/released/build/build_client.py
imafidon2020/azure-devops-python-api
248
9934
<filename>azure-devops/azure/devops/released/build/build_client.py # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ...
<filename>azure-devops/azure/devops/released/build/build_client.py # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ...
en
0.613944
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
2.117377
2
tests/test_train.py
hugobb/sgda
1
9935
import unittest from gamesopt.train import train, TrainConfig class TestOptimizer(unittest.TestCase): def test_sgda(self): config = TrainConfig(num_iter=2) train(config)
import unittest from gamesopt.train import train, TrainConfig class TestOptimizer(unittest.TestCase): def test_sgda(self): config = TrainConfig(num_iter=2) train(config)
none
1
2.310287
2
loadCSVdata.py
christostsekouronas/academyposttestanalysis
0
9936
<filename>loadCSVdata.py import pandas as pd def loadTest(filepath): df = pd.read_csv(filepath) return df
<filename>loadCSVdata.py import pandas as pd def loadTest(filepath): df = pd.read_csv(filepath) return df
none
1
2.417324
2
sdk/applicationinsights/azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/v2015_05_01/models/_application_insights_management_client_enums.py
iscai-msft/azure-sdk-for-python
8
9937
# 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 ...
# 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 ...
en
0.583126
# 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 ...
2.01122
2
setup.py
dhruvdcoder/allennlp-wandb
0
9938
<reponame>dhruvdcoder/allennlp-wandb from setuptools import setup, find_packages install_requires = [ "allennlp>=0.9.0", "wandb==0.8.15", ] setup( name='allennlp_wandb', version='0.0.1', description='Utilities to use allennlp with wandb', packages=find_packages( exclude=["*.tests", "*....
from setuptools import setup, find_packages install_requires = [ "allennlp>=0.9.0", "wandb==0.8.15", ] setup( name='allennlp_wandb', version='0.0.1', description='Utilities to use allennlp with wandb', packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), p...
none
1
1.446868
1
setup.py
mark-mishyn/django-axes
0
9939
<gh_stars>0 #!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-axes", description="Keep track of failed login attempts in Django-powered sites.", long_description="\n".join( [ open("README.rst", encoding="utf-8").read(), open("CHANGES.rst"...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-axes", description="Keep track of failed login attempts in Django-powered sites.", long_description="\n".join( [ open("README.rst", encoding="utf-8").read(), open("CHANGES.rst", encoding="...
ru
0.26433
#!/usr/bin/env python
1.299096
1
achievements/admin.py
peterkrauz/rpg-achievements-django
1
9940
<reponame>peterkrauz/rpg-achievements-django<filename>achievements/admin.py from django.contrib import admin from achievements import models admin.site.register(models.Achievement)
from django.contrib import admin from achievements import models admin.site.register(models.Achievement)
none
1
1.244523
1
src/modules/loss.py
ab3llini/BlindLess
1
9941
<gh_stars>1-10 from torch.nn import CrossEntropyLoss class GPT2Loss(CrossEntropyLoss): def __init__(self, pad_token_id): super(GPT2Loss, self).__init__(ignore_index=pad_token_id) def forward(self, output, labels): """ Loss function for gpt2 :param output: :param labels...
from torch.nn import CrossEntropyLoss class GPT2Loss(CrossEntropyLoss): def __init__(self, pad_token_id): super(GPT2Loss, self).__init__(ignore_index=pad_token_id) def forward(self, output, labels): """ Loss function for gpt2 :param output: :param labels: :retu...
en
0.572096
Loss function for gpt2 :param output: :param labels: :return: # Flatten the tensors (shift-align) # Remove last token from output # Remove the first token from labels e do not care for question # Compute the actual loss # Compute the actual loss Loss function for gpt2 :param output: ...
2.544577
3
analyze_tls.py
khushhallchandra/CN-project
0
9942
<gh_stars>0 import numpy as np import pandas as pd import matplotlib.pyplot as plt def main(filename): data = pd.read_csv(filename, header=None) means = data.mean(axis = 0) stds = data.std(axis = 0) return means[0], means[1], stds[0], stds[1] if __name__ == '__main__': files_http1 = ['./results/b...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def main(filename): data = pd.read_csv(filename, header=None) means = data.mean(axis = 0) stds = data.std(axis = 0) return means[0], means[1], stds[0], stds[1] if __name__ == '__main__': files_http1 = ['./results/benchmark_siz...
en
0.219685
# ax.errorbar(x, time_contentTransfer_http2, yerr=std_contentTransfer_http2, fmt='-', color='r', label="HTTP2") # ax.errorbar(x, time_contentTransfer_quic, yerr=std_contentTransfer_quic, fmt='-', color='b', label="QUIC") # ax.errorbar(x, time_tot_http2, yerr=std_tot_http2, fmt='-', color='r', label="HTTP2") # ax.errorb...
2.656194
3
validation/utils/m1.py
PedrV/stfX
0
9943
<filename>validation/utils/m1.py import unittest import os from matplotlib import pyplot as plt from shapely import geometry, affinity X_COORDINATE = 0 Y_COORDINATE = 1 def extract_x_y(polygon: list) -> (list, list): """Extract the x and y coordinates as two separate lists""" x_list = [] y_list = [] ...
<filename>validation/utils/m1.py import unittest import os from matplotlib import pyplot as plt from shapely import geometry, affinity X_COORDINATE = 0 Y_COORDINATE = 1 def extract_x_y(polygon: list) -> (list, list): """Extract the x and y coordinates as two separate lists""" x_list = [] y_list = [] ...
en
0.809982
Extract the x and y coordinates as two separate lists Save the current plt figure in the given directory under the name: m1.png Plot the given two polygons, in a single figure, with different colors # Figure settings # fig.suptitle('Convex hull area (red) VS real representation area (blue)') # Plotting hulls # Plotting...
2.769521
3
movefiles.py
linhailan/JPG-PNG-to-MNIST-NN-Format
0
9944
<reponame>linhailan/JPG-PNG-to-MNIST-NN-Format import os from PIL import Image from array import * from random import shuffle import shutil def move_file(src_path, dst_path, file): print("from : ",src_path) print("to : ",dst_path) try: # cmd = 'chmod -R +x ' + src_path # os.popen(cmd) ...
import os from PIL import Image from array import * from random import shuffle import shutil def move_file(src_path, dst_path, file): print("from : ",src_path) print("to : ",dst_path) try: # cmd = 'chmod -R +x ' + src_path # os.popen(cmd) f_src = os.path.join(src_path, file) ...
en
0.718689
# cmd = 'chmod -R +x ' + src_path # os.popen(cmd) # Load from and save to
2.67991
3
spark_work.py
nszceta/spark-python-celery-demo
8
9945
<reponame>nszceta/spark-python-celery-demo import sys from pyspark import SparkContext import json print('spark got python path -> ' + str(sys.executable)) logfile = sys.argv[1] sc = SparkContext() logdata = sc.textFile(logfile).cache() a_count = logdata.filter(lambda s: 'a' in s).count() b_count = logdata.filter(lambd...
import sys from pyspark import SparkContext import json print('spark got python path -> ' + str(sys.executable)) logfile = sys.argv[1] sc = SparkContext() logdata = sc.textFile(logfile).cache() a_count = logdata.filter(lambda s: 'a' in s).count() b_count = logdata.filter(lambda s: 'b' in s).count() print(json.dumps({'a...
none
1
2.63323
3
nodes/List/GetTaskRenderListIndex.py
atticus-lv/RenderNode
17
9946
import bpy from bpy.props import * from ...nodes.BASE.node_base import RenderNodeBase class RenderNodeGetListIndex(RenderNodeBase): """A simple input node""" bl_idname = 'RenderNodeGetListIndex' bl_label = 'Get List Index' def init(self, context): self.create_output('RenderNodeSocketInt', "i...
import bpy from bpy.props import * from ...nodes.BASE.node_base import RenderNodeBase class RenderNodeGetListIndex(RenderNodeBase): """A simple input node""" bl_idname = 'RenderNodeGetListIndex' bl_label = 'Get List Index' def init(self, context): self.create_output('RenderNodeSocketInt', "i...
ru
0.108344
A simple input node
2.21483
2
src/recognizeDigit.py
RsTaK/Sudoku
2
9947
from keras.models import load_model import cv2 import pickle import keras.backend as K import numpy as np from src.model_path import MODEL_PATH '''def predict(self, cell): model = load_model('./model/Model.h5') f = K.function([model.layers[0].input, K.learning_phase()],[model.layers[-1].output]) rescaled_cell = ...
from keras.models import load_model import cv2 import pickle import keras.backend as K import numpy as np from src.model_path import MODEL_PATH '''def predict(self, cell): model = load_model('./model/Model.h5') f = K.function([model.layers[0].input, K.learning_phase()],[model.layers[-1].output]) rescaled_cell = ...
en
0.232765
def predict(self, cell): model = load_model('./model/Model.h5') f = K.function([model.layers[0].input, K.learning_phase()],[model.layers[-1].output]) rescaled_cell = self.rescale(cell) result = [] for _ in range(10): result.append(f([rescaled_cell, 1])) result = np.array(result) prediction = res...
2.821057
3
plots.py
olihawkins/penguin-models
1
9948
# -*- coding: utf-8 -*- """A module for plotting penguins data for modelling with scikit-learn.""" # Imports --------------------------------------------------------------------- import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd # Constants -----------------------------...
# -*- coding: utf-8 -*- """A module for plotting penguins data for modelling with scikit-learn.""" # Imports --------------------------------------------------------------------- import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd # Constants -----------------------------...
en
0.495892
# -*- coding: utf-8 -*- A module for plotting penguins data for modelling with scikit-learn. # Imports --------------------------------------------------------------------- # Constants ------------------------------------------------------------------- # Set style -------------------------------------------------------...
3.1296
3
dojo/db_migrations/0147_rename_sslyze_parser.py
dant24/django-DefectDojo
249
9949
<filename>dojo/db_migrations/0147_rename_sslyze_parser.py from django.db import migrations def rename_sslyze_parser(apps, schema_editor): Test_Type_model = apps.get_model('dojo', 'Test_Type') try: test_type_sslyze = Test_Type_model.objects.get(name='SSLyze 3 Scan (JSON)') test_type_sslyze.name...
<filename>dojo/db_migrations/0147_rename_sslyze_parser.py from django.db import migrations def rename_sslyze_parser(apps, schema_editor): Test_Type_model = apps.get_model('dojo', 'Test_Type') try: test_type_sslyze = Test_Type_model.objects.get(name='SSLyze 3 Scan (JSON)') test_type_sslyze.name...
en
0.902714
# This happens when a new instance of DD is initialized
1.908974
2
server/forestgame/game/test_world.py
Nick-Pearson/forestgame
0
9950
import unittest from forestgame.game.world import World class WorldTest(unittest.TestCase): def test_world_inits_to_empty_data(self): world = World(None, "1", "0", 0, 0, [], []) self.assertEqual(0, world.get_size_x()) self.assertEqual(0, world.get_size_y()) self.assertEqual([], world.get_tile_data(...
import unittest from forestgame.game.world import World class WorldTest(unittest.TestCase): def test_world_inits_to_empty_data(self): world = World(None, "1", "0", 0, 0, [], []) self.assertEqual(0, world.get_size_x()) self.assertEqual(0, world.get_size_y()) self.assertEqual([], world.get_tile_data(...
en
0.422011
# set tile range checks
3.479223
3
invconv/xlsx.py
TechPowerAwaits/ax-toolkit
0
9951
# Copyright 2021 <NAME> <<EMAIL>> # SPDX-license-identifier: 0BSD import string from loguru import logger try: import cell_pos from exceptions import InvconvMissingHeaders import ftype import msg_handler except ModuleNotFoundError: import invconv.cell_pos as cell_pos from invconv.exceptions i...
# Copyright 2021 <NAME> <<EMAIL>> # SPDX-license-identifier: 0BSD import string from loguru import logger try: import cell_pos from exceptions import InvconvMissingHeaders import ftype import msg_handler except ModuleNotFoundError: import invconv.cell_pos as cell_pos from invconv.exceptions i...
en
0.902773
# Copyright 2021 <NAME> <<EMAIL>> # SPDX-license-identifier: 0BSD # load_workbook is used repeatedly with similar settings # every time. # Set relevant values and gets the number of operations # to be performed based on the dimensions. # Will store a file, worksheet tuple-like class # with additional data accessible. #...
2.083139
2
solvers/generation_solver/img_interface.py
Anthony102899/Lego-ImageGenerator
1
9952
import os from tkinter import * import tkinter.filedialog as tkfd from PIL import Image import numpy as np import solvers.generation_solver.image_seperation as IS def layer_interface(img_num): layer_names = [] layer_nums = [] for k in range(img_num): master = Toplevel() master.title(f"Imag...
import os from tkinter import * import tkinter.filedialog as tkfd from PIL import Image import numpy as np import solvers.generation_solver.image_seperation as IS def layer_interface(img_num): layer_names = [] layer_nums = [] for k in range(img_num): master = Toplevel() master.title(f"Imag...
en
0.450673
# input image and layer # input No. image and button # input background color # input rotation and scaling # input translation
2.988318
3
Constellations/get_brightest_stars.py
PatD123/Polar-Constellation
0
9953
<filename>Constellations/get_brightest_stars.py<gh_stars>0 from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import re, json # Getting the page URL = "https://www.astronomytrek.com/star-constellations-brightest-stars/" uClient = uReq(url=URL) page_html = uClient.read() page_soup = soup(p...
<filename>Constellations/get_brightest_stars.py<gh_stars>0 from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import re, json # Getting the page URL = "https://www.astronomytrek.com/star-constellations-brightest-stars/" uClient = uReq(url=URL) page_html = uClient.read() page_soup = soup(p...
en
0.891561
# Getting the page # Opening a file to write in #
3.192519
3
TwoPointers/Leetcode11.py
Rylie-W/LeetRecord
0
9954
class Solution: def maxArea(self, height) -> int: left=0 right=len(height)-1 res=min(height[left],height[right])*(right-left) while right>left: res=max(res,(right-left)*min(height[right],height[left])) if height[left]<height[right]: left+=1 ...
class Solution: def maxArea(self, height) -> int: left=0 right=len(height)-1 res=min(height[left],height[right])*(right-left) while right>left: res=max(res,(right-left)*min(height[right],height[left])) if height[left]<height[right]: left+=1 ...
en
0.267327
# height = [1, 1]
3.37379
3
tensorflow_text/python/ops/bert_tokenizer_test.py
hashim361/text
1
9955
# coding=utf-8 # Copyright 2020 TF.Text 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 ag...
# coding=utf-8 # Copyright 2020 TF.Text 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 ag...
en
0.655648
# coding=utf-8 # Copyright 2020 TF.Text 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 ag...
2.405519
2
tests/index_test.py
DubeySandeep/pending-review-notification
0
9956
<filename>tests/index_test.py """Unit test for the index.py file.""" import unittest from datetime import datetime, timedelta, timezone import json from unittest.mock import patch, mock_open import requests_mock from src import index from src import github_services class ModuleIntegerationTest(unittest.TestCase): ...
<filename>tests/index_test.py """Unit test for the index.py file.""" import unittest from datetime import datetime, timedelta, timezone import json from unittest.mock import patch, mock_open import requests_mock from src import index from src import github_services class ModuleIntegerationTest(unittest.TestCase): ...
en
0.564575
Unit test for the index.py file. Integeration test for the send notification feature. #123](https://githuburl.pull/123) ' #234](https://githuburl.pull/234) ' #123](https://githuburl.pull/123) '
2.891431
3
rqalpha/data/instrument_mixin.py
mysky528/rqalpha
3
9957
<gh_stars>1-10 # -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, 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...
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, 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 ...
en
0.717039
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, 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 ...
2.039205
2
Python 3/19.prac_no2.py
ByeonUi-Hyeok/practice
1
9958
import funcvote as vote votes = input("투표내용 >>>") # print(votes) # print(type(votes)) result = vote.str2int(votes) print(vote.countvotes(result)) result = vote.countvotes(result) vote.printvote(result) # 투표 초안
import funcvote as vote votes = input("투표내용 >>>") # print(votes) # print(type(votes)) result = vote.str2int(votes) print(vote.countvotes(result)) result = vote.countvotes(result) vote.printvote(result) # 투표 초안
en
0.635178
# print(votes) # print(type(votes)) # 투표 초안
3.411888
3
tutorials/30-days-of-code/30-operators.py
PingHuskar/hackerrank
41
9959
<filename>tutorials/30-days-of-code/30-operators.py # Day 2: Operators # Start using arithmetic operators. # # https://www.hackerrank.com/challenges/30-operators/problem # #!/bin/python3 import sys if __name__ == "__main__": meal_cost = float(input().strip()) tip_percent = int(input().strip()) tax_percen...
<filename>tutorials/30-days-of-code/30-operators.py # Day 2: Operators # Start using arithmetic operators. # # https://www.hackerrank.com/challenges/30-operators/problem # #!/bin/python3 import sys if __name__ == "__main__": meal_cost = float(input().strip()) tip_percent = int(input().strip()) tax_percen...
en
0.617835
# Day 2: Operators # Start using arithmetic operators. # # https://www.hackerrank.com/challenges/30-operators/problem # #!/bin/python3
4.146666
4
articles/views.py
qwghlm/CommentIsMee
0
9960
from django.http import HttpResponse from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404, redirect from django.core.urlresolvers import reverse from django.core.cache import cache from articles.models import CIFArticle from .forms import CIFArticleForm def index(r...
from django.http import HttpResponse from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404, redirect from django.core.urlresolvers import reverse from django.core.cache import cache from articles.models import CIFArticle from .forms import CIFArticleForm def index(r...
en
0.856561
Handle requests to the homepage # If a user has submitted a URL... # If no URL submitted, just set up a blank form # If an article is found or created due to a user submission, redirect there # Else show the homepage & rendered form Handle detail view for an article # Quite simple, set up article and form
2.357103
2
utils/runtime_mode.py
omiderfanmanesh/dengue-infections-prediction
0
9961
<gh_stars>0 # Copyright (c) 2021, <NAME>, All rights reserved. class RuntimeMode: TRAIN = 0 TUNING = 1 CROSS_VAL = 2 FEATURE_IMPORTANCE = 3
# Copyright (c) 2021, <NAME>, All rights reserved. class RuntimeMode: TRAIN = 0 TUNING = 1 CROSS_VAL = 2 FEATURE_IMPORTANCE = 3
en
0.906055
# Copyright (c) 2021, <NAME>, All rights reserved.
1.375117
1
pydoc_fork/__main__.py
matthewdeanmartin/pydoc_fork
0
9962
<gh_stars>0 # noinspection PyPep8 """pydoc_fork A fork of pydoc that is optimized for generating html documentation in a CI context Usage: pydoc_fork <package>... [options] pydoc_fork (-h | --help) pydoc_fork --version Options: -h --help Show this screen. -v --version Show...
# noinspection PyPep8 """pydoc_fork A fork of pydoc that is optimized for generating html documentation in a CI context Usage: pydoc_fork <package>... [options] pydoc_fork (-h | --help) pydoc_fork --version Options: -h --help Show this screen. -v --version Show version. ...
en
0.317534
# noinspection PyPep8 pydoc_fork A fork of pydoc that is optimized for generating html documentation in a CI context Usage: pydoc_fork <package>... [options] pydoc_fork (-h | --help) pydoc_fork --version Options: -h --help Show this screen. -v --version Show version. --q...
2.280258
2
backend/src/libs/strings.py
codeglitchz/attendance-system
37
9963
""" libs.strings By default, uses `en-gb.json` file inside the `strings` top-level folder. If language changes, set `libs.strings.default_locale` and run `libs.strings.refresh()`. """ import json default_locale = "en-us" cached_strings = {} def refresh(): global cached_strings with open(f"strings/{default_...
""" libs.strings By default, uses `en-gb.json` file inside the `strings` top-level folder. If language changes, set `libs.strings.default_locale` and run `libs.strings.refresh()`. """ import json default_locale = "en-us" cached_strings = {} def refresh(): global cached_strings with open(f"strings/{default_...
en
0.405185
libs.strings By default, uses `en-gb.json` file inside the `strings` top-level folder. If language changes, set `libs.strings.default_locale` and run `libs.strings.refresh()`.
2.530092
3
nemo_cmd/deflate.py
SalishSeaCast/NEMO-Cmd
1
9964
# Copyright 2013-2021 The Salish Sea MEOPAR Contributors # and The University of British Columbia # 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...
# Copyright 2013-2021 The Salish Sea MEOPAR Contributors # and The University of British Columbia # 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...
en
0.810321
# Copyright 2013-2021 The Salish Sea MEOPAR Contributors # and The University of British Columbia # 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...
2.086054
2
src/UQpy/distributions/collection/__init__.py
SURGroup/UncertaintyQuantification
0
9965
"""distributions module.""" from UQpy.distributions.collection.Beta import Beta from UQpy.distributions.collection.Binomial import Binomial from UQpy.distributions.collection.Cauchy import Cauchy from UQpy.distributions.collection.ChiSquare import ChiSquare from UQpy.distributions.collection.Exponential import Exponent...
"""distributions module.""" from UQpy.distributions.collection.Beta import Beta from UQpy.distributions.collection.Binomial import Binomial from UQpy.distributions.collection.Cauchy import Cauchy from UQpy.distributions.collection.ChiSquare import ChiSquare from UQpy.distributions.collection.Exponential import Exponent...
fr
0.268453
distributions module.
1.138766
1
Learning Python/Exercise Files/Ch2/helloworld_my.py
RomanShevtsiv/linkedin-learning
0
9966
# # Example file for HelloWorld # def main(): print("Hello World") name = input("What is your name? ") print("Nice to meet you,", name) if __name__ == "__main__": main()
# # Example file for HelloWorld # def main(): print("Hello World") name = input("What is your name? ") print("Nice to meet you,", name) if __name__ == "__main__": main()
en
0.657668
# # Example file for HelloWorld #
3.554072
4
RocketSimulation.py
pietrotrope/SolarSystemSimulation
0
9967
<filename>RocketSimulation.py<gh_stars>0 import sys import csv import json import math import pygame import numpy as np from pygame.locals import * import pandas as pd from data import * from agent import agentsList, Agent global screenSize screenSize = [1920, 1080] def load_parameters(path): package = [] f...
<filename>RocketSimulation.py<gh_stars>0 import sys import csv import json import math import pygame import numpy as np from pygame.locals import * import pandas as pd from data import * from agent import agentsList, Agent global screenSize screenSize = [1920, 1080] def load_parameters(path): package = [] f...
en
0.785137
# Environmental Constants # noqa # Layer base altitudes # Layer base pressures # Layer base temperatures # Layer lapse rates # noqa # noqa # noqa # noqa # Environment # Burn time # Engine specs # noqa # Fuel Specs # Flow Rate # Fuel & Oxidizer # Mass # Aerodynamics # Output # Flight Runs a simulation within the given p...
2.62287
3
sourcecode/GAN/FID/__init__.py
toufeeqahamedns/GeneratingHumanFaces
0
9968
""" Package has implementation for the FID score calculation """ from GAN.FID import fid_score from GAN.FID import inception
""" Package has implementation for the FID score calculation """ from GAN.FID import fid_score from GAN.FID import inception
en
0.844631
Package has implementation for the FID score calculation
1.193588
1
flask_monitoringdashboard/test/core/profiler/util/test_stringhash.py
timgates42/Flask-MonitoringDashboard
3
9969
import unittest from flask_monitoringdashboard.core.profiler.util.stringHash import StringHash class TestStringHash(unittest.TestCase): def test_stringhash(self): string_hash = StringHash() self.assertEqual(string_hash.hash('abc'), 0) self.assertEqual(string_hash.hash('def'), 1) ...
import unittest from flask_monitoringdashboard.core.profiler.util.stringHash import StringHash class TestStringHash(unittest.TestCase): def test_stringhash(self): string_hash = StringHash() self.assertEqual(string_hash.hash('abc'), 0) self.assertEqual(string_hash.hash('def'), 1) ...
none
1
3.022659
3
news/views.py
valch85/newssite
0
9970
from django.shortcuts import render, get_object_or_404 from .models import News # Create your views here. def index(request): latest_news_list = News.objects.order_by('-pub_date')[:10] context = {'latest_news_list': latest_news_list} return render(request, 'news/index.html', context) def detail(request, ...
from django.shortcuts import render, get_object_or_404 from .models import News # Create your views here. def index(request): latest_news_list = News.objects.order_by('-pub_date')[:10] context = {'latest_news_list': latest_news_list} return render(request, 'news/index.html', context) def detail(request, ...
en
0.968116
# Create your views here.
1.994599
2
benchmark/generate_libs/jamplus.py
chadaustin/ibb
4
9971
#!/usr/bin/python import os.path import cppcodebase import random def CreateLibJamfile(lib_number, classes): os.chdir(cppcodebase.lib_name(lib_number)) handle = file("Jamfile.jam", "w") handle.write ("SubDir TOP lib_" + str(lib_number) + " ;\n\n") handle.write ("SubDirHdrs $(INCLUDES) ;\n\n") han...
#!/usr/bin/python import os.path import cppcodebase import random def CreateLibJamfile(lib_number, classes): os.chdir(cppcodebase.lib_name(lib_number)) handle = file("Jamfile.jam", "w") handle.write ("SubDir TOP lib_" + str(lib_number) + " ;\n\n") handle.write ("SubDirHdrs $(INCLUDES) ;\n\n") han...
ru
0.258958
#!/usr/bin/python
2.451575
2
inbm/dispatcher-agent/dispatcher/fota/fota.py
intel/intel-inb-manageability
5
9972
""" FOTA update tool which is called from the dispatcher during installation Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ import logging import os import platform from threading import Timer from typing import Any, Optional, Mapping from future.moves.urllib.parse impo...
""" FOTA update tool which is called from the dispatcher during installation Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ import logging import os import platform from threading import Timer from typing import Any, Optional, Mapping from future.moves.urllib.parse impo...
en
0.770043
FOTA update tool which is called from the dispatcher during installation Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 AKA FOTA Tool An instance of this class will be called from the dispatcher if the requested type of update is FOTA Base class constructor for variable a...
1.731397
2
syncflux.py
nagylzs/syncflux
0
9973
<reponame>nagylzs/syncflux import copy import datetime import sys import os import time import argparse import traceback import pytz import syncthing from influxdb import InfluxDBClient import yaml from yaml2dataclass import Schema, SchemaPath from typing import Optional, Dict, Type, List from dataclasses import data...
import copy import datetime import sys import os import time import argparse import traceback import pytz import syncthing from influxdb import InfluxDBClient import yaml from yaml2dataclass import Schema, SchemaPath from typing import Optional, Dict, Type, List from dataclasses import dataclass, asdict, field @dat...
en
0.65841
# Common ports: 443 Load application configuration from a stream. # Collect data # My own device id # Collect device stats # List all remote devices # Device ID # Device Name # Number of seconds last seen # Folders # Get completion for my own device # Create data points for devices # Create points for folders #%d start...
2.387259
2
tests/input/pdf/test_pdf.py
asweeney86/preview-generator
0
9974
<filename>tests/input/pdf/test_pdf.py<gh_stars>0 # -*- coding: utf-8 -*- import os import re import shutil import typing from PIL import Image from PyPDF2 import PdfFileReader import PyPDF2.utils import pytest from preview_generator.exception import UnavailablePreviewType from preview_generator.manager import Previe...
<filename>tests/input/pdf/test_pdf.py<gh_stars>0 # -*- coding: utf-8 -*- import os import re import shutil import typing from PIL import Image from PyPDF2 import PdfFileReader import PyPDF2.utils import pytest from preview_generator.exception import UnavailablePreviewType from preview_generator.manager import Previe...
en
0.815207
# -*- coding: utf-8 -*- #  ensure file is encrpyted # TODO - G.M - 2018-11-06 - To be completed # TODO - G.M - 2018-11-06 - To be completed # verify if the size of the pdf refer to a normal content # verify if the size of the pdf refer to a normal content
2.394355
2
ipt/ipt_filter_contour_by_size.py
tpmp-inra/ipapi
1
9975
from ipso_phen.ipapi.base.ipt_abstract import IptBase from ipso_phen.ipapi.tools import regions import numpy as np import cv2 import logging logger = logging.getLogger(__name__) from ipso_phen.ipapi.base import ip_common as ipc class IptFilterContourBySize(IptBase): def build_params(self): ...
from ipso_phen.ipapi.base.ipt_abstract import IptBase from ipso_phen.ipapi.tools import regions import numpy as np import cv2 import logging logger = logging.getLogger(__name__) from ipso_phen.ipapi.base import ip_common as ipc class IptFilterContourBySize(IptBase): def build_params(self): ...
en
0.801592
Filter contour by size: 'Keep or descard contours according to their size Real time: False Keyword Arguments (in parentheses, argument name): * Activate tool (enabled): Toggle whether or not tool is active * Lower bound limit (min_threshold): Only contours bigger t...
2.330983
2
tests/main.py
deeso/json-search-replace
1
9976
from wrapper_tests.upsert_test import * from wrapper_tests.upsertvaluedict_test import * import os import logging import sys import argparse import signal logging.getLogger().setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s - %(name)s...
from wrapper_tests.upsert_test import * from wrapper_tests.upsertvaluedict_test import * import os import logging import sys import argparse import signal logging.getLogger().setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s - %(name)s...
none
1
2.264069
2
Sending_email/email.py
Satyam-Bhalla/Python-Scripts
8
9977
<reponame>Satyam-Bhalla/Python-Scripts import smtplib gmail_user = 'your email' gmail_password = '<PASSWORD>' sent_from = gmail_user to = ['reciever email'] #Create a list for all the recievers subject = 'OMG Super Important Message' body = 'Hey, what\'s up?\n- You' email_text = """\ From: %s To: %s Sub...
import smtplib gmail_user = 'your email' gmail_password = '<PASSWORD>' sent_from = gmail_user to = ['reciever email'] #Create a list for all the recievers subject = 'OMG Super Important Message' body = 'Hey, what\'s up?\n- You' email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", ".joi...
en
0.338145
#Create a list for all the recievers \ From: %s To: %s Subject: %s %s
2.663954
3
FlaskDaemon/load_test.py
caffeinate/test-pylot
0
9978
<filename>FlaskDaemon/load_test.py ''' Created on 11 Sep 2015 @author: si ''' import json import random import time from threading import Thread # import urllib import urllib2 from Queue import Queue import logging logger = logging.getLogger(__name__) API_URL = "http://127.0.0.1:5000/" class LoadTest(object): "...
<filename>FlaskDaemon/load_test.py ''' Created on 11 Sep 2015 @author: si ''' import json import random import time from threading import Thread # import urllib import urllib2 from Queue import Queue import logging logger = logging.getLogger(__name__) API_URL = "http://127.0.0.1:5000/" class LoadTest(object): "...
en
0.772649
Created on 11 Sep 2015 @author: si # import urllib Create a single process with one thread per test user. @param test_users_count: int @param requests_per_user: int # wait for threads to complete # could time.sleep(0.5) or just wait for all threads to finish #print "alive:%s" % alive_count # time_taken is real...
2.60504
3
urls.py
jeylani99/Real-Estate
0
9979
<reponame>jeylani99/Real-Estate from django.contrib import admin from django.conf.urls import include,url from .import views urlpatterns = [ url(r'^$', views.IndexView.as_view(),name='index'), #homeapp_detail_view_url url(r'^(?P<pk>[0-9]+)/$',views.LocationView.as_view(),name='property'), #homeapp/deta...
from django.contrib import admin from django.conf.urls import include,url from .import views urlpatterns = [ url(r'^$', views.IndexView.as_view(),name='index'), #homeapp_detail_view_url url(r'^(?P<pk>[0-9]+)/$',views.LocationView.as_view(),name='property'), #homeapp/detailview/moredetailview url(r'...
en
0.682227
#homeapp_detail_view_url #homeapp/detailview/moredetailview
1.707543
2
main.py
ngh3053/auto_spacing_with_tensorflow
0
9980
<filename>main.py from utils import * from model import Model2 if __name__ == '__main__': train_data = DataLoader('../data/trainX.txt', '../data/trainY.txt') test_data = DataLoader('../data/testX.txt', '../data/testY.txt') train_data.set_batch(100) test_data.set_batch(100) char_dic = Ch...
<filename>main.py from utils import * from model import Model2 if __name__ == '__main__': train_data = DataLoader('../data/trainX.txt', '../data/trainY.txt') test_data = DataLoader('../data/testX.txt', '../data/testY.txt') train_data.set_batch(100) test_data.set_batch(100) char_dic = Ch...
none
1
2.223725
2
src/sardana/taurus/qt/qtgui/extra_macroexecutor/macrodescriptionviewer.py
marc2332/sardana
43
9981
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under th...
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under th...
en
0.706254
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under the...
1.706114
2
torch/metrics/accuracy_score.py
LilDataScientist/PyTorch-From-Scratch
0
9982
<gh_stars>0 import numpy as np def accuracy_score(y_true, y_pred): a = np.argmax(y_true, axis=1) b = np.argmax(y_pred, axis=1) return np.count_nonzero(a == b) / y_true.shape[0]
import numpy as np def accuracy_score(y_true, y_pred): a = np.argmax(y_true, axis=1) b = np.argmax(y_pred, axis=1) return np.count_nonzero(a == b) / y_true.shape[0]
none
1
2.559866
3
asaas/financial_transactions.py
marlonjsilva/asaas_sdk_python
0
9983
from asaas.typing import SyncAsync from typing import Any, Optional, Dict class FinancialTransactions: def __init__(self, parent: Any) -> None: self.parent = parent def list( self, query: Optional[Dict[Any, Any]] = None, **kwars: Any ) -> SyncAsync[Any]: return self.parent.request...
from asaas.typing import SyncAsync from typing import Any, Optional, Dict class FinancialTransactions: def __init__(self, parent: Any) -> None: self.parent = parent def list( self, query: Optional[Dict[Any, Any]] = None, **kwars: Any ) -> SyncAsync[Any]: return self.parent.request...
none
1
2.222399
2
datahub/core/serializers.py
uktrade/data-hub-api
6
9984
from functools import partial from uuid import UUID from dateutil.parser import parse as dateutil_parse from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from rest_framework.exceptions import ValidationError from r...
from functools import partial from uuid import UUID from dateutil.parser import parse as dateutil_parse from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from rest_framework.exceptions import ValidationError from r...
en
0.705766
Constant models serializer. Lets you get permitted fields only. Needs 'permissions' attribute on Meta class in following format: permissions = { 'app_name.permission': 'field' } If user doesn't have required permission, corresponding field will be filtered out. Note: The curre...
2.125828
2
samples/s07-rigid-objects/main.py
nomadsinteractive/ark
5
9985
<reponame>nomadsinteractive/ark<filename>samples/s07-rigid-objects/main.py import math import random from ark import dear_imgui, ApplicationFacade, Arena, Event, Integer, Collider, RenderObject, Size, Camera, Vec3, Numeric class Application: def __init__(self, application: ApplicationFacade): self._down_...
import math import random from ark import dear_imgui, ApplicationFacade, Arena, Event, Integer, Collider, RenderObject, Size, Camera, Vec3, Numeric class Application: def __init__(self, application: ApplicationFacade): self._down_x = 0 self._down_y = 0 self._application = application ...
none
1
2.284181
2
jamf/models/computer_extension_attribute.py
jensenbox/python-jamf
1
9986
<reponame>jensenbox/python-jamf # coding: utf-8 """ Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoint...
# coding: utf-8 """ Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh...
en
0.522105
# coding: utf-8 Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and should be u...
1.732702
2
SSOKeyGen/ssokeygendialog.py
chrcoe/sso-keygen
0
9987
<reponame>chrcoe/sso-keygen<filename>SSOKeyGen/ssokeygendialog.py<gh_stars>0 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ssokeygendialog.ui' # # Created: Sun Feb 1 12:33:36 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ssokeygendialog.ui' # # Created: Sun Feb 1 12:33:36 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(s...
en
0.780946
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ssokeygendialog.ui' # # Created: Sun Feb 1 12:33:36 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost!
1.882803
2
util/n_download_util.py
TwrFyr/n-hen.py
0
9988
<reponame>TwrFyr/n-hen.py import urllib.request import os from typing import List from util.n_util import NUser from util.n_util import get_n_entry import time import threading from util.array_util import slice_array delay: float = 2.5 class ProgressWrapper: """The progress wrapper keeps track of the progress of...
import urllib.request import os from typing import List from util.n_util import NUser from util.n_util import get_n_entry import time import threading from util.array_util import slice_array delay: float = 2.5 class ProgressWrapper: """The progress wrapper keeps track of the progress of a operation by wrapping a...
en
0.801619
The progress wrapper keeps track of the progress of a operation by wrapping a current number and a total number. It also wraps an optional function, which uses the current values and has to have the form 'func(current, total)'. Saves all files represented by a list of url resources to the folder specified. The ...
3.283534
3
stable-baselines/tests/test_deterministic.py
princeton-vl/PackIt
49
9989
import pytest from stable_baselines import A2C, ACER, ACKTR, DeepQ, DDPG, PPO1, PPO2, TRPO from stable_baselines.ddpg import AdaptiveParamNoiseSpec from stable_baselines.common.identity_env import IdentityEnv, IdentityEnvBox from stable_baselines.common.vec_env import DummyVecEnv PARAM_NOISE_DDPG = AdaptiveParamNoise...
import pytest from stable_baselines import A2C, ACER, ACKTR, DeepQ, DDPG, PPO1, PPO2, TRPO from stable_baselines.ddpg import AdaptiveParamNoiseSpec from stable_baselines.common.identity_env import IdentityEnv, IdentityEnvBox from stable_baselines.common.vec_env import DummyVecEnv PARAM_NOISE_DDPG = AdaptiveParamNoise...
en
0.85846
# Hyperparameters for learning identity for each RL model Test if the algorithm (with a given policy) can learn an identity transformation (i.e. return observation as an action) :param model_name: (str) Name of the RL model # Free memory Test if the algorithm (with a given policy) can learn an identity tra...
2.033496
2
tests/models/tensorflow/convert_to_tensorflow_serving.py
filipecosta90/dlbench
14
9990
import tensorflow as tf from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants export_dir = './reference/00000002' graph_pb = './creditcardfraud.pb' builder = tf.saved_model.builder.SavedModelBuilder(export_dir) with tf.gfile.GFile(graph_pb, "rb") as f: ...
import tensorflow as tf from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants export_dir = './reference/00000002' graph_pb = './creditcardfraud.pb' builder = tf.saved_model.builder.SavedModelBuilder(export_dir) with tf.gfile.GFile(graph_pb, "rb") as f: ...
en
0.946029
# name="" is important to ensure we don't get spurious prefixing
2.335721
2
pycuda/characterize.py
grlee77/pycuda
0
9991
<gh_stars>0 from __future__ import division from __future__ import absolute_import from pycuda.tools import context_dependent_memoize import numpy as np def platform_bits(): return tuple.__itemsize__ * 8 def has_stack(): from pycuda.driver import Context return Context.get_device().compute_capability()...
from __future__ import division from __future__ import absolute_import from pycuda.tools import context_dependent_memoize import numpy as np def platform_bits(): return tuple.__itemsize__ * 8 def has_stack(): from pycuda.driver import Context return Context.get_device().compute_capability() >= (2, 0) ...
en
0.306936
%s extern "C" __global__ void write_size(size_t *output) { *output = sizeof(%s); }
2.181261
2
bopt/transforms.py
georgedeath/bomean
2
9992
import torch from scipy.stats import median_absolute_deviation class Transform_Base(object): """ Base class for transformations based on some data. """ def __init__(self, Ytr): self.Ytr = Ytr # Transform the mean def scale_mean(self, mu): return mu # Reve...
import torch from scipy.stats import median_absolute_deviation class Transform_Base(object): """ Base class for transformations based on some data. """ def __init__(self, Ytr): self.Ytr = Ytr # Transform the mean def scale_mean(self, mu): return mu # Reve...
en
0.815178
Base class for transformations based on some data. # Transform the mean # Reverse the transformation to the mean # Reverse the transformation to the variance Standardize the data Robustly standardize the data by estimating its scale
2.658891
3
pygs/graphserver/compiler/dedupe.py
abyrd/graphserver
2
9993
# eliminate duplicate service periods from a GTFS database from graphserver.ext.gtfs.gtfsdb import GTFSDatabase import sys from optparse import OptionParser def main(): usage = """usage: python dedupe.py <graphdb_filename>""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() ...
# eliminate duplicate service periods from a GTFS database from graphserver.ext.gtfs.gtfsdb import GTFSDatabase import sys from optparse import OptionParser def main(): usage = """usage: python dedupe.py <graphdb_filename>""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() ...
en
0.808423
# eliminate duplicate service periods from a GTFS database usage: python dedupe.py <graphdb_filename> SELECT count(*), monday, tuesday, wednesday, thursday, friday, saturday, sunday, start_date, end_date FROM calendar GROUP BY monday, tuesday, wednesday, thursday, friday, saturday, sunday, start_date, end_date...
2.885315
3
10/01/03/2.py
pylangstudy/201707
0
9994
class MyClass: def __repr__(self): return self.__class__.__name__ + '()' print(MyClass().__repr__())
class MyClass: def __repr__(self): return self.__class__.__name__ + '()' print(MyClass().__repr__())
none
1
3.001307
3
tests/tasks/core/test_core.py
andykawabata/prefect
2
9995
import pytest from prefect.core import Edge, Flow, Parameter, Task from prefect.tasks.core import collections from prefect.tasks.core.constants import Constant from prefect.tasks.core.function import FunctionTask class IdentityTask(Task): def run(self, x): return x class TestConstant: def test_cons...
import pytest from prefect.core import Edge, Flow, Parameter, Task from prefect.tasks.core import collections from prefect.tasks.core.constants import Constant from prefect.tasks.core.function import FunctionTask class IdentityTask(Task): def run(self, x): return x class TestConstant: def test_cons...
en
0.589738
An example docstring. # Original docstring available on class # Wrapped function is docstring on instance # Except when no docstring on wrapped function An example function # 2 params, identity, Dict, List of dict values # 2 params, identity, Dict, List of dict values # https://github.com/PrefectHQ/prefect/issues/2451 ...
2.216334
2
Tree/node.py
philipwerner/python_data_structures
0
9996
"""Node class module for Binary Tree.""" class Node(object): """The Node class.""" def __init__(self, value): """Initialization of node object.""" self.value = value self.left = None self.right = None def __str__(self): """Return a string representation of the nod...
"""Node class module for Binary Tree.""" class Node(object): """The Node class.""" def __init__(self, value): """Initialization of node object.""" self.value = value self.left = None self.right = None def __str__(self): """Return a string representation of the nod...
en
0.717058
Node class module for Binary Tree. The Node class. Initialization of node object. Return a string representation of the node object. Return a representation of the node object.
3.928241
4
qutip/operators.py
pschindler/qutip
1
9997
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, <NAME> and <NAME>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistribut...
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, <NAME> and <NAME>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistribut...
en
0.661367
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, <NAME> and <NAME>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistribut...
1.519419
2
tests/test_deepsv.py
lsantuari/deepsv
0
9998
<filename>tests/test_deepsv.py #!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from deepsv import deepsv from unittest.mock import patch """Tests for the deepsv module. """ def test_something(): assert True def test_adding_numbers(): assert deepsv.add_numbers(1, 1) == 2 assert deepsv.add_n...
<filename>tests/test_deepsv.py #!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from deepsv import deepsv from unittest.mock import patch """Tests for the deepsv module. """ def test_something(): assert True def test_adding_numbers(): assert deepsv.add_numbers(1, 1) == 2 assert deepsv.add_n...
en
0.515679
#!/usr/bin/env python # -*- coding: utf-8 -*- Tests for the deepsv module. # Do something that raises a ValueError # Fixture example # book = 'https://www.gutenberg.org/files/59560/59560-0.txt'
3.300925
3
tcex/bin/dep.py
phuerta-tc/tcex
0
9999
<filename>tcex/bin/dep.py #!/usr/bin/env python """TcEx Dependencies Command""" # standard library import os import platform import shutil import subprocess # nosec import sys from distutils.version import StrictVersion # pylint: disable=no-name-in-module from pathlib import Path from typing import List from urllib.p...
<filename>tcex/bin/dep.py #!/usr/bin/env python """TcEx Dependencies Command""" # standard library import os import platform import shutil import subprocess # nosec import sys from distutils.version import StrictVersion # pylint: disable=no-name-in-module from pathlib import Path from typing import List from urllib.p...
en
0.649885
#!/usr/bin/env python TcEx Dependencies Command # standard library # nosec # pylint: disable=no-name-in-module # third-party # first-party Install dependencies for App. Initialize Class properties. # properties # update tcex.json Build the pip command for installing dependencies. Args: python_execu...
2.093531
2