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 |
|---|---|---|---|---|---|---|---|---|---|---|
analysis/networks/autoencoder/train_eval.py | nriesterer/iccm-neural-bound | 0 | 3300 | <filename>analysis/networks/autoencoder/train_eval.py
""" Evaluates the training performance of the autoencoder.
"""
import time
import pandas as pd
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import ccobra
import onehot
import autoencoder
# General settings
training_datafil... | <filename>analysis/networks/autoencoder/train_eval.py
""" Evaluates the training performance of the autoencoder.
"""
import time
import pandas as pd
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import ccobra
import onehot
import autoencoder
# General settings
training_datafil... | en | 0.818771 | Evaluates the training performance of the autoencoder. # General settings # Obtain the task-response mapping for all syllogisms # Convert the task-response mapping to the reasoner profile # Construct the training and test tensors # Query the network for a prediction # Add the true response to the profile # Training loo... | 2.578986 | 3 |
Tools/GAutomator/wpyscripts/uiautomator/uiautomator_manager.py | Aver58/ColaFrameWork | 1 | 3301 | #-*- coding: UTF-8 -*-
"""
Tencent is pleased to support the open source community by making GAutomator available.
Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a... | #-*- coding: UTF-8 -*-
"""
Tencent is pleased to support the open source community by making GAutomator available.
Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a... | en | 0.844602 | #-*- coding: UTF-8 -*- Tencent is pleased to support the open source community by making GAutomator available. Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a cop... | 2.072488 | 2 |
IMU/VTK-6.2.0/Filters/Core/Testing/Python/TestSynchronizedTemplates3D.py | timkrentz/SunTracker | 0 | 3302 | <gh_stars>0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
class TestSynchronizedTemplates3D(Testing.vtkTest):
def testAll(self):
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader... | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
class TestSynchronizedTemplates3D(Testing.vtkTest):
def testAll(self):
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExte... | en | 0.653561 | #!/usr/bin/env python # write isosurface to file #vtkSynchronizedTemplates3D stemp # Create the RenderWindow, Renderer and Interactor # # Add the actors to the renderer, set the background and size # # render the image # # prevent the tk window from showing up then start the event loop # --- end of script -- | 1.992047 | 2 |
deserialize/__init__.py | iAndriy/deserialize | 0 | 3303 | """A module for deserializing data to Python objects."""
# pylint: disable=unidiomatic-typecheck
# pylint: disable=protected-access
# pylint: disable=too-many-branches
# pylint: disable=wildcard-import
import enum
import functools
import typing
from typing import Any, Callable, Dict, List, Optional, Union
from deser... | """A module for deserializing data to Python objects."""
# pylint: disable=unidiomatic-typecheck
# pylint: disable=protected-access
# pylint: disable=too-many-branches
# pylint: disable=wildcard-import
import enum
import functools
import typing
from typing import Any, Callable, Dict, List, Optional, Union
from deser... | en | 0.852683 | A module for deserializing data to Python objects. # pylint: disable=unidiomatic-typecheck # pylint: disable=protected-access # pylint: disable=too-many-branches # pylint: disable=wildcard-import The storage mode for the raw data on each object. If a store mode is set, the data will be stored in the attribute name... | 2.419669 | 2 |
tests/test_get_set.py | snoopyjc/ssf | 3 | 3304 | from ssf import SSF
ssf = SSF(errors='raise')
def test_get_set_days():
dn = ssf.get_day_names()
assert isinstance(dn, tuple)
assert dn == (('Mon', 'Monday'),
('Tue', 'Tuesday'),
('Wed', 'Wednesday'),
('Thu', 'Thursday'),
('Fri', 'Friday'),
('Sat',... | from ssf import SSF
ssf = SSF(errors='raise')
def test_get_set_days():
dn = ssf.get_day_names()
assert isinstance(dn, tuple)
assert dn == (('Mon', 'Monday'),
('Tue', 'Tuesday'),
('Wed', 'Wednesday'),
('Thu', 'Thursday'),
('Fri', 'Friday'),
('Sat',... | en | 0.879028 | # Failed # Failed # Failed # Failed # Will be inserted at 5 | 2.626468 | 3 |
script.py | devppratik/Youtube-Downloader | 0 | 3305 | <filename>script.py<gh_stars>0
import os
import pyfiglet
from pytube import YouTube, Playlist
file_size = 0
folder_name = ""
# Progress Bar
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end="\r"):
percent = ("{0:." + str(decimals) + "f}").format(100 *
... | <filename>script.py<gh_stars>0
import os
import pyfiglet
from pytube import YouTube, Playlist
file_size = 0
folder_name = ""
# Progress Bar
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='#', print_end="\r"):
percent = ("{0:." + str(decimals) + "f}").format(100 *
... | en | 0.536707 | # Progress Bar # Show Progress Bar # Get Download Location # Get Desired Resolution # Single Video Download # Playlist Single Video Download # Playlist Download # Main Function MENU 1.Download Single Video 2.Download Playlist\n Enter Your Choice : # Start of Program | 2.920291 | 3 |
test/python/test.py | alex952/cdr | 0 | 3306 | #
# Copyright 2014-2018 Neueda Ltd.
#
from cdr import Cdr
import unittest
field1 = 1
field2 = 2
field3 = 55
class TestCdr(unittest.TestCase):
def get_a_cdr(self):
d = Cdr()
d.setInteger(field1, 123)
d.setString(field2, "Hello")
d.setString(field3, "World")
return d
... | #
# Copyright 2014-2018 Neueda Ltd.
#
from cdr import Cdr
import unittest
field1 = 1
field2 = 2
field3 = 55
class TestCdr(unittest.TestCase):
def get_a_cdr(self):
d = Cdr()
d.setInteger(field1, 123)
d.setString(field2, "Hello")
d.setString(field3, "World")
return d
... | en | 0.222685 | # # Copyright 2014-2018 Neueda Ltd. # | 3.346141 | 3 |
vendor/mo_times/vendor/dateutil/tz.py | klahnakoski/auth0-api | 0 | 3307 | <gh_stars>0
"""
Copyright (c) 2003-2007 <NAME> <<EMAIL>>
This module offers extensions to the standard Python
datetime module.
"""
import datetime
import os
import struct
import sys
import time
from mo_future import PY3, string_types
__license__ = "Simplified BSD"
__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile... | """
Copyright (c) 2003-2007 <NAME> <<EMAIL>>
This module offers extensions to the standard Python
datetime module.
"""
import datetime
import os
import struct
import sys
import time
from mo_future import PY3, string_types
__license__ = "Simplified BSD"
__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange"... | en | 0.844638 | Copyright (c) 2003-2007 <NAME> <<EMAIL>> This module offers extensions to the standard Python datetime module. Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings # We can't use mktime here. It is unstable when decid... | 2.904383 | 3 |
example/first_example/window/inputWindow/view.py | suuperhu/Pyside2MVCFramework | 1 | 3308 | # -*- coding: utf-8 -*-
"""
# @SoftwareIDE : PyCharm2020Pro
# @ProjectName : PySide2MVCFramework
# @FileName : view.py
# @Author : 胡守杰
# @Email : <EMAIL>
# @ZhFileDescription :
# @EnFileDescription :
"""
import os
from pyside2mvcframework.core.view import... | # -*- coding: utf-8 -*-
"""
# @SoftwareIDE : PyCharm2020Pro
# @ProjectName : PySide2MVCFramework
# @FileName : view.py
# @Author : 胡守杰
# @Email : <EMAIL>
# @ZhFileDescription :
# @EnFileDescription :
"""
import os
from pyside2mvcframework.core.view import... | fr | 0.270046 | # -*- coding: utf-8 -*- # @SoftwareIDE : PyCharm2020Pro # @ProjectName : PySide2MVCFramework # @FileName : view.py # @Author : 胡守杰 # @Email : <EMAIL> # @ZhFileDescription : # @EnFileDescription : | 2.070679 | 2 |
src/finn/custom_op/fpgadataflow/streamingfifo.py | AlexMontgomerie/finn | 283 | 3309 | # Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the follow... | # Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the follow... | en | 0.762342 | # Copyright (c) 2020, Xilinx # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the follow... | 1.349702 | 1 |
android_fonts.py | chrissimpkins/android_fonts | 1 | 3310 | import ast
import emoji
import os
import pandas as pd
_SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv')
_API_LEVELS = {
1: ("(no codename)", "1.0"),
2: ("(no codename)", "1.1"),
3: ("Cupcake", "1.5 "),
4: ("Donut", "1.6 "),
5: ("Eclair", "2.0"),
6: ("Eclair", "2.0.1"),
7: ("Eclair", "2.1 "),
8:... | import ast
import emoji
import os
import pandas as pd
_SUPPORT_CACHE_CSV = emoji.datafile('emoji_support.csv')
_API_LEVELS = {
1: ("(no codename)", "1.0"),
2: ("(no codename)", "1.1"),
3: ("Cupcake", "1.5 "),
4: ("Donut", "1.6 "),
5: ("Eclair", "2.0"),
6: ("Eclair", "2.0.1"),
7: ("Eclair", "2.1 "),
8:... | en | 0.746302 | Dataframe of [emoji_level, font_file, codepoints, supported]. Includes every sequence we could find of any type. Requires prior execution of populate_emoji_support.py # merge emoji metadata to gain the status column | 2.486173 | 2 |
tests/test_list.py | amikrop/django-paste | 3 | 3311 | import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from paste import constants
from tests.mixins import SnippetListTestCaseMixin
from tests.utils import constant, create_snippet, create_user
class SnippetListTestCase(SnippetListTestCaseMixin, ... | import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from paste import constants
from tests.mixins import SnippetListTestCaseMixin
from tests.utils import constant, create_snippet, create_user
class SnippetListTestCase(SnippetListTestCaseMixin, ... | en | 0.794787 | Tests for the snippet list view. Return the snippet list URL. Send a POST request to the view's URL with data indicated by given kwargs, as JSON, using the proper content-type, and return the response. Snippet list GET must return all the viewable snippets. Snippet list GET must return private snippets ... | 2.49473 | 2 |
Algorithmic Toolbox/Greedy Algorithms/Maximum Advertisement Revenue/maximum_ad_revenue.py | ganeshbhandarkar/Python-Projects | 9 | 3312 | <gh_stars>1-10
# python3
from itertools import permutations
def max_dot_product_naive(first_sequence, second_sequence):
assert len(first_sequence) == len(second_sequence)
assert len(first_sequence) <= 10 ** 3
assert all(0 <= f <= 10 ** 5 for f in first_sequence)
assert all(0 <= s <= 10 ** 5 for s in ... | # python3
from itertools import permutations
def max_dot_product_naive(first_sequence, second_sequence):
assert len(first_sequence) == len(second_sequence)
assert len(first_sequence) <= 10 ** 3
assert all(0 <= f <= 10 ** 5 for f in first_sequence)
assert all(0 <= s <= 10 ** 5 for s in second_sequence... | none | 1 | 3.370768 | 3 | |
HelloWorldPython/IfStatements.py | SamIge7/Tutorials | 0 | 3313 | <gh_stars>0
hasGoodCredit = True
price = 1000000
deposit = 0
if hasGoodCredit:
deposit = price/10
else:
deposit = price/5
print(f"Deposit needed: £{deposit}") | hasGoodCredit = True
price = 1000000
deposit = 0
if hasGoodCredit:
deposit = price/10
else:
deposit = price/5
print(f"Deposit needed: £{deposit}") | none | 1 | 2.833555 | 3 | |
main.py | vsundesha/documentation-hub-dependencies | 0 | 3314 | <reponame>vsundesha/documentation-hub-dependencies<gh_stars>0
import config as props
import sys
import getopt
from GitHubDataFetcher import GitHubDataFetcher
from DependencyFile import DependencyFile
from ErrorFile import ErrorFile
# Github Token
TOKEN = props.token
OWNER = ""
REPOSITORY = ""
OUTPUTFILE =... | import config as props
import sys
import getopt
from GitHubDataFetcher import GitHubDataFetcher
from DependencyFile import DependencyFile
from ErrorFile import ErrorFile
# Github Token
TOKEN = props.token
OWNER = ""
REPOSITORY = ""
OUTPUTFILE = ""
def showHelp():
print('-r or --repo The name of t... | en | 0.770282 | # Github Token # opts are the arguments and remainders are the arrguments that will not be complete if something goes wrong # check if repo and owner are specified # create the fetcher # get the response object # response is type ErrorFile or DependencyFile # write file | 2.683404 | 3 |
inference_realesrgan.py | blabra/Real-ESRGAN | 0 | 3315 | import argparse
import cv2
import glob
import os
from basicsr.archs.rrdbnet_arch import RRDBNet
import time
from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
def main():
"""Inference demo for Real-ESRGAN.
"""
parser = argparse.ArgumentParser()
parser.add_argu... | import argparse
import cv2
import glob
import os
from basicsr.archs.rrdbnet_arch import RRDBNet
import time
from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
def main():
"""Inference demo for Real-ESRGAN.
"""
parser = argparse.ArgumentParser()
parser.add_argu... | en | 0.764104 | Inference demo for Real-ESRGAN. # determine models according to model names # x4 RRDBNet model # x4 RRDBNet model with 6 blocks # x2 RRDBNet model # x2 VGG-style model (XS size) # x4 VGG-style model (XS size) # determine model paths # restorer # Use GFPGAN for face enhancement # RGBA images should be saved in png forma... | 2.245941 | 2 |
examples/Fe__vasp/Fe_fcc_afm_D/Fe_fcc_afm_D_vac_A/clean_vasp.py | eragasa/pypospack | 4 | 3316 | <reponame>eragasa/pypospack
import os
filenames_delete = [
'CHG',
'CHGCAR',
'CONTCAR',
'DOSCAR',
'EIGENVAL',
'IBZKPT',
'job.err',
'job.out',
'OSZICAR',
'PCDAT',
'REPORT',
'vasp.log',
'vasprun.xml',
'WAVECAR',
'XDATCAR'
]
for filename in filen... | import os
filenames_delete = [
'CHG',
'CHGCAR',
'CONTCAR',
'DOSCAR',
'EIGENVAL',
'IBZKPT',
'job.err',
'job.out',
'OSZICAR',
'PCDAT',
'REPORT',
'vasp.log',
'vasprun.xml',
'WAVECAR',
'XDATCAR'
]
for filename in filenames_delete:
try:
... | none | 1 | 3.06172 | 3 | |
binary_trees/largest_values_in_tree_rows.py | ethyl2/code_challenges | 0 | 3317 | <gh_stars>0
'''
<NAME>'s solution.
See mine in largest_values_in_each_row.py
'''
from collection import deque
def largest_values_in_tree_rows(t):
rv = []
if t is None:
return rv
current_depth = 0
current_max = t.value
q = deque()
# add the root node to the queue at a depth of 0
... | '''
<NAME>'s solution.
See mine in largest_values_in_each_row.py
'''
from collection import deque
def largest_values_in_tree_rows(t):
rv = []
if t is None:
return rv
current_depth = 0
current_max = t.value
q = deque()
# add the root node to the queue at a depth of 0
q.append((t... | en | 0.769511 | <NAME>'s solution. See mine in largest_values_in_each_row.py # add the root node to the queue at a depth of 0 # if the depth of the current node is different from # `current_node`, add `current_max` to `rv` and then # reset `current_max` and `current_depth` # otherwise, we update `current_max` if we need to # add the l... | 3.593493 | 4 |
src/infer/_ExtractSimpleDeformTTA.py | RamsteinWR/PneumoniaRSNA1 | 0 | 3318 | <reponame>RamsteinWR/PneumoniaRSNA1
import json
import os
import re
import numpy as np
import pandas as pd
from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR
WDIR = os.path.dirname(os.path.abspath(__file__))
def get_results(det_folder, test_set, suffix):
fil... | import json
import os
import re
import numpy as np
import pandas as pd
from src.infer.ExtractDeformableTTA import MAPPINGS_PATH, test_image_set, METADATA_PATH, RCNN0_DETS_DIR
WDIR = os.path.dirname(os.path.abspath(__file__))
def get_results(det_folder, test_set, suffix):
filepath = os.path.join(det_folder, tes... | en | 0.565564 | box (list, length 4): [x1, y1, w, h] # Get top right corner of prediction # Top left corner of flipped box is: # Create new DataFrame | 2.439307 | 2 |
pool4.py | yfii/yfiiapi | 4 | 3319 | from web3 import Web3, HTTPProvider
import json
w3url = "https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca"
w3 = Web3(HTTPProvider(w3url))
WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
YFII = "0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83"
DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
iUSDT = "0x... | from web3 import Web3, HTTPProvider
import json
w3url = "https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca"
w3 = Web3(HTTPProvider(w3url))
WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
YFII = "0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83"
DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
iUSDT = "0x... | none | 1 | 2.199141 | 2 | |
obswebsocket/requests.py | PanBartosz/obs-websocket-py | 123 | 3320 | <filename>obswebsocket/requests.py<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# THIS FILE WAS GENERATED BY generate_classes.py - DO NOT EDIT #
# (Generated on 2020-12-20 18:26:33.661372) #
from .base_classes import Baserequests
class GetVersion(Baserequests):
"""Returns the latest version o... | <filename>obswebsocket/requests.py<gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# THIS FILE WAS GENERATED BY generate_classes.py - DO NOT EDIT #
# (Generated on 2020-12-20 18:26:33.661372) #
from .base_classes import Baserequests
class GetVersion(Baserequests):
"""Returns the latest version o... | en | 0.622897 | #!/usr/bin/env python # -*- coding: utf-8 -*- # THIS FILE WAS GENERATED BY generate_classes.py - DO NOT EDIT # # (Generated on 2020-12-20 18:26:33.661372) # Returns the latest version of the plugin and the API. :Returns: *version* type: double OBSRemote compatible API version. Fixed ... | 2.05728 | 2 |
simple_history/tests/custom_user/admin.py | rdurica/django-simple-history | 911 | 3321 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
admin.site.register(CustomUser, UserAdmin)
| from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser
admin.site.register(CustomUser, UserAdmin)
| none | 1 | 1.334881 | 1 | |
tools/accuracy_checker/openvino/tools/accuracy_checker/evaluators/custom_evaluators/mtcnn_evaluator_utils.py | Pandinosaurus/open_model_zoo | 1 | 3322 | """
Copyright (c) 2018-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | """
Copyright (c) 2018-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... | en | 0.842246 | Copyright (c) 2018-2022 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing... | 1.789475 | 2 |
pytests/Atomicity/basic_ops.py | ashwin2002/TAF | 0 | 3323 | <gh_stars>0
from Cb_constants import DocLoading
from basetestcase import ClusterSetup
from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator
from couchbase_helper.tuq_generators import JsonGenerator
from remote.remote_util import RemoteMachineShellConnection
from sdk_client3 import SDKClient
f... | from Cb_constants import DocLoading
from basetestcase import ClusterSetup
from couchbase_helper.documentgenerator import DocumentGenerator, doc_generator
from couchbase_helper.tuq_generators import JsonGenerator
from remote.remote_util import RemoteMachineShellConnection
from sdk_client3 import SDKClient
from com.couc... | en | 0.795539 | Basic test cases with commit,rollback scenarios # Reset active_resident_threshold to avoid further data load as DGM Test transaction commit, rollback, time ahead, time behind scenarios with replica, persist_to and replicate_to settings # Atomicity.basic_ops.basic_ops.test_basic_commit # Create doc_gen f... | 1.849491 | 2 |
reverseWord.py | lovefov/Python | 0 | 3324 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
#Author:贾江超
def spin_words(sentence):
list1=sentence.split()
l=len(list1)
for i in range(l):
relen = len(sentence.split()[i:][0])
if relen > 5:
list1[i]=list1[i][::-1]
return ' '.join(list1)
'''
注意 在2.x版本可以用len()得到list的长度 3.x版本就不行... | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
#Author:贾江超
def spin_words(sentence):
list1=sentence.split()
l=len(list1)
for i in range(l):
relen = len(sentence.split()[i:][0])
if relen > 5:
list1[i]=list1[i][::-1]
return ' '.join(list1)
'''
注意 在2.x版本可以用len()得到list的长度 3.x版本就不行... | zh | 0.579056 | #!/usr/bin/env python3 #-*- coding:utf-8 -*- #Author:贾江超 注意 在2.x版本可以用len()得到list的长度 3.x版本就不行了 优化版本 def spin_words(sentence): # Your code goes here return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")]) 在这里倒序字符串用切片很方便 str[::-1] 就ok了 | 3.682326 | 4 |
src/scs_host/comms/network_socket.py | south-coast-science/scs_host_cpc | 0 | 3325 | <reponame>south-coast-science/scs_host_cpc<gh_stars>0
"""
Created on 30 May 2017
@author: <NAME> (<EMAIL>)
A network socket abstraction, implementing ProcessComms
"""
import socket
import time
from scs_core.sys.process_comms import ProcessComms
# -------------------------------------------------------------------... | """
Created on 30 May 2017
@author: <NAME> (<EMAIL>)
A network socket abstraction, implementing ProcessComms
"""
import socket
import time
from scs_core.sys.process_comms import ProcessComms
# --------------------------------------------------------------------------------------------------------------------
cla... | en | 0.253718 | Created on 30 May 2017 @author: <NAME> (<EMAIL>) A network socket abstraction, implementing ProcessComms # -------------------------------------------------------------------------------------------------------------------- classdocs # seconds # bytes # ----------------------------------------------------------------... | 3.160978 | 3 |
dateparser/date.py | JKhakpour/dateparser | 2 | 3326 | <reponame>JKhakpour/dateparser
# -*- coding: utf-8 -*-
import calendar
import collections
from datetime import datetime, timedelta
from warnings import warn
import six
import regex as re
from dateutil.relativedelta import relativedelta
from dateparser.date_parser import date_parser
from dateparser.freshness_date_pars... | # -*- coding: utf-8 -*-
import calendar
import collections
from datetime import datetime, timedelta
from warnings import warn
import six
import regex as re
from dateutil.relativedelta import relativedelta
from dateparser.date_parser import date_parser
from dateparser.freshness_date_parser import freshness_date_parser... | en | 0.58546 | # -*- coding: utf-8 -*- # u'\u2019' # u'\u02bc' # u'\u02bb' # u'\u055a' # u'\ua78c' # u'\u2032' # u'\u2035' # u'\u02b9' # u'\uff07' # handles edge-case when iterating months and last interval is < 30 days # remove u'г.' (Russian for year) but not in words Parse with formats and return a dictionary with 'period' and 'ob... | 2.035626 | 2 |
src/models/functions/connection/mixture_density_network.py | kristofbc/handwriting-synthesis | 0 | 3327 | import chainer
import chainer.functions
from chainer.utils import type_check
from chainer import cuda
from chainer import function
import numpy as np
#from chainer import function_node
from utils import clip_grad
#class MixtureDensityNetworkFunction(function_node.FunctionNode):
class MixtureDensityNetworkFunction(fu... | import chainer
import chainer.functions
from chainer.utils import type_check
from chainer import cuda
from chainer import function
import numpy as np
#from chainer import function_node
from utils import clip_grad
#class MixtureDensityNetworkFunction(function_node.FunctionNode):
class MixtureDensityNetworkFunction(fu... | en | 0.665169 | #from chainer import function_node #class MixtureDensityNetworkFunction(function_node.FunctionNode): #self.retain_inputs(range(len(inputs))) # Retain everything for backward # Get MDN coeff. Eq #18 to #22 # F.sigmoid. NOTE: usually sigmoid is 1/(1+e^-x). Here 'x' is >0! #z_pi = xp.exp(pi_input) #z_pi = z_pi / xp.sum(z_... | 2.189591 | 2 |
flask__webservers/bootstrap_4__toggle_switch__examples/main.py | DazEB2/SimplePyScripts | 0 | 3328 | <reponame>DazEB2/SimplePyScripts
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://github.com/twbs/bootstrap
# SOURCE: https://github.com/gitbrent/bootstrap4-toggle
# SOURCE: https://gitbrent.github.io/bootstrap4-toggle/
from flask import Flask, render_template
app = Flask(__... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://github.com/twbs/bootstrap
# SOURCE: https://github.com/gitbrent/bootstrap4-toggle
# SOURCE: https://gitbrent.github.io/bootstrap4-toggle/
from flask import Flask, render_template
app = Flask(__name__)
import logging
logging.b... | en | 0.669573 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # SOURCE: https://github.com/twbs/bootstrap # SOURCE: https://github.com/gitbrent/bootstrap4-toggle # SOURCE: https://gitbrent.github.io/bootstrap4-toggle/ # Localhost # port=0 -- random free port # app.run(port=0) # :param threaded: should the process handle each request ... | 2.415038 | 2 |
dev/phonts/visualization/phonts.py | eragasa/pypospack | 4 | 3329 | <gh_stars>1-10
import pypospack.io.phonts as phonts
# <---- additional classes and functions in which to add top
# <---- pypospack.io.phonts
if __name__ == "__main__":
| import pypospack.io.phonts as phonts
# <---- additional classes and functions in which to add top
# <---- pypospack.io.phonts
if __name__ == "__main__": | en | 0.746415 | # <---- additional classes and functions in which to add top # <---- pypospack.io.phonts | 1.340711 | 1 |
omegaconf/_utils.py | sugatoray/omegaconf | 1,091 | 3330 | <reponame>sugatoray/omegaconf<gh_stars>1000+
import copy
import os
import re
import string
import sys
import warnings
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
... | import copy
import os
import re
import string
import sys
import warnings
from contextlib import contextmanager
from enum import Enum
from textwrap import dedent
from typing import (
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
get_type_hints,
)
import yaml
from .errors ... | en | 0.782162 | # pragma: no cover # type: ignore # pragma: no cover # pragma: no cover # type: ignore # pragma: no cover # Regexprs to match key paths like: a.b, a[b], ..a[c].d, etc. # We begin by matching the head (in these examples: a, a, ..a). # This can be read as "dots followed by any character but `.` or `[`" # Note that a key ... | 2.347888 | 2 |
darc/amber_clustering.py | loostrum/darc | 0 | 3331 | <gh_stars>0
#!/usr/bin/env python3
#
# AMBER Clustering
import os
from time import sleep
import yaml
import ast
import threading
import multiprocessing as mp
import numpy as np
from astropy.time import Time, TimeDelta
import astropy.units as u
from astropy.coordinates import SkyCoord
from darc import DARCBase, VOEve... | #!/usr/bin/env python3
#
# AMBER Clustering
import os
from time import sleep
import yaml
import ast
import threading
import multiprocessing as mp
import numpy as np
from astropy.time import Time, TimeDelta
import astropy.units as u
from astropy.coordinates import SkyCoord
from darc import DARCBase, VOEventQueueServe... | en | 0.77656 | #!/usr/bin/env python3 # # AMBER Clustering Trigger IQUV / LOFAR / VOEvent system based on AMBER candidates 1. Cluster incoming triggers 2. Apply thresholds (separate for known and new sources, and for IQUV vs LOFAR) 3. Put IQUV triggers on output queue 4. Put LOFAR triggers on remote LOFAR trigger que... | 2.196687 | 2 |
tools/load_demo_data.py | glenn2763/skyportal | 0 | 3332 | import datetime
import os
import subprocess
import base64
from pathlib import Path
import shutil
import pandas as pd
import signal
import requests
from baselayer.app.env import load_env
from baselayer.app.model_util import status, create_tables, drop_tables
from social_tornado.models import TornadoStorage
from skyport... | import datetime
import os
import subprocess
import base64
from pathlib import Path
import shutil
import pandas as pd
import signal
import requests
from baselayer.app.env import load_env
from baselayer.app.model_util import status, create_tables, drop_tables
from social_tornado.models import TornadoStorage
from skyport... | en | 0.071733 | Insert test data | 1.876319 | 2 |
framework/Exploits/CUTEFLOW_0024.py | UncleWillis/BugBox | 1 | 3333 |
# Copyright 2013 University of Maryland. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE.TXT file.
import sys
import os
import time
from selenium.common.exceptions import NoAlertPresentException
import framework
class Exploit (framework.Exploit... |
# Copyright 2013 University of Maryland. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE.TXT file.
import sys
import os
import time
from selenium.common.exceptions import NoAlertPresentException
import framework
class Exploit (framework.Exploit... | en | 0.915784 | # Copyright 2013 University of Maryland. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE.TXT file. | 2.398885 | 2 |
telethon/tl/custom/button.py | HosseyNJF/Telethon | 4 | 3334 | <reponame>HosseyNJF/Telethon
from .. import types
from ... import utils
class Button:
"""
.. note::
This class is used to **define** reply markups, e.g. when
sending a message or replying to events. When you access
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
... | from .. import types
from ... import utils
class Button:
"""
.. note::
This class is used to **define** reply markups, e.g. when
sending a message or replying to events. When you access
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
they are actually `MessageBu... | en | 0.795497 | .. note:: This class is used to **define** reply markups, e.g. when sending a message or replying to events. When you access `Message.buttons <telethon.tl.custom.message.Message.buttons>` they are actually `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`, ... | 3.364468 | 3 |
src/main/resources/pys/join.py | addUsername/javaBoring | 0 | 3335 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 7 20:14:22 2020
Simple script to join json files
@author: SERGI
"""
import json
import sys
import os
def readJson(path):
with open(path, "r") as file:
return json.load(file)
def writeJson(path, dicc):
with open(path, "w") as file... | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 7 20:14:22 2020
Simple script to join json files
@author: SERGI
"""
import json
import sys
import os
def readJson(path):
with open(path, "r") as file:
return json.load(file)
def writeJson(path, dicc):
with open(path, "w") as file... | en | 0.516353 | # -*- coding: utf-8 -*- Created on Tue Jul 7 20:14:22 2020
Simple script to join json files
@author: SERGI # ============================================================================= # jsonPath = "../eclipse-workspace/prueba/target/json/" # ================================================================... | 3.193305 | 3 |
app/grandchallenge/challenges/migrations/0023_auto_20200123_1102.py | njmhendrix/grand-challenge.org | 1 | 3336 | # Generated by Django 3.0.2 on 2020-01-23 11:02
import re
import django.contrib.postgres.fields.citext
import django.core.validators
from django.db import migrations
import grandchallenge.challenges.models
class Migration(migrations.Migration):
dependencies = [
("challenges", "0022_auto_20200121_1639"... | # Generated by Django 3.0.2 on 2020-01-23 11:02
import re
import django.contrib.postgres.fields.citext
import django.core.validators
from django.db import migrations
import grandchallenge.challenges.models
class Migration(migrations.Migration):
dependencies = [
("challenges", "0022_auto_20200121_1639"... | en | 0.87888 | # Generated by Django 3.0.2 on 2020-01-23 11:02 | 2.000653 | 2 |
autosk_dev_test/component/LinReg.py | hmendozap/master-arbeit-files | 2 | 3337 | <reponame>hmendozap/master-arbeit-files
import numpy as np
import scipy.sparse as sp
from HPOlibConfigSpace.configuration_space import ConfigurationSpace
from HPOlibConfigSpace.conditions import EqualsCondition, InCondition
from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \
UniformIntegerH... | import numpy as np
import scipy.sparse as sp
from HPOlibConfigSpace.configuration_space import ConfigurationSpace
from HPOlibConfigSpace.conditions import EqualsCondition, InCondition
from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \
UniformIntegerHyperparameter, CategoricalHyperparameter... | en | 0.688293 | # Empty features and shape # Regression # Normalize the output # Cap the max number of possible epochs | 2.062277 | 2 |
python_work/Chapter5/exe3_alien_color.py | Elektra-2/python_crash_course_2nd | 1 | 3338 | <filename>python_work/Chapter5/exe3_alien_color.py
# Creating a elif chain
alien_color = 'red'
if alien_color == 'green':
print('Congratulations! You won 5 points!')
elif alien_color == 'yellow':
print('Congratulations! You won 10 points!')
elif alien_color == 'red':
print('Congratulations! You won 15 p... | <filename>python_work/Chapter5/exe3_alien_color.py
# Creating a elif chain
alien_color = 'red'
if alien_color == 'green':
print('Congratulations! You won 5 points!')
elif alien_color == 'yellow':
print('Congratulations! You won 10 points!')
elif alien_color == 'red':
print('Congratulations! You won 15 p... | en | 0.783694 | # Creating a elif chain | 3.96712 | 4 |
DigiPsych_API/Data_Science_API/evaluate_model.py | larryzhang95/Voice-Analysis-Pipeline | 7 | 3339 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import learning_curve
# Plot learning curve
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
plt.figu... | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import learning_curve
# Plot learning curve
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
plt.figu... | en | 0.869738 | # Plot learning curve # Plot validation curve | 3.487533 | 3 |
oomi/__init__.py | sremes/oomi | 0 | 3340 | """Utilities for downloading comsumption data from Oomi."""
from oomi.oomi_downloader import OomiDownloader, OomiConfig
| """Utilities for downloading comsumption data from Oomi."""
from oomi.oomi_downloader import OomiDownloader, OomiConfig
| en | 0.764657 | Utilities for downloading comsumption data from Oomi. | 1.249247 | 1 |
BaseTools/Source/Python/UPT/Object/Parser/InfMisc.py | KaoTuz/edk2-stable202108 | 9 | 3341 | ## @file
# This file is used to define class objects of INF file miscellaneous.
# Include BootMode/HOB/Event and others. It will consumed by InfParser.
#
# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
'''
InfMisc
'''
import Logger.Log as Logge... | ## @file
# This file is used to define class objects of INF file miscellaneous.
# Include BootMode/HOB/Event and others. It will consumed by InfParser.
#
# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
'''
InfMisc
'''
import Logger.Log as Logge... | en | 0.633258 | ## @file # This file is used to define class objects of INF file miscellaneous. # Include BootMode/HOB/Event and others. It will consumed by InfParser. # # Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR> # # SPDX-License-Identifier: BSD-2-Clause-Patent InfMisc ## # BootModeObject # ## # EventObje... | 2.15186 | 2 |
21-08/Starters8/1.py | allenalvin333/Codechef_Competitions | 0 | 3342 | # https://www.codechef.com/START8C/problems/PENALTY
for T in range(int(input())):
n=list(map(int,input().split()))
a=b=0
for i in range(len(n)):
if(n[i]==1):
if(i%2==0): a+=1
else: b+=1
if(a>b): print(1)
elif(b>a): print(2)
else: print(0) | # https://www.codechef.com/START8C/problems/PENALTY
for T in range(int(input())):
n=list(map(int,input().split()))
a=b=0
for i in range(len(n)):
if(n[i]==1):
if(i%2==0): a+=1
else: b+=1
if(a>b): print(1)
elif(b>a): print(2)
else: print(0) | en | 0.48443 | # https://www.codechef.com/START8C/problems/PENALTY | 2.749437 | 3 |
util/eval.py | jhong93/vpd | 7 | 3343 | <filename>util/eval.py
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
def save_confusion_matrix(truth, pred, out_file, norm=None):
label_names = list(set(truth) | set(pred))
label_names.sort()
truth_compact = [label_names.index(x) for x in truth]
p... | <filename>util/eval.py
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
def save_confusion_matrix(truth, pred, out_file, norm=None):
label_names = list(set(truth) | set(pred))
label_names.sort()
truth_compact = [label_names.index(x) for x in truth]
p... | none | 1 | 2.741494 | 3 | |
python/py3study/pytorch-lab/demo-cifar.py | sillyemperor/langstudy | 0 | 3344 | import torch
import torchvision
import torchvision.transforms as transforms
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
root = os.path.join(BASE_DIR, '../data/')
trainset ... | import torch
import torchvision
import torchvision.transforms as transforms
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
root = os.path.join(BASE_DIR, '../data/')
trainset ... | en | 0.548018 | # print(x.shape) # print(x.shape) # print(x.shape) # print(x.shape) # print(x.shape) # print(x.shape) # print(x.shape) # torch.Size([1, 3, 32, 32]) # torch.Size([1, 6, 14, 14]) # torch.Size([1, 16, 5, 5]) # torch.Size([1, 400]) # torch.Size([1, 120]) # torch.Size([1, 84]) # torch.Size([1, 100]) # [1, 5000] loss: 2.293... | 2.864218 | 3 |
astroquery/neodys/tests/test_neodys_remote.py | B612-Asteroid-Institute/astroquery | 0 | 3345 |
from ... import neodys
def test_neodys_query():
test_object = "2018VP1"
res_kep_0 = neodys.core.NEODyS.query_object(
test_object, orbital_element_type="ke", epoch_near_present=0)
res_kep_1 = neodys.core.NEODyS.query_object(
test_object, orbital_element_type="ke", epoch_near_present=1)
... |
from ... import neodys
def test_neodys_query():
test_object = "2018VP1"
res_kep_0 = neodys.core.NEODyS.query_object(
test_object, orbital_element_type="ke", epoch_near_present=0)
res_kep_1 = neodys.core.NEODyS.query_object(
test_object, orbital_element_type="ke", epoch_near_present=1)
... | none | 1 | 2.194304 | 2 | |
corehq/apps/accounting/migrations/0026_auto_20180508_1956.py | kkrampa/commcare-hq | 1 | 3346 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
def noop(*args, **kwargs):
pass
def _convert_emailed_to_array_field(apps, schema_editor):
BillingRecord =... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
def noop(*args, **kwargs):
pass
def _convert_emailed_to_array_field(apps, schema_editor):
BillingRecord = apps.get_model... | en | 0.645639 | # -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-05-08 19:56 | 1.916985 | 2 |
tensor2tensor/rl/evaluator.py | SouBanerjee/tensor2tensor | 1 | 3347 | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | # coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | en | 0.678169 | # coding=utf-8 # Copyright 2018 The Tensor2Tensor 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... | 1.643522 | 2 |
src/part_2_automation/test_test1.py | AndreiHustiuc/IT_Factory_Course | 0 | 3348 | <reponame>AndreiHustiuc/IT_Factory_Course
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium... | # Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWa... | en | 0.916736 | # Generated by Selenium IDE | 2.471174 | 2 |
app/grandchallenge/components/admin.py | njmhendrix/grand-challenge.org | 1 | 3349 | from django.contrib import admin
from grandchallenge.components.models import (
ComponentInterface,
ComponentInterfaceValue,
)
class ComponentInterfaceAdmin(admin.ModelAdmin):
list_display = (
"pk",
"title",
"slug",
"kind",
"default_value",
"relative_path",... | from django.contrib import admin
from grandchallenge.components.models import (
ComponentInterface,
ComponentInterfaceValue,
)
class ComponentInterfaceAdmin(admin.ModelAdmin):
list_display = (
"pk",
"title",
"slug",
"kind",
"default_value",
"relative_path",... | none | 1 | 1.825742 | 2 | |
publishtimer/__init__.py | paragguruji/publishtimer | 0 | 3350 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 28 15:28:24 2016
@author: <NAME>, <EMAIL>
"""
from .helpers import setup_env
done = setup_env() | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 28 15:28:24 2016
@author: <NAME>, <EMAIL>
"""
from .helpers import setup_env
done = setup_env() | en | 0.477961 | # -*- coding: utf-8 -*- Created on Mon Mar 28 15:28:24 2016 @author: <NAME>, <EMAIL> | 1.020373 | 1 |
netdisco/discoverables/nanoleaf_aurora.py | jjlawren/netdisco | 1 | 3351 | <reponame>jjlawren/netdisco<filename>netdisco/discoverables/nanoleaf_aurora.py
"""Discover Nanoleaf Aurora devices."""
from . import MDNSDiscoverable
class Discoverable(MDNSDiscoverable):
"""Add support for discovering Nanoleaf Aurora devices."""
def __init__(self, nd):
super(Discoverable, self).__in... | """Discover Nanoleaf Aurora devices."""
from . import MDNSDiscoverable
class Discoverable(MDNSDiscoverable):
"""Add support for discovering Nanoleaf Aurora devices."""
def __init__(self, nd):
super(Discoverable, self).__init__(nd, '_nanoleafapi._tcp.local.') | en | 0.756749 | Discover Nanoleaf Aurora devices. Add support for discovering Nanoleaf Aurora devices. | 1.846968 | 2 |
debug/compute_score_common_ts_RETREAT.py | DavidSabbagh/meeg_power_regression | 1 | 3352 | import os.path as op
import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import RidgeCV
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold, cross_val_score
import mne
from pyriemann.tangentspace import TangentSpace
import ... | import os.path as op
import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import RidgeCV
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold, cross_val_score
import mne
from pyriemann.tangentspace import TangentSpace
import ... | en | 0.119137 | # covs2 = covs.reshape(n_sub*n_fb, n_ch, n_ch) # covs_avg = np.mean(covs2, axis=0) # (sub, fb, ch, ch) | 1.851649 | 2 |
bter/publish.py | mengalong/bter | 1 | 3353 | <filename>bter/publish.py
# Copyright 2017~ mengalong <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | <filename>bter/publish.py
# Copyright 2017~ mengalong <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | en | 0.839482 | # Copyright 2017~ mengalong <<EMAIL>> # # 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... | 2.141166 | 2 |
web3/_utils/module_testing/math_contract.py | y19818/web3.py | 0 | 3354 |
MATH_BYTECODE = (
"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000"
"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22"
"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780"
"63dcf537b11461014057610074565b... |
MATH_BYTECODE = (
"606060405261022e806100126000396000f360606040523615610074576000357c01000000000000"
"000000000000000000000000000000000000000000009004806316216f391461007657806361bc22"
"1a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d5780"
"63dcf537b11461014057610074565b... | none | 1 | 1.196077 | 1 | |
dnsdb/config.py | nuby/open_dnsdb | 1 | 3355 | <reponame>nuby/open_dnsdb
# -*- coding: utf-8 -*-
import os
import sys
from datetime import timedelta
from oslo.config import cfg
CONF = cfg.CONF
CONF.register_opts([
cfg.StrOpt('log-dir'),
cfg.StrOpt('log-file'),
cfg.StrOpt('debug'),
cfg.StrOpt('verbose'),
], 'log')
CONF.register_opts([
cfg.St... | # -*- coding: utf-8 -*-
import os
import sys
from datetime import timedelta
from oslo.config import cfg
CONF = cfg.CONF
CONF.register_opts([
cfg.StrOpt('log-dir'),
cfg.StrOpt('log-file'),
cfg.StrOpt('debug'),
cfg.StrOpt('verbose'),
], 'log')
CONF.register_opts([
cfg.StrOpt('connection'),
cf... | en | 0.290445 | # -*- coding: utf-8 -*- # print 'conf_dir: ', conf_dir # SECRET_KEY = os.environ.get('SECRET_KEY') or CONF.etc.secret_key # SQLALCHEMY_DATABASE_URI = CONF.DB.connection # SQLALCHEMY_TRACK_MODIFICATIONS = False # PERMANENT_SESSION_LIFETIME = timedelta(days=1) | 1.841725 | 2 |
rover/rover.py | cloudy/osr-rover-code | 0 | 3356 | from __future__ import print_function
import time
from rover import Robot
from connections import Connections
class Rover(Robot, Connections):
def __init__( self,
config,
bt_flag = 0,
xbox_flag = 0,
unix_flag = 0
):
self.bt_flag = bt_flag
self.xbox_flag = xbox_flag
self.unix_flag =... | from __future__ import print_function
import time
from rover import Robot
from connections import Connections
class Rover(Robot, Connections):
def __init__( self,
config,
bt_flag = 0,
xbox_flag = 0,
unix_flag = 0
):
self.bt_flag = bt_flag
self.xbox_flag = xbox_flag
self.unix_flag =... | none | 1 | 2.659314 | 3 | |
aswiki/parser.py | scanner/django-aswiki | 0 | 3357 | <filename>aswiki/parser.py
#
# File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner $
#
"""
This is where the logic and definition of our wiki markup parser lives.
We use the Python Creoleparser (which requires Genshi)
We make a custom dialect so that the parser can know the URL base for
all of the topics (pages) i... | <filename>aswiki/parser.py
#
# File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner $
#
"""
This is where the logic and definition of our wiki markup parser lives.
We use the Python Creoleparser (which requires Genshi)
We make a custom dialect so that the parser can know the URL base for
all of the topics (pages) i... | en | 0.767861 | # # File: $Id: parser.py 1865 2008-10-28 00:47:27Z scanner $ # This is where the logic and definition of our wiki markup parser lives. We use the Python Creoleparser (which requires Genshi) We make a custom dialect so that the parser can know the URL base for all of the topics (pages) in the wiki and some additional ... | 2.705861 | 3 |
oauth_api/validators.py | anobi/django-oauth-api | 0 | 3358 | <reponame>anobi/django-oauth-api
import base64
import binascii
from datetime import timedelta
from django.contrib.auth import authenticate
from django.utils import timezone
from oauthlib.oauth2 import RequestValidator
from oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken, A... | import base64
import binascii
from datetime import timedelta
from django.contrib.auth import authenticate
from django.utils import timezone
from oauthlib.oauth2 import RequestValidator
from oauth_api.models import get_application_model, AccessToken, AuthorizationCode, RefreshToken, AbstractApplication
from oauth_api... | en | 0.81032 | Load application instance for given client_id and store it in request as 'client' attribute Try authenticating the client using HTTP Basic Authentication method Try authenticating the client using values from request body Determine if client authentication is required for current request. According to the rfc6... | 2.438445 | 2 |
objects/fun_return.py | padmacho/pythontutorial | 0 | 3359 | def modify(y):
return y # returns same reference. No new object is created
x = [1, 2, 3]
y = modify(x)
print("x == y", x == y)
print("x == y", x is y) | def modify(y):
return y # returns same reference. No new object is created
x = [1, 2, 3]
y = modify(x)
print("x == y", x == y)
print("x == y", x is y) | en | 0.843642 | # returns same reference. No new object is created | 3.972492 | 4 |
edx_gen/_write_comps.py | hberndl70/mooc-generator | 0 | 3360 | import sys, os
import tarfile
import shutil
from edx_gen import _edx_consts
from edx_gen import _read_metadata
from edx_gen import _write_structure
from edx_gen import _write_comps
from edx_gen import _write_comp_html
from edx_gen import _write_comp_checkboxes
from edx_gen import _write_comp_video
from edx_gen i... | import sys, os
import tarfile
import shutil
from edx_gen import _edx_consts
from edx_gen import _read_metadata
from edx_gen import _write_structure
from edx_gen import _write_comps
from edx_gen import _write_comp_html
from edx_gen import _write_comp_checkboxes
from edx_gen import _write_comp_video
from edx_gen i... | en | 0.592802 | #-------------------------------------------------------------------------------------------------- # Text strings #-------------------------------------------------------------------------------------------------- # write to either units folder or problems folder, depending on the type # print("component_path", compon... | 2.113489 | 2 |
grading_program.py | ByeonghoonJeon/Student-Grading | 0 | 3361 | # 1. Create students score dictionary.
students_score = {}
# 2. Input student's name and check if input is correct. (Alphabet, period, and blank only.)
# 2.1 Creat a function that evaluate the validity of name.
def check_name(name):
# 2.1.1 Remove period and blank and check it if the name is comprised with on... | # 1. Create students score dictionary.
students_score = {}
# 2. Input student's name and check if input is correct. (Alphabet, period, and blank only.)
# 2.1 Creat a function that evaluate the validity of name.
def check_name(name):
# 2.1.1 Remove period and blank and check it if the name is comprised with on... | en | 0.713984 | # 1. Create students score dictionary. # 2. Input student's name and check if input is correct. (Alphabet, period, and blank only.) # 2.1 Creat a function that evaluate the validity of name. # 2.1.1 Remove period and blank and check it if the name is comprised with only Alphabet. # 2.1.1.1 Make a list of spelling... | 4.302821 | 4 |
test/test_utils.py | by46/recipe | 0 | 3362 | import unittest
from recipe import utils
class UtilTestCase(unittest.TestCase):
def test_valid_project_slug(self):
project_slug = "Recipe0123456789_mock"
self.assertTrue(utils.valid_project_slug(project_slug))
project_slug = 'Recipe00000000000000000000000000000000000000000000'
... | import unittest
from recipe import utils
class UtilTestCase(unittest.TestCase):
def test_valid_project_slug(self):
project_slug = "Recipe0123456789_mock"
self.assertTrue(utils.valid_project_slug(project_slug))
project_slug = 'Recipe00000000000000000000000000000000000000000000'
... | ja | 0.330916 | #$%^&*()_+" | 2.99928 | 3 |
extern/smplx_kinect/smplx_kinect/common/avakhitov_utils.py | wangxihao/rgbd-kinect-pose | 1 | 3363 | import numpy as np
import cv2
import os.path as osp
import json
from human_body_prior.tools.model_loader import load_vposer
import torch
vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/'
def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl):
po... | import numpy as np
import cv2
import os.path as osp
import json
from human_body_prior.tools.model_loader import load_vposer
import torch
vposer_ckpt = '/Vol1/dbstore/datasets/a.vakhitov/projects/pykinect_fresh/smplify-x/smplify-x-data/vposer_v1_0/'
def load_avakhitov_fits_vposer(vposer, part_path, dev_lbl):
po... | en | 0.516263 | # do we use vposer embeddings # gender of a subject # id of a device (used to decode the rigid pose of the device) # load the device pose # convert from vposer to rotation matrices #load the vposer model #convert from vposer to rotation matrices Calculates the rotation matrices for a batch of rotation vectors P... | 2.171277 | 2 |
scripts/dev/dockerutil.py | axelbarjon/mongodb-kubernetes-operator | 1 | 3364 | import docker
from dockerfile_generator import render
import os
import json
from tqdm import tqdm
from typing import Union, Any, Optional
def build_image(repo_url: str, tag: str, path: str) -> None:
"""
build_image builds the image with the given tag
"""
client = docker.from_env()
print(f"Buildin... | import docker
from dockerfile_generator import render
import os
import json
from tqdm import tqdm
from typing import Union, Any, Optional
def build_image(repo_url: str, tag: str, path: str) -> None:
"""
build_image builds the image with the given tag
"""
client = docker.from_env()
print(f"Buildin... | en | 0.906266 | build_image builds the image with the given tag push_image pushes the given tag. It uses the current docker environment # We do not want to republish an image that has not changed, so we check if the new # pair repo:tag already exists. # We also need to catch APIError as if the image has been recently deleted (unco... | 2.423348 | 2 |
scripts/VCF/UTILS/select_variants.py | elowy01/igsr_analysis | 3 | 3365 | <gh_stars>1-10
from VcfFilter import VcfFilter
import argparse
import os
#get command line arguments
parser = argparse.ArgumentParser(description='Script to select a certain variant type from a VCF file')
#parameters
parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the Bcfto... | from VcfFilter import VcfFilter
import argparse
import os
#get command line arguments
parser = argparse.ArgumentParser(description='Script to select a certain variant type from a VCF file')
#parameters
parser.add_argument('--bcftools_folder', type=str, required=True, help='Folder containing the Bcftools binary' )
p... | en | 0.046184 | #get command line arguments #parameters | 3.03187 | 3 |
site/tests/unittests/test/test_base64.py | martinphellwig/brython_wf | 652 | 3366 | <filename>site/tests/unittests/test/test_base64.py
import unittest
from test import support
import base64
import binascii
import os
import sys
import subprocess
class LegacyBase64TestCase(unittest.TestCase):
def test_encodebytes(self):
eq = self.assertEqual
eq(base64.encodebytes(b"www.python.org"... | <filename>site/tests/unittests/test/test_base64.py
import unittest
from test import support
import base64
import binascii
import os
import sys
import subprocess
class LegacyBase64TestCase(unittest.TestCase):
def test_encodebytes(self):
eq = self.assertEqual
eq(base64.encodebytes(b"www.python.org"... | en | 0.653369 | #0^&*();:<>,. []{}"), # Non-bytes #0^&*();:<>,. []{}") # Non-bytes #0^&*();:<>,. []{}') # Non-binary files # Non-binary files # Test default alphabet #0^&*();:<>,. []{}"), # Test with arbitrary alternative characters # Non-bytes # Check if passing a str object raises an error # Test standard alphabet #0^&*();:<>,. []{}... | 2.826496 | 3 |
appliance_catalog/migrations/0015_appliance_icon_py3.py | ChameleonCloud/portal | 3 | 3367 | <filename>appliance_catalog/migrations/0015_appliance_icon_py3.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-02-25 20:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
"""Updates ImageField syntax for later version.
"... | <filename>appliance_catalog/migrations/0015_appliance_icon_py3.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-02-25 20:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
"""Updates ImageField syntax for later version.
"... | en | 0.800606 | # -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-02-25 20:32 Updates ImageField syntax for later version. | 1.204292 | 1 |
twitoff/twitter.py | ChristopherKchilton/twitoff-ChristopherKchilton | 1 | 3368 | <reponame>ChristopherKchilton/twitoff-ChristopherKchilton
"""Retrieve and request tweets from the DS API"""
import requests
import spacy
from .models import DB, Tweet, User
nlp = spacy.load("my_model")
def vectorize_tweet(tweet_text):
return nlp(tweet_text).vector
# Add and updates tweets
def add_or_update_use... | """Retrieve and request tweets from the DS API"""
import requests
import spacy
from .models import DB, Tweet, User
nlp = spacy.load("my_model")
def vectorize_tweet(tweet_text):
return nlp(tweet_text).vector
# Add and updates tweets
def add_or_update_user(username):
"""Adds and updates the user with twiter ... | en | 0.501005 | Retrieve and request tweets from the DS API # Add and updates tweets Adds and updates the user with twiter handle 'username' to our database #TODO: Figure out # print(user) # This is either respectively grabs or creates a user for our db # This adds the db_user to our database # if tweets: # db_user.newest_twee... | 3.298044 | 3 |
day22.py | p88h/aoc2017 | 1 | 3369 | import io
grid = {}
y = 0
x = 0
for l in io.open("day22.in").read().splitlines():
for x in range(len(l)):
grid[(y,x)] = l[x]
y += 1
y = y // 2
x = x // 2
dx = 0
dy = -1
r = 0
for iter in range(10000000):
if (y,x) not in grid or grid[(y,x)] == '.':
(dy, dx) = (-dx, dy)
grid[(y,x)] = ... | import io
grid = {}
y = 0
x = 0
for l in io.open("day22.in").read().splitlines():
for x in range(len(l)):
grid[(y,x)] = l[x]
y += 1
y = y // 2
x = x // 2
dx = 0
dy = -1
r = 0
for iter in range(10000000):
if (y,x) not in grid or grid[(y,x)] == '.':
(dy, dx) = (-dx, dy)
grid[(y,x)] = ... | none | 1 | 3.034955 | 3 | |
ansys/dpf/core/errors.py | TheGoldfish01/pydpf-core | 11 | 3370 | from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous
from functools import wraps
_COMPLEX_PLOTTING_ERROR_MSG = """
Complex fields cannot be plotted. Use operators to get the amplitude
or the result at a defined sweeping phase before plotting.
"""
_FIELD_CONTAINER_PLOTTING_MSG = """"
This fields_conta... | from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous
from functools import wraps
_COMPLEX_PLOTTING_ERROR_MSG = """
Complex fields cannot be plotted. Use operators to get the amplitude
or the result at a defined sweeping phase before plotting.
"""
_FIELD_CONTAINER_PLOTTING_MSG = """"
This fields_conta... | en | 0.770039 | Complex fields cannot be plotted. Use operators to get the amplitude or the result at a defined sweeping phase before plotting. " This fields_container contains multiple fields. Only one time-step result can be plotted at a time. Extract a field with ``fields_container[index]``. Error raised when the dpf-core/grpc-dpf... | 2.301663 | 2 |
deep_disfluency/feature_extraction/wer_calculation_from_final_asr_results.py | askender/deep_disfluency | 0 | 3371 | from mumodo.mumodoIO import open_intervalframe_from_textgrid
import numpy
from deep_disfluency.utils.accuracy import wer
final_file = open('wer_test.text', "w")
ranges1 = [line.strip() for line in open(
"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detectio... | from mumodo.mumodoIO import open_intervalframe_from_textgrid
import numpy
from deep_disfluency.utils.accuracy import wer
final_file = open('wer_test.text', "w")
ranges1 = [line.strip() for line in open(
"/media/data/jh/simple_rnn_disf/rnn_disf_detection/data/disfluency_detection/swda_divisions_disfluency_detectio... | en | 0.592691 | # Based on the results, output the 'good' ASR results # print l # both speakers are under 40% error rate- likely half decent separation # print l #file.write(l.strip('\n').split(" ")[0]+l.strip('\n').split(" ")[1]+"\n") | 2.394509 | 2 |
newsweec/utils/_dataclasses.py | Adwaith-Rajesh/newsweec | 13 | 3372 | from dataclasses import dataclass
from dataclasses import field
from time import time
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
@dataclass
class NewUser:
"""Deals with the commands the user is currently ... | from dataclasses import dataclass
from dataclasses import field
from time import time
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
@dataclass
class NewUser:
"""Deals with the commands the user is currently ... | en | 0.864548 | Deals with the commands the user is currently sending Stores the latest command sent by the user # for garbage collection Important things in the message Info about the user from the DB # if false, the bot will not send any news feeds on a daily basis For FunctionStagingArea | 2.956521 | 3 |
vivo2notld/definitions/person_definition.py | gwu-libraries/vivo2notld | 5 | 3373 | <filename>vivo2notld/definitions/person_definition.py
from .document_summary import definition as document_summary_definition
from .organization_summary import definition as organization_summmary_definition
definition = {
"where": "?subj a foaf:Person .",
"fields": {
"name": {
"where": "?su... | <filename>vivo2notld/definitions/person_definition.py
from .document_summary import definition as document_summary_definition
from .organization_summary import definition as organization_summmary_definition
definition = {
"where": "?subj a foaf:Person .",
"fields": {
"name": {
"where": "?su... | es | 0.456749 | #Contact info ?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ?vc vcard:hasEmail ?vce . ?vce a vcard:Email, vcard:Work . ?vce vcard:email ?obj . ?subj obo:ARG_2000028 ?vc . ?vc a vcard:Kind . ... | 2.192925 | 2 |
apart/search.py | ruslan-ok/ServerApps | 1 | 3374 | <filename>apart/search.py
from django.db.models import Q
from hier.search import SearchResult
from .models import app_name, Apart, Meter, Bill, Service, Price
def search(user, query):
result = SearchResult(query)
lookups = Q(name__icontains=query) | Q(addr__icontains=query)
items = Apart.objects.filte... | <filename>apart/search.py
from django.db.models import Q
from hier.search import SearchResult
from .models import app_name, Apart, Meter, Bill, Service, Price
def search(user, query):
result = SearchResult(query)
lookups = Q(name__icontains=query) | Q(addr__icontains=query)
items = Apart.objects.filte... | none | 1 | 2.199438 | 2 | |
pyrevolve/experiment_management.py | MRebolle/Battery-Robot | 0 | 3375 | <filename>pyrevolve/experiment_management.py<gh_stars>0
import os
import shutil
import numpy as np
from pyrevolve.custom_logging.logger import logger
import sys
class ExperimentManagement:
# ids of robots in the name of all types of files are always phenotype ids, and the standard for id is 'robot_ID'
def __... | <filename>pyrevolve/experiment_management.py<gh_stars>0
import os
import shutil
import numpy as np
from pyrevolve.custom_logging.logger import logger
import sys
class ExperimentManagement:
# ids of robots in the name of all types of files are always phenotype ids, and the standard for id is 'robot_ID'
def __... | en | 0.88955 | # ids of robots in the name of all types of files are always phenotype ids, and the standard for id is 'robot_ID' # body and brain files # the latest complete snapshot # number of robots expected until the snapshot # if there are more robots to recover than the number expected in this snapshot # then recover also this ... | 2.352227 | 2 |
books/model/Instrumentation.py | nudglabs/books-python-wrappers | 9 | 3376 | #$Id$
class Instrumentation:
"""This class is used tocreate object for instrumentation."""
def __init__(self):
"""Initialize parameters for Instrumentation object."""
self.query_execution_time = ''
self.request_handling_time = ''
self.response_write_time = ''
self.page_c... | #$Id$
class Instrumentation:
"""This class is used tocreate object for instrumentation."""
def __init__(self):
"""Initialize parameters for Instrumentation object."""
self.query_execution_time = ''
self.request_handling_time = ''
self.response_write_time = ''
self.page_c... | en | 0.7718 | #$Id$ This class is used tocreate object for instrumentation. Initialize parameters for Instrumentation object. Set query execution time. Args: query_execution_time(str): Query execution time. Get query execution time. Returns: str: Query execution time. Set request handling ti... | 2.582251 | 3 |
DPR/setup.py | sophiaalthammer/parm | 18 | 3377 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from setuptools import setup
with open("README.md") as f:
readme = f.read()
setup(
name="dpr",
version="... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from setuptools import setup
with open("README.md") as f:
readme = f.read()
setup(
name="dpr",
version="... | en | 0.895295 | #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. | 1.130064 | 1 |
leetcode/hard/smallest_range/srcs/a_with_ordered_dict.py | BillionsRichard/pycharmWorkspace | 0 | 3378 | # encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: <EMAIL>
@site:
@software: PyCharm
@time: 2019/9/12 20:37
"""
from pprint import pprint as pp
from operator import itemgetter
import time
from collections import OrderedDict
from hard.smallest_range.srcs.big_2d_list impo... | # encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: <EMAIL>
@site:
@software: PyCharm
@time: 2019/9/12 20:37
"""
from pprint import pprint as pp
from operator import itemgetter
import time
from collections import OrderedDict
from hard.smallest_range.srcs.big_2d_list impo... | en | 0.368997 | # encoding: utf-8 @version: v1.0 @author: Richard @license: Apache Licence @contact: <EMAIL> @site: @software: PyCharm @time: 2019/9/12 20:37 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出: [20,24] # print(k_tagged_merged_list) # print('min_range_len', min_range_len) # print('tot_len', tot_len) # print('... | 3.207368 | 3 |
pcf/particle/gcp/storage/storage.py | davidyum/Particle-Cloud-Framework | 0 | 3379 | <reponame>davidyum/Particle-Cloud-Framework<filename>pcf/particle/gcp/storage/storage.py
from pcf.core.gcp_resource import GCPResource
from pcf.core import State
import logging
from google.cloud import storage
from google.cloud import exceptions
logger = logging.getLogger(__name__)
class Storage(GCPResource):
"... | from pcf.core.gcp_resource import GCPResource
from pcf.core import State
import logging
from google.cloud import storage
from google.cloud import exceptions
logger = logging.getLogger(__name__)
class Storage(GCPResource):
"""
This is the implementation of Google's storage service.
"""
flavor = "stor... | en | 0.732241 | This is the implementation of Google's storage service. Logic that sets keys from state definition that are used to uniquely identify the storage bucket Determines if the bucket exists Returns: status (dict) Deletes the storage bucket Returns: response of gcp delete Creates t... | 2.509573 | 3 |
cimcb/utils/smooth.py | CIMCB/cimcb | 5 | 3380 | import numpy as np
def smooth(a, WSZ):
# a: NumPy 1-D array containing the data to be smoothed
# WSZ: smoothing window size needs, which must be odd number,
# as in the original MATLAB implementation
if WSZ % 2 == 0:
WSZ = WSZ - 1
out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / W... | import numpy as np
def smooth(a, WSZ):
# a: NumPy 1-D array containing the data to be smoothed
# WSZ: smoothing window size needs, which must be odd number,
# as in the original MATLAB implementation
if WSZ % 2 == 0:
WSZ = WSZ - 1
out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / W... | en | 0.79542 | # a: NumPy 1-D array containing the data to be smoothed # WSZ: smoothing window size needs, which must be odd number, # as in the original MATLAB implementation | 2.983879 | 3 |
ezeeai/core/extensions/best_exporter.py | jmarine/ezeeai | 19 | 3381 | from __future__ import absolute_import
import abc
import os
import json
import glob
import shutil
from tensorflow.python.estimator import gc
from tensorflow.python.estimator import util
from tensorflow.python.estimator.canned import metric_keys
from tensorflow.python.framework import errors_impl
from tensorflow.pytho... | from __future__ import absolute_import
import abc
import os
import json
import glob
import shutil
from tensorflow.python.estimator import gc
from tensorflow.python.estimator import util
from tensorflow.python.estimator.canned import metric_keys
from tensorflow.python.framework import errors_impl
from tensorflow.pytho... | en | 0.655279 | Verifies compare_fn arguments. Compares two evaluation results and returns true if the 2nd one is smaller. Both evaluation results should have the values for MetricKeys.LOSS, which are used for comparison. Args: best_eval_result: best eval metrics. current_eval_result: current eval metrics. ... | 2.068379 | 2 |
src/pkgcore/restrictions/restriction.py | mgorny/pkgcore | 0 | 3382 | <reponame>mgorny/pkgcore<filename>src/pkgcore/restrictions/restriction.py<gh_stars>0
# Copyright: 2005-2012 <NAME> <<EMAIL>
# Copyright: 2006 <NAME> <<EMAIL>>
# License: BSD/GPL2
"""
base restriction class
"""
from functools import partial
from snakeoil import caching, klass
from snakeoil.currying import pretty_docs... | # Copyright: 2005-2012 <NAME> <<EMAIL>
# Copyright: 2006 <NAME> <<EMAIL>>
# License: BSD/GPL2
"""
base restriction class
"""
from functools import partial
from snakeoil import caching, klass
from snakeoil.currying import pretty_docs
class base(object, metaclass=caching.WeakInstMeta):
"""base restriction matchi... | en | 0.666384 | # Copyright: 2005-2012 <NAME> <<EMAIL> # Copyright: 2006 <NAME> <<EMAIL>> # License: BSD/GPL2 base restriction class base restriction matching object. all derivatives *should* be __slot__ based (lot of instances may wind up in memory). # __weakref__ here is implicit via the metaclass restriction that always yi... | 2.417399 | 2 |
keylime/migrations/versions/8da20383f6e1_extend_ip_field.py | kkaarreell/keylime | 18 | 3383 | """extend_ip_field
Revision ID: 8da20383f6e1
Revises: <KEY>
Create Date: 2021-01-14 10:50:56.275257
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "8da20383f6e1"
down_revision = "<KEY>"
branch_labels = None
depends_on = None
def upgrade(engine_name):
glob... | """extend_ip_field
Revision ID: 8da20383f6e1
Revises: <KEY>
Create Date: 2021-01-14 10:50:56.275257
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "8da20383f6e1"
down_revision = "<KEY>"
branch_labels = None
depends_on = None
def upgrade(engine_name):
glob... | en | 0.400478 | extend_ip_field Revision ID: 8da20383f6e1 Revises: <KEY> Create Date: 2021-01-14 10:50:56.275257 # revision identifiers, used by Alembic. | 1.445187 | 1 |
token_train/quickdemo(1)(1).py | Tatsuya26/processamento_de_linguagens | 0 | 3384 | <filename>token_train/quickdemo(1)(1).py
import ply.lex as lex
tokens =["NUM","OPERADORES"]
t_NUM = '\d+'
t_OPERADORES = '[+|*|-]'
t_ignore='\n\t '
def t_error(t):
print("Erro")
print(t)
lexer = lex.lex()
# 1+2 1-2 1*2
# ola mundo
import sys
for line in sys.stdin:
lexer.input(line)
for tok in lex... | <filename>token_train/quickdemo(1)(1).py
import ply.lex as lex
tokens =["NUM","OPERADORES"]
t_NUM = '\d+'
t_OPERADORES = '[+|*|-]'
t_ignore='\n\t '
def t_error(t):
print("Erro")
print(t)
lexer = lex.lex()
# 1+2 1-2 1*2
# ola mundo
import sys
for line in sys.stdin:
lexer.input(line)
for tok in lex... | en | 0.174855 | # 1+2 1-2 1*2 # ola mundo | 3.033324 | 3 |
ucsrb/migrations/0013_auto_20180710_2040.py | Ecotrust/ucsrb | 1 | 3385 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-07-10 20:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ucsrb', '0012_auto_20180710_1249'),
]
operations = [
migrations.AddField(
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-07-10 20:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ucsrb', '0012_auto_20180710_1249'),
]
operations = [
migrations.AddField(
... | en | 0.649276 | # -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-07-10 20:40 | 1.62959 | 2 |
src/ctc/protocols/fei_utils/analytics/payload_crud.py | fei-protocol/checkthechain | 94 | 3386 | from __future__ import annotations
import typing
from ctc import spec
from . import timestamp_crud
from . import metric_crud
from . import analytics_spec
async def async_create_payload(
*,
blocks: typing.Sequence[spec.BlockNumberReference] | None = None,
timestamps: typing.Sequence[int] | None = None,
... | from __future__ import annotations
import typing
from ctc import spec
from . import timestamp_crud
from . import metric_crud
from . import analytics_spec
async def async_create_payload(
*,
blocks: typing.Sequence[spec.BlockNumberReference] | None = None,
timestamps: typing.Sequence[int] | None = None,
... | en | 0.528355 | create data payload from scratch # get data # # time data # # metric data # def update_payload( # timescale: analytics_spec.Timescale, # old_payload: analytics_spec.AnalyticsPayload, # ) -> analytics_spec.AnalyticsPayload: # new_timestamps = get_new_timestamps( # timescale=timescale, # old_p... | 2.238209 | 2 |
research/video_prediction/prediction_model.py | mbz/models | 1 | 3387 | # Copyright 2016 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 applicab... | # Copyright 2016 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 applicab... | en | 0.800815 | # Copyright 2016 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 applicab... | 2.072664 | 2 |
junit5/rules.bzl | prashantsharma04/bazel_java_rules | 1 | 3388 | <filename>junit5/rules.bzl
load("@rules_jvm_external//:defs.bzl", "artifact")
# For more information see
# - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD
# - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5
# - https://github.com/junit-team/junit5-samples/tree/m... | <filename>junit5/rules.bzl
load("@rules_jvm_external//:defs.bzl", "artifact")
# For more information see
# - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD
# - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5
# - https://github.com/junit-team/junit5-samples/tree/m... | en | 0.62342 | # For more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starter-bazel JUnit runner macro | 1.892612 | 2 |
tests/mocked_carla.py | fangedward/pylot | 0 | 3389 | # This module provides mocked versions of classes and functions provided
# by Carla in our runtime environment.
class Location(object):
""" A mock class for carla.Location. """
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Rotation(object):
""" A mock class... | # This module provides mocked versions of classes and functions provided
# by Carla in our runtime environment.
class Location(object):
""" A mock class for carla.Location. """
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Rotation(object):
""" A mock class... | en | 0.823416 | # This module provides mocked versions of classes and functions provided # by Carla in our runtime environment. A mock class for carla.Location. A mock class for carla.Rotation. A mock class for carla.Vector3D. | 3.103577 | 3 |
rgb_to_cmyk.py | Zweizack/fuzzy-rainbow | 0 | 3390 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
ee = '\033[1m'
green = '\033[32m'
yellow = '\033[33m'
cyan = '\033[36m'
line = cyan+'-' * 0x2D
print(ee+line)
R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()]
K = 1-max(R,G,B)
C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]]
K = r... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
ee = '\033[1m'
green = '\033[32m'
yellow = '\033[33m'
cyan = '\033[36m'
line = cyan+'-' * 0x2D
print(ee+line)
R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()]
K = 1-max(R,G,B)
C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]]
K = r... | en | 0.308914 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- | 2.937515 | 3 |
docs/updatedoc.py | JukeboxPipeline/jukedj | 2 | 3391 | <gh_stars>1-10
#!/usr/bin/env python
"""Builds the documentaion. First it runs gendoc to create rst files for the source code. Then it runs sphinx make.
.. Warning:: This will delete the content of the output directory first! So you might loose data.
You can use updatedoc.py -nod.
Usage, just call::
upd... | #!/usr/bin/env python
"""Builds the documentaion. First it runs gendoc to create rst files for the source code. Then it runs sphinx make.
.. Warning:: This will delete the content of the output directory first! So you might loose data.
You can use updatedoc.py -nod.
Usage, just call::
updatedoc.py -h
"... | en | 0.626617 | #!/usr/bin/env python Builds the documentaion. First it runs gendoc to create rst files for the source code. Then it runs sphinx make. .. Warning:: This will delete the content of the output directory first! So you might loose data. You can use updatedoc.py -nod. Usage, just call:: updatedoc.py -h Sets ... | 2.390479 | 2 |
sort/selectionsort.py | vitormrts/sorting-algorithms | 0 | 3392 | def selection_sort(A): # O(n^2)
n = len(A)
for i in range(n-1): # percorre a lista
min = i
for j in range(i+1, n): # encontra o menor elemento da lista a partir de i + 1
if A[j] < A[min]:
min = j
A[i], A[min] = A[min], A[i] # insere o elemento na posicao corre... | def selection_sort(A): # O(n^2)
n = len(A)
for i in range(n-1): # percorre a lista
min = i
for j in range(i+1, n): # encontra o menor elemento da lista a partir de i + 1
if A[j] < A[min]:
min = j
A[i], A[min] = A[min], A[i] # insere o elemento na posicao corre... | pt | 0.206747 | # O(n^2) # percorre a lista # encontra o menor elemento da lista a partir de i + 1 # insere o elemento na posicao correta # 1 + (n-1)*[3 + X] = 1 + 3*(n-1) + X*(n-1) = 1 + 3*(n-1) + (n^2 + n - 2)/2 # = (1 - 3 - 1) + (3n + n/2) + (n^2/2) # The complexity is O(n^2) | 3.793517 | 4 |
BridgeOptimizer/scriptBuilder/ScriptBuilderBoundaryConditions.py | manuel1618/bridgeOptimizer | 1 | 3393 | import os
from typing import List, Tuple
from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector
from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep
from BridgeOptimizer.datastructure.hypermesh.Force import Force
from BridgeOptimizer.datastructure.hypermesh.SPC import SPC
cla... | import os
from typing import List, Tuple
from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector
from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep
from BridgeOptimizer.datastructure.hypermesh.Force import Force
from BridgeOptimizer.datastructure.hypermesh.SPC import SPC
cla... | en | 0.74238 | Extra class for generating Loadstep, Loadcollectors, Forces and Constraints Parameters: --------- None Creates all the load collectors (has to be done before creating loadsteps, as the loadcollectors are referenced) # create all load collectors and loads first # create loads Single method to write all tcl... | 2.078032 | 2 |
Lekcija08/script01.py | islamspahic/python-uup | 0 | 3394 | tajniBroj = 51
broj = 2
while tajniBroj != broj:
broj = int(input("Pogodite tajni broj: "))
if tajniBroj == broj:
print("Pogodak!")
elif tajniBroj < broj:
print("Tajni broj je manji od tog broja.")
else:
print("Tajni broj je veci od tog broja.")
print("Kraj programa")
| tajniBroj = 51
broj = 2
while tajniBroj != broj:
broj = int(input("Pogodite tajni broj: "))
if tajniBroj == broj:
print("Pogodak!")
elif tajniBroj < broj:
print("Tajni broj je manji od tog broja.")
else:
print("Tajni broj je veci od tog broja.")
print("Kraj programa")
| none | 1 | 3.684495 | 4 | |
tests/algorithms/memory/test_cmac.py | FrostByte266/neupy | 801 | 3395 | <gh_stars>100-1000
import numpy as np
from sklearn import metrics
from neupy import algorithms
from base import BaseTestCase
class CMACTestCase(BaseTestCase):
def test_cmac(self):
X_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1))
X_train_before = X_train.copy()
X_test = np.r... | import numpy as np
from sklearn import metrics
from neupy import algorithms
from base import BaseTestCase
class CMACTestCase(BaseTestCase):
def test_cmac(self):
X_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1))
X_train_before = X_train.copy()
X_test = np.reshape(np.linspace(... | en | 0.966877 | # Test that algorithm didn't modify data samples | 2.270041 | 2 |
src/ggrc_workflows/models/task_group_object.py | Smotko/ggrc-core | 0 | 3396 | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>
from sqlalchemy.ext.associationproxy import association_proxy
from ggrc import db
from ggrc.models.mixins import ... | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>
from sqlalchemy.ext.associationproxy import association_proxy
from ggrc import db
from ggrc.models.mixins import ... | en | 0.584746 | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: <EMAIL> # Maintained By: <EMAIL> | 1.891685 | 2 |
verification/tb_template.py | ahmednofal/DFFRAM | 0 | 3397 | # Copyright ©2020-2021 The American University in Cairo and the Cloud V Project.
#
# This file is part of the DFFRAM Memory Compiler.
# See https://github.com/Cloud-V/DFFRAM for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | # Copyright ©2020-2021 The American University in Cairo and the Cloud V Project.
#
# This file is part of the DFFRAM Memory Compiler.
# See https://github.com/Cloud-V/DFFRAM for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | en | 0.446877 | # Copyright ©2020-2021 The American University in Cairo and the Cloud V Project. # # This file is part of the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further info. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li... | 1.884027 | 2 |
services/stocks-api/app/api/clients/coinbase/CoinbaseResponse.py | krystianbajno/stocks | 3 | 3398 | <reponame>krystianbajno/stocks<filename>services/stocks-api/app/api/clients/coinbase/CoinbaseResponse.py<gh_stars>1-10
class CoinbaseResponse:
bid = 0
ask = 0
product_id = None
def set_bid(self, bid):
self.bid = float(bid)
def get_bid(self):
return self.bid
def set_ask(self, a... | class CoinbaseResponse:
bid = 0
ask = 0
product_id = None
def set_bid(self, bid):
self.bid = float(bid)
def get_bid(self):
return self.bid
def set_ask(self, ask):
self.ask = float(ask)
def get_ask(self):
return self.ask
def get_product_id(self):
... | none | 1 | 2.706544 | 3 | |
xclim/indices/_anuclim.py | bzah/xclim | 1 | 3399 | # noqa: D100
from typing import Optional
import numpy as np
import xarray
from xclim.core.units import (
convert_units_to,
declare_units,
pint_multiply,
rate2amount,
units,
units2pint,
)
from xclim.core.utils import ensure_chunk_size
from ._multivariate import (
daily_temperature_range,
... | # noqa: D100
from typing import Optional
import numpy as np
import xarray
from xclim.core.units import (
convert_units_to,
declare_units,
pint_multiply,
rate2amount,
units,
units2pint,
)
from xclim.core.utils import ensure_chunk_size
from ._multivariate import (
daily_temperature_range,
... | en | 0.771725 | # noqa: D100 # Frequencies : YS: year start, QS-DEC: seasons starting in december, MS: month start # See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases # -------------------------------------------------- # # ATTENTION: ASSUME ALL INDICES WRONG UNTIL TESTED ! # # ----------------------------... | 2.438198 | 2 |