uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
f2ff9a671bc3b5b66bfc93bc
train
class
class SmspNhsNumberNotVerifiedException(SmspException): message = 'NHS number does not match demographic details'
class SmspNhsNumberNotVerifiedException(SmspException):
message = 'NHS number does not match demographic details'
' class SmspNhsNumberSupersededException(SmspException): message = 'NHS number superseded' class SmspNhsNumberInvalidException(SmspException): message = 'NHS number not in use' class SmspNhsNumberNotVerifiedException(SmspException):
64
64
27
14
50
LCBRU/identity
identity/demographics/smsp.py
Python
SmspNhsNumberNotVerifiedException
SmspNhsNumberNotVerifiedException
166
167
166
166
b19a6f5843779645b31debedd98bac765566ebb0
bigcode/the-stack
train
f93b7b4b8bfb022c47de5d77
train
function
@check_no_collection def xmlvalue(self, value): if isinstance(value, six.string_types): # Make sure the string is a valid ISO date/time return value return self._xmlvalue(value)
@check_no_collection def xmlvalue(self, value):
if isinstance(value, six.string_types): # Make sure the string is a valid ISO date/time return value return self._xmlvalue(value)
from requests.auth import HTTPBasicAuth from zeep import Client from zeep.transports import Transport from zeep.xsd.types.builtins import check_no_collection, DateTime from pprint import pprint as pp from lxml import etree @check_no_collection def xmlvalue(self, value):
64
64
46
12
51
LCBRU/identity
identity/demographics/smsp.py
Python
xmlvalue
xmlvalue
12
19
12
14
b4969e83d211648f02151077d822dab45a47e993
bigcode/the-stack
train
a3cc7e10c74a019719e73ddb
train
class
class SmspNhsNumberSupersededException(SmspException): message = 'NHS number superseded'
class SmspNhsNumberSupersededException(SmspException):
message = 'NHS number superseded'
spException(Exception): message='Unspecified exception' class SmspNoMatchException(SmspException): message = 'No match found' class SmspMultipleMatchesException(SmspException): message = 'Multiple matches found' class SmspNhsNumberSupersededException(SmspException):
64
64
25
15
49
LCBRU/identity
identity/demographics/smsp.py
Python
SmspNhsNumberSupersededException
SmspNhsNumberSupersededException
162
163
162
162
dd457ffab0b13d0add940292accf6333e157cebd
bigcode/the-stack
train
60d56f74094b46384ce85389
train
class
class SmspException(Exception): message='Unspecified exception'
class SmspException(Exception):
message='Unspecified exception'
is not a 10 digit new style # NHS Number. Error code 42 is a typical example of one # error code which could have been returned by PDS in # this scenario. _SMSP_ERR_NHS_NUMBER_NOT_NEW_STYLE = 'DEMOG-0042' class SmspException(Exception):
64
64
13
6
58
LCBRU/identity
identity/demographics/smsp.py
Python
SmspException
SmspException
156
157
156
156
eff0b859b8008e0d50f557a12c4a9f4ad7ef81e2
bigcode/the-stack
train
821619ed963b5c8886db6d36
train
function
def get_demographics_from_nhs_number(nhs_number, dob): current_app.logger.info(f'Getting demographics from NHS Number ({nhs_number}) and date of birth ({dob})') client = _get_demographics_client() response = client.service.getPatientByNHSNumber( nhsNumber=nhs_number, dob=dob, )...
def get_demographics_from_nhs_number(nhs_number, dob):
current_app.logger.info(f'Getting demographics from NHS Number ({nhs_number}) and date of birth ({dob})') client = _get_demographics_client() response = client.service.getPatientByNHSNumber( nhsNumber=nhs_number, dob=dob, ) if response.responseCode == _SMSP_OK: r...
if response.responseCode == _SMSP_OK: return SmspPatient(response.nhsNumber, response.subject._value_1[0]) time.sleep(1) raise _SMSP_EXCEPTIONS[response.responseCode]() def get_demographics_from_nhs_number(nhs_number, dob):
63
64
138
14
49
LCBRU/identity
identity/demographics/smsp.py
Python
get_demographics_from_nhs_number
get_demographics_from_nhs_number
246
260
246
246
9d63a2a49f97c9b01497ca9faf4f434b40918e47
bigcode/the-stack
train
d923a02e8e27f1042f4cab53
train
class
class SmspNhsNumberNotNewStyleException(SmspException): message = 'NHS number invalid'
class SmspNhsNumberNotNewStyleException(SmspException):
message = 'NHS number invalid'
spNhsNumberInvalidException(SmspException): message = 'NHS number not in use' class SmspNhsNumberNotVerifiedException(SmspException): message = 'NHS number does not match demographic details' class SmspNhsNumberNotNewStyleException(SmspException):
64
64
24
15
49
LCBRU/identity
identity/demographics/smsp.py
Python
SmspNhsNumberNotNewStyleException
SmspNhsNumberNotNewStyleException
168
169
168
168
54694167c30e2b840d2cd5ff029703edb264c03c
bigcode/the-stack
train
c6d51367d54b8eb26bf84bfb
train
function
def get_demographics_from_search(family_name, given_name, gender, dob, postcode): # # family_name: Full surname, at least 2 characters and wildcard (*), or blank # given_name: Full given name, at least 2 characters and wildcard (*), or blank # gender: SEX_MALE or SEX_FEMALE # If gender ...
def get_demographics_from_search(family_name, given_name, gender, dob, postcode): # # family_name: Full surname, at least 2 characters and wildcard (*), or blank # given_name: Full given name, at least 2 characters and wildcard (*), or blank # gender: SEX_MALE or SEX_FEMALE # If gender ...
current_app.logger.info(f'Getting demographics from search') client = _get_demographics_client() if postcode: postcodes = [postcode, ''] else: postcodes = [''] if given_name: given_names = [given_name, ''] else: given_names = [''] response = ...
def get_demographics_from_search(family_name, given_name, gender, dob, postcode): # # family_name: Full surname, at least 2 characters and wildcard (*), or blank # given_name: Full given name, at least 2 characters and wildcard (*), or blank # gender: SEX_MALE or SEX_FEMALE # If gender ...
147
97
325
147
0
LCBRU/identity
identity/demographics/smsp.py
Python
get_demographics_from_search
get_demographics_from_search
201
243
201
210
a5163e53ea1bc3ab3e2913e5049d03a4828b1146
bigcode/the-stack
train
14247d202275f638278d8d8d
train
class
class SmspPatient: def __init__(self, nhs_number, xml): self._nhs_number = nhs_number self._xml = xml def get_text_from_xpath(self, xpath): element = self.get_element_from_xpath(xpath) if element is not None: return element.text def get_element_from_...
class SmspPatient:
def __init__(self, nhs_number, xml): self._nhs_number = nhs_number self._xml = xml def get_text_from_xpath(self, xpath): element = self.get_element_from_xpath(xpath) if element is not None: return element.text def get_element_from_xpath(self, xpath): ...
import six import time from flask import current_app from requests import Session from requests.auth import HTTPBasicAuth from zeep import Client from zeep.transports import Transport from zeep.xsd.types.builtins import check_no_collection, DateTime from pprint import pprint as pp from lxml import etree @ch...
139
184
616
5
133
LCBRU/identity
identity/demographics/smsp.py
Python
SmspPatient
SmspPatient
26
106
26
26
852567a9dd5a184670922c26bc0f89cdec9ff4bb
bigcode/the-stack
train
e9575567fe10569bde7322ba
train
function
def _get_demographics_client(): # This web service is maintained by Joss Markham (Joss.Markham@orionhealth.com) session = Session() session.verify = False session.auth = HTTPBasicAuth( current_app.config['SMSP_USERNAME'], current_app.config['SMSP_PASSWORD'], ) transport =...
def _get_demographics_client(): # This web service is maintained by Joss Markham (Joss.Markham@orionhealth.com)
session = Session() session.verify = False session.auth = HTTPBasicAuth( current_app.config['SMSP_USERNAME'], current_app.config['SMSP_PASSWORD'], ) transport = Transport(session=session) return Client( current_app.config['SMSP_URL'], transport=transport,...
0]) else: current_app.logger.info(f'SMSP error response "{response}"') raise _SMSP_EXCEPTIONS[response.responseCode]() def _get_demographics_client(): # This web service is maintained by Joss Markham (Joss.Markham@orionhealth.com)
63
64
96
30
33
LCBRU/identity
identity/demographics/smsp.py
Python
_get_demographics_client
_get_demographics_client
263
275
263
264
7575129597c2ad3d7583f9c1a308acc71e650b6d
bigcode/the-stack
train
4828ec1176d98a4c077fd8ce
train
function
def verify_nhs_number(family_name, given_name, nhs_number, dob): client = _get_demographics_client() response = client.service.verifyNHSNumber( familyName=family_name, givenName=given_name, nhs_number=nhs_number, dob=dob, ) if response.responseCode == _SMSP_...
def verify_nhs_number(family_name, given_name, nhs_number, dob):
client = _get_demographics_client() response = client.service.verifyNHSNumber( familyName=family_name, givenName=given_name, nhs_number=nhs_number, dob=dob, ) if response.responseCode == _SMSP_OK: return response.isValid else: raise _SMSP...
, _SMSP_ERR_NHS_NUMBER_NOT_NEW_STYLE: SmspNhsNumberNotNewStyleException, } SMSP_SEX_MALE = '1' SMSP_SEX_FEMALE = '2' def verify_nhs_number(family_name, given_name, nhs_number, dob):
63
64
101
18
45
LCBRU/identity
identity/demographics/smsp.py
Python
verify_nhs_number
verify_nhs_number
184
198
184
185
49caaf7f787e02bf616b92d1383a5662dc9203d1
bigcode/the-stack
train
a8a560257e0690d94119367f
train
class
class SmspMultipleMatchesException(SmspException): message = 'Multiple matches found'
class SmspMultipleMatchesException(SmspException):
message = 'Multiple matches found'
# this scenario. _SMSP_ERR_NHS_NUMBER_NOT_NEW_STYLE = 'DEMOG-0042' class SmspException(Exception): message='Unspecified exception' class SmspNoMatchException(SmspException): message = 'No match found' class SmspMultipleMatchesException(SmspException):
64
64
19
11
53
LCBRU/identity
identity/demographics/smsp.py
Python
SmspMultipleMatchesException
SmspMultipleMatchesException
160
161
160
160
d7baea120b31a5cea2308c1e2d211ef7dbda4e36
bigcode/the-stack
train
392ff35d8972dea5834f2896
train
class
class Allocation(base.Resource): pass
class Allocation(base.Resource):
pass
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from placementclient import base class Allocation(base.Resource)...
64
64
8
5
58
NeCTAR-RC/python-placementclient
placementclient/v1/allocations.py
Python
Allocation
Allocation
17
18
17
17
0d661834cd6d59b58494228d1c62aa8e2a66a18b
bigcode/the-stack
train
d316ca9f6e89f911f32c13e2
train
class
class AllocationManager(base.BasicManager): base_url = 'allocations' resource_class = Allocation def list(self, consumer_id): return self._list('/%s/%s' % (self.base_url, consumer_id), response_key=self.base_url) def delete(self, consumer_id): return self._de...
class AllocationManager(base.BasicManager):
base_url = 'allocations' resource_class = Allocation def list(self, consumer_id): return self._list('/%s/%s' % (self.base_url, consumer_id), response_key=self.base_url) def delete(self, consumer_id): return self._delete('/%s/%s' % (self.base_url, consumer_id))...
AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from placementclient import base class Allocation(base.Resource): pass class AllocationManager(base.BasicManager)...
64
64
84
7
56
NeCTAR-RC/python-placementclient
placementclient/v1/allocations.py
Python
AllocationManager
AllocationManager
21
31
21
22
8246e787287d7426f8322a71ec298b93fe275e57
bigcode/the-stack
train
40de7d232e507dcdc8a070db
train
class
class LexerBuilder: tokens = () def __init__(self): LexerBuilder.tokens = list(set().union( modelTokens, dataTypeTokens, trainTokens, trainProfileTokens, basicSQL )) pass def build( self, **kwargs): print( ...
class LexerBuilder:
tokens = () def __init__(self): LexerBuilder.tokens = list(set().union( modelTokens, dataTypeTokens, trainTokens, trainProfileTokens, basicSQL )) pass def build( self, **kwargs): print( LexerBuilder.tokens )...
import ply.lex as lex import dill from tokens.definitions import * from tokens.data_types import * from tokens.manipulations import * from tokens.sql import * class LexerBuilder:
37
93
310
4
33
adhocmaster/MLSQL
parser/LexerBuilder_del.py
Python
LexerBuilder
LexerBuilder
8
62
8
9
78e38abb4e754f7400bf143da3524afff6e38350
bigcode/the-stack
train
4927d5e5b40770eac4d44774
train
class
class TestSkipQobjValidation(QiskitAlgorithmsTestCase): """Test Skip Qobj Validation""" def setUp(self): super().setUp() self.random_seed = 10598 qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]...
class TestSkipQobjValidation(QiskitAlgorithmsTestCase):
"""Test Skip Qobj Validation""" def setUp(self): super().setUp() self.random_seed = 10598 qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 ...
iskit. # # (C) Copyright IBM 2019, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code m...
256
256
884
13
242
WiFisunset/qiskit-terra
test/python/algorithms/test_skip_qobj_validation.py
Python
TestSkipQobjValidation
TestSkipQobjValidation
36
131
36
36
136433a3e400019a9ef3ec0790ac492f5dc24b58
bigcode/the-stack
train
7e395c08095903457dd15f9f
train
function
def _compare_dict(dict1, dict2): equal = True for key1, value1 in dict1.items(): if key1 not in dict2: equal = False break if value1 != dict2[key1]: equal = False break return equal
def _compare_dict(dict1, dict2):
equal = True for key1, value1 in dict1.items(): if key1 not in dict2: equal = False break if value1 != dict2[key1]: equal = False break return equal
test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer from qiskit.utils import QuantumInstance from qiskit.exceptions import QiskitError def _compare_dict(dict1, dict2):
64
64
66
10
53
WiFisunset/qiskit-terra
test/python/algorithms/test_skip_qobj_validation.py
Python
_compare_dict
_compare_dict
24
33
24
24
6c29a6548def6a74d9bc1b88efe59a39b1b6f00e
bigcode/the-stack
train
14069922e37a053bd215d4d4
train
class
class TestFlowControlDataQueue: def test_feed_pause(self, buffer: Any) -> None: buffer._protocol._reading_paused = False buffer.feed_data(object(), 100) assert buffer._protocol.pause_reading.called async def test_resume_on_read(self, buffer: Any) -> None: buffer.feed_data(objec...
class TestFlowControlDataQueue:
def test_feed_pause(self, buffer: Any) -> None: buffer._protocol._reading_paused = False buffer.feed_data(object(), 100) assert buffer._protocol.pause_reading.called async def test_resume_on_read(self, buffer: Any) -> None: buffer.feed_data(object(), 100) buffer._proto...
" assert stream._protocol.resume_reading.call_count == 1 stream._protocol._reading_paused = False res = stream.read_nowait(5) assert res == b"" assert stream._protocol.resume_reading.call_count == 1 class TestFlowControlDataQueue:
64
64
102
7
56
ikrivosheev/aiohttp
tests/test_flowcontrol_streams.py
Python
TestFlowControlDataQueue
TestFlowControlDataQueue
119
131
119
119
5760ab380f5a554e8f063e6ff77d5b3159676ba9
bigcode/the-stack
train
ec33af730dd202ccf76a3ef7
train
class
class TestFlowControlStreamReader: async def test_read(self, stream: Any) -> None: stream.feed_data(b"da", 2) res = await stream.read(1) assert res == b"d" assert not stream._protocol.resume_reading.called async def test_read_resume_paused(self, stream: Any) -> None: str...
class TestFlowControlStreamReader:
async def test_read(self, stream: Any) -> None: stream.feed_data(b"da", 2) res = await stream.read(1) assert res == b"d" assert not stream._protocol.resume_reading.called async def test_read_resume_paused(self, stream: Any) -> None: stream.feed_data(b"test", 4) s...
# type: ignore from typing import Any from unittest import mock import pytest from aiohttp import streams @pytest.fixture def protocol(): return mock.Mock(_reading_paused=False) @pytest.fixture def stream(loop: Any, protocol: Any): out = streams.StreamReader(protocol, limit=1, loop=loop) out._allow_pa...
131
244
814
7
123
ikrivosheev/aiohttp
tests/test_flowcontrol_streams.py
Python
TestFlowControlStreamReader
TestFlowControlStreamReader
29
116
29
29
dc6757978344155d50ecd1d6ff4774f2b099b28c
bigcode/the-stack
train
3b6e1378ef790351f8d707d0
train
function
@pytest.fixture def stream(loop: Any, protocol: Any): out = streams.StreamReader(protocol, limit=1, loop=loop) out._allow_pause = True return out
@pytest.fixture def stream(loop: Any, protocol: Any):
out = streams.StreamReader(protocol, limit=1, loop=loop) out._allow_pause = True return out
# type: ignore from typing import Any from unittest import mock import pytest from aiohttp import streams @pytest.fixture def protocol(): return mock.Mock(_reading_paused=False) @pytest.fixture def stream(loop: Any, protocol: Any):
53
64
41
13
40
ikrivosheev/aiohttp
tests/test_flowcontrol_streams.py
Python
stream
stream
15
19
15
16
2423090e0357387e1b4a5aa8b201c51862ca0ce4
bigcode/the-stack
train
0fa711a2b764eee3ab51a98b
train
function
@pytest.fixture def protocol(): return mock.Mock(_reading_paused=False)
@pytest.fixture def protocol():
return mock.Mock(_reading_paused=False)
# type: ignore from typing import Any from unittest import mock import pytest from aiohttp import streams @pytest.fixture def protocol():
30
64
16
6
23
ikrivosheev/aiohttp
tests/test_flowcontrol_streams.py
Python
protocol
protocol
10
12
10
11
6b2131d57c9273d4b1195b81a7cc711748b7a8b4
bigcode/the-stack
train
9b31063fd6b208cf4bbacbeb
train
function
@pytest.fixture def buffer(loop: Any, protocol: Any): out = streams.FlowControlDataQueue(protocol, limit=1, loop=loop) out._allow_pause = True return out
@pytest.fixture def buffer(loop: Any, protocol: Any):
out = streams.FlowControlDataQueue(protocol, limit=1, loop=loop) out._allow_pause = True return out
return mock.Mock(_reading_paused=False) @pytest.fixture def stream(loop: Any, protocol: Any): out = streams.StreamReader(protocol, limit=1, loop=loop) out._allow_pause = True return out @pytest.fixture def buffer(loop: Any, protocol: Any):
64
64
43
13
50
ikrivosheev/aiohttp
tests/test_flowcontrol_streams.py
Python
buffer
buffer
22
26
22
23
fc625f35c6500a2fa28606b932f62a92e39b9052
bigcode/the-stack
train
598c1e60dff04a0346a6589f
train
class
class AddAlgorithmPageLocators: DATA_TABLE = By.CLASS_NAME, 'table-responsive' ADD_FORM = By.ID, 'add-form' ADD_BUTTON = By.ID, 'addButton' DELETE_BUTTON = By.CLASS_NAME, 'delete-button' ALGORITHM = By.XPATH, '//*[@class="center sorting_1"]'
class AddAlgorithmPageLocators:
DATA_TABLE = By.CLASS_NAME, 'table-responsive' ADD_FORM = By.ID, 'add-form' ADD_BUTTON = By.ID, 'addButton' DELETE_BUTTON = By.CLASS_NAME, 'delete-button' ALGORITHM = By.XPATH, '//*[@class="center sorting_1"]'
from selenium.webdriver.common.by import By class AddAlgorithmPageLocators:
15
64
70
7
7
LukaszMalucha/Flask-Js-Survey
tests/acceptance/locators/add_algorithm_page.py
Python
AddAlgorithmPageLocators
AddAlgorithmPageLocators
5
10
5
5
a1d153d3968350cbe526b6a4c2115c8974fa676b
bigcode/the-stack
train
480786005e21d3f9a9d90053
train
class
class TestFetchVar(op_test.OpTest): def test_fetch_var(self): val = numpy.array([1, 3, 5]).astype(numpy.int32) x = layers.create_tensor(dtype="int32", persistable=True, name="x") layers.assign(input=val, output=x) exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_m...
class TestFetchVar(op_test.OpTest):
def test_fetch_var(self): val = numpy.array([1, 3, 5]).astype(numpy.int32) x = layers.create_tensor(dtype="int32", persistable=True, name="x") layers.assign(input=val, output=x) exe = fluid.Executor(fluid.CPUPlace()) exe.run(fluid.default_main_program(), feed={}, fetch_list=[...
express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import paddle.fluid as fluid import paddle.fluid.layers as layers import op_test import numpy import unittest class TestFetchVar(op_test.OpTest):
64
64
148
9
54
ysh329/Paddle
python/paddle/fluid/tests/unittests/test_fetch_var.py
Python
TestFetchVar
TestFetchVar
24
35
24
24
4c7a303a520532b7304c148540b443133be1c256
bigcode/the-stack
train
9e298eb8b555c80d7fa3a83c
train
function
def create_file(path, conversation): with open(path, 'w') as f: for dialog in conversation: for turn in dialog: user, utter = turn f.write(utter + '\n') f.write('\n')
def create_file(path, conversation):
with open(path, 'w') as f: for dialog in conversation: for turn in dialog: user, utter = turn f.write(utter + '\n') f.write('\n')
_size, turn_size] conversations.append([lines[i] for i in dialog]) print(len(conversations), conversations[-1]) train_size, test_size, dev_size = 80000, 1500, len(conversations) - 81500 # create the file def create_file(path, conversation):
64
64
52
7
56
zhongerqiandan/OpenDialog
data/cornell/process.py
Python
create_file
create_file
31
37
31
31
c7204cf49c93b0c6c77a7649fbd22dd30aeb13e6
bigcode/the-stack
train
83e6adc528c50fbceedc584e
train
function
def imprimir_mensagem(): print("********************************************") print("**** Bem-vindo ao Cardápio Digital ****") print("********************************************\n")
def imprimir_mensagem():
print("********************************************") print("**** Bem-vindo ao Cardápio Digital ****") print("********************************************\n")
import random import os import cardapio total = 0 def acessar(): imprimir_mensagem() identificar() def imprimir_mensagem():
32
64
35
5
27
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
imprimir_mensagem
imprimir_mensagem
9
12
9
9
ab15b777ac6c0fded4b0852b7cb3022d69e89a52
bigcode/the-stack
train
430543ad8250d9e683ecafed
train
function
def menu_inicial(): while 1: print("**Escolha uma das opções abaixo**") print("[1] - Sobre nós") print("[2] - Cardápio") print("[3] - Sair") res = int(input("Opcao: ")) print("**********************************") if res == 1: print("*************...
def menu_inicial():
while 1: print("**Escolha uma das opções abaixo**") print("[1] - Sobre nós") print("[2] - Cardápio") print("[3] - Sair") res = int(input("Opcao: ")) print("**********************************") if res == 1: print("**********************************...
format(nome)) menu_inicial() def visitante(): print("Para fins de melhor atendimento, preencha o campo abaixo!") nome= input("Qual é o seu nome? ") print("Olá {}! Seja bem-vind@.".format(nome)) menu_inicial() def menu_inicial():
64
64
158
6
58
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
menu_inicial
menu_inicial
49
68
49
49
d651ea4bf54671a2e711593e20a42612fbc6f6ca
bigcode/the-stack
train
42d9d8ec1503a3a1e05846bf
train
function
def exit(): print("***********************************") print("** Obrigada pela utilização! **") print("** Tenha um ótimo dia! **") print("***********************************")
def exit():
print("***********************************") print("** Obrigada pela utilização! **") print("** Tenha um ótimo dia! **") print("***********************************")
izar o funcionamento de um restaurante\n* de uma instituição de ensino que tem muitos clientes.") print("**************************************************************************************") elif res == 2: print("Menu Cardapio") cardapio.menu_cardapio() brea...
64
64
42
3
60
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
exit
exit
69
73
69
69
33acd34f1f96ed489f1f5e9a8061f5d3cd0f5840
bigcode/the-stack
train
3b2f407f8e740a70d6617d6c
train
function
def acessar(): imprimir_mensagem() identificar()
def acessar():
imprimir_mensagem() identificar()
import random import os import cardapio total = 0 def acessar():
19
64
11
3
15
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
acessar
acessar
5
7
5
5
6567088ff7c8d22a80500691816f7f4da2397108
bigcode/the-stack
train
15ff87e732956f5a8e8ff63d
train
function
def visitante(): print("Para fins de melhor atendimento, preencha o campo abaixo!") nome= input("Qual é o seu nome? ") print("Olá {}! Seja bem-vind@.".format(nome)) menu_inicial()
def visitante():
print("Para fins de melhor atendimento, preencha o campo abaixo!") nome= input("Qual é o seu nome? ") print("Olá {}! Seja bem-vind@.".format(nome)) menu_inicial()
Para fins de reconhecimento do estudante, preencha os campos abaixo!") nome= input("Qual é o seu nome? \n") curso= input("Qual é seu curso? \n") print("Olá {}! Seja bem-vind@.".format(nome)) menu_inicial() def visitante():
64
64
50
3
61
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
visitante
visitante
43
47
43
43
0e4e2a1da13a2ebd74b30e302e28d423972e113d
bigcode/the-stack
train
6f1ac22483ef74163fe46aab
train
function
def estudante(): print("Para fins de reconhecimento do estudante, preencha os campos abaixo!") nome= input("Qual é o seu nome? \n") curso= input("Qual é seu curso? \n") print("Olá {}! Seja bem-vind@.".format(nome)) menu_inicial()
def estudante():
print("Para fins de reconhecimento do estudante, preencha os campos abaixo!") nome= input("Qual é o seu nome? \n") curso= input("Qual é seu curso? \n") print("Olá {}! Seja bem-vind@.".format(nome)) menu_inicial()
("Resposta inválida, digite uma resposta válida.") ident=input("Você é estudante?\n(Responda com S para sim e N para não!)\n") ident=ident.upper() if ( ident == "S"): estudante() else: visitante() def estudante():
64
64
67
3
61
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
estudante
estudante
36
41
36
36
c531c8424b6143ab0b701e94235f6f1ee18336a1
bigcode/the-stack
train
99c34876ba9382044ca47298
train
function
def identificar(): ident=input("Você é estudante?\n(Responda com S para sim e N para não!)\n") ident=ident.upper() if ( ident == "S"): estudante() elif (ident == "N"): visitante() else: print("Opção invalida, digite uma opção válida.") ident=input("Você é estudant...
def identificar():
ident=input("Você é estudante?\n(Responda com S para sim e N para não!)\n") ident=ident.upper() if ( ident == "S"): estudante() elif (ident == "N"): visitante() else: print("Opção invalida, digite uma opção válida.") ident=input("Você é estudante?\n(Responda com S ...
random import os import cardapio total = 0 def acessar(): imprimir_mensagem() identificar() def imprimir_mensagem(): print("********************************************") print("**** Bem-vindo ao Cardápio Digital ****") print("********************************************\n") def identificar()...
64
64
183
3
61
camilacarvalhon/cantinadigital
projeto/projeto.py
Python
identificar
identificar
14
34
14
15
66650053c5e535a1def98786143ba5c331511303
bigcode/the-stack
train
0bd72a13ce9656113fe6fad9
train
class
class TestStatus(Enum): PASSED = "passed" FAILED = "failed"
class TestStatus(Enum):
PASSED = "passed" FAILED = "failed"
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import Enum class TestStatus(Enu...
64
64
18
5
58
NickFlatow/winnf-rel2-testharness
CBRS_Mock_SAS_Python_Master/cbrsPython-master/cbrsPython/controllers/CLIUtils/enums.py
Python
TestStatus
TestStatus
15
17
15
15
4db74d1cd3ea697982859d25a125bde4455be6e0
bigcode/the-stack
train
71157119fc821d2d65f81bb0
train
class
class StepStatus(Enum): PASSED = "passed" FAILED = "failed"
class StepStatus(Enum):
PASSED = "passed" FAILED = "failed"
" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from enum import Enum class TestStatus(Enum): PASSED = "passed" FAILED = "failed" class StepStatus(Enum):
63
64
18
5
58
NickFlatow/winnf-rel2-testharness
CBRS_Mock_SAS_Python_Master/cbrsPython-master/cbrsPython/controllers/CLIUtils/enums.py
Python
StepStatus
StepStatus
19
21
19
19
c9cd97e7894b9251b4893655de45565b35a823f1
bigcode/the-stack
train
ffca6ea435c17f2d187693df
train
function
def get_all_reverse_indices_info(domain, case_ids, relationship=None): from casexml.apps.case.models import CommCareCase def _row_to_index_info(row): return CaseIndexInfo( case_id=row['id'], identifier=row['value']['identifier'], referenced_id=row['key'][1], ...
def get_all_reverse_indices_info(domain, case_ids, relationship=None):
from casexml.apps.case.models import CommCareCase def _row_to_index_info(row): return CaseIndexInfo( case_id=row['id'], identifier=row['value']['identifier'], referenced_id=row['key'][1], referenced_type=row['value']['referenced_type'], relati...
ml.apps.case.models import CommCareCase return CommCareCase.view( 'case_indices/related', keys=_get_keys_for_reverse_index_view(domain, case_ids, relationship), reduce=False, include_docs=True, ) def get_all_reverse_indices_info(domain, case_ids, relationship=None):
64
64
135
14
50
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_all_reverse_indices_info
get_all_reverse_indices_info
51
67
51
51
8bf510e1af79d81296147ee3651123c77b9f8d27
bigcode/the-stack
train
7beebc852c32c4c0271df067
train
function
def _get_keys_for_reverse_index_view(domain, case_ids, relationship=None): assert not isinstance(case_ids, (six.text_type, bytes)) if relationship is None: return [[domain, case_id, 'reverse_index', reln] for case_id in case_ids for reln in [CASE_INDEX_CHILD, CASE_INDEX_EXTENSION]] e...
def _get_keys_for_reverse_index_view(domain, case_ids, relationship=None):
assert not isinstance(case_ids, (six.text_type, bytes)) if relationship is None: return [[domain, case_id, 'reverse_index', reln] for case_id in case_ids for reln in [CASE_INDEX_CHILD, CASE_INDEX_EXTENSION]] else: return [[domain, case_id, 'reverse_index', relationship] for c...
return list(map(_row_to_index_info, CommCareCase.get_db().view( 'case_indices/related', keys=_get_keys_for_reverse_index_view(domain, case_ids, relationship), reduce=False, ))) def _get_keys_for_reverse_index_view(domain, case_ids, relationship=None):
64
64
95
16
48
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
_get_keys_for_reverse_index_view
_get_keys_for_reverse_index_view
70
76
70
70
d2e4f86db636908734b22d0b9dd022cf46fec5a0
bigcode/the-stack
train
c744380c1979ec8ec9b8a55c
train
function
def get_extension_case_ids(domain, case_ids): """ Given a base list of case ids, get all ids of all extension cases that reference them """ return [r.case_id for r in get_all_reverse_indices_info(domain, case_ids, CASE_INDEX_EXTENSION)]
def get_extension_case_ids(domain, case_ids):
""" Given a base list of case ids, get all ids of all extension cases that reference them """ return [r.case_id for r in get_all_reverse_indices_info(domain, case_ids, CASE_INDEX_EXTENSION)]
case_id, 'index'] for case_id in case_ids] return [r['value']['referenced_id'] for r in CommCareCase.get_db().view( 'case_indices/related', keys=keys, reduce=False, )] def get_extension_case_ids(domain, case_ids):
64
64
58
10
54
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_extension_case_ids
get_extension_case_ids
24
28
24
24
cb6c6dd8ff6c431df304f166d2bcc6835fac2fc9
bigcode/the-stack
train
29ba2048160fd3096bbb37f4
train
function
def get_indexed_case_ids(domain, case_ids): """ Given a base list of case ids, gets all ids of cases they reference (parent and host cases) """ from casexml.apps.case.models import CommCareCase keys = [[domain, case_id, 'index'] for case_id in case_ids] return [r['value']['referenced_id'] for r ...
def get_indexed_case_ids(domain, case_ids):
""" Given a base list of case ids, gets all ids of cases they reference (parent and host cases) """ from casexml.apps.case.models import CommCareCase keys = [[domain, case_id, 'index'] for case_id in case_ids] return [r['value']['referenced_id'] for r in CommCareCase.get_db().view( 'case...
CaseIndex from casexml.apps.case.const import CASE_INDEX_CHILD, CASE_INDEX_EXTENSION from corehq.form_processor.interfaces.dbaccessors import CaseIndexInfo from dimagi.utils.couch.database import iter_docs import six from six.moves import map def get_indexed_case_ids(domain, case_ids):
64
64
110
11
52
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_indexed_case_ids
get_indexed_case_ids
11
21
11
11
61f72f5db2e8c751517034e0dadf2bfeaba21736
bigcode/the-stack
train
a028e94d2607e5f7c57778b3
train
function
def get_reverse_indices_json(domain, case_id): from casexml.apps.case.models import CommCareCase return CommCareCase.get_db().view( "case_indices/related", startkey=[domain, case_id, "reverse_index"], endkey=[domain, case_id, "reverse_index", {}], reduce=False, wrapper=la...
def get_reverse_indices_json(domain, case_id):
from casexml.apps.case.models import CommCareCase return CommCareCase.get_db().view( "case_indices/related", startkey=[domain, case_id, "reverse_index"], endkey=[domain, case_id, "reverse_index", {}], reduce=False, wrapper=lambda r: r['value'], ).all()
case_id, 'reverse_index', reln] for case_id in case_ids for reln in [CASE_INDEX_CHILD, CASE_INDEX_EXTENSION]] else: return [[domain, case_id, 'reverse_index', relationship] for case_id in case_ids] def get_reverse_indices_json(domain, case_id):
64
64
85
10
54
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_reverse_indices_json
get_reverse_indices_json
79
87
79
79
63fdae412ff1e9983651bda28922d13d72322824
bigcode/the-stack
train
bdea937967fdfc5101b3536d
train
function
def get_related_indices(domain, case_ids, exclude_indices): """Get related index records (parents and children, non-recursive) Excludes closed extension cases. WARNING this is inefficient (better version in SQL). """ from casexml.apps.case.models import CommCareCase def index_key(case_id, ide...
def get_related_indices(domain, case_ids, exclude_indices):
"""Get related index records (parents and children, non-recursive) Excludes closed extension cases. WARNING this is inefficient (better version in SQL). """ from casexml.apps.case.models import CommCareCase def index_key(case_id, identifier): return "{} {}".format(case_id, identifier)...
, "reverse_index"], endkey=[domain, case_id, "reverse_index", {}], reduce=False, wrapper=lambda r: r['value'], ).all() def get_reverse_indices(case): return get_reverse_indices_for_case_id(case['domain'], case['_id']) def get_reverse_indices_for_case_id(domain, case_id): return [...
107
108
363
12
95
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_related_indices
get_related_indices
99
142
99
99
ed90d11fa2ea9476cbf4082ebcfa47c3fc68102e
bigcode/the-stack
train
df29d1fb0091152f7d1f0293
train
function
def get_reverse_indices_for_case_id(domain, case_id): return [CommCareCaseIndex.wrap(raw) for raw in get_reverse_indices_json(domain, case_id)]
def get_reverse_indices_for_case_id(domain, case_id):
return [CommCareCaseIndex.wrap(raw) for raw in get_reverse_indices_json(domain, case_id)]
=[domain, case_id, "reverse_index", {}], reduce=False, wrapper=lambda r: r['value'], ).all() def get_reverse_indices(case): return get_reverse_indices_for_case_id(case['domain'], case['_id']) def get_reverse_indices_for_case_id(domain, case_id):
63
64
35
12
51
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_reverse_indices_for_case_id
get_reverse_indices_for_case_id
94
96
94
94
dc0850c5515156d473ac4e00e9466e29db4e914f
bigcode/the-stack
train
0c56f60d26d7be0ef3ef8bbe
train
function
def get_reverse_indexed_case_ids(domain, case_ids): """ Given a base list of case ids, gets all ids of cases that reference them (child cases) """ return [r.case_id for r in get_all_reverse_indices_info(domain, case_ids, CASE_INDEX_CHILD)]
def get_reverse_indexed_case_ids(domain, case_ids):
""" Given a base list of case ids, gets all ids of cases that reference them (child cases) """ return [r.case_id for r in get_all_reverse_indices_info(domain, case_ids, CASE_INDEX_CHILD)]
case_ids): """ Given a base list of case ids, get all ids of all extension cases that reference them """ return [r.case_id for r in get_all_reverse_indices_info(domain, case_ids, CASE_INDEX_EXTENSION)] def get_reverse_indexed_case_ids(domain, case_ids):
63
64
60
12
51
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_reverse_indexed_case_ids
get_reverse_indexed_case_ids
31
35
31
31
d2e0a5324495d62f1d6cc43dd8f803202d2ffe56
bigcode/the-stack
train
80624838bfcd885c11f49c96
train
function
def get_reverse_indices(case): return get_reverse_indices_for_case_id(case['domain'], case['_id'])
def get_reverse_indices(case):
return get_reverse_indices_for_case_id(case['domain'], case['_id'])
Case.get_db().view( "case_indices/related", startkey=[domain, case_id, "reverse_index"], endkey=[domain, case_id, "reverse_index", {}], reduce=False, wrapper=lambda r: r['value'], ).all() def get_reverse_indices(case):
64
64
22
6
58
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_reverse_indices
get_reverse_indices
90
91
90
90
37914d6566ebf1c37d3b55027549c73ce1d7dea4
bigcode/the-stack
train
b87cd638ced1a4d27b8b9350
train
function
def get_reverse_indexed_cases(domain, case_ids, relationship=None): """ Gets all reverse indexed cases of a case (including child cases and extensions). """ from casexml.apps.case.models import CommCareCase return CommCareCase.view( 'case_indices/related', keys=_get_keys_for_reverse_...
def get_reverse_indexed_cases(domain, case_ids, relationship=None):
""" Gets all reverse indexed cases of a case (including child cases and extensions). """ from casexml.apps.case.models import CommCareCase return CommCareCase.view( 'case_indices/related', keys=_get_keys_for_reverse_index_view(domain, case_ids, relationship), reduce=False, ...
): """ Given a base list of case ids, gets all ids of cases that reference them (child cases) """ return [r.case_id for r in get_all_reverse_indices_info(domain, case_ids, CASE_INDEX_CHILD)] def get_reverse_indexed_cases(domain, case_ids, relationship=None):
63
64
88
14
49
kkrampa/commcare-hq
corehq/ex-submodules/casexml/apps/case/dbaccessors/related.py
Python
get_reverse_indexed_cases
get_reverse_indexed_cases
38
48
38
38
23e7afd8dcbf429bebe4d810a42db7c3c514aa65
bigcode/the-stack
train
af4936b1ea83c169344e2556
train
function
def add_middleware(app: FastAPI): @app.middleware("http") async def response_time_logger(request: Request, call_next): # Inbound: Customer - --> Server - --> Middleware --> Correct Endpoint # Outbound: Correct Endpoint --> Middleware --> Server --> Customer start_time = time.perf_counter...
def add_middleware(app: FastAPI): @app.middleware("http")
async def response_time_logger(request: Request, call_next): # Inbound: Customer - --> Server - --> Middleware --> Correct Endpoint # Outbound: Correct Endpoint --> Middleware --> Server --> Customer start_time = time.perf_counter() response = await call_next(request) total_t...
import logging import time from fastapi import FastAPI, Request logger = logging.getLogger(__name__) def add_middleware(app: FastAPI): @app.middleware("http")
39
64
112
16
23
imagination-ai/kerem-side-projects-monorepo
style/api/middleware.py
Python
add_middleware
add_middleware
9
18
9
10
bf3517db061f4e3858ff0b818341dc9179ae3b80
bigcode/the-stack
train
e9ad05c41fca614aa111aae2
train
class
class StructuredArrayTests(unittest.TestCase): def test_isstructuredarray_true(self): x = np.array([(1,2.,'Hello'), (2,3.,"World")], dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')]) self.assertTrue(isstructuredarray(x)) def test_isstructuredarray_false(self): x = np.array([[1,2,3],...
class StructuredArrayTests(unittest.TestCase):
def test_isstructuredarray_true(self): x = np.array([(1,2.,'Hello'), (2,3.,"World")], dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')]) self.assertTrue(isstructuredarray(x)) def test_isstructuredarray_false(self): x = np.array([[1,2,3], [1,2,3]]) self.assertFalse(isstructured...
', KMeans()) ]) self.assertTrue(is_clusterer(model)) def test_clusterer_visualizer(self): """ Test that is_clusterer works on visualizers """ model = ScoreVisualizer(KMeans()) self.assertTrue(is_clusterer(model)) class StructuredArrayTests(unittest.TestCase)...
64
64
144
8
56
mattharrison/yellowbrick
tests/test_utils/test_types.py
Python
StructuredArrayTests
StructuredArrayTests
393
405
393
394
34b3fbc2fba20cf547cda727f1350f9c10b8918c
bigcode/the-stack
train
d1952569762a2bace3c064c5
train
class
class ModelUtilityTests(unittest.TestCase): ##//////////////////////////////////////////////////////////////////// ## isestimator testing ##//////////////////////////////////////////////////////////////////// def test_estimator_alias(self): """ Assert is_estimator aliases isestimator ...
class ModelUtilityTests(unittest.TestCase): ##//////////////////////////////////////////////////////////////////// ## isestimator testing ##////////////////////////////////////////////////////////////////////
def test_estimator_alias(self): """ Assert is_estimator aliases isestimator """ self.assertEqual( is_estimator(LinearRegression), isestimator(LinearRegression) ) def test_estimator_instance(self): """ Test that isestimator works for instances ...
.test_types # Very difficult test library for type detection and flexibility. # # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Fri May 19 10:58:32 2017 -0700 # # Copyright (C) 2017 District Data Labs # For license information, see LICENSE.txt # # ID: test_types.py [79cd8cf] benjamin@bengfort...
256
256
1,759
23
233
mattharrison/yellowbrick
tests/test_utils/test_types.py
Python
ModelUtilityTests
ModelUtilityTests
41
390
41
46
6ae1c1051fb3023268340cc323d499bd4c5fbe81
bigcode/the-stack
train
1a813212833ab40aaba4c2c4
train
function
def clean_index(s): return s.replace("/", "_").replace("-", "_").replace("(", "_").replace(")", "").replace("#", "")
def clean_index(s):
return s.replace("/", "_").replace("-", "_").replace("(", "_").replace(")", "").replace("#", "")
": convert_or_none(lrtscore,float), } } return one_snp_json def convert_or_none(v, to_f, none_vals=[]): if (not v) or (v in none_vals): return None return to_f(v) def clean_index(s):
63
64
29
5
58
NikkiBytes/pending.api
plugins/denovodb/parser.py
Python
clean_index
clean_index
107
108
107
107
d945b2cb71a005262c267280afcb4520000fb18d
bigcode/the-stack
train
286e95b0a4ac5f378dea1bfd
train
function
def _map_line_to_json(df): # specific variable treatment chrom = df["Chr"] if chrom == 'M': chrom = 'MT' position = int(df["Position"]) ref, alt = df["Variant"].upper().split(">") HGVS = get_hgvs_from_vcf(chrom, position, ref, alt, mutant_type=False) sampleid = df["SampleID"] ...
def _map_line_to_json(df): # specific variable treatment
chrom = df["Chr"] if chrom == 'M': chrom = 'MT' position = int(df["Position"]) ref, alt = df["Variant"].upper().split(">") HGVS = get_hgvs_from_vcf(chrom, position, ref, alt, mutant_type=False) sampleid = df["SampleID"] studyname = df["StudyName"] pubmedid = df["PubmedID"] ...
import os import csv from biothings.utils.dataload import unlist from biothings.utils.dataload import value_convert_to_number from biothings.utils.dataload import merge_duplicate_rows, dict_sweep from myvariant.src.utils.hgvs import get_hgvs_from_vcf from itertools import groupby VALID_COLUMN_NO = 31 '''this parser i...
136
256
1,022
14
121
NikkiBytes/pending.api
plugins/denovodb/parser.py
Python
_map_line_to_json
_map_line_to_json
16
100
16
17
ebeae1b2e76064d9f04ea1ef30f332ff6c72e116
bigcode/the-stack
train
65e0c6f41a45a950857cf99f
train
function
def clean_rsid(d, vals): if d in vals: return None else: return "rs{}".format(d)
def clean_rsid(d, vals):
if d in vals: return None else: return "rs{}".format(d)
) def clean_index(s): return s.replace("/", "_").replace("-", "_").replace("(", "_").replace(")", "").replace("#", "") def clean_data(d, vals): if d in vals: return None else: return d def clean_rsid(d, vals):
64
64
29
8
55
NikkiBytes/pending.api
plugins/denovodb/parser.py
Python
clean_rsid
clean_rsid
117
121
117
117
eff417fe5696439c2e9ebfab6163eae70487c63f
bigcode/the-stack
train
d4a84e48cd83016a89fb5f10
train
function
def convert_or_none(v, to_f, none_vals=[]): if (not v) or (v in none_vals): return None return to_f(v)
def convert_or_none(v, to_f, none_vals=[]):
if (not v) or (v in none_vals): return None return to_f(v)
score": convert_or_none(caddscore,float), "lofscore": convert_or_none(lofscore,float), "lrtscore": convert_or_none(lrtscore,float), } } return one_snp_json def convert_or_none(v, to_f, none_vals=[]):
64
64
37
13
50
NikkiBytes/pending.api
plugins/denovodb/parser.py
Python
convert_or_none
convert_or_none
102
105
102
102
141ebee3663a6603d0ef748e2d5fc8db882c1f1f
bigcode/the-stack
train
15b3b9aa254dd974b39ca8ce
train
function
def load_data(data_folder): input_fn = os.path.join(data_folder,"denovo-db.non-ssc-samples.variants.tsv") open_file = open(input_fn) db_denovodb = csv.reader(open_file, delimiter="\t") index = next(db_denovodb) while index[0].startswith("##"): index = next(db_denovodb) assert len(index) ...
def load_data(data_folder):
input_fn = os.path.join(data_folder,"denovo-db.non-ssc-samples.variants.tsv") open_file = open(input_fn) db_denovodb = csv.reader(open_file, delimiter="\t") index = next(db_denovodb) while index[0].startswith("##"): index = next(db_denovodb) assert len(index) == VALID_COLUMN_NO, "Expecti...
(", "_").replace(")", "").replace("#", "") def clean_data(d, vals): if d in vals: return None else: return d def clean_rsid(d, vals): if d in vals: return None else: return "rs{}".format(d) # open file, parse, pass to json mapper def load_data(data_folder):
82
82
276
6
75
NikkiBytes/pending.api
plugins/denovodb/parser.py
Python
load_data
load_data
125
141
125
125
3d773b7285f744f1fa4ae72b10f2d865d22029ba
bigcode/the-stack
train
21a9ff8fb7d003048789e06f
train
function
def clean_data(d, vals): if d in vals: return None else: return d
def clean_data(d, vals):
if d in vals: return None else: return d
_vals=[]): if (not v) or (v in none_vals): return None return to_f(v) def clean_index(s): return s.replace("/", "_").replace("-", "_").replace("(", "_").replace(")", "").replace("#", "") def clean_data(d, vals):
63
64
24
7
56
NikkiBytes/pending.api
plugins/denovodb/parser.py
Python
clean_data
clean_data
111
115
111
111
ad67b99e594ba6841dbc2e4cd36d0ac9a6371eb7
bigcode/the-stack
train
fde85698fa5ef381eba3ec61
train
class
class Caption(Resource): def post(self): args = parser.parse_args() imageSource = args['src'] try: if(requests.get(imageSource, timeout=1).raise_for_status): # If the URL, when opened by the server, is given a 200 (OK) code return {'caption': args['src'] + ' is a valid ...
class Caption(Resource):
def post(self): args = parser.parse_args() imageSource = args['src'] try: if(requests.get(imageSource, timeout=1).raise_for_status): # If the URL, when opened by the server, is given a 200 (OK) code return {'caption': args['src'] + ' is a valid URL that you just sent to...
150" Post -v # Example for failure: curl https://altML-Server.thatrobotdev.repl.co/api/v1/caption -d "src=notaurl" Post -v # takes src, and asks cloudsight api for a caption, then returns a caption class Caption(Resource):
64
64
188
4
59
saharshy29/altML
flask_server/main.py
Python
Caption
Caption
21
29
21
21
9929d89e074d18530ee57022866b581252476af2
bigcode/the-stack
train
3f8d4ae1b4f4a7f1c9507e60
train
function
def run_SEIR_ODE_model( N: 'population size', Ev0: 'init. exposed population', Ej0: 'init. exposed population', I0: 'init. infected population', R0: 'init. removed population', beta: 'infection probability', gamma: 'removal probability', omega: 'atenuatin...
def run_SEIR_ODE_model( N: 'population size', Ev0: 'init. exposed population', Ej0: 'init. exposed population', I0: 'init. infected population', R0: 'init. removed population', beta: 'infection probability', gamma: 'removal probability', omega: 'atenuatin...
percentual_pop_idosa = 0.2 V0 = (N - I0 - R0 - Ej0 -Ev0)*percentual_pop_idosa J0 = (N - I0 - R0 - Ej0 -Ev0)*(1-percentual_pop_idosa) HJ0 = I0*tax_intJ*(1-percentual_pop_idosa) UJ0 = I0*tax_utiV*(1-percentual_pop_idosa) HV0 = I0*tax_intV*percentual_pop_idosa UV0 = I0*tax_utiV*percentual_pop...
def run_SEIR_ODE_model( N: 'population size', Ev0: 'init. exposed population', Ej0: 'init. exposed population', I0: 'init. infected population', R0: 'init. removed population', beta: 'infection probability', gamma: 'removal probability', omega: 'atenuatin...
261
256
1,010
261
0
viniciusriosfuck/vertical
legacy/legado_simples.py
Python
run_SEIR_ODE_model
run_SEIR_ODE_model
6
74
6
25
aae2167b9eb6fa7897f2e681ebe2b3e94bd72926
bigcode/the-stack
train
ff374d196d20b44e624a3122
train
class
class simulator: """ logp property """ def __init__(self, property): self.property=property #print (self.property) if self.property=="logP": self.val=['\n', '&', 'C', '(', ')', 'c', '1', '2', 'o', '=', 'O', 'N', '3', 'F', '[C@@H]', 'n', '-', '#', 'S', ...
class simulator:
""" logp property """ def __init__(self, property): self.property=property #print (self.property) if self.property=="logP": self.val=['\n', '&', 'C', '(', ')', 'c', '1', '2', 'o', '=', 'O', 'N', '3', 'F', '[C@@H]', 'n', '-', '#', 'S', 'Cl', '[O-]', '[C...
from keras.preprocessing import sequence #from Gaussian_DFT.RDKitText import tansfersdf #from Gaussian_DFT.SDF2GauInput import GauTDDFT_ForDFT #from Gaussian_DFT.GaussianRunPack import GaussianDFTRun from pmcts import sascorer from rdkit import Chem from rdkit.Chem import Descriptors from rdkit.Chem import MolFromSmile...
112
256
1,050
3
108
molecule-generator-collection/MPChemTS
pmcts/property_simulator.py
Python
simulator
simulator
12
102
12
12
78711cc885e12d3c24e944c76493572ef5b6c909
bigcode/the-stack
train
02434f5389761c63307e154b
train
function
def __main__(): input_name = sys.argv[1] output_name = sys.argv[2] skipped_lines = 0 first_skipped_line = 0 i = 0 with open(output_name, "w") as out, open(input_name) as fh_in: for i, line in enumerate(fh_in): complete_bed = False line = line.rstrip("\r\n") ...
def __main__():
input_name = sys.argv[1] output_name = sys.argv[2] skipped_lines = 0 first_skipped_line = 0 i = 0 with open(output_name, "w") as out, open(input_name) as fh_in: for i, line in enumerate(fh_in): complete_bed = False line = line.rstrip("\r\n") if line an...
#!/usr/bin/env python # This code exists in 2 places: ~/datatypes/converters and ~/tools/filters from __future__ import print_function import sys assert sys.version_info[:2] >= (2, 6) def __main__():
56
200
669
5
51
beatrizserrano/galaxy
tools/filters/bed_to_gff_converter.py
Python
__main__
__main__
10
83
10
10
176cb1ad9329f9a5232ecfc1b3ce01959f549f73
bigcode/the-stack
train
33464d02b2c51c17d37843c6
train
class
class TestSystemDetailsAnalysis(BaseTestCase): """Test getting the system details. """ def setUp(self): self._unicode_size = sys.maxunicode def tearDown(self): sys.maxunicode = self._unicode_size def test_getting_system_details(self): sys.maxunicode = 65535 path =...
class TestSystemDetailsAnalysis(BaseTestCase):
"""Test getting the system details. """ def setUp(self): self._unicode_size = sys.maxunicode def tearDown(self): sys.maxunicode = self._unicode_size def test_getting_system_details(self): sys.maxunicode = 65535 path = os.path.join(os.path.dirname(__file__), "fake-...
e.exception.args[0]) def round_trip_block_converstion(self, values, to_block, from_block, msg): """Test that block conversion round trip as expected. """ containers = (list, tuple) + ((np.array,) if np else ()) for cont in containers: conv = co...
168
168
561
9
159
KOLANICH/pyvisa
pyvisa/testsuite/test_util.py
Python
TestSystemDetailsAnalysis
TestSystemDetailsAnalysis
291
376
291
291
490d453d97c5581dd8789899b1507de36c48cb02
bigcode/the-stack
train
02f8f0a89665611c349d9fa4
train
class
class TestConfigFile(BaseTestCase): """Test reading information from a user configuration file. """ def setUp(self): # Skip if a real config file exists if any(os.path.isfile(p) for p in [os.path.join(sys.prefix, "share", "pyvisa", ".pyvisarc"), os.p...
class TestConfigFile(BaseTestCase):
"""Test reading information from a user configuration file. """ def setUp(self): # Skip if a real config file exists if any(os.path.isfile(p) for p in [os.path.join(sys.prefix, "share", "pyvisa", ".pyvisarc"), os.path.join(os.path.expanduser("~"), "....
# -*- coding: utf-8 -*- """Test pyvisa utility functions. """ import array import contextlib import os import subprocess import sys import tempfile import unittest from configparser import ConfigParser from io import StringIO from functools import partial from pyvisa import util, highlevel from pyvisa.ctwrapper impor...
119
136
456
8
110
KOLANICH/pyvisa
pyvisa/testsuite/test_util.py
Python
TestConfigFile
TestConfigFile
27
78
27
27
2ee32c22a23b61cd3ef409d37f79529fd1fbe4bf
bigcode/the-stack
train
a33013efefdf99c9834b2019
train
class
class TestLibraryAnalysis(BaseTestCase): """Test (through monkey patching) the analysis of binary libraries. """ def test_get_shared_library_arch(self): """Test analysing a library on Windows. """ dirname = os.path.join(os.path.dirname(__file__), "fakelibs") for f, a in zi...
class TestLibraryAnalysis(BaseTestCase):
"""Test (through monkey patching) the analysis of binary libraries. """ def test_get_shared_library_arch(self): """Test analysing a library on Windows. """ dirname = os.path.join(os.path.dirname(__file__), "fakelibs") for f, a in zip(["_32", "_64", "_64_2"], ["I386", "IA64...
IVIVisaLibrary elif backend == "test2": class BrokenBackend: @classmethod def get_debug_info(cls): raise Exception() return BrokenBackend elif backend == "test4": class WeirdBacke...
256
256
1,039
8
248
KOLANICH/pyvisa
pyvisa/testsuite/test_util.py
Python
TestLibraryAnalysis
TestLibraryAnalysis
379
496
379
379
5c6d63e5242c5483ca0e6ecb9fa8f79ea9d4893c
bigcode/the-stack
train
96a484c7b5b60923af8ad8d2
train
class
class TestParser(BaseTestCase): def test_parse_binary(self): s = (b'#A@\xe2\x8b<@\xe2\x8b<@\xe2\x8b<@\xe2\x8b<@\xde\x8b<@\xde\x8b<@' b'\xde\x8b<@\xde\x8b<@\xe0\x8b<@\xe0\x8b<@\xdc\x8b<@\xde\x8b<@' b'\xe2\x8b<@\xe0\x8b<') e = [0.01707566, 0.01707566, 0.01707566, 0.01707566,...
class TestParser(BaseTestCase):
def test_parse_binary(self): s = (b'#A@\xe2\x8b<@\xe2\x8b<@\xe2\x8b<@\xe2\x8b<@\xde\x8b<@\xde\x8b<@' b'\xde\x8b<@\xde\x8b<@\xe0\x8b<@\xe0\x8b<@\xdc\x8b<@\xde\x8b<@' b'\xe2\x8b<@\xe0\x8b<') e = [0.01707566, 0.01707566, 0.01707566, 0.01707566, 0.01707375, 0.01707...
Parser() config['Paths'] = {} config['Paths']["visa library"] = "test" with open(self.config_path, "w") as f: config.write(f) self.assertEqual(util.read_user_library_path(), "test") def test_no_section(self): config = ConfigParser() with open(self.config_...
256
256
2,276
7
249
KOLANICH/pyvisa
pyvisa/testsuite/test_util.py
Python
TestParser
TestParser
80
288
80
81
78643bc9f103488e0aaae74b5036909cb54ecdf6
bigcode/the-stack
train
084e6c723d54b83190a388d0
train
class
class DataHelper: def __init__(self, config): self.config = config # Label mappings self.label2emotion = {0:"others", 1:"happy", 2: "sad", 3:"angry"} self.emotion2label = {"others":0, "happy":1, "sad":2, "angry":3} def preprocessData(self, dataFilePath, mode): """Load ...
class DataHelper:
def __init__(self, config): self.config = config # Label mappings self.label2emotion = {0:"others", 1:"happy", 2: "sad", 3:"angry"} self.emotion2label = {"others":0, "happy":1, "sad":2, "angry":3} def preprocessData(self, dataFilePath, mode): """Load data from a file, p...
import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Embedding, LSTM from keras import optimizers from keras.models import load_model from pathli...
90
256
2,071
4
85
laic/conv-emotion
ICON-end-to-end/data_helper.py
Python
DataHelper
DataHelper
20
209
20
21
ba94c4fe1076e35d4b08ca6af4f309e0f7528eda
bigcode/the-stack
train
22194c4d7e89d1028c59f5d1
train
function
def loadBestEver(benchs): map = {} with open(benchs, 'r') as f: f.readline() # to skip the first line for line in f: parts = line.split(';') # fname=(parts[1]+"/"+parts[2]) fname=(parts[2]) res = [parts[4]] obj = parts[5].replace('\n','...
def loadBestEver(benchs):
map = {} with open(benchs, 'r') as f: f.readline() # to skip the first line for line in f: parts = line.split(';') # fname=(parts[1]+"/"+parts[2]) fname=(parts[2]) res = [parts[4]] obj = parts[5].replace('\n','') if obj != '...
default=True, ) parser.add_argument( "-det", "--details", help="Add all instances' detail", default=True, ) maxtime=599. maxobj=999999999 ## LOAD BEST KNOW RESULTS (extracted from MZN website) def loadBestEver(benchs):
64
64
113
8
56
dimitri-justeau/choco-solver
parsers/src/main/python/mzn2pdf.py
Python
loadBestEver
loadBestEver
69
82
69
69
aa270a2f6224a727dcebb2edabf773d93f8443ba
bigcode/the-stack
train
5d25cee339da0fe467de4696
train
function
def test_travis(): assert True
def test_travis():
assert True
def test_travis():
5
64
9
5
0
akbo/datalaunch
tests/test_travis.py
Python
test_travis
test_travis
1
2
1
1
ca2b81b05c7d60959e284e53d286f0642c610260
bigcode/the-stack
train
5032553585d9e6baac3195c4
train
class
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.CBC("\x00" * 8) ), skip_message="Does not support Blowfish CBC", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeCBC(object): test_CBC = gene...
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.CBC("\x00" * 8) ), skip_message="Does not support Blowfish CBC", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeCBC(object):
test_CBC = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Blowfish"), ["bf-cbc.txt"], lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), )
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.CBC("\x00" * 8) ), skip_message="Does not support Blowfish CBC", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeCBC(object):
73
64
147
73
0
balabit-deps/balabit-os-6-python-cryptography
tests/hazmat/primitives/test_blowfish.py
Python
TestBlowfishModeCBC
TestBlowfishModeCBC
36
50
36
43
ebffdd674f618269693a8b83e3496a2cd57b07cf
bigcode/the-stack
train
dd7c64589e77004742eb7403
train
class
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.CFB("\x00" * 8) ), skip_message="Does not support Blowfish CFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeCFB(object): test_CFB = gene...
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.CFB("\x00" * 8) ), skip_message="Does not support Blowfish CFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeCFB(object):
test_CFB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Blowfish"), ["bf-cfb.txt"], lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)), lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), )
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.CFB("\x00" * 8) ), skip_message="Does not support Blowfish CFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeCFB(object):
75
64
149
75
0
balabit-deps/balabit-os-6-python-cryptography
tests/hazmat/primitives/test_blowfish.py
Python
TestBlowfishModeCFB
TestBlowfishModeCFB
70
84
70
77
5732b690ba7f28faa6b193a9baae521203395547
bigcode/the-stack
train
68e477bd9ee822a76840d307
train
class
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.ECB() ), skip_message="Does not support Blowfish ECB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeECB(object): test_ECB = generate_encry...
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.ECB() ), skip_message="Does not support Blowfish ECB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeECB(object):
test_ECB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Blowfish"), ["bf-ecb.txt"], lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)), lambda **kwargs: modes.ECB(), )
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.ECB() ), skip_message="Does not support Blowfish ECB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeECB(object):
66
64
132
66
0
balabit-deps/balabit-os-6-python-cryptography
tests/hazmat/primitives/test_blowfish.py
Python
TestBlowfishModeECB
TestBlowfishModeECB
19
33
19
26
e93d0bcb791f7d9bb2e398f628b2038e857ae6e1
bigcode/the-stack
train
46c266a7ee8c0db9a381d4f7
train
class
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.OFB("\x00" * 8) ), skip_message="Does not support Blowfish OFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeOFB(object): test_OFB = gene...
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.OFB("\x00" * 8) ), skip_message="Does not support Blowfish OFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeOFB(object):
test_OFB = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Blowfish"), ["bf-ofb.txt"], lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)), lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), )
@pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.Blowfish("\x00" * 56), modes.OFB("\x00" * 8) ), skip_message="Does not support Blowfish OFB", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestBlowfishModeOFB(object):
75
64
149
75
0
balabit-deps/balabit-os-6-python-cryptography
tests/hazmat/primitives/test_blowfish.py
Python
TestBlowfishModeOFB
TestBlowfishModeOFB
53
67
53
60
a16a731e24911c6879b31ca689b0d3be415e2ac1
bigcode/the-stack
train
77a50da804bd24f200954e42
train
class
@admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = (("User", {"fields": ("name",)}),) + auth_admin.UserAdmin.fieldsets list_display = ["username", "email", "is_superuser"] search_fields = ["name", "email"]
@admin.register(User) class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm add_form = UserCreationForm fieldsets = (("User", {"fields": ("name",)}),) + auth_admin.UserAdmin.fieldsets list_display = ["username", "email", "is_superuser"] search_fields = ["name", "email"]
import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from open.users.forms import UserChangeForm, UserCreationForm User = get_user_model() admin.site.site_header = "Open Control Panel" @admin.register(User) class UserAdmin(auth_admin.UserAdmin):
64
64
78
13
51
awesome-archive/open
open/users/admin.py
Python
UserAdmin
UserAdmin
13
19
13
14
9d838433456a21ea8c1e56f533239d84e7e9565e
bigcode/the-stack
train
2fae556e5c031393c347fa9c
train
function
def handle_share_ratio(value): if value == '∞': return '0' else: return value
def handle_share_ratio(value):
if value == '∞': return '0' else: return value
import re from dateutil.parser import parse from ..schema.site_base import SignState, Work, NetworkState, SiteBase def handle_share_ratio(value):
33
64
25
6
26
kbnq/flexget_qbittorrent_mod
ptsites/sites/torrentdb.py
Python
handle_share_ratio
handle_share_ratio
8
12
8
8
6107bbce2377d6a30c2e1ba2684c38ee52ef6cea
bigcode/the-stack
train
bd80e2c33f7f55ec4d1216d4
train
class
class MainClass(SiteBase): URL = 'https://torrentdb.net' USER_CLASSES = { 'uploaded': [10995116277760], 'days': [1095], 'share_ratio': [2] } @classmethod def build_sign_in_schema(cls): return { cls.get_module_name(): { 'type': 'object', ...
class MainClass(SiteBase):
URL = 'https://torrentdb.net' USER_CLASSES = { 'uploaded': [10995116277760], 'days': [1095], 'share_ratio': [2] } @classmethod def build_sign_in_schema(cls): return { cls.get_module_name(): { 'type': 'object', 'properties':...
}, 'points': { 'regex': r'([\d,.]+)(?= BP)' }, 'join_date': { 'regex': r'Joined on (\w+ \w+ \w+)', 'handle': handle_join_date }, 'seeding': { 'regex': r'Total seeding: ([\d,]+)' ...
126
126
422
7
119
kbnq/flexget_qbittorrent_mod
ptsites/sites/torrentdb.py
Python
MainClass
MainClass
60
123
60
60
2d3be2e57207d084d3559041f205d3632ec40745
bigcode/the-stack
train
d21b77b063c2bd89613243fc
train
function
def handle_join_date(value): return parse(value).date()
def handle_join_date(value):
return parse(value).date()
import re from dateutil.parser import parse from ..schema.site_base import SignState, Work, NetworkState, SiteBase def handle_share_ratio(value): if value == '∞': return '0' else: return value def handle_join_date(value):
58
64
13
6
51
kbnq/flexget_qbittorrent_mod
ptsites/sites/torrentdb.py
Python
handle_join_date
handle_join_date
15
16
15
15
5645ef9b470a61f8596670f3eaa8751463ef4723
bigcode/the-stack
train
beb745c86dbac5f04dcc49dc
train
function
def build_selector(): return { 'user_id': r'<strong class="align-middle">(.+?)</strong>', 'detail_sources': { 'default': { 'link': '/profile/{}', 'elements': { 'join_date': 'div.bg-gray-light.rounded.p-5 div:nth-child(4) > div:nth-child...
def build_selector():
return { 'user_id': r'<strong class="align-middle">(.+?)</strong>', 'detail_sources': { 'default': { 'link': '/profile/{}', 'elements': { 'join_date': 'div.bg-gray-light.rounded.p-5 div:nth-child(4) > div:nth-child(2)', ...
import re from dateutil.parser import parse from ..schema.site_base import SignState, Work, NetworkState, SiteBase def handle_share_ratio(value): if value == '∞': return '0' else: return value def handle_join_date(value): return parse(value).date() def build_selector():
69
97
324
4
65
kbnq/flexget_qbittorrent_mod
ptsites/sites/torrentdb.py
Python
build_selector
build_selector
19
57
19
19
b880f72b1f01cb84c9de12cd8f9ebd5726e79b27
bigcode/the-stack
train
4f3ec9c822546e47723b1f15
train
function
def _init_maps(): '''Compile LED font info into useful maps to get letter width and bit columns''' global LETTER_TO_BITCOLS global LETTER_TO_WIDTH if LETTER_TO_BITCOLS is not None: return # Compile rows of individual 0/1 bits into columns of 8-bit bytes LETTER_TO_BITCOLS = {} LETTER...
def _init_maps():
'''Compile LED font info into useful maps to get letter width and bit columns''' global LETTER_TO_BITCOLS global LETTER_TO_WIDTH if LETTER_TO_BITCOLS is not None: return # Compile rows of individual 0/1 bits into columns of 8-bit bytes LETTER_TO_BITCOLS = {} LETTER_TO_WIDTH = {} ...
... MSB is the bottom row (7) def get_letter_bitcols(char): global LETTER_TO_BITCOLS _init_maps() return LETTER_TO_BITCOLS[char] # Return width, in columns, of a letter def get_letter_width(char): global LETTER_TO_WIDTH _init_maps() return LETTER_TO_WIDTH[char] # Pre-compile maps def _init_ma...
87
87
292
5
81
jhinsdale/arduino-rgb-matrix
font/font_util.py
Python
_init_maps
_init_maps
52
80
52
52
0b7449390180189cbe68e2d11c75698696929e55
bigcode/the-stack
train
c28507640bab36ae5873437c
train
function
def get_letter_bitcols(char): global LETTER_TO_BITCOLS _init_maps() return LETTER_TO_BITCOLS[char]
def get_letter_bitcols(char):
global LETTER_TO_BITCOLS _init_maps() return LETTER_TO_BITCOLS[char]
first = False result.extend(get_letter_bitcols(c)) return result # Return array of bytes corresponding to the bit columns of a letter # LSB of the byte is the first, top row (0) ... MSB is the bottom row (7) def get_letter_bitcols(char):
64
64
30
7
57
jhinsdale/arduino-rgb-matrix
font/font_util.py
Python
get_letter_bitcols
get_letter_bitcols
40
43
40
40
adffb0a94e1e2b18930f75874d5b678fe770d74b
bigcode/the-stack
train
b30c9e977de4960b92722931
train
function
def get_word_width(word): word_width = 0 for c in word: word_width += get_letter_width(c) # Add width of inter-letter spaces if len(word) >= 2: word_width += len(word) - 1 return word_width
def get_word_width(word):
word_width = 0 for c in word: word_width += get_letter_width(c) # Add width of inter-letter spaces if len(word) >= 2: word_width += len(word) - 1 return word_width
retained. import ledfont # Cached info. Map letters to array of bit columns and width LETTER_TO_BITCOLS = None LETTER_TO_WIDTH = None LETTER_HEIGHT = 8 # Get width of a word, in bit columns, including inter-letter space def get_word_width(word):
64
64
62
6
57
jhinsdale/arduino-rgb-matrix
font/font_util.py
Python
get_word_width
get_word_width
15
22
15
15
399b71dfcbed3dd4ff9dc835082b76cd3560d02a
bigcode/the-stack
train
40cff5d155f58b0a1e054d3b
train
function
def get_letter_width(char): global LETTER_TO_WIDTH _init_maps() return LETTER_TO_WIDTH[char]
def get_letter_width(char):
global LETTER_TO_WIDTH _init_maps() return LETTER_TO_WIDTH[char]
first, top row (0) ... MSB is the bottom row (7) def get_letter_bitcols(char): global LETTER_TO_BITCOLS _init_maps() return LETTER_TO_BITCOLS[char] # Return width, in columns, of a letter def get_letter_width(char):
64
64
25
6
57
jhinsdale/arduino-rgb-matrix
font/font_util.py
Python
get_letter_width
get_letter_width
46
49
46
46
240edee01a8080c7e65a6718842f51be651b9d32
bigcode/the-stack
train
2b3a964629c55be506ceecb2
train
function
def get_word_bitcols(word): result = [] first = True for c in word: if not first: # Inter-letter space column result.append(0) else: first = False result.extend(get_letter_bitcols(c)) return result
def get_word_bitcols(word):
result = [] first = True for c in word: if not first: # Inter-letter space column result.append(0) else: first = False result.extend(get_letter_bitcols(c)) return result
width of inter-letter spaces if len(word) >= 2: word_width += len(word) - 1 return word_width # Return array of bytes corresponding to the concatenated bit columns # of a word, with a one-column inter-letter space def get_word_bitcols(word):
64
64
61
7
56
jhinsdale/arduino-rgb-matrix
font/font_util.py
Python
get_word_bitcols
get_word_bitcols
26
36
26
26
5589a4dff6206325761caa913e5baba4bef95fd2
bigcode/the-stack
train
cb6af38cf243e634868ab1ed
train
function
def test_c_discovery_plugin_scan_exceptions(): """Test that the C discovery plugin finds valid C source/header files.""" cdp = CDiscoveryPlugin() package = Package('valid_package', os.path.join(os.path.dirname(__file__), 'valid_package')) exceptions = ...
def test_c_discovery_plugin_scan_exceptions():
"""Test that the C discovery plugin finds valid C source/header files.""" cdp = CDiscoveryPlugin() package = Package('valid_package', os.path.join(os.path.dirname(__file__), 'valid_package')) exceptions = Exceptions(os.path.join(os.path.dirname(__file_...
find non-C files.""" cdp = CDiscoveryPlugin() package = Package('invalid_package', os.path.join(os.path.dirname(__file__), 'invalid_package')) cdp.scan(package, 'level') assert not package['c_src'] def test_c_discovery_plugin_scan_exceptions():
64
64
203
10
54
axydes/statick
tests/plugins/discovery/c_discovery_plugin/test_c_discovery_plugin.py
Python
test_c_discovery_plugin_scan_exceptions
test_c_discovery_plugin_scan_exceptions
91
106
91
91
d95683a5bc7aaf37ca56f3b54f290ba17cf0623c
bigcode/the-stack
train
4c077d51563fb4fc69d3bf49
train
function
def test_c_discovery_plugin_no_file_cmd(): """ Test when file command does not exist. Test that files are not discovered with file command output if file command does not exist. """ with modified_environ(PATH=''): cdp = CDiscoveryPlugin() package = Package('valid_package', ...
def test_c_discovery_plugin_no_file_cmd():
""" Test when file command does not exist. Test that files are not discovered with file command output if file command does not exist. """ with modified_environ(PATH=''): cdp = CDiscoveryPlugin() package = Package('valid_package', os.path.join(os.path.d...
each of the above expected_fullpath = [os.path.join(package.path, filename) for filename in expected] # Neat trick to verify that two unordered lists are the same assert set(package['c_src']) == set(expected_fullpath) def test_c_discovery_plugin_no_file_cmd():
64
64
203
10
54
axydes/statick
tests/plugins/discovery/c_discovery_plugin/test_c_discovery_plugin.py
Python
test_c_discovery_plugin_no_file_cmd
test_c_discovery_plugin_no_file_cmd
109
128
109
109
63206b74d598484a62497d6346e60a66ae546185
bigcode/the-stack
train
8fd58ecce6d2ba66efd80c37
train
function
def test_c_discovery_plugin_scan_valid(): """Test that the C discovery plugin finds valid C source/header files.""" cdp = CDiscoveryPlugin() package = Package('valid_package', os.path.join(os.path.dirname(__file__), 'valid_package')) cdp.scan(package, ...
def test_c_discovery_plugin_scan_valid():
"""Test that the C discovery plugin finds valid C source/header files.""" cdp = CDiscoveryPlugin() package = Package('valid_package', os.path.join(os.path.dirname(__file__), 'valid_package')) cdp.scan(package, 'level') expected = ['test.c', 'test.c...
in manager.getPluginsOfCategory("Discovery")) # While we're at it, verify that a plugin is named C Discovery Plugin assert any(plugin_info.name == 'C/C++ Discovery Plugin' for plugin_info in manager.getPluginsOfCategory("Discovery")) def test_c_discovery_plugin_scan_valid():
63
64
198
9
54
axydes/statick
tests/plugins/discovery/c_discovery_plugin/test_c_discovery_plugin.py
Python
test_c_discovery_plugin_scan_valid
test_c_discovery_plugin_scan_valid
64
78
64
64
1640a4b69ee065f338105a65de69a874cdbac856
bigcode/the-stack
train
14ad97e4c2306aa8ef679fbb
train
function
def test_c_discovery_plugin_found(): """Test that the plugin manager finds the C discovery plugin.""" manager = PluginManager() # Get the path to statick_tool/__init__.py, get the directory part, and # add 'plugins' to that to get the standard plugins dir manager.setPluginPlaces([os.path.join(os.pat...
def test_c_discovery_plugin_found():
"""Test that the plugin manager finds the C discovery plugin.""" manager = PluginManager() # Get the path to statick_tool/__init__.py, get the directory part, and # add 'plugins' to that to get the standard plugins dir manager.setPluginPlaces([os.path.join(os.path.dirname(statick_tool.__file__), ...
(k for k in update if k not in env) try: env.update(update) [env.pop(k, None) for k in remove] yield finally: env.update(update_after) [env.pop(k) for k in remove_after] def test_c_discovery_plugin_found():
64
64
195
8
56
axydes/statick
tests/plugins/discovery/c_discovery_plugin/test_c_discovery_plugin.py
Python
test_c_discovery_plugin_found
test_c_discovery_plugin_found
45
61
45
45
98bd9b4b95c0c49108123455997f1d28f7bcebe3
bigcode/the-stack
train
1925b5c678e17133f6768760
train
function
@contextlib.contextmanager def modified_environ(*remove, **update): """ Temporarily updates the ``os.environ`` dictionary in-place. The ``os.environ`` dictionary is updated in-place so that the modification is sure to work in all situations. :param remove: Environment variables to remove. :para...
@contextlib.contextmanager def modified_environ(*remove, **update):
""" Temporarily updates the ``os.environ`` dictionary in-place. The ``os.environ`` dictionary is updated in-place so that the modification is sure to work in all situations. :param remove: Environment variables to remove. :param update: Dictionary of environment variables and values to add/upda...
ick_tool.exceptions import Exceptions from statick_tool.package import Package from statick_tool.plugins.discovery.c_discovery_plugin import CDiscoveryPlugin # From https://stackoverflow.com/questions/2059482/python-temporarily-modify-the-current-processs-environment @contextlib.contextmanager def modified_environ(*r...
69
69
231
16
52
axydes/statick
tests/plugins/discovery/c_discovery_plugin/test_c_discovery_plugin.py
Python
modified_environ
modified_environ
15
42
15
16
fdcec205b3138acb6687e20e3572f589a60e5861
bigcode/the-stack
train
1ce46dd7a29797815e260230
train
function
def test_c_discovery_plugin_scan_invalid(): """Test that the C discovery plugin doesn't find non-C files.""" cdp = CDiscoveryPlugin() package = Package('invalid_package', os.path.join(os.path.dirname(__file__), 'invalid_package')) cdp.scan(package...
def test_c_discovery_plugin_scan_invalid():
"""Test that the C discovery plugin doesn't find non-C files.""" cdp = CDiscoveryPlugin() package = Package('invalid_package', os.path.join(os.path.dirname(__file__), 'invalid_package')) cdp.scan(package, 'level') assert not package['c_src']
the above...yuck expected_fullpath = [os.path.join(package.path, filename) for filename in expected] # Neat trick to verify that two unordered lists are the same assert set(package['c_src']) == set(expected_fullpath) def test_c_discovery_plugin_scan_invalid():
64
64
72
9
55
axydes/statick
tests/plugins/discovery/c_discovery_plugin/test_c_discovery_plugin.py
Python
test_c_discovery_plugin_scan_invalid
test_c_discovery_plugin_scan_invalid
81
88
81
81
fdda3c2041b4fe78605f3c0d32ea9f3a0d06df48
bigcode/the-stack
train
f90e393e8f9b3586b1f573c7
train
class
class TestDocstringCheckerReturn(CheckerTestCase): """Tests for pylint_plugin.RaiseDocChecker""" CHECKER_CLASS = DocstringParameterChecker def test_ignores_no_docstring(self): return_node = astroid.extract_node(''' def my_func(self): return False #@ ''') with sel...
class TestDocstringCheckerReturn(CheckerTestCase):
"""Tests for pylint_plugin.RaiseDocChecker""" CHECKER_CLASS = DocstringParameterChecker def test_ignores_no_docstring(self): return_node = astroid.extract_node(''' def my_func(self): return False #@ ''') with self.assertNoMessages(): self.checker.visi...
# -*- coding: utf-8 -*- # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk> # Copyright (c) 2016 Moisés López <moylop260@vauxoo.com> # Copyright (c) 2016 Glenn Matthews <glenn@e-dad.net> # Copyright (c) 2016 Claudiu Popa <pcmanticore@gmail.com> # Licensed under the GPL: https://www.gnu.org/licenses/old-license...
216
256
3,317
11
204
zwachtel11/fruitful-backend
venv/lib/python2.7/site-packages/pylint/test/extensions/test_check_return_docs.py
Python
TestDocstringCheckerReturn
TestDocstringCheckerReturn
21
571
21
21
188bfd920cabe08f363ebd228b1ad918c32b2c03
bigcode/the-stack
train
7422974e0075eb387e09b12a
train
class
class GitPolicySource(BasePolicySource): """ Watches a git repository for changes and can trigger callbacks when detecting new commits on the tracked branch. Checking for changes is done following a git pull from a tracked remote. The pull can be either triggered by a method (i.e: you can call ...
class GitPolicySource(BasePolicySource):
""" Watches a git repository for changes and can trigger callbacks when detecting new commits on the tracked branch. Checking for changes is done following a git pull from a tracked remote. The pull can be either triggered by a method (i.e: you can call it from a webhook) or can be triggered pe...
import asyncio from typing import Callable, Coroutine, List, Optional from git.objects import Commit from git import Repo, remote from opal_common.git.branch_tracker import BranchTracker from opal_common.git.repo_cloner import RepoCloner from opal_common.git.exceptions import GitFailed from opal_common.logger import l...
90
222
743
8
81
MatanyaStroh/opal
opal_common/sources/git_policy_source.py
Python
GitPolicySource
GitPolicySource
13
90
13
13
ea9ef8bf4871058b4843c8b01fab41f82b867dbb
bigcode/the-stack
train
b65de59b74a8eb96515e282a
train
class
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: n = len(board) row = [set() for i in range(n)] col = [set() for i in range(n)] for i in range(n): for j in range(n): if board[i][j] != '.': if board[i][j] in row[i...
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool: n = len(board) row = [set() for i in range(n)] col = [set() for i in range(n)] for i in range(n): for j in range(n): if board[i][j] != '.': if board[i][j] in row[i] or board[i][j]...
class Solution:
3
71
238
3
0
YiqunPeng/leetcode_pro
solutions/36_valid_sudoku.py
Python
Solution
Solution
1
24
1
1
ff66e36aa52fab3b2ab8150bc5d6543942b90561
bigcode/the-stack
train
d9e006b9614ffabde5a49e2e
train
function
@beam.ptransform_fn @beam.typehints.with_input_types(beam.typehints.Any) @beam.typehints.with_output_types(evaluator.Evaluation) def EvaluateExtracts( # pylint: disable=invalid-name extracts, key = constants.ANALYSIS_KEY): """Creates Evaluation output for extracts. Args: extracts: PCollection of Extra...
@beam.ptransform_fn @beam.typehints.with_input_types(beam.typehints.Any) @beam.typehints.with_output_types(evaluator.Evaluation) def EvaluateExtracts( # pylint: disable=invalid-name extracts, key = constants.ANALYSIS_KEY):
"""Creates Evaluation output for extracts. Args: extracts: PCollection of Extracts. key: Name to use for key in Evaluation output. Returns: Evaluation containing PCollection of Extracts. """ return {key: extracts}
-for-parameter @beam.ptransform_fn @beam.typehints.with_input_types(beam.typehints.Any) @beam.typehints.with_output_types(evaluator.Evaluation) def EvaluateExtracts( # pylint: disable=invalid-name extracts, key = constants.ANALYSIS_KEY):
64
64
113
60
3
chuanyu/model-analysis
tensorflow_model_analysis/evaluators/analysis_table_evaluator.py
Python
EvaluateExtracts
EvaluateExtracts
53
68
53
58
cdcebeb82efeb6eb1d4beaf4a6dec1e638bcbebd
bigcode/the-stack
train
4c18ee613d433de184fed8d7
train
function
def AnalysisTableEvaluator( # pylint: disable=invalid-name key = constants.ANALYSIS_KEY, run_after = extractor.LAST_EXTRACTOR_STAGE_NAME ): """Creates an Evaluator for returning Extracts data for analysis. Args: key: Name to use for key in Evaluation output. run_after: Extractor to run after (None...
def AnalysisTableEvaluator( # pylint: disable=invalid-name key = constants.ANALYSIS_KEY, run_after = extractor.LAST_EXTRACTOR_STAGE_NAME ):
"""Creates an Evaluator for returning Extracts data for analysis. Args: key: Name to use for key in Evaluation output. run_after: Extractor to run after (None means before any extractors). Returns: Evaluator for collecting analysis data. The output is stored under the key 'analysis'. """ # p...
_model_analysis.evaluators import evaluator from tensorflow_model_analysis.extractors import extractor from tensorflow_model_analysis.types_compat import Text def AnalysisTableEvaluator( # pylint: disable=invalid-name key = constants.ANALYSIS_KEY, run_after = extractor.LAST_EXTRACTOR_STAGE_NAME ):
64
64
151
37
26
chuanyu/model-analysis
tensorflow_model_analysis/evaluators/analysis_table_evaluator.py
Python
AnalysisTableEvaluator
AnalysisTableEvaluator
31
49
31
34
4c839cacfff2e8c431edee76418f5acfb20df5c3
bigcode/the-stack
train
d35b67d800317aa662b4cb60
train
function
def step2(np, x, y): return np.dot(x, y)
def step2(np, x, y):
return np.dot(x, y)
# See the License for the specific language governing permissions and # limitations under the License. # import random import numpy import cunumeric # Code written using the NumPy interface def step1(np, n): return np.ones(n), np.ones(n) def step2(np, x, y):
64
64
17
9
55
bryevdv/cunumeric
tests/interop.py
Python
step2
step2
28
29
28
28
b9913fc7a4b387a3a0e701a7871a9496642f1d2b
bigcode/the-stack
train
62c28effdb7979b872176637
train
function
def step1(np, n): return np.ones(n), np.ones(n)
def step1(np, n):
return np.ones(n), np.ones(n)
AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import random import numpy import cunumeric # Code written using the NumPy interface def step1(np, n):
64
64
17
7
56
bryevdv/cunumeric
tests/interop.py
Python
step1
step1
24
25
24
24
81b921c82ff6976f84d22151644df0d820391bf6
bigcode/the-stack
train
1104b096c63b0f0b1b33f21e
train
function
def to_float2(original: Tuple[int, int]) -> Tuple[float, float]: return (original[0] + 0.5, original[1] + 0.5)
def to_float2(original: Tuple[int, int]) -> Tuple[float, float]:
return (original[0] + 0.5, original[1] + 0.5)
from . sc2pathlib import PathFind #from . import _sc2pathlib #import sc2pathlib import numpy as np from typing import Union, List, Tuple from math import floor def to_float2(original: Tuple[int, int]) -> Tuple[float, float]:
62
64
41
18
43
eladyaniv01/sharpy-sc2
sc2pathlibp/path_finder.py
Python
to_float2
to_float2
8
9
8
8
515b09990173d1b5eb6cfac7fa6bcc162929068f
bigcode/the-stack
train
c22377f66f7191bb7a5236ab
train
class
class PathFinder(): def __init__(self, maze: Union[List[List[int]], np.array]): """ pathing values need to be integers to improve performance. Initialization should be done with array consisting values of 0 and 1. """ self._path_find = PathFind(maze) self.heuristic_...
class PathFinder():
def __init__(self, maze: Union[List[List[int]], np.array]): """ pathing values need to be integers to improve performance. Initialization should be done with array consisting values of 0 and 1. """ self._path_find = PathFind(maze) self.heuristic_accuracy = 1 # Octi...
from . sc2pathlib import PathFind #from . import _sc2pathlib #import sc2pathlib import numpy as np from typing import Union, List, Tuple from math import floor def to_float2(original: Tuple[int, int]) -> Tuple[float, float]: return (original[0] + 0.5, original[1] + 0.5) class PathFinder():
89
256
1,496
4
85
eladyaniv01/sharpy-sc2
sc2pathlibp/path_finder.py
Python
PathFinder
PathFinder
12
161
12
12
fa49d0127be595c930a5bf957bc2919a6b2e1f50
bigcode/the-stack
train
522d2dd64987f099dd533cf2
train
function
@contextlib.contextmanager def current_ioloop(io_loop): ''' A context manager that will set the current ioloop to io_loop for the context ''' orig_loop = tornado.ioloop.IOLoop.current() io_loop.make_current() try: yield finally: orig_loop.make_current()
@contextlib.contextmanager def current_ioloop(io_loop):
''' A context manager that will set the current ioloop to io_loop for the context ''' orig_loop = tornado.ioloop.IOLoop.current() io_loop.make_current() try: yield finally: orig_loop.make_current()
tornado asynchronous stuff ''' from __future__ import absolute_import, print_function, unicode_literals import sys import tornado.ioloop import tornado.concurrent import contextlib from salt.ext import six from salt.utils import zeromq @contextlib.contextmanager def current_ioloop(io_loop):
64
64
71
14
49
timgates42/salt
salt/utils/asynchronous.py
Python
current_ioloop
current_ioloop
17
27
17
18
90d02c43322d482fc257dad5b2da078f3cbb6269
bigcode/the-stack
train
15852953f6276abb911ec090
train
class
class SyncWrapper(object): ''' A wrapper to make Async classes synchronous This is uses as a simple wrapper, for example: asynchronous = AsyncClass() # this method would reguarly return a future future = asynchronous.async_method() sync = SyncWrapper(async_factory_method, (arg1, arg2), {'...
class SyncWrapper(object):
''' A wrapper to make Async classes synchronous This is uses as a simple wrapper, for example: asynchronous = AsyncClass() # this method would reguarly return a future future = asynchronous.async_method() sync = SyncWrapper(async_factory_method, (arg1, arg2), {'kwarg1': 'val'}) # the ...
# -*- coding: utf-8 -*- ''' Helpers/utils for working with tornado asynchronous stuff ''' from __future__ import absolute_import, print_function, unicode_literals import sys import tornado.ioloop import tornado.concurrent import contextlib from salt.ext import six from salt.utils import zeromq @contextlib.contextm...
140
159
532
5
135
timgates42/salt
salt/utils/asynchronous.py
Python
SyncWrapper
SyncWrapper
30
100
30
30
1e282f05586331b0a971de9472744c7a93d2b7b0
bigcode/the-stack
train
ce8816041c0d372f28c737fc
train
function
def create_relationship( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa """Create relationship between proposal and parent instance.""" if isinstance(obj, all_models.Proposal): all_models.Relationship( source=obj.instance, destination=obj )
def create_relationship( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa
"""Create relationship between proposal and parent instance.""" if isinstance(obj, all_models.Proposal): all_models.Relationship( source=obj.instance, destination=obj )
"""Make proposal procedure hook.""" obj.proposed_by = login.get_current_user() add_comment_about(obj, obj.STATES.PROPOSED, obj.agenda) def create_relationship( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa
64
64
65
28
36
pbedn/ggrc-core
src/ggrc/models/hooks/proposal.py
Python
create_relationship
create_relationship
84
92
84
86
55da30b3cbad7ce6b792550044ebabf46e1975c2
bigcode/the-stack
train
38f3d2e03c59bd3287fe7442
train
function
def make_proposal( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa """Make proposal procedure hook.""" obj.proposed_by = login.get_current_user() add_comment_about(obj, obj.STATES.PROPOSED, obj.agenda)
def make_proposal( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa
"""Make proposal procedure hook.""" obj.proposed_by = login.get_current_user() add_comment_about(obj, obj.STATES.PROPOSED, obj.agenda)
= login.get_current_user() obj.decline_datetime = datetime.datetime.utcnow() add_comment_about(obj, obj.STATES.DECLINED, obj.decline_reason) def make_proposal( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa
64
64
64
29
35
pbedn/ggrc-core
src/ggrc/models/hooks/proposal.py
Python
make_proposal
make_proposal
76
81
76
78
94404e80fecaec1841e938e7d43dd5eca44b02f8
bigcode/the-stack
train
fd0431a63ca08ed1880d24c9
train
function
def add_comment_about(proposal, reason, txt): """Create comment about proposal for reason with required text.""" if not isinstance(proposal.instance, comment.Commentable): return txt = txt or "" txt = txt.strip() if txt.startswith("<p>"): txt = txt[3:] if txt.endswith("</p>"): txt = txt[:-4]...
def add_comment_about(proposal, reason, txt):
"""Create comment about proposal for reason with required text.""" if not isinstance(proposal.instance, comment.Commentable): return txt = txt or "" txt = txt.strip() if txt.startswith("<p>"): txt = txt[3:] if txt.endswith("</p>"): txt = txt[:-4] txt = txt.strip() comment_text = proposal...
import comment from ggrc import login from ggrc.utils.revisions_diff import applier def is_status_changed_to(required_status, obj): return (inspect(obj).attrs.status.history.has_changes() and obj.status == required_status) def add_comment_about(proposal, reason, txt):
64
64
153
11
53
pbedn/ggrc-core
src/ggrc/models/hooks/proposal.py
Python
add_comment_about
add_comment_about
22
40
22
22
7195714cadc016b7b5d6a11da0dd6f524954b15a
bigcode/the-stack
train
152350157b2b8f677989c282
train
function
def is_status_changed_to(required_status, obj): return (inspect(obj).attrs.status.history.has_changes() and obj.status == required_status)
def is_status_changed_to(required_status, obj):
return (inspect(obj).attrs.status.history.has_changes() and obj.status == required_status)
hooks.""" import datetime from sqlalchemy import inspect from ggrc.services import signals from ggrc.models import all_models from ggrc.models import comment from ggrc import login from ggrc.utils.revisions_diff import applier def is_status_changed_to(required_status, obj):
64
64
31
10
53
pbedn/ggrc-core
src/ggrc/models/hooks/proposal.py
Python
is_status_changed_to
is_status_changed_to
17
19
17
17
7f5fcb35b176f90870b289a331c000837caa77d9
bigcode/the-stack
train
c3689aadde5d9dad979fca0b
train
function
def init_hook(): """Init proposal signal handlers.""" signals.Restful.model_posted.connect(make_proposal, all_models.Proposal, weak=False) signals.Restful.model_posted.connect(create_relationship, ...
def init_hook():
"""Init proposal signal handlers.""" signals.Restful.model_posted.connect(make_proposal, all_models.Proposal, weak=False) signals.Restful.model_posted.connect(create_relationship, all_models.Propos...
# noqa """Create relationship between proposal and parent instance.""" if isinstance(obj, all_models.Proposal): all_models.Relationship( source=obj.instance, destination=obj ) # pylint: enable=unused-argument # pylint: enable=too-many-arguments def init_hook():
64
64
98
4
59
pbedn/ggrc-core
src/ggrc/models/hooks/proposal.py
Python
init_hook
init_hook
99
112
99
99
19875c418cd4904438e11d368cc3c41fc60247e2
bigcode/the-stack
train
e929ef51e355cbc71e2f0246
train
function
def apply_proposal( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa """Apply proposal procedure hook.""" if not is_status_changed_to(obj.STATES.APPLIED, obj): return current_user = login.get_current_user() now = datetime.datetime.utcnow() obj.applied_by = current...
def apply_proposal( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa
"""Apply proposal procedure hook.""" if not is_status_changed_to(obj.STATES.APPLIED, obj): return current_user = login.get_current_user() now = datetime.datetime.utcnow() obj.applied_by = current_user obj.apply_datetime = now if applier.apply_action(obj.instance, obj.content): obj.instance.modifie...
_models.Relationship( source=proposal.instance, destination=created_comment) # pylint: disable=unused-argument # pylint: disable=too-many-arguments def apply_proposal( sender, obj=None, src=None, service=None, event=None, initial_state=None): # noqa
64
64
160
29
34
pbedn/ggrc-core
src/ggrc/models/hooks/proposal.py
Python
apply_proposal
apply_proposal
46
62
46
48
c6494535a9510ee8561d4f705d2138cb1e3c2729
bigcode/the-stack
train