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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
044748e350f64c26a61626c0 | train | class | class GroupByTestCase(test_base.PipelineBasedTest):
def test_value_extractor(self):
"""
"""
data = self._pipeline.parallelize([("A", 4), ("A", 3), ("B", 2), ("A", 1)])
grouped = transforms.group_by(data, lambda x: x, lambda x: x[1])
self.assertEqual({("A", 1): [1],
... | class GroupByTestCase(test_base.PipelineBasedTest):
| def test_value_extractor(self):
"""
"""
data = self._pipeline.parallelize([("A", 4), ("A", 3), ("B", 2), ("A", 1)])
grouped = transforms.group_by(data, lambda x: x, lambda x: x[1])
self.assertEqual({("A", 1): [1],
("B", 2): [2],
... | #
########################################################################
"""
File: group_by_test.py
Author: Wang Cong(bigflow-opensource@baidu.com)
Date: 2015/03/25 15:41:43
"""
import unittest
from bigflow.test import test_base
from bigflow import transforms
from bigflow import error
class GroupByTestCase(test_ba... | 77 | 77 | 259 | 12 | 64 | tushushu/bigflow | bigflow_python/python/bigflow/transform_impls/test/group_by_test.py | Python | GroupByTestCase | GroupByTestCase | 35 | 58 | 35 | 36 | 89ff7549dd024dc448807d4a449a5c17b172e34c | bigcode/the-stack | train |
4b05473a5052e8954c27eec0 | train | function | def _generate_titlepage_svg(title: str, authors: Union[str, list], contributors: dict, title_string: str) -> str:
"""
Generate a draft of the titlepage SVG.
The function tries to build the title with the widest line at the bottom, moving up.
We approximate a few values, like the width of a space, which are variable... | def _generate_titlepage_svg(title: str, authors: Union[str, list], contributors: dict, title_string: str) -> str:
| """
Generate a draft of the titlepage SVG.
The function tries to build the title with the widest line at the bottom, moving up.
We approximate a few values, like the width of a space, which are variable in the font.
INPUTS
title: The title
authors: an author, or an array of authors
contributors: a dict in the ... | the widest at the bottom.
INPUTS
string: The string to inspect
target_height: The target letter height, in pixels
canvas_width: The width of the canvas, in pixels
OUTPUTS
An array of strings. Each string represents one line of text in the final image. The lines are ordered with the widest at the bottom.
"""
... | 256 | 256 | 1,015 | 29 | 226 | rbergmair/setools | se/executables_create_draft.py | Python | _generate_titlepage_svg | _generate_titlepage_svg | 93 | 186 | 93 | 93 | 5f8b2869a5c77ba49ed536b5d610c1f131cd424d | bigcode/the-stack | train |
c910d37009bf061f424ab850 | train | function | def _get_wikipedia_url(string: str, get_nacoaf_url: bool) -> (str, str):
"""
Helper function.
Given a string, try to see if there's a Wikipedia page entry for that string.
INPUTS
string: The string to find on Wikipedia
get_nacoaf_url: Include NACOAF URL in resulting tuple, if found?
OUTPUTS
A tuple of two str... | def _get_wikipedia_url(string: str, get_nacoaf_url: bool) -> (str, str):
| """
Helper function.
Given a string, try to see if there's a Wikipedia page entry for that string.
INPUTS
string: The string to find on Wikipedia
get_nacoaf_url: Include NACOAF URL in resulting tuple, if found?
OUTPUTS
A tuple of two strings. The first string is the Wikipedia URL, the second is the NACOAF URL... | vg = regex.sub(r"\n\n\t\t\.title-small\{.+?\}", "", svg, flags=regex.DOTALL)
if title_class != "title-xsmall":
svg = regex.sub(r"\n\n\t\t\.title-xsmall\{.+?\}", "", svg, flags=regex.DOTALL)
svg = svg.replace("</svg>", "\n" + text_elements + "</svg>\n").replace("TITLE_STRING", title_string)
return svg
def _get_w... | 123 | 123 | 413 | 24 | 98 | rbergmair/setools | se/executables_create_draft.py | Python | _get_wikipedia_url | _get_wikipedia_url | 283 | 323 | 283 | 283 | cd212a096ccd17d6ad3f3671a4fa351efc2b85d9 | bigcode/the-stack | train |
a53a7ebb62c6a95c5c2ca769 | train | function | def _calculate_image_lines(string: str, target_height: int, canvas_width: int) -> list:
"""
Helper function.
Given a string, a target letter height, and the canvas width, return an array representing the string
broken down into enough lines to fill the canvas without overflowing. Lines are ordered with the widest a... | def _calculate_image_lines(string: str, target_height: int, canvas_width: int) -> list:
| """
Helper function.
Given a string, a target letter height, and the canvas width, return an array representing the string
broken down into enough lines to fill the canvas without overflowing. Lines are ordered with the widest at the bottom.
INPUTS
string: The string to inspect
target_height: The target letter ... | _SPARTAN_KERNING + se.LEAGUE_SPARTAN_AVERAGE_SPACING
width = width - se.LEAGUE_SPARTAN_KERNING - se.LEAGUE_SPARTAN_AVERAGE_SPACING
words.append({"word": word, "width": width})
return words
def _calculate_image_lines(string: str, target_height: int, canvas_width: int) -> list:
| 88 | 88 | 294 | 22 | 65 | rbergmair/setools | se/executables_create_draft.py | Python | _calculate_image_lines | _calculate_image_lines | 53 | 91 | 53 | 53 | 64908d60ce86159f1a422c6532906e52445cdd58 | bigcode/the-stack | train |
a28195cbb98398bfb71bfae6 | train | function | def _get_word_widths(string: str, target_height: int) -> list:
"""
Helper function.
Given a string and a target letter height, return an array of words with their corresponding widths.
INPUTS
string: The string to inspect
target_height: The target letter height, in pixels.
OUTPUTS
An array of objects. Each ob... | def _get_word_widths(string: str, target_height: int) -> list:
| """
Helper function.
Given a string and a target letter height, return an array of words with their corresponding widths.
INPUTS
string: The string to inspect
target_height: The target letter height, in pixels.
OUTPUTS
An array of objects. Each object represents a word and its corresponding width in pixels.
... | subprocess import call
import unicodedata
import urllib
from typing import Union
import requests
import git
import regex
from pkg_resources import resource_filename
from ftfy import fix_text
from bs4 import BeautifulSoup
import se
import se.formatting
def _get_word_widths(string: str, target_height: int) -> list:
| 73 | 73 | 244 | 18 | 54 | rbergmair/setools | se/executables_create_draft.py | Python | _get_word_widths | _get_word_widths | 25 | 51 | 25 | 25 | 48b5b91195a6f6e7240cbd2b688226fc304f039f | bigcode/the-stack | train |
2239d11aa9989d7d3dd117c1 | train | function | def create_draft(args: list):
"""
Entry point for `se create-draft`
"""
# Put together some variables for later use
identifier = se.formatting.make_url_safe(args.author) + "/" + se.formatting.make_url_safe(args.title)
title_string = args.title.replace("'", "’") + ", by " + args.author.replace("'", "’")
sorted_t... | def create_draft(args: list):
| """
Entry point for `se create-draft`
"""
# Put together some variables for later use
identifier = se.formatting.make_url_safe(args.author) + "/" + se.formatting.make_url_safe(args.title)
title_string = args.title.replace("'", "’") + ", by " + args.author.replace("'", "’")
sorted_title = regex.sub(r"^(A|An|The)... | If the search page
# returns HTTP 200, then we didn't find a direct match and return nothing.
try:
response = requests.get("https://en.wikipedia.org/wiki/Special:Search", params={"search": string, "go": "Go", "ns0": 1}, allow_redirects=False)
except Exception as ex:
se.print_error("Couldn’t contact Wikipedia.... | 256 | 256 | 4,427 | 8 | 247 | rbergmair/setools | se/executables_create_draft.py | Python | create_draft | create_draft | 325 | 648 | 325 | 325 | 9d2364f3868f980f7c06d31b62b73bc92cec68fe | bigcode/the-stack | train |
dcc43eda5c8b60a01497a282 | train | function | def _generate_cover_svg(title: str, authors: Union[str, list], title_string: str) -> str:
"""
Generate a draft of the cover SVG.
The function tries to build the title box with the widest line at the bottom, moving up.
We approximate a few values, like the width of a space, which are variable in the font.
INPUTS
... | def _generate_cover_svg(title: str, authors: Union[str, list], title_string: str) -> str:
| """
Generate a draft of the cover SVG.
The function tries to build the title box with the widest line at the bottom, moving up.
We approximate a few values, like the width of a space, which are variable in the font.
INPUTS
title: The title
authors: an author, or an array of authors
title_string: The SE titlest... | class=\"contributor\" x=\"700\" y=\"{:.0f}\">{}</text>\n".format(element_y, person)
element_y += se.TITLEPAGE_CONTRIBUTOR_MARGIN
element_y -= se.TITLEPAGE_CONTRIBUTOR_MARGIN
element_y += se.TITLEPAGE_CONTRIBUTOR_DESCRIPTOR_MARGIN
element_y -= se.TITLEPAGE_CONTRIBUTOR_DESCRIPTOR_MARGIN
else:
# Remove ... | 256 | 256 | 912 | 24 | 231 | rbergmair/setools | se/executables_create_draft.py | Python | _generate_cover_svg | _generate_cover_svg | 188 | 281 | 188 | 188 | 53f1344043a1c8216969db3baf067238961f31f9 | bigcode/the-stack | train |
53ce59730ce9d614304543b9 | train | function | def test_sw_pulse_lst():
"""
Test function of sliding window extractor for LST camera pulse shape with
the correction for the integration window completeness
"""
# prepare array with 1 LST
subarray = SubarrayDescription(
"LST1",
tel_positions={1: np.zeros(3) * u.m},
tel_... | def test_sw_pulse_lst():
| """
Test function of sliding window extractor for LST camera pulse shape with
the correction for the integration window completeness
"""
# prepare array with 1 LST
subarray = SubarrayDescription(
"LST1",
tel_positions={1: np.zeros(3) * u.m},
tel_descriptions={
... | """
Test of sliding window extractor for LST camera pulse shape with
the correction for the integration window completeness
"""
import numpy as np
import astropy.units as u
from numpy.testing import assert_allclose
from traitlets.config.loader import Config
from ctapipe.image.extractor import SlidingWindowMaxSum, Ima... | 100 | 116 | 388 | 7 | 92 | watsonjj/ctapipe | ctapipe/image/tests/test_sliding_window_correction.py | Python | test_sw_pulse_lst | test_sw_pulse_lst | 16 | 58 | 16 | 16 | b5638c942dd550d21518c4e0d59bfd21c41b05b0 | bigcode/the-stack | train |
efe39c9bdd2e9c3e783f6918 | train | class | class WebpackLoader(object):
_assets = {}
def __init__(self, name, config):
self.name = name
self.config = config
def load_assets(self):
try:
with open(self.config['STATS_FILE'], encoding="utf-8") as f:
return json.load(f)
except IOError:
... | class WebpackLoader(object):
| _assets = {}
def __init__(self, name, config):
self.name = name
self.config = config
def load_assets(self):
try:
with open(self.config['STATS_FILE'], encoding="utf-8") as f:
return json.load(f)
except IOError:
raise IOError(
... | import json
import time
from io import open
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
from .exceptions import (
WebpackError,
WebpackLoaderBadStatsError,
WebpackLoaderTimeoutError,
WebpackBundleLookupError
)
class WebpackLoader(object):
| 67 | 190 | 635 | 6 | 61 | EricRabil/django-webpack-loader | webpack_loader/loader.py | Python | WebpackLoader | WebpackLoader | 16 | 101 | 16 | 16 | ad7e84f0018908bb86d770eafaab159186fd2aff | bigcode/the-stack | train |
63e5e3413b3f31c92faa0a23 | train | function | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, True),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, True),
(AgreementState.rejected_on_behalf, False),
))
def test_accepted(dummy_agreement, state, expected):
dum... | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, True),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, True),
(AgreementState.rejected_on_behalf, False),
))
def test_accepted(dummy_agreement, state, expected):
| dummy_agreement.state = state
assert dummy_agreement.accepted == expected
assert Agreement.find_one(accepted=expected) == dummy_agreement
| @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, True),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, True),
(AgreementState.rejected_on_behalf, False),
))
def test_accepted(dummy_agreement, state, expected):
| 73 | 64 | 106 | 73 | 0 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_accepted | test_accepted | 20 | 30 | 20 | 27 | 48d027361900e5f94f455b6dcb80f0a87ca3f835 | bigcode/the-stack | train |
5f9de814a60495aceb1be4c1 | train | function | @pytest.mark.usefixtures('mock_agreement_definition')
def test_is_orphan(dummy_event):
agreement = Agreement(event=dummy_event)
agreement.is_orphan()
agreement.definition.is_agreement_orphan(agreement.event, agreement)
| @pytest.mark.usefixtures('mock_agreement_definition')
def test_is_orphan(dummy_event):
| agreement = Agreement(event=dummy_event)
agreement.is_orphan()
agreement.definition.is_agreement_orphan(agreement.event, agreement)
| ):
agreement.render(None)
def test_belongs_to():
agreement = Agreement(identifier='foo')
assert agreement.belongs_to(MagicMock(identifier='foo'))
assert not agreement.belongs_to(MagicMock(identifier='bar'))
@pytest.mark.usefixtures('mock_agreement_definition')
def test_is_orphan(dummy_event):
| 63 | 64 | 47 | 18 | 45 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_is_orphan | test_is_orphan | 174 | 178 | 174 | 175 | feadfd5d99ca151dba607ce8617b93be4117f505 | bigcode/the-stack | train |
69d72d5f355a0be6b67b563a | train | function | def test_is_orphan_no_definition(monkeypatch):
monkeypatch.setattr(Agreement, 'definition', property(lambda s: None))
agreement = Agreement()
with pytest.raises(ServiceUnavailable):
agreement.is_orphan()
| def test_is_orphan_no_definition(monkeypatch):
| monkeypatch.setattr(Agreement, 'definition', property(lambda s: None))
agreement = Agreement()
with pytest.raises(ServiceUnavailable):
agreement.is_orphan()
| Mock(identifier='bar'))
@pytest.mark.usefixtures('mock_agreement_definition')
def test_is_orphan(dummy_event):
agreement = Agreement(event=dummy_event)
agreement.is_orphan()
agreement.definition.is_agreement_orphan(agreement.event, agreement)
def test_is_orphan_no_definition(monkeypatch):
| 64 | 64 | 46 | 11 | 53 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_is_orphan_no_definition | test_is_orphan_no_definition | 181 | 185 | 181 | 181 | a1bc31efe0189f5c995528406b786e1eb8e3a407 | bigcode/the-stack | train |
a8990746875708039339c56d | train | function | def test_belongs_to():
agreement = Agreement(identifier='foo')
assert agreement.belongs_to(MagicMock(identifier='foo'))
assert not agreement.belongs_to(MagicMock(identifier='bar'))
| def test_belongs_to():
| agreement = Agreement(identifier='foo')
assert agreement.belongs_to(MagicMock(identifier='foo'))
assert not agreement.belongs_to(MagicMock(identifier='bar'))
| (None)
agreement.definition.render_form.assert_called_with(agreement, None)
def test_render_no_definition(monkeypatch):
monkeypatch.setattr(Agreement, 'definition', property(lambda s: None))
agreement = Agreement()
with pytest.raises(ServiceUnavailable):
agreement.render(None)
def test_belongs... | 64 | 64 | 39 | 6 | 58 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_belongs_to | test_belongs_to | 168 | 171 | 168 | 168 | 586ee447fc6dd640bbb5fae411a28ca765b54af9 | bigcode/the-stack | train |
4bf443822842016e086468f3 | train | function | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, False),
(AgreementState.rejected, True),
(AgreementState.accepted_on_behalf, False),
(AgreementState.rejected_on_behalf, True),
))
def test_rejected(dummy_agreement, state, expected):
dum... | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, False),
(AgreementState.rejected, True),
(AgreementState.accepted_on_behalf, False),
(AgreementState.rejected_on_behalf, True),
))
def test_rejected(dummy_agreement, state, expected):
| dummy_agreement.state = state
assert dummy_agreement.rejected == expected
assert Agreement.find_one(rejected=expected) == dummy_agreement
| @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, False),
(AgreementState.rejected, True),
(AgreementState.accepted_on_behalf, False),
(AgreementState.rejected_on_behalf, True),
))
def test_rejected(dummy_agreement, state, expected):
| 73 | 64 | 106 | 73 | 0 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_rejected | test_rejected | 48 | 58 | 48 | 55 | a84dc6f084461bc269a7919d7355efe8253a4d1c | bigcode/the-stack | train |
997808b2c569f2bf39890e77 | train | function | def test_render_no_definition(monkeypatch):
monkeypatch.setattr(Agreement, 'definition', property(lambda s: None))
agreement = Agreement()
with pytest.raises(ServiceUnavailable):
agreement.render(None)
| def test_render_no_definition(monkeypatch):
| monkeypatch.setattr(Agreement, 'definition', property(lambda s: None))
agreement = Agreement()
with pytest.raises(ServiceUnavailable):
agreement.render(None)
| assert agreement.signed_dt is None
assert agreement.signed_from_ip is None
@pytest.mark.usefixtures('mock_agreement_definition')
def test_render():
agreement = Agreement()
agreement.render(None)
agreement.definition.render_form.assert_called_with(agreement, None)
def test_render_no_definition(monkeyp... | 64 | 64 | 43 | 9 | 55 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_render_no_definition | test_render_no_definition | 161 | 165 | 161 | 161 | 0edfc0a9067fde7dfcd592a3b2c31b6a6692816e | bigcode/the-stack | train |
cefaca08bf4db099a1b34d26 | train | function | @pytest.mark.parametrize('person_with_user', (True, False))
def test_create_from_data(dummy_event, dummy_person, dummy_user, person_with_user):
type_ = 'dummy'
dummy_person.user = dummy_user if person_with_user else None
agreement = Agreement.create_from_data(event=dummy_event, type_=type_, person=dummy_per... | @pytest.mark.parametrize('person_with_user', (True, False))
def test_create_from_data(dummy_event, dummy_person, dummy_user, person_with_user):
| type_ = 'dummy'
dummy_person.user = dummy_user if person_with_user else None
agreement = Agreement.create_from_data(event=dummy_event, type_=type_, person=dummy_person)
assert agreement.event == dummy_event
assert agreement.type == type_
assert agreement.state == AgreementState.pending
asser... |
agreement = Agreement(id=id_, event_id=event_id)
assert agreement.locator == {'id': id_,
'confId': event_id}
@pytest.mark.parametrize('person_with_user', (True, False))
def test_create_from_data(dummy_event, dummy_person, dummy_user, person_with_user):
| 64 | 64 | 149 | 31 | 33 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_create_from_data | test_create_from_data | 89 | 102 | 89 | 90 | a8997b1829076cdf19b81d351dc7864f0c58a476 | bigcode/the-stack | train |
389c279dc9f438218595bf06 | train | function | def test_locator():
id_ = 1337
event_id = 9000
agreement = Agreement(id=id_, event_id=event_id)
assert agreement.locator == {'id': id_,
'confId': event_id}
| def test_locator():
| id_ = 1337
event_id = 9000
agreement = Agreement(id=id_, event_id=event_id)
assert agreement.locator == {'id': id_,
'confId': event_id}
| (mocker):
from indico.modules.events.agreements import util
mocker.patch.object(util, 'get_agreement_definitions', return_value={'foobar': 'test'})
assert Agreement(type='foobar').definition == 'test'
assert Agreement(type='barfoo').definition is None
def test_locator():
| 64 | 64 | 52 | 4 | 59 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_locator | test_locator | 81 | 86 | 81 | 81 | 502570c71b2e7fc40506c8951b4657932414cbb9 | bigcode/the-stack | train |
9c6acd8d78352762d2086f4a | train | function | @freeze_time(now_utc())
@pytest.mark.usefixtures('mock_agreement_definition')
@pytest.mark.parametrize(('reason', 'on_behalf', 'expected_state'), (
(None, True, AgreementState.accepted_on_behalf),
(None, False, AgreementState.accepted),
('reason', False, AgreementState.accepted),
))
def test_accept... | @freeze_time(now_utc())
@pytest.mark.usefixtures('mock_agreement_definition')
@pytest.mark.parametrize(('reason', 'on_behalf', 'expected_state'), (
(None, True, AgreementState.accepted_on_behalf),
(None, False, AgreementState.accepted),
('reason', False, AgreementState.accepted),
))
def test_accept... | ip = '127.0.0.1'
agreement = Agreement()
agreement.accept(from_ip=ip, reason=reason, on_behalf=on_behalf)
assert agreement.state == expected_state
assert agreement.signed_from_ip == ip
assert agreement.reason == reason
assert agreement.signed_dt == now_utc()
agreement.definition.handle_a... | @freeze_time(now_utc())
@pytest.mark.usefixtures('mock_agreement_definition')
@pytest.mark.parametrize(('reason', 'on_behalf', 'expected_state'), (
(None, True, AgreementState.accepted_on_behalf),
(None, False, AgreementState.accepted),
('reason', False, AgreementState.accepted),
))
def test_accept... | 85 | 64 | 170 | 85 | 0 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_accept | test_accept | 105 | 120 | 105 | 112 | d8240e4fae5ed8d0e6d858763e19d6bd9747dd3a | bigcode/the-stack | train |
355c6addd14ffeb190896035 | train | function | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, True),
(AgreementState.accepted, False),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, False),
(AgreementState.rejected_on_behalf, False),
))
def test_pending(dummy_agreement, state, expected):
dum... | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, True),
(AgreementState.accepted, False),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, False),
(AgreementState.rejected_on_behalf, False),
))
def test_pending(dummy_agreement, state, expected):
| dummy_agreement.state = state
filter_ = Agreement.pending if expected else ~Agreement.pending
assert dummy_agreement.pending == expected
assert Agreement.find_one(filter_) == dummy_agreement
assert not Agreement.find_first(~filter_)
| @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, True),
(AgreementState.accepted, False),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, False),
(AgreementState.rejected_on_behalf, False),
))
def test_pending(dummy_agreement, state, expected):
| 72 | 64 | 123 | 72 | 0 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_pending | test_pending | 33 | 45 | 33 | 40 | e7a4efa8a167761ef115dfabb6c67fa48cc90a08 | bigcode/the-stack | train |
d7084223e91f816708165ceb | train | function | def test_definition(mocker):
from indico.modules.events.agreements import util
mocker.patch.object(util, 'get_agreement_definitions', return_value={'foobar': 'test'})
assert Agreement(type='foobar').definition == 'test'
assert Agreement(type='barfoo').definition is None
| def test_definition(mocker):
| from indico.modules.events.agreements import util
mocker.patch.object(util, 'get_agreement_definitions', return_value={'foobar': 'test'})
assert Agreement(type='foobar').definition == 'test'
assert Agreement(type='barfoo').definition is None
| half, True),
))
def test_signed_on_behalf(dummy_agreement, state, expected):
dummy_agreement.state = state
assert dummy_agreement.signed_on_behalf == expected
assert Agreement.find_one(signed_on_behalf=expected) == dummy_agreement
def test_definition(mocker):
| 64 | 64 | 63 | 6 | 57 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_definition | test_definition | 74 | 78 | 74 | 74 | 9c260363c1e0bea337b9588a56588e6c993bccf5 | bigcode/the-stack | train |
490991d34c075d4d933ef8cf | train | function | @freeze_time(now_utc())
@pytest.mark.usefixtures('mock_agreement_definition')
@pytest.mark.parametrize(('reason', 'on_behalf', 'expected_state'), (
(None, True, AgreementState.rejected_on_behalf),
(None, False, AgreementState.rejected),
('reason', False, AgreementState.rejected),
))
def test_reject... | @freeze_time(now_utc())
@pytest.mark.usefixtures('mock_agreement_definition')
@pytest.mark.parametrize(('reason', 'on_behalf', 'expected_state'), (
(None, True, AgreementState.rejected_on_behalf),
(None, False, AgreementState.rejected),
('reason', False, AgreementState.rejected),
))
def test_reject... | ip = '127.0.0.1'
agreement = Agreement()
agreement.reject(from_ip=ip, reason=reason, on_behalf=on_behalf)
assert agreement.state == expected_state
assert agreement.signed_from_ip == ip
assert agreement.reason == reason
assert agreement.signed_dt == now_utc()
agreement.definition.handle_r... | @freeze_time(now_utc())
@pytest.mark.usefixtures('mock_agreement_definition')
@pytest.mark.parametrize(('reason', 'on_behalf', 'expected_state'), (
(None, True, AgreementState.rejected_on_behalf),
(None, False, AgreementState.rejected),
('reason', False, AgreementState.rejected),
))
def test_reject... | 86 | 64 | 171 | 86 | 0 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_reject | test_reject | 123 | 138 | 123 | 130 | 4da6b81bd5370956acdae21228d1375d0eaab888 | bigcode/the-stack | train |
6708bc015a849312c037a922 | train | function | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, False),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, True),
(AgreementState.rejected_on_behalf, True),
))
def test_signed_on_behalf(dummy_agreement, state, expected):... | @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, False),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, True),
(AgreementState.rejected_on_behalf, True),
))
def test_signed_on_behalf(dummy_agreement, state, expected):... | dummy_agreement.state = state
assert dummy_agreement.signed_on_behalf == expected
assert Agreement.find_one(signed_on_behalf=expected) == dummy_agreement
| @pytest.mark.parametrize(('state', 'expected'), (
(AgreementState.pending, False),
(AgreementState.accepted, False),
(AgreementState.rejected, False),
(AgreementState.accepted_on_behalf, True),
(AgreementState.rejected_on_behalf, True),
))
def test_signed_on_behalf(dummy_agreement, state, expected):... | 75 | 64 | 114 | 75 | 0 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_signed_on_behalf | test_signed_on_behalf | 61 | 71 | 61 | 68 | 5492c2dfd1a1458967f26a122169907ca5be065d | bigcode/the-stack | train |
3868a4d97a460cb9667da5ee | train | function | @pytest.mark.usefixtures('mock_agreement_definition')
def test_render():
agreement = Agreement()
agreement.render(None)
agreement.definition.render_form.assert_called_with(agreement, None)
| @pytest.mark.usefixtures('mock_agreement_definition')
def test_render():
| agreement = Agreement()
agreement.render(None)
agreement.definition.render_form.assert_called_with(agreement, None)
| assert agreement.attachment is None
assert agreement.attachment_filename is None
assert agreement.data is None
assert agreement.reason is None
assert agreement.signed_dt is None
assert agreement.signed_from_ip is None
@pytest.mark.usefixtures('mock_agreement_definition')
def test_render():
| 64 | 64 | 37 | 14 | 49 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_render | test_render | 154 | 158 | 154 | 155 | 440d3d5f63692a8e63d83bd3cdd5a2c31908e8d7 | bigcode/the-stack | train |
abd82b81fcb21d734de31b6f | train | function | @pytest.mark.usefixtures('mock_agreement_definition')
def test_reset():
agreement = Agreement()
agreement.reset()
assert agreement.state == AgreementState.pending
assert agreement.attachment is None
assert agreement.attachment_filename is None
assert agreement.data is None
assert agreement.r... | @pytest.mark.usefixtures('mock_agreement_definition')
def test_reset():
| agreement = Agreement()
agreement.reset()
assert agreement.state == AgreementState.pending
assert agreement.attachment is None
assert agreement.attachment_filename is None
assert agreement.data is None
assert agreement.reason is None
assert agreement.signed_dt is None
assert agreemen... | half)
assert agreement.state == expected_state
assert agreement.signed_from_ip == ip
assert agreement.reason == reason
assert agreement.signed_dt == now_utc()
agreement.definition.handle_rejected.assert_called_with(agreement)
@pytest.mark.usefixtures('mock_agreement_definition')
def test_reset():
| 64 | 64 | 82 | 14 | 50 | UNOG-Indico/UNOG-Indico-v2 | indico/modules/events/agreements/models/agreements_test.py | Python | test_reset | test_reset | 141 | 151 | 141 | 142 | 62870bb4a82b1be119d56ab1cd3824b2910548e1 | bigcode/the-stack | train |
29a54803da9e16eaaac861c5 | train | class | class Predictor():
def __init__(self, config):
device = config['device']
model, vocab = build_model(config)
weights = '/tmp/weights.pth'
if config['weights'].startswith('http'):
weights = download_weights(config['weights'])
else:
weights = c... | class Predictor():
| def __init__(self, config):
device = config['device']
model, vocab = build_model(config)
weights = '/tmp/weights.pth'
if config['weights'].startswith('http'):
weights = download_weights(config['weights'])
else:
weights = config['weights']
... | from vietocr.tool.translate import build_model, translate, process_input, predict
from vietocr.tool.utils import download_weights
import yaml
import torch
class Predictor():
| 34 | 64 | 153 | 3 | 30 | PhatDatPQ/vietocr | vietocr/tool/predictor.py | Python | Predictor | Predictor | 7 | 34 | 7 | 7 | a11a7cbe04de62717a437407c1de4316a86a8399 | bigcode/the-stack | train |
8a92255a06267d1b91c7b31a | train | function | def productSum(array, depth=1):
sum = 0
for item in array:
if type(item) == list:
sum += productSum(item, depth+1)
else:
sum += item
sum *= depth
return sum
| def productSum(array, depth=1):
| sum = 0
for item in array:
if type(item) == list:
sum += productSum(item, depth+1)
else:
sum += item
sum *= depth
return sum
| (n) - n is the number of elements in array and their sub arrays.
# Ex: [1, 2, [[[3]], [4]]] - O(8)
# space O(d) - d is max depth of arrays (call stack size)
def productSum(array, depth=1):
| 64 | 64 | 57 | 9 | 55 | Iftakharpy/AlgoExpert-Questions | 023 Product Sum/Product_Sum.py | Python | productSum | productSum | 4 | 12 | 4 | 4 | c6e8f6beac7e5b3a01773616a26ba77a08c280d0 | bigcode/the-stack | train |
fe587012d6432a871bae125c | train | class | class ProviderOperationsMetadataOperations:
"""ProviderOperationsMetadataOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in ... | class ProviderOperationsMetadataOperations:
| """ProviderOperationsMetadataOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azu... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | 211 | 256 | 1,376 | 6 | 205 | ankitarorabit/azure-sdk-for-python | sdk/authorization/azure-mgmt-authorization/azure/mgmt/authorization/v2018_01_01_preview/aio/operations/_provider_operations_metadata_operations.py | Python | ProviderOperationsMetadataOperations | ProviderOperationsMetadataOperations | 22 | 167 | 22 | 22 | 48c4a9bb2f845a57461ee79660f430984be00179 | bigcode/the-stack | train |
0585ddf0fcc274ed0155216a | train | class | class StrReprPrinter(StrPrinter):
"""(internal) -- see sstrrepr"""
def _print_str(self, s):
return repr(s)
def _print_Str(self, s):
# Str does not to be printed same as str here
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
| class StrReprPrinter(StrPrinter):
| """(internal) -- see sstrrepr"""
def _print_str(self, s):
return repr(s)
def _print_Str(self, s):
# Str does not to be printed same as str here
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
| >>> a, b = symbols('a b')
>>> sstr(Eq(a + b, 0))
'Eq(a + b, 0)'
"""
p = StrPrinter(settings)
s = p.doprint(expr)
return s
class StrReprPrinter(StrPrinter):
| 64 | 64 | 76 | 8 | 55 | ricardoprins/sympy | sympy/printing/str.py | Python | StrReprPrinter | StrReprPrinter | 1,006 | 1,014 | 1,006 | 1,006 | 81bf30018eef6455e39c18db2219c8b42d1c0c87 | bigcode/the-stack | train |
95985a877316129528be0a39 | train | class | class StrPrinter(Printer):
printmethod = "_sympystr"
_default_settings = {
"order": None,
"full_prec": "auto",
"sympy_integers": False,
"abbrev": False,
"perm_cyclic": True,
"min": None,
"max": None,
} # type: tDict[str, Any]
_relationals = dict(... | class StrPrinter(Printer):
| printmethod = "_sympystr"
_default_settings = {
"order": None,
"full_prec": "auto",
"sympy_integers": False,
"abbrev": False,
"perm_cyclic": True,
"min": None,
"max": None,
} # type: tDict[str, Any]
_relationals = dict() # type: tDict[str, str]
... | """
A Printer for generating readable representation of most SymPy classes.
"""
from typing import Any, Dict as tDict
from sympy.core import S, Rational, Pow, Basic, Mul, Number
from sympy.core.mul import _keep_coeff
from sympy.core.relational import Relational
from sympy.core.sorting import default_sort_key
from sym... | 140 | 256 | 8,087 | 6 | 133 | ricardoprins/sympy | sympy/printing/str.py | Python | StrPrinter | StrPrinter | 20 | 980 | 20 | 20 | a6464eade30add8e5c12a06c8e8df9f90fc27db7 | bigcode/the-stack | train |
3cd8e761b8c5e16902ffff86 | train | function | @print_function(StrReprPrinter)
def sstrrepr(expr, **settings):
"""return expr in mixed str/repr form
i.e. strings are returned in repr form with quotes, and everything else
is returned in str form.
This function could be useful for hooking into sys.displayhook
"""
p = StrReprPrinter... | @print_function(StrReprPrinter)
def sstrrepr(expr, **settings):
| """return expr in mixed str/repr form
i.e. strings are returned in repr form with quotes, and everything else
is returned in str form.
This function could be useful for hooking into sys.displayhook
"""
p = StrReprPrinter(settings)
s = p.doprint(expr)
return s
| return repr(s)
def _print_Str(self, s):
# Str does not to be printed same as str here
return "%s(%s)" % (s.__class__.__name__, self._print(s.name))
@print_function(StrReprPrinter)
def sstrrepr(expr, **settings):
| 64 | 64 | 89 | 17 | 47 | ricardoprins/sympy | sympy/printing/str.py | Python | sstrrepr | sstrrepr | 1,017 | 1,030 | 1,017 | 1,018 | 2cd775ff69a1e9de4c3314b897c410ef2079da69 | bigcode/the-stack | train |
aa83bd55c9cc030752d682a2 | train | function | @print_function(StrPrinter)
def sstr(expr, **settings):
"""Returns the expression as a string.
For large expressions where speed is a concern, use the setting
order='none'. If abbrev=True setting is used then units are printed in
abbreviated form.
Examples
========
>>> from sympy import s... | @print_function(StrPrinter)
def sstr(expr, **settings):
| """Returns the expression as a string.
For large expressions where speed is a concern, use the setting
order='none'. If abbrev=True setting is used then units are printed in
abbreviated form.
Examples
========
>>> from sympy import symbols, Eq, sstr
>>> a, b = symbols('a b')
>>> s... | _print_AppliedBinaryRelation(self, expr):
rel = expr.function
return '%s(%s, %s)' % (self._print(rel),
self._print(expr.lhs),
self._print(expr.rhs))
@print_function(StrPrinter)
def sstr(expr, **settings):
| 64 | 64 | 135 | 14 | 50 | ricardoprins/sympy | sympy/printing/str.py | Python | sstr | sstr | 983 | 1,003 | 983 | 984 | 63bc2c9da902374c5ec1c38560987a36a90e8f18 | bigcode/the-stack | train |
9d15b1b72634ca0887c13511 | train | class | class STSConnection(AWSQueryConnection):
"""
AWS Security Token Service
The AWS Security Token Service is a web service that enables you
to request temporary, limited-privilege credentials for AWS
Identity and Access Management (IAM) users or for users that you
authenticate (federated users). Th... | class STSConnection(AWSQueryConnection):
| """
AWS Security Token Service
The AWS Security Token Service is a web service that enables you
to request temporary, limited-privilege credentials for AWS
Identity and Access Management (IAM) users or for users that you
authenticate (federated users). This guide provides descriptions
of the... | modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the... | 255 | 256 | 6,014 | 9 | 246 | soulseekah/boto | boto/sts/connection.py | Python | STSConnection | STSConnection | 37 | 652 | 37 | 37 | 49b898b2ddda670fff343aade0aa1e1148b95ad7 | bigcode/the-stack | train |
234f27099e1f6ed4068eaf12 | train | function | def netmiko_args(optional_args):
"""Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the Netmiko
ConnectHandler call.
"""
if sys.version_info < (3,):
# (args, varargs, keywords, defaults)
... | def netmiko_args(optional_args):
| """Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the Netmiko
ConnectHandler call.
"""
if sys.version_info < (3,):
# (args, varargs, keywords, defaults)
args, _, _, defaults = inspect... | .apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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 li... | 103 | 103 | 345 | 8 | 94 | nachosn89/napalm | napalm/base/netmiko_helpers.py | Python | netmiko_args | netmiko_args | 18 | 53 | 18 | 18 | 7e5def0355c218db41a0a1c9141d06d4f505f744 | bigcode/the-stack | train |
2e5db11c970f0366f2403a16 | train | class | class StormPdb(Pdb):
me = 'Storm pdb'
_prev_outs = None
_sock = None
def __init__(self, host=HOST, port=PORT,
port_search_limit=100, port_skew=+0, out=sys.stdout):
self.active = True
self.out = out
self._prev_handles = sys.stdin, sys.stdout
self._sock,... | class StormPdb(Pdb):
| me = 'Storm pdb'
_prev_outs = None
_sock = None
def __init__(self, host=HOST, port=PORT,
port_search_limit=100, port_skew=+0, out=sys.stdout):
self.active = True
self.out = out
self._prev_handles = sys.stdin, sys.stdout
self._sock, this_port = self.get... | 'debugger', 'set_trace']
default_port = 7999
HOST = os.environ.get('STORM_PDB_HOST') or '127.0.0.1'
PORT = int(os.environ.get('STORM_PDB_PORT') or default_port)
#: Holds the currently active debugger.
_current = [None]
_frame = getattr(sys, '_getframe')
NO_AVAILABLE_PORT = """\
{self.ident}: Couldn't find an avai... | 186 | 187 | 625 | 7 | 179 | thedrow/streamparse | streamparse/debug.py | Python | StormPdb | StormPdb | 48 | 130 | 48 | 48 | f9dfca5820bd2d4b1f068da5fa7a0bb3626905ca | bigcode/the-stack | train |
d3e7649dd16a25beb89e1e4c | train | function | def debugger():
"""Return the current debugger instance (if any),
or creates a new one."""
rdb = _current[0]
if rdb is None or not rdb.active:
rdb = _current[0] = StormPdb()
return rdb
| def debugger():
| """Return the current debugger instance (if any),
or creates a new one."""
rdb = _current[0]
if rdb is None or not rdb.active:
rdb = _current[0] = StormPdb()
return rdb
| def set_trace(self, frame=None):
if frame is None:
frame = _frame().f_back
Pdb.set_trace(self, frame)
def set_quit(self):
# this raises a BdbQuit exception that we are unable to catch.
sys.settrace(None)
def debugger():
| 64 | 64 | 61 | 3 | 61 | thedrow/streamparse | streamparse/debug.py | Python | debugger | debugger | 133 | 139 | 133 | 133 | d1f9edeadf23e72d0696c09c5acf0a4741c2122c | bigcode/the-stack | train |
f77fac5217243d300f9ce743 | train | function | def set_trace(frame=None):
"""Set breakpoint at current location, or a specified frame"""
if frame is None:
frame = _frame().f_back
return debugger().set_trace(frame)
| def set_trace(frame=None):
| """Set breakpoint at current location, or a specified frame"""
if frame is None:
frame = _frame().f_back
return debugger().set_trace(frame)
| """Return the current debugger instance (if any),
or creates a new one."""
rdb = _current[0]
if rdb is None or not rdb.active:
rdb = _current[0] = StormPdb()
return rdb
def set_trace(frame=None):
| 64 | 64 | 42 | 6 | 57 | thedrow/streamparse | streamparse/debug.py | Python | set_trace | set_trace | 142 | 146 | 142 | 142 | b3e6ac3dba0686cdca073d88951bc7330f977e0a | bigcode/the-stack | train |
de24a269f42059a24fa59b14 | train | class | class MySQLIdentifierPreparer(compiler.IdentifierPreparer):
reserved_words = RESERVED_WORDS
def __init__(self, dialect, server_ansiquotes=False, **kw):
if not server_ansiquotes:
quote = "`"
else:
quote = '"'
super(MySQLIdentifierPreparer, self).__init__(
... | class MySQLIdentifierPreparer(compiler.IdentifierPreparer):
| reserved_words = RESERVED_WORDS
def __init__(self, dialect, server_ansiquotes=False, **kw):
if not server_ansiquotes:
quote = "`"
else:
quote = '"'
super(MySQLIdentifierPreparer, self).__init__(
dialect, initial_quote=quote, escape_quote=quote
... | type_, type_.enums)
def visit_SET(self, type_, **kw):
return self._visit_enumerated_values("SET", type_, type_.values)
def visit_BOOLEAN(self, type_, **kw):
return "BOOL"
class MySQLIdentifierPreparer(compiler.IdentifierPreparer):
| 64 | 64 | 131 | 12 | 52 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | MySQLIdentifierPreparer | MySQLIdentifierPreparer | 2,322 | 2,339 | 2,322 | 2,323 | 00f8a8e158a532273c64ca4122c09d77adc16012 | bigcode/the-stack | train |
d20aaafa166f7d56d5b55c4f | train | class | class MySQLDDLCompiler(compiler.DDLCompiler):
def get_column_specification(self, column, **kw):
"""Builds column DDL."""
colspec = [
self.preparer.format_column(column),
self.dialect.type_compiler.process(
column.type, type_expression=column
),
... | class MySQLDDLCompiler(compiler.DDLCompiler):
| def get_column_specification(self, column, **kw):
"""Builds column DDL."""
colspec = [
self.preparer.format_column(column),
self.dialect.type_compiler.process(
column.type, type_expression=column
),
]
if column.computed is not Non... | SQL."""
return "USING " + ", ".join(
t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw)
for t in [from_table] + extra_froms
)
def visit_empty_set_expr(self, element_types):
return (
"SELECT %(outer)s FROM (SELECT %(inner)s) "
... | 256 | 256 | 1,745 | 11 | 245 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | MySQLDDLCompiler | MySQLDDLCompiler | 1,755 | 2,017 | 1,755 | 1,755 | 83008488dc0749016583b2dec3b1115e31082cb4 | bigcode/the-stack | train |
4016efe70b2bb329f0434d9c | train | class | class _DecodingRow(object):
"""Return unicode-decoded values based on type inspection.
Smooth over data type issues (esp. with alpha driver versions) and
normalize strings as Unicode regardless of user-configured driver
encoding settings.
"""
# Some MySQL-python versions can return some colum... | class _DecodingRow(object):
| """Return unicode-decoded values based on type inspection.
Smooth over data type issues (esp. with alpha driver versions) and
normalize strings as Unicode regardless of user-configured driver
encoding settings.
"""
# Some MySQL-python versions can return some columns as
# sets.Set(['value... | elif code == 1356:
util.raise_(
exc.UnreflectableTableError(
"Table or view named %s could not be "
"reflected: %s" % (full_name, e)
),
replace_context=e,
... | 100 | 100 | 335 | 7 | 92 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | _DecodingRow | _DecodingRow | 3,273 | 3,315 | 3,273 | 3,273 | 61e5e306d059bc5307003da637f0194987ad33e5 | bigcode/the-stack | train |
eec227daea63adeeb581c200 | train | class | class MySQLExecutionContext(default.DefaultExecutionContext):
def should_autocommit_text(self, statement):
return AUTOCOMMIT_RE.match(statement)
def create_server_side_cursor(self):
if self.dialect.supports_server_side_cursors:
return self._dbapi_connection.cursor(self.dialect._sscu... | class MySQLExecutionContext(default.DefaultExecutionContext):
| def should_autocommit_text(self, statement):
return AUTOCOMMIT_RE.match(statement)
def create_server_side_cursor(self):
if self.dialect.supports_server_side_cursors:
return self._dbapi_connection.cursor(self.dialect._sscursor)
else:
raise NotImplementedError()
... | ": TIMESTAMP,
"tinyblob": TINYBLOB,
"tinyint": TINYINT,
"tinytext": TINYTEXT,
"varbinary": VARBINARY,
"varchar": VARCHAR,
"year": YEAR,
}
class MySQLExecutionContext(default.DefaultExecutionContext):
| 64 | 64 | 122 | 10 | 54 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | MySQLExecutionContext | MySQLExecutionContext | 1,320 | 1,337 | 1,320 | 1,320 | 54852641e1c514bfa48c1cd0daea564e89b77f11 | bigcode/the-stack | train |
d3c5ff079f6540a30a3b9bcc | train | class | class MySQLCompiler(compiler.SQLCompiler):
render_table_with_column_in_update_from = True
"""Overridden from base SQLCompiler value"""
extract_map = compiler.SQLCompiler.extract_map.copy()
extract_map.update({"milliseconds": "millisecond"})
def default_from(self):
"""Called when a ``SELEC... | class MySQLCompiler(compiler.SQLCompiler):
| render_table_with_column_in_update_from = True
"""Overridden from base SQLCompiler value"""
extract_map = compiler.SQLCompiler.extract_map.copy()
extract_map.update({"milliseconds": "millisecond"})
def default_from(self):
"""Called when a ``SELECT`` statement has no froms,
and no `... | LOB,
"mediumint": MEDIUMINT,
"mediumtext": MEDIUMTEXT,
"nchar": NCHAR,
"nvarchar": NVARCHAR,
"numeric": NUMERIC,
"set": SET,
"smallint": SMALLINT,
"text": TEXT,
"time": TIME,
"timestamp": TIMESTAMP,
"tinyblob": TINYBLOB,
"tinyint": TINYINT,
"tinytext": TINYTEXT,
"... | 256 | 256 | 3,289 | 9 | 247 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | MySQLCompiler | MySQLCompiler | 1,340 | 1,752 | 1,340 | 1,341 | 4f9edba487ba0e6a842b15d20b264557871e4102 | bigcode/the-stack | train |
e4a598bced578691ccb1475a | train | class | class MySQLTypeCompiler(compiler.GenericTypeCompiler):
def _extend_numeric(self, type_, spec):
"Extend a numeric-type declaration with MySQL specific extensions."
if not self._mysql_type(type_):
return spec
if type_.unsigned:
spec += " UNSIGNED"
if type_.zer... | class MySQLTypeCompiler(compiler.GenericTypeCompiler):
| def _extend_numeric(self, type_, spec):
"Extend a numeric-type declaration with MySQL specific extensions."
if not self._mysql_type(type_):
return spec
if type_.unsigned:
spec += " UNSIGNED"
if type_.zerofill:
spec += " ZEROFILL"
return s... | ""
const = self.preparer.format_constraint(constraint)
return "ALTER TABLE %s DROP %s%s" % (
self.preparer.format_table(constraint.table),
qual,
const,
)
def define_constraint_match(self, constraint):
if constraint.match is not None:
... | 256 | 256 | 2,281 | 11 | 245 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | MySQLTypeCompiler | MySQLTypeCompiler | 2,020 | 2,319 | 2,020 | 2,020 | 2152cfe2a4b7ddb6045959d097b99b5310645146 | bigcode/the-stack | train |
4aaddcc0167af6d156e4ed97 | train | class | @log.class_logger
class MySQLDialect(default.DefaultDialect):
"""Details of the MySQL dialect.
Not used directly in application code.
"""
name = "mysql"
supports_alter = True
# MySQL has no true "boolean" type; we
# allow for the "true" and "false" keywords, however
supports_native_boo... | @log.class_logger
class MySQLDialect(default.DefaultDialect):
| """Details of the MySQL dialect.
Not used directly in application code.
"""
name = "mysql"
supports_alter = True
# MySQL has no true "boolean" type; we
# allow for the "true" and "false" keywords, however
supports_native_boolean = False
# identifiers are 64, however aliases can be... | e.replace("'", "''"))
return self._extend_string(
type_, {}, "%s(%s)" % (name, ",".join(quoted_enums))
)
def visit_ENUM(self, type_, **kw):
return self._visit_enumerated_values("ENUM", type_, type_.enums)
def visit_SET(self, type_, **kw):
return self._visit_enumera... | 256 | 256 | 6,802 | 13 | 243 | Jesse-Bakker/sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | Python | MySQLDialect | MySQLDialect | 2,342 | 3,270 | 2,342 | 2,343 | 05a96381515627f7a031d059ba68e39aa027fd53 | bigcode/the-stack | train |
ced3e350f6913b13aa7e2aca | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BroadlinkCommand',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BroadlinkCommand',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_le... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2018-02-06 04:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 188 | 7 | 46 | reid418/pyrmbridge | pyrmbridge/migrations/0001_initial.py | Python | Migration | Migration | 8 | 36 | 8 | 9 | a4c36f11ae7781056b0bae4d83c218f343c94c53 | bigcode/the-stack | train |
d1ffed24f2156e5efa542577 | train | class | class DataWriter():
def __init__(self, cfg, opt, save_video=False,
video_save_opt=DEFAULT_VIDEO_SAVE_OPT,
queueSize=1024):
self.cfg = cfg
self.opt = opt
self.video_save_opt = video_save_opt
self.eval_joints = EVAL_JOINTS
self.save_video = sa... | class DataWriter():
| def __init__(self, cfg, opt, save_video=False,
video_save_opt=DEFAULT_VIDEO_SAVE_OPT,
queueSize=1024):
self.cfg = cfg
self.opt = opt
self.video_save_opt = video_save_opt
self.eval_joints = EVAL_JOINTS
self.save_video = save_video
sel... | import os
import time
from threading import Thread
from queue import Queue
import cv2
import numpy as np
import torch
import torch.multiprocessing as mp
from alphapose.utils.transforms import get_func_heatmap_to_coord
from alphapose.utils.pPose_nms import pose_nms, write_json
DEFAULT_VIDEO_SAVE_OPT = {
'savepath... | 184 | 256 | 2,164 | 4 | 180 | HaoyiZhu/AlphaPose | alphapose/utils/writer.py | Python | DataWriter | DataWriter | 24 | 237 | 24 | 24 | 1f7550512bba9ccb3f75a8ce8bff85ab9b3f2a63 | bigcode/the-stack | train |
d8fc3342f189617f9f85d47c | train | class | class RegrepTest(unittest.TestCase):
def test_regrep(self):
"""
We are making sure a file containing line numbers is read in reverse
order, i.e. the first line that is read corresponds to the last line.
number
"""
fname = os.path.join(test_dir, "3000_lines.txt")
... | class RegrepTest(unittest.TestCase):
| def test_regrep(self):
"""
We are making sure a file containing line numbers is read in reverse
order, i.e. the first line that is read corresponds to the last line.
number
"""
fname = os.path.join(test_dir, "3000_lines.txt")
matches = regrep(fname, {"1": r"1(... | import os
import unittest
from monty.re import regrep
test_dir = os.path.join(os.path.dirname(__file__), "test_files")
class RegrepTest(unittest.TestCase):
| 38 | 64 | 215 | 8 | 30 | munrojm/monty | tests/test_re.py | Python | RegrepTest | RegrepTest | 9 | 30 | 9 | 9 | 1878a4c3fc7ae6d65dde56ab8974c7d88c1d322e | bigcode/the-stack | train |
64af639335eab49f519dad25 | train | class | class LocalStorageAccessor(iDatabase):
# Allow setting the storage location so that tests can run on a separate
# directory and not break anything in the production database folder
def __init__(self, storage_loc = METADATA_STORAGE_DIR):
self.storage_loc = storage_loc
if not os.path.exists(... | class LocalStorageAccessor(iDatabase):
# Allow setting the storage location so that tests can run on a separate
# directory and not break anything in the production database folder
| def __init__(self, storage_loc = METADATA_STORAGE_DIR):
self.storage_loc = storage_loc
if not os.path.exists(self.storage_loc):
os.mkdir(self.storage_loc)
self.url_list = []
self.id_list = []
for filename in os.listdir(self.storage_loc):
metadata = me... | import uuid
from typing import List
import os
from ..data.FilterCondition import FilterCondition
from ..data.MetaDataItem import MetaDataItem, metadata_from_file, gen_filename, delete_metadata_file
from .iDatabase import iDatabase, AlreadyExistsException, NotExistingException
from ..utils import get_project_root
MET... | 119 | 165 | 551 | 37 | 82 | AutoDash/AutoDash | src/database/LocalStorageAccessor.py | Python | LocalStorageAccessor | LocalStorageAccessor | 13 | 91 | 13 | 16 | 0eed84cd720f7c3e5737c1de4bb90cb65e75f5da | bigcode/the-stack | train |
b7913b8c92a5ac37953b9067 | train | class | class Daemon(DaemonThread):
def __init__(self, config, fd, is_gui):
DaemonThread.__init__(self)
self.config = config
if config.get('offline'):
self.network = None
else:
self.network = Network(config)
self.network.start()
self.fx = FxThread... | class Daemon(DaemonThread):
| def __init__(self, config, fd, is_gui):
DaemonThread.__init__(self)
self.config = config
if config.get('offline'):
self.network = None
else:
self.network = Network(config)
self.network.start()
self.fx = FxThread(config, self.network)
... | get_server]", e)
if not create_time or create_time < time.time() - 1.0:
return None
# Sleep a bit and try again; it might have just been started
time.sleep(1.0)
def get_rpc_credentials(config):
rpc_user = config.get('rpcuser', None)
rpc_password = config.get('rpcpassword', ... | 256 | 256 | 1,543 | 8 | 247 | apollomatheus/electrum | lib/daemon.py | Python | Daemon | Daemon | 119 | 311 | 119 | 120 | 616f3b2fc1e1e00183c55c2aeb3e3ec5c49c8b6c | bigcode/the-stack | train |
1d74fc84f5e663d2f611e12f | train | function | def get_server(config):
lockfile = get_lockfile(config)
while True:
create_time = None
try:
with open(lockfile) as f:
(host, port), create_time = ast.literal_eval(f.read())
rpc_user, rpc_password = get_rpc_credentials(config)
if rpc_pas... | def get_server(config):
| lockfile = get_lockfile(config)
while True:
create_time = None
try:
with open(lockfile) as f:
(host, port), create_time = ast.literal_eval(f.read())
rpc_user, rpc_password = get_rpc_credentials(config)
if rpc_password == '':
... | os.O_WRONLY, 0o644), None
except OSError:
pass
server = get_server(config)
if server is not None:
return None, server
# Couldn't connect; remove lockfile and try again.
remove_lockfile(lockfile)
def get_server(config):
| 64 | 64 | 213 | 5 | 59 | apollomatheus/electrum | lib/daemon.py | Python | get_server | get_server | 73 | 96 | 73 | 73 | 5ec48a0eb113874cfbb8709f9e9704899c366c55 | bigcode/the-stack | train |
42ee0e6c95412bd18f91a660 | train | function | def get_lockfile(config):
return os.path.join(config.path, 'daemon')
| def get_lockfile(config):
| return os.path.join(config.path, 'daemon')
| .util import json_decode, DaemonThread
from .util import print_error, to_string
from .wallet import Wallet
from .storage import WalletStorage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
def get_lockfile(config):
| 64 | 64 | 17 | 6 | 57 | apollomatheus/electrum | lib/daemon.py | Python | get_lockfile | get_lockfile | 46 | 47 | 46 | 46 | 94f3762e5cbd2eebfd98de312c567aec395e6acf | bigcode/the-stack | train |
bd08227ac6add2c44021b9dc | train | function | def get_fd_or_server(config):
'''Tries to create the lockfile, using O_EXCL to
prevent races. If it succeeds it returns the FD.
Otherwise try and connect to the server specified in the lockfile.
If this succeeds, the server is returned. Otherwise remove the
lockfile and try again.'''
lockfile ... | def get_fd_or_server(config):
| '''Tries to create the lockfile, using O_EXCL to
prevent races. If it succeeds it returns the FD.
Otherwise try and connect to the server specified in the lockfile.
If this succeeds, the server is returned. Otherwise remove the
lockfile and try again.'''
lockfile = get_lockfile(config)
whi... | Storage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
def get_lockfile(config):
return os.path.join(config.path, 'daemon')
def remove_lockfile(lockfile):
os.unlink(lockfile)
def get_fd_or_server(config):
| 64 | 64 | 164 | 7 | 57 | apollomatheus/electrum | lib/daemon.py | Python | get_fd_or_server | get_fd_or_server | 54 | 70 | 54 | 54 | 98d88dafafb878c8fd3419ff66231a938ff269d8 | bigcode/the-stack | train |
38bd1a9fab79829a2ae5e6a5 | train | function | def remove_lockfile(lockfile):
os.unlink(lockfile)
| def remove_lockfile(lockfile):
| os.unlink(lockfile)
| _string
from .wallet import Wallet
from .storage import WalletStorage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
def get_lockfile(config):
return os.path.join(config.path, 'daemon')
def remove_lockfile(lockfile):
| 64 | 64 | 13 | 7 | 57 | apollomatheus/electrum | lib/daemon.py | Python | remove_lockfile | remove_lockfile | 50 | 51 | 50 | 50 | 956f42754bcf750ed19fa3fdd4581c4163627d9b | bigcode/the-stack | train |
49e7568dda6ec443ca7ddfee | train | function | def get_rpc_credentials(config):
rpc_user = config.get('rpcuser', None)
rpc_password = config.get('rpcpassword', None)
if rpc_user is None or rpc_password is None:
rpc_user = 'user'
import ecdsa, base64
bits = 128
nbytes = bits // 8 + (bits % 8 > 0)
pw_int = ecdsa.uti... | def get_rpc_credentials(config):
| rpc_user = config.get('rpcuser', None)
rpc_password = config.get('rpcpassword', None)
if rpc_user is None or rpc_password is None:
rpc_user = 'user'
import ecdsa, base64
bits = 128
nbytes = bits // 8 + (bits % 8 > 0)
pw_int = ecdsa.util.randrange(pow(2, bits))
... | as e:
print_error("[get_server]", e)
if not create_time or create_time < time.time() - 1.0:
return None
# Sleep a bit and try again; it might have just been started
time.sleep(1.0)
def get_rpc_credentials(config):
| 64 | 64 | 197 | 6 | 58 | apollomatheus/electrum | lib/daemon.py | Python | get_rpc_credentials | get_rpc_credentials | 99 | 116 | 99 | 99 | 75c6f34a31a1228e7b2e526a592921bc86165849 | bigcode/the-stack | train |
b9d9a6f34535a7a3ff50b47e | train | class | class ClientsViewSet(viewsets.ModelViewSet):
queryset = Client.objects.all()
serializer_class = ClientsSerializer
# Ordenação, Filtros e Buscas
filter_backends = [DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
ordering_fields = ['name']
# Busca não exata
search_fields = [... | class ClientsViewSet(viewsets.ModelViewSet):
| queryset = Client.objects.all()
serializer_class = ClientsSerializer
# Ordenação, Filtros e Buscas
filter_backends = [DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
ordering_fields = ['name']
# Busca não exata
search_fields = ['name', 'cpf']
# Busca Exata
filterse... | _framework import viewsets, filters
from .serializers import ClientsSerializer
from .models import Client
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
# Create your views here.
class Cl... | 63 | 64 | 120 | 10 | 53 | Gabriel-limadev/clientes-API | client/views.py | Python | ClientsViewSet | ClientsViewSet | 10 | 22 | 10 | 10 | 1372df55fb4df68c9cb15a3928317c919a7e3d18 | bigcode/the-stack | train |
fea7e4deb21aeab4454179ab | train | function | def window(
iterable: Union[List[K], str],
n: int,
) -> Iterable[Tuple[Union[K, str], ...]]:
"""
Return a sliding window of size ``n`` of the given iterable.
"""
for start_idx in range(len(iterable) - n + 1):
yield tuple(iterable[start_idx + idx] for idx in range(n))
| def window(
iterable: Union[List[K], str],
n: int,
) -> Iterable[Tuple[Union[K, str], ...]]:
| """
Return a sliding window of size ``n`` of the given iterable.
"""
for start_idx in range(len(iterable) - n + 1):
yield tuple(iterable[start_idx + idx] for idx in range(n))
|
for x in sequence:
min_ = min(min_, x)
max_ = max(max_, x)
return int(min_), int(max_)
def window(
iterable: Union[List[K], str],
n: int,
) -> Iterable[Tuple[Union[K, str], ...]]:
| 63 | 64 | 81 | 30 | 33 | sumnerevans/advent-of-code | 2021/14.py | Python | window | window | 59 | 67 | 59 | 62 | 13c756c5bd3c0e4c15b3f4b44fcb5d8115b23f43 | bigcode/the-stack | train |
940ed8587ca8617ebd1a83fe | train | class | class bcolors:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
| class bcolors:
| HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
| "inputs/14.txt"
TESTFILENAME = "inputs/14.test.txt"
for arg in sys.argv:
if arg == "--notest":
test = False
if arg == "--debug":
debug = True
if arg == "--stdin":
stdin = True
class bcolors:
| 64 | 64 | 92 | 4 | 59 | sumnerevans/advent-of-code | 2021/14.py | Python | bcolors | bcolors | 23 | 32 | 23 | 23 | 59770a9b96690c66b8efc7003f4d30915ecfae1a | bigcode/the-stack | train |
af9a6d1cf54efff28061d69f | train | function | def seqminmax(sequence: Iterable[int]) -> Tuple[int, int]:
"""
Returns a tuple containing the minimum and maximum element of the ``sequence``.
"""
min_, max_ = math.inf, -math.inf
for x in sequence:
min_ = min(min_, x)
max_ = max(max_, x)
return int(min_), int(max_)
| def seqminmax(sequence: Iterable[int]) -> Tuple[int, int]:
| """
Returns a tuple containing the minimum and maximum element of the ``sequence``.
"""
min_, max_ = math.inf, -math.inf
for x in sequence:
min_ = min(min_, x)
max_ = max(max_, x)
return int(min_), int(max_)
|
def cache(): # Python 3.9 compat
"""
LRU cache. Make sure to treat output as immutable so that you don't override the
cache.
"""
return ft.lru_cache(maxsize=None)
def seqminmax(sequence: Iterable[int]) -> Tuple[int, int]:
| 64 | 64 | 80 | 15 | 49 | sumnerevans/advent-of-code | 2021/14.py | Python | seqminmax | seqminmax | 48 | 56 | 48 | 48 | 428a3f9055709aaaf7d372211aaa373b1e5695f6 | bigcode/the-stack | train |
ed10ca7d677cf7f69ca6f223 | train | function | def part2(lines: List[str]) -> int:
template = lines[0]
insertion_rules = {a: b for a, b in map(lambda line: line.split(" -> "), lines[2:])}
@cache()
def count_between_keys(a, b, d) -> Counter:
"""
This really bit me in the ass because I forgot that when I return dictionaries,
I... | def part2(lines: List[str]) -> int:
| template = lines[0]
insertion_rules = {a: b for a, b in map(lambda line: line.split(" -> "), lines[2:])}
@cache()
def count_between_keys(a, b, d) -> Counter:
"""
This really bit me in the ass because I forgot that when I return dictionaries,
I have to actually deepcopy them befo... | print("Tries Part 1:", tries)
assert ans_part1 not in tries, "Same as an incorrect answer!"
# Regression Test
expected = 2549
if expected is not None:
assert ans_part1 == expected
# Part 2
########################################################################################
print("\nPart 2:")
def part2(l... | 77 | 78 | 262 | 11 | 67 | sumnerevans/advent-of-code | 2021/14.py | Python | part2 | part2 | 158 | 186 | 158 | 158 | bb6d441964c3923d50e8a183b3837b6e4a5d0783 | bigcode/the-stack | train |
8331f23bfa88071397b234e7 | train | function | def cache(): # Python 3.9 compat
"""
LRU cache. Make sure to treat output as immutable so that you don't override the
cache.
"""
return ft.lru_cache(maxsize=None)
| def cache(): # Python 3.9 compat
| """
LRU cache. Make sure to treat output as immutable so that you don't override the
cache.
"""
return ft.lru_cache(maxsize=None)
| FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
# Type variables
K = TypeVar("K")
# Utilities
def cache(): # Python 3.9 compat
| 64 | 64 | 48 | 12 | 51 | sumnerevans/advent-of-code | 2021/14.py | Python | cache | cache | 40 | 45 | 40 | 40 | 11416fb42f9233eb5832aba0468192a8f8a851a3 | bigcode/the-stack | train |
8bf4d24ed9714f1b2a1b2b46 | train | function | def part1(lines: List[str]) -> int:
"""
I'm going to leave this in a cleaned-up form of my original approach.
"""
template = lines[0]
insertion_rules = {a: b for a, b in map(lambda line: line.split(" -> "), lines[2:])}
for _ in range(10):
new_template = (
"".join(a + inserti... | def part1(lines: List[str]) -> int:
| """
I'm going to leave this in a cleaned-up form of my original approach.
"""
template = lines[0]
insertion_rules = {a: b for a, b in map(lambda line: line.split(" -> "), lines[2:])}
for _ in range(10):
new_template = (
"".join(a + insertion_rules[a + b] for a, b in window(t... | ILENAME) as f:
test_lines: List[str] = [l.strip() for l in f.readlines()]
except Exception:
test_lines = []
# Shared
########################################################################################
# Part 1
########################################################################################
... | 63 | 64 | 137 | 11 | 53 | sumnerevans/advent-of-code | 2021/14.py | Python | part1 | part1 | 96 | 111 | 96 | 96 | 9d812cf623cc0f1ed50ee761b27be1469a9e5d6d | bigcode/the-stack | train |
76512133ddc2759a67535271 | train | class | @fdao_pws_override
class PWSTestEntityData(TestCase):
def test_by_regid(self):
#Valid data, shouldn't throw exceptions
self._test_regid('somalt', '605764A811A847E690F107D763A4B32A')
def test_by_netid(self):
#Valid data, shouldn't throw exceptions
self._test_netid('somalt', '605... | @fdao_pws_override
class PWSTestEntityData(TestCase):
| def test_by_regid(self):
#Valid data, shouldn't throw exceptions
self._test_regid('somalt', '605764A811A847E690F107D763A4B32A')
def test_by_netid(self):
#Valid data, shouldn't throw exceptions
self._test_netid('somalt', '605764A811A847E690F107D763A4B32A')
def test_bad_netid... | from django.test import TestCase
from restclients.pws import PWS
from restclients.exceptions import InvalidRegID, InvalidNetID,\
DataFailureException
from restclients.test import fdao_pws_override
@fdao_pws_override
class PWSTestEntityData(TestCase):
| 61 | 174 | 580 | 16 | 44 | uw-it-cte/uw-restclients | restclients/test/pws/entity.py | Python | PWSTestEntityData | PWSTestEntityData | 8 | 63 | 8 | 10 | 7a0079d023133e62bb591e9b267c42a085cf139b | bigcode/the-stack | train |
29f46f45865d3c510e3b6ae6 | train | function | def learn_single(ppo, update_timestep, eps_decay, env, increase_batch, log_path, max_reward=-2.0):
memory = Memory()
timestep = 0
log_interval = 2 # print avg reward in the interval
jjj = 0
wrong = 0.0 # for logging
nu_remote = 10 #less is... | def learn_single(ppo, update_timestep, eps_decay, env, increase_batch, log_path, max_reward=-2.0):
| memory = Memory()
timestep = 0
log_interval = 2 # print avg reward in the interval
jjj = 0
wrong = 0.0 # for logging
nu_remote = 10 #less is better, more games are finished! for update_timestep=30k 100 is better than 10 here!
steps ... | total_ai_reward += i[2]
total_correct += i[3]
finished_random += i[4]
#print every nth game:
if jjj%print_game == 0:
state = env.resetRandomPlay_Env(print__=True)
done = 0
while not done:
action = policy.act(state, None... | 239 | 239 | 797 | 28 | 210 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | learn_single | learn_single | 341 | 400 | 341 | 341 | e73b612d664c951d2a8927785151ee093ec9c962 | bigcode/the-stack | train |
d6b50798c9587f7c850dc91a | train | function | def test_with_random(policy, env, jjj, max_corr, episodes=5000, print_game=5):
finished_ai_reward, finished_games, total_ai_reward, total_correct, finished_random = 0.0, 0.0, 0.0, 0.0, 0.0
nu_remote = 10
steps = int(episodes/nu_remote)
result = ray.get([playRandomSteps.remote(... | def test_with_random(policy, env, jjj, max_corr, episodes=5000, print_game=5):
| finished_ai_reward, finished_games, total_ai_reward, total_correct, finished_random = 0.0, 0.0, 0.0, 0.0, 0.0
nu_remote = 10
steps = int(episodes/nu_remote)
result = ray.get([playRandomSteps.remote(policy, env, steps, max_corr) for i in range(nu_remote)])
for i in result:
... | 100, -100]
if done and corr_moves == max_corr:
finished_ai_reward +=rewards[0]
finished_random +=rewards[1]
finished_games +=1
total_correct +=corr_moves
total_ai_reward +=rewards[0]
return finished_ai_reward, finished_games, total_ai_reward, to... | 104 | 104 | 348 | 24 | 79 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | test_with_random | test_with_random | 309 | 339 | 309 | 309 | 177c7f114a47082a9bec73a5ecb105ff477e6c8e | bigcode/the-stack | train |
2daf552f27a9d000572945d2 | train | class | class ActorCritic(nn.Module):
def __init__(self, state_dim, action_dim, number_of_cards, n_latent_var):
super(ActorCritic, self).__init__()
self.a_dim = action_dim
self.number_of_cards = number_of_cards
# actor critic
self.actor_critic = ActorModel(state_dim, action_dim, n... | class ActorCritic(nn.Module):
| def __init__(self, state_dim, action_dim, number_of_cards, n_latent_var):
super(ActorCritic, self).__init__()
self.a_dim = action_dim
self.number_of_cards = number_of_cards
# actor critic
self.actor_critic = ActorModel(state_dim, action_dim, number_of_cards, n_latent_var)
... | _of_cards*4]
actor_out = torch.cat( [ac, options], 1)
actor_out = self.a1(actor_out)
actor_out = actor_out.softmax(dim=-1)
# Get Critic Result:
critic = self.c1(ac)
critic = self.c1_prelu(critic)
critic = self.c2(critic)
return actor_out, critic
cl... | 91 | 91 | 304 | 7 | 83 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | ActorCritic | ActorCritic | 141 | 173 | 141 | 141 | 6b0e3ec639af60c6708cbc58b54364f18c61e847 | bigcode/the-stack | train |
da714ffd5d270b03be28e513 | train | function | @ray.remote
def playRandomSteps(policy, env, steps, max_corr):
# difference here is that it is played until the END!
finished_ai_reward = 0
finished_games = 0
total_ai_reward = 0
total_correct = 0
finished_random = 0
for i in range(steps):
state = env.resetRandom... | @ray.remote
def playRandomSteps(policy, env, steps, max_corr):
# difference here is that it is played until the END!
| finished_ai_reward = 0
finished_games = 0
total_ai_reward = 0
total_correct = 0
finished_random = 0
for i in range(steps):
state = env.resetRandomPlay_Env()
done = 0
tmp = 0
corr_moves = 0
while not done:
action = poli... | [jjj])
batches[jjj].clear_batch()
if done and (i+max_corr)>steps:
break
return result_memory
###
### in order to test the performance with random enemys:
###
@ray.remote
def playRandomSteps(policy, env, steps, max_corr):
# difference here is that it is played until the END!
| 75 | 75 | 251 | 30 | 45 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | playRandomSteps | playRandomSteps | 281 | 307 | 281 | 283 | 86bdf99b005b3a4684cfe36e5bacf7a5c3fa1097 | bigcode/the-stack | train |
60bf4342f74867270ff0086e | train | class | class ActorModel(nn.Module):
def __init__(self, state_dim, action_dim, number_of_cards, n_latent_var):
super(ActorModel, self).__init__()
self.a_dim = action_dim
self.number_of_cards = number_of_cards
self.ac = nn.Linear(state_dim, n_latent_var)
self.ac_prelu= nn.PReL... | class ActorModel(nn.Module):
| def __init__(self, state_dim, action_dim, number_of_cards, n_latent_var):
super(ActorModel, self).__init__()
self.a_dim = action_dim
self.number_of_cards = number_of_cards
self.ac = nn.Linear(state_dim, n_latent_var)
self.ac_prelu= nn.PReLU()
self.ac1 = n... | self.batches = []
def appendBatch(self, batch):
#only append batch if it has data!
if len(batch.actions)>0:
self.batches.append(deepcopy(batch))
def append_memo(self, input_memory):
self.batches.extend(input_memory.batches)
def shuffle(self):
return random.shu... | 158 | 158 | 527 | 6 | 151 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | ActorModel | ActorModel | 90 | 139 | 90 | 90 | e30fd34cedd592384e7a46b157c8b96aa4b6ad0d | bigcode/the-stack | train |
49671c0a3ff4ccf4b9bd3ce7 | train | class | class Batch(object):
def __init__(self):
self.actions = []
self.states = []
self.logprobs = []
self.rewards = []
self.is_terminals = []
def __unicode__(self):
return self.show()
def __str__(self):
return self.show()
def __repr__(self):
ret... | class Batch(object):
| def __init__(self):
self.actions = []
self.states = []
self.logprobs = []
self.rewards = []
self.is_terminals = []
def __unicode__(self):
return self.show()
def __str__(self):
return self.show()
def __repr__(self):
return self.show()
... | : pip install ray[rllib]
ray.init() # num_cpus=12
# use for PPO Training:
import torch # pip3 install torch
import torch.nn as nn
from torch.distributions import Categorical
import torch.onnx # required for export as onnx
import ... | 86 | 86 | 288 | 4 | 81 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | Batch | Batch | 22 | 58 | 22 | 22 | ef80d686c6c2249c9b32bdb5be4dbe2b345df90d | bigcode/the-stack | train |
311288100c11f91e7ad0d6b0 | train | function | @ray.remote
def playSteps(env, policy, steps, max_corr):
batches = [Batch(), Batch(), Batch(), Batch()]
result_memory = Memory()
done = 0
state = env.reset()
for i in range(steps):
player = env.my_game.active_player
action = policy.act(state, batches[player])# <- state is appende... | @ray.remote
def playSteps(env, policy, steps, max_corr):
| batches = [Batch(), Batch(), Batch(), Batch()]
result_memory = Memory()
done = 0
state = env.reset()
for i in range(steps):
player = env.my_game.active_player
action = policy.act(state, batches[player])# <- state is appended to memory in act function
state, rewards, done,... | ()
loss = self.calculate_total_loss(state_values, logprobs, old_logprobs, advantages, rewards, dist_entropy)
# take gradient step
self.optimizer.zero_grad()
loss.mean().backward()
self.optimizer.step()
# Copy new weights into old policy:
... | 90 | 90 | 300 | 16 | 74 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | playSteps | playSteps | 249 | 276 | 249 | 250 | 0e3470dd5bf7ac3d45b00b96fd9049210d81f5a1 | bigcode/the-stack | train |
4da410d4a105956a060795a1 | train | class | class PPO:
def __init__(self, state_dim, action_dim, number_of_cards, n_latent_var, lr, betas, gamma, K_epochs, eps_clip):
self.lr = lr
self.betas = betas
self.gamma = gamma
self.eps_clip = eps_clip
self.K_epochs = K_epochs
self.policy = ActorCritic(state_dim, action... | class PPO:
| def __init__(self, state_dim, action_dim, number_of_cards, n_latent_var, lr, betas, gamma, K_epochs, eps_clip):
self.lr = lr
self.betas = betas
self.gamma = gamma
self.eps_clip = eps_clip
self.K_epochs = K_epochs
self.policy = ActorCritic(state_dim, action_dim, numbe... | self.actor_critic = ActorModel(state_dim, action_dim, number_of_cards, n_latent_var)
def act(self, state, memory):
if type(state) is np.ndarray:
state = torch.from_numpy(state).float()
action_probs, _ = self.actor_critic(state)
# here make a filter for only possible acti... | 243 | 243 | 813 | 3 | 239 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | PPO | PPO | 175 | 247 | 175 | 175 | b7ca135c41b906ef3f22d52d82c9f78a0cac792e | bigcode/the-stack | train |
27da7f13448106c6dafdb4d6 | train | class | class Memory:
def __init__(self):
self.batches = []
def appendBatch(self, batch):
#only append batch if it has data!
if len(batch.actions)>0:
self.batches.append(deepcopy(batch))
def append_memo(self, input_memory):
self.batches.extend(input_memory.batches)
... | class Memory:
| def __init__(self):
self.batches = []
def appendBatch(self, batch):
#only append batch if it has data!
if len(batch.actions)>0:
self.batches.append(deepcopy(batch))
def append_memo(self, input_memory):
self.batches.extend(input_memory.batches)
def shuffle(s... | _batch_tensor(self):
self.states = torch.Tensor(self.states)
self.actions= torch.Tensor(self.actions)
self.logprobs = torch.Tensor(self.logprobs)
#self.states = torch.from_numpy(self.states).float()
#print(torch.from_numpy(self.states[0]).float())
class Memory:
| 64 | 64 | 163 | 3 | 61 | CesMak/gym_schafkopf | 01_Tutorials/04_Policy_PPO/policy_ppo.py | Python | Memory | Memory | 62 | 88 | 62 | 62 | fec009a72568b1200647b8f027d4fd6b72368033 | bigcode/the-stack | train |
9f7c12faff6c29a83f8117de | train | function | def update_added_from_copyright_info(delta):
"""
Increase an 'added' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a copyright change.
"""
if delta.new_file.has_copyrights():
delta.update(10, 'copyright info added')
r... | def update_added_from_copyright_info(delta):
| """
Increase an 'added' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a copyright change.
"""
if delta.new_file.has_copyrights():
delta.update(10, 'copyright info added')
return
| 'factors' attribute if there has
been a copyright change and depending on the nature of that change.
"""
if delta.is_added():
update_added_from_copyright_info(delta)
if delta.is_modified():
update_modified_from_copyright_info(delta)
def update_added_from_copyright_info(delta):
| 64 | 64 | 74 | 9 | 55 | Hritik14/deltacode | src/deltacode/utils.py | Python | update_added_from_copyright_info | update_added_from_copyright_info | 131 | 139 | 131 | 131 | 6b25fabf7e29ac451d6b42a9544a2137046aff0a | bigcode/the-stack | train |
2ed8a715af7a25e0590bba18 | train | function | def update_modified_from_license_info(delta, unique_categories):
"""
Increase a 'modified' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a license change.
"""
if not delta.new_file.has_licenses() and delta.old_file.has_licenses():
... | def update_modified_from_license_info(delta, unique_categories):
| """
Increase a 'modified' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a license change.
"""
if not delta.new_file.has_licenses() and delta.old_file.has_licenses():
delta.update(15, 'license info removed')
return
... |
been a license change.
"""
new_licenses = delta.new_file.licenses or []
new_categories = set(license.category for license in new_licenses)
if delta.new_file.has_licenses():
delta.update(20, 'license info added')
for category in new_categories:
# no license ==> 'Copylef... | 140 | 140 | 469 | 11 | 128 | Hritik14/deltacode | src/deltacode/utils.py | Python | update_modified_from_license_info | update_modified_from_license_info | 72 | 115 | 72 | 72 | e35abca0d650f90084a27146555982dd18055764 | bigcode/the-stack | train |
9930d48710a4ef6e410a3c99 | train | function | def deltas(deltacode, all_delta_types=False):
"""
Return a generator of Delta dictionaries for JSON serialized ouput. Omit
all unmodified Delta objects unless the user selects the '-a'/'--all'
option.
"""
for delta in deltacode.deltas:
if all_delta_types is True:
yield delta... | def deltas(deltacode, all_delta_types=False):
| """
Return a generator of Delta dictionaries for JSON serialized ouput. Omit
all unmodified Delta objects unless the user selects the '-a'/'--all'
option.
"""
for delta in deltacode.deltas:
if all_delta_types is True:
yield delta.to_dict()
elif not delta.is_unmodifie... | 5, 'copyright change')
def collect_errors(deltacode):
errors = []
errors.extend(deltacode.new.errors)
errors.extend(deltacode.old.errors)
errors.extend(deltacode.errors)
return errors
def deltas(deltacode, all_delta_types=False):
| 64 | 64 | 93 | 13 | 50 | Hritik14/deltacode | src/deltacode/utils.py | Python | deltas | deltas | 174 | 184 | 174 | 174 | 53979546e5744acfb1ab262a270aabb8a1628d08 | bigcode/the-stack | train |
81ea5d5d05f1f428a5fb1608 | train | function | def update_modified_from_copyright_info(delta):
"""
Increase a 'modified' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a copyright change.
"""
new_copyrights = delta.new_file.copyrights or []
old_copyrights = delta.old_file.copy... | def update_modified_from_copyright_info(delta):
| """
Increase a 'modified' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a copyright change.
"""
new_copyrights = delta.new_file.copyrights or []
old_copyrights = delta.old_file.copyrights or []
if delta.new_file.has_copyrigh... | 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a copyright change.
"""
if delta.new_file.has_copyrights():
delta.update(10, 'copyright info added')
return
def update_modified_from_copyright_info(delta):
| 64 | 64 | 208 | 9 | 54 | Hritik14/deltacode | src/deltacode/utils.py | Python | update_modified_from_copyright_info | update_modified_from_copyright_info | 142 | 162 | 142 | 142 | 58fca327ce859a7b3253c9a9dee180aec5429c66 | bigcode/the-stack | train |
e4ef271af0504fb4f92ce91a | train | function | def update_from_copyright_info(delta):
"""
Increase an 'added' or 'modified' Delta object's 'score' attribute and add
one or more appropriate categories to its 'factors' attribute if there has
been a copyright change and depending on the nature of that change.
"""
if delta.is_added():
up... | def update_from_copyright_info(delta):
| """
Increase an 'added' or 'modified' Delta object's 'score' attribute and add
one or more appropriate categories to its 'factors' attribute if there has
been a copyright change and depending on the nature of that change.
"""
if delta.is_added():
update_added_from_copyright_info(delta)
... | .lower() + ' added')
# 'Permissive' or 'Public Domain' ==> 'Permissive' or 'Public Domain' if not in old_categories
elif category not in unique_categories:
delta.update(0, category.lower() + ' added')
def update_from_copyright_info(delta):
| 64 | 64 | 92 | 8 | 56 | Hritik14/deltacode | src/deltacode/utils.py | Python | update_from_copyright_info | update_from_copyright_info | 118 | 128 | 118 | 118 | dbe456ca2ee3c707cfc9b1b24ea9093f3ba66da4 | bigcode/the-stack | train |
cff56a2c0d2b57e170c9323c | train | function | def calculate_percent(value, total):
"""
Return the rounded value percentage of total.
"""
ratio = (value / total) * 100
return round(ratio, 2)
| def calculate_percent(value, total):
| """
Return the rounded value percentage of total.
"""
ratio = (value / total) * 100
return round(ratio, 2)
| Delta objects unless the user selects the '-a'/'--all'
option.
"""
for delta in deltacode.deltas:
if all_delta_types is True:
yield delta.to_dict()
elif not delta.is_unmodified():
yield delta.to_dict()
def calculate_percent(value, total):
| 64 | 64 | 41 | 7 | 57 | Hritik14/deltacode | src/deltacode/utils.py | Python | calculate_percent | calculate_percent | 186 | 191 | 186 | 186 | d7f678924d80cc164ce452dcf6c686ec637eb68f | bigcode/the-stack | train |
a5b5f835973b477dda2325db | train | function | def align_trees(a_files, b_files):
"""
Given two sequences of File objects 'a' and 'b', return a tuple of
two integers that represent the number path segments to remove
respectively from a File path in 'a' or a File path in 'b' to obtain the
equal paths for two files that are the same in 'a' and 'b'... | def align_trees(a_files, b_files):
| """
Given two sequences of File objects 'a' and 'b', return a tuple of
two integers that represent the number path segments to remove
respectively from a File path in 'a' or a File path in 'b' to obtain the
equal paths for two files that are the same in 'a' and 'b'.
"""
# we need to find one... | """
for delta in deltacode.deltas:
if all_delta_types is True:
yield delta.to_dict()
elif not delta.is_unmodified():
yield delta.to_dict()
def calculate_percent(value, total):
"""
Return the rounded value percentage of total.
"""
ratio = (value / total) *... | 110 | 110 | 367 | 10 | 99 | Hritik14/deltacode | src/deltacode/utils.py | Python | align_trees | align_trees | 199 | 235 | 199 | 199 | 5b8fabff404e12e17e88c4dc041c1a139d81cbca | bigcode/the-stack | train |
7c79ebb64b3e7c48e4f93bc6 | train | function | def update_from_license_info(delta, unique_categories):
"""
Increase an 'added' or 'modified' Delta object's 'score' attribute and add
one or more appropriate categories to its 'factors' attribute if there has
been a license change and depending on the nature of that change.
"""
if delta.is_adde... | def update_from_license_info(delta, unique_categories):
| """
Increase an 'added' or 'modified' Delta object's 'score' attribute and add
one or more appropriate categories to its 'factors' attribute if there has
been a license change and depending on the nature of that change.
"""
if delta.is_added():
update_added_from_license_info(delta, uniqu... | B/deltacode/ for support and download.
#
from __future__ import absolute_import, division
from bitarray import bitarray
from collections import defaultdict
from bitarray import bitdiff
import binascii
import os
from commoncode import paths
def update_from_license_info(delta, unique_categories):
| 64 | 64 | 98 | 10 | 53 | Hritik14/deltacode | src/deltacode/utils.py | Python | update_from_license_info | update_from_license_info | 37 | 47 | 37 | 37 | fdf98165a6bf2d36789b9cb0a813ebe28bc7e61e | bigcode/the-stack | train |
e3b59f43d315bf19584c1fe4 | train | function | def update_added_from_license_info(delta, unique_categories):
"""
Increase an 'added' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a license change.
"""
new_licenses = delta.new_file.licenses or []
new_categories = set(license.c... | def update_added_from_license_info(delta, unique_categories):
| """
Increase an 'added' Delta object's 'score' attribute and add
one or more categories to its 'factors' attribute if there has
been a license change.
"""
new_licenses = delta.new_file.licenses or []
new_categories = set(license.category for license in new_licenses)
if delta.new_file.ha... | there has
been a license change and depending on the nature of that change.
"""
if delta.is_added():
update_added_from_license_info(delta, unique_categories)
if delta.is_modified():
update_modified_from_license_info(delta, unique_categories)
def update_added_from_license_info(delta, un... | 64 | 64 | 172 | 11 | 53 | Hritik14/deltacode | src/deltacode/utils.py | Python | update_added_from_license_info | update_added_from_license_info | 50 | 69 | 50 | 50 | 409c6e128173ac5bca1d4c345b550cda61d3abf9 | bigcode/the-stack | train |
91d9f8d7b4c010e3459cef30 | train | function | def fix_trees(a_files, b_files):
"""
Given two sequences of File objects 'a' and 'b', use the tuple of two
integers returned by align_trees() to remove the number of path segments
required to create equal paths for two files that are the same in 'a' and
'b'.
"""
a_offset, b_offset = align_tr... | def fix_trees(a_files, b_files):
| """
Given two sequences of File objects 'a' and 'b', use the tuple of two
integers returned by align_trees() to remove the number of path segments
required to create equal paths for two files that are the same in 'a' and
'b'.
"""
a_offset, b_offset = align_trees(a_files, b_files)
for a_f... | common_suffix, common_segments = paths.common_path_suffix(a_unique.path, b_unique.path)
a_segments = len(paths.split(a_unique.path))
b_segments = len(paths.split(b_unique.path))
return a_segments - common_segments, b_segments - common_segments
def fix_trees(a_files, b_files):
| 64 | 64 | 160 | 10 | 53 | Hritik14/deltacode | src/deltacode/utils.py | Python | fix_trees | fix_trees | 238 | 252 | 238 | 238 | e055a6495d3380ebf22bb4443551002b6c4c436c | bigcode/the-stack | train |
d76fd6bdc4f32e38da5179e7 | train | function | def bitarray_from_bytes(b):
"""
Return bitarray from a byte string, interpreted as machine values.
"""
a = bitarray()
a.frombytes(b)
return a | def bitarray_from_bytes(b):
| """
Return bitarray from a byte string, interpreted as machine values.
"""
a = bitarray()
a.frombytes(b)
return a | result = int(distance)
return result
def bitarray_from_hex(fingerprint_hex):
"""
Return bitarray from a hex string.
"""
bytes = binascii.unhexlify(fingerprint_hex)
result = bitarray_from_bytes(bytes)
return result
def bitarray_from_bytes(b):
| 64 | 64 | 40 | 7 | 56 | Hritik14/deltacode | src/deltacode/utils.py | Python | bitarray_from_bytes | bitarray_from_bytes | 308 | 315 | 308 | 308 | 469243955829455e76266cae1e85db64569cc23f | bigcode/the-stack | train |
498ad89bd6e75f244b591339 | train | class | class AlignmentException(Exception):
"""
Named exception for alignment errors.
"""
pass
| class AlignmentException(Exception):
| """
Named exception for alignment errors.
"""
pass
| delta.to_dict()
elif not delta.is_unmodified():
yield delta.to_dict()
def calculate_percent(value, total):
"""
Return the rounded value percentage of total.
"""
ratio = (value / total) * 100
return round(ratio, 2)
class AlignmentException(Exception):
| 64 | 64 | 19 | 5 | 59 | Hritik14/deltacode | src/deltacode/utils.py | Python | AlignmentException | AlignmentException | 193 | 197 | 193 | 193 | 14d31f429793cf66221df89b7ffb14278e2b3181 | bigcode/the-stack | train |
18193abdd01de083efb9448c | train | function | def bitarray_from_hex(fingerprint_hex):
"""
Return bitarray from a hex string.
"""
bytes = binascii.unhexlify(fingerprint_hex)
result = bitarray_from_bytes(bytes)
return result
| def bitarray_from_hex(fingerprint_hex):
| """
Return bitarray from a hex string.
"""
bytes = binascii.unhexlify(fingerprint_hex)
result = bitarray_from_bytes(bytes)
return result
| Hamming distance is the difference in the bits of two binary string.
Files with fingerprints whose hamming distance are less tends to be more similar.
"""
distance = bitdiff(fingerprint1, fingerprint2)
result = int(distance)
return result
def bitarray_from_hex(fingerprint_hex):
| 64 | 64 | 47 | 9 | 54 | Hritik14/deltacode | src/deltacode/utils.py | Python | bitarray_from_hex | bitarray_from_hex | 299 | 306 | 299 | 299 | 212a5ae75dd296e283b2493aadc9f4b236277726 | bigcode/the-stack | train |
6f0f372f25703bc960f59d90 | train | function | def collect_errors(deltacode):
errors = []
errors.extend(deltacode.new.errors)
errors.extend(deltacode.old.errors)
errors.extend(deltacode.errors)
return errors
| def collect_errors(deltacode):
| errors = []
errors.extend(deltacode.new.errors)
errors.extend(deltacode.old.errors)
errors.extend(deltacode.errors)
return errors
| (holder for copyright in new_copyrights for holder in copyright.holders)
old_holders = set(holder for copyright in old_copyrights for holder in copyright.holders)
if new_holders != old_holders:
delta.update(5, 'copyright change')
def collect_errors(deltacode):
| 64 | 64 | 45 | 8 | 56 | Hritik14/deltacode | src/deltacode/utils.py | Python | collect_errors | collect_errors | 165 | 171 | 165 | 165 | 909dd8f4836b059a5a0b348bfb6802bb8215cd56 | bigcode/the-stack | train |
b8ecf903b410b619d0649041 | train | function | def check_moved(added_sha1, added_deltas, removed_sha1, removed_deltas):
"""
Return True if there is only one pair of matching 'added' and 'removed'
Delta objects and their respective File objects have the same 'name' attribute.
"""
if added_sha1 != removed_sha1:
return False
if len(adde... | def check_moved(added_sha1, added_deltas, removed_sha1, removed_deltas):
| """
Return True if there is only one pair of matching 'added' and 'removed'
Delta objects and their respective File objects have the same 'name' attribute.
"""
if added_sha1 != removed_sha1:
return False
if len(added_deltas) != 1 or len(removed_deltas) != 1:
return False
if a... | _file.path)[a_offset:])
for b_file in b_files:
b_file.original_path = b_file.path
b_file.path = '/'.join(paths.split(b_file.path)[b_offset:])
def check_moved(added_sha1, added_deltas, removed_sha1, removed_deltas):
| 63 | 64 | 125 | 21 | 43 | Hritik14/deltacode | src/deltacode/utils.py | Python | check_moved | check_moved | 255 | 265 | 255 | 255 | 21263218611372c1e4c70150b262137245f765b3 | bigcode/the-stack | train |
5ac7a58379f366c33eeb4dca | train | function | def get_notice():
"""
Retrieve the notice text from the NOTICE file for display in the JSON output.
"""
notice_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'NOTICE')
notice_text = open(notice_path).read()
delimiter = '\n\n\n'
[notice_text, extra_notice_text] = notice_text... | def get_notice():
| """
Retrieve the notice text from the NOTICE file for display in the JSON output.
"""
notice_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'NOTICE')
notice_text = open(notice_path).read()
delimiter = '\n\n\n'
[notice_text, extra_notice_text] = notice_text.split(delimiter, ... | removed_sha1:
return False
if len(added_deltas) != 1 or len(removed_deltas) != 1:
return False
if added_deltas[0].new_file.name == removed_deltas[0].old_file.name:
return True
def get_notice():
| 64 | 64 | 145 | 4 | 59 | Hritik14/deltacode | src/deltacode/utils.py | Python | get_notice | get_notice | 268 | 285 | 268 | 268 | c44275f87ea46c84f0f3fe2d3bdec6a6a0844acb | bigcode/the-stack | train |
334850dd81c1b8545532ebc8 | train | function | def hamming_distance(fingerprint1, fingerprint2):
"""
Return hamming distance between two given fingerprints.
Hamming distance is the difference in the bits of two binary string.
Files with fingerprints whose hamming distance are less tends to be more similar.
"""
distance = bitdiff(fingerprint1... | def hamming_distance(fingerprint1, fingerprint2):
| """
Return hamming distance between two given fingerprints.
Hamming distance is the difference in the bits of two binary string.
Files with fingerprints whose hamming distance are less tends to be more similar.
"""
distance = bitdiff(fingerprint1, fingerprint2)
result = int(distance)
re... |
delimiter = '\n\n '
[notice_text, acknowledgment_text] = notice_text.split(delimiter, 1)
acknowledgment_text = delimiter + acknowledgment_text
notice = acknowledgment_text.strip().replace(' ', '')
return notice
def hamming_distance(fingerprint1, fingerprint2):
| 64 | 64 | 78 | 11 | 52 | Hritik14/deltacode | src/deltacode/utils.py | Python | hamming_distance | hamming_distance | 288 | 297 | 288 | 288 | 3e8503ba33752f653d0bc8eda219d6ba3e37461e | bigcode/the-stack | train |
963933806e32be9fee393da2 | train | function | def indices_of_wrong_classifications(test_dataset, classifier):
x_test, y_test = preprocess(test_dataset)
predictions = classifier.predict(x_test)
wrong_predictions = []
for i in range(len(predictions)):
if predictions[i] != y_test[i]:
wrong_predictions.append(i)
result = metri... | def indices_of_wrong_classifications(test_dataset, classifier):
| x_test, y_test = preprocess(test_dataset)
predictions = classifier.predict(x_test)
wrong_predictions = []
for i in range(len(predictions)):
if predictions[i] != y_test[i]:
wrong_predictions.append(i)
result = metric.compute(predictions=predictions, references=y_test)
print(... | results: {eval_k_fold(results)}")
report_results("baseline", eval_k_fold(results), datasets)
def train_baseline(train_dataset):
x_train, y_train = preprocess(train_dataset)
classifier.fit(x_train, y_train)
return classifier
def indices_of_wrong_classifications(test_dataset, classifier):
| 64 | 64 | 114 | 11 | 52 | DFKI-NLP/covid19-law-matching | training/baseline_law_matching.py | Python | indices_of_wrong_classifications | indices_of_wrong_classifications | 70 | 85 | 70 | 70 | 6f1a93cf5560a3a70f773c3d0aea3d67751ee690 | bigcode/the-stack | train |
97aef45cadefb4e1954c6642 | train | function | def train_baseline(train_dataset):
x_train, y_train = preprocess(train_dataset)
classifier.fit(x_train, y_train)
return classifier
| def train_baseline(train_dataset):
| x_train, y_train = preprocess(train_dataset)
classifier.fit(x_train, y_train)
return classifier
| ["precision"] = precision_score(y_test, predictions)
result["recall"] = recall_score(y_test, predictions)
results.append(result)
print(f"Overall results: {eval_k_fold(results)}")
report_results("baseline", eval_k_fold(results), datasets)
def train_baseline(train_dataset):
| 64 | 64 | 31 | 7 | 57 | DFKI-NLP/covid19-law-matching | training/baseline_law_matching.py | Python | train_baseline | train_baseline | 63 | 67 | 63 | 63 | 58807f64385cf745edc8bb793b4e32852ef1e9ca | bigcode/the-stack | train |
68e76ae153e30e0714dee272 | train | function | def preprocess(X):
texts = []
x_set = []
y_set = []
for claim, subsection, label in X:
texts.append(claim)
texts.append(subsection)
y_set.append(int(label))
vectors = vectorizer.fit_transform(texts)
for i in range(0, vectors.shape[0], 2):
x_set.append(cosine_simil... | def preprocess(X):
| texts = []
x_set = []
y_set = []
for claim, subsection, label in X:
texts.append(claim)
texts.append(subsection)
y_set.append(int(label))
vectors = vectorizer.fit_transform(texts)
for i in range(0, vectors.shape[0], 2):
x_set.append(cosine_similarity(vectors[i], v... | for token in doc
if not token.is_stop and not (token.text in string.punctuation)
]
classifier = LogisticRegression()
vectorizer = TfidfVectorizer(tokenizer=_tokenizer, preprocessor=None)
metric = load_metric("glue", "mrpc")
def preprocess(X):
| 64 | 64 | 101 | 4 | 60 | DFKI-NLP/covid19-law-matching | training/baseline_law_matching.py | Python | preprocess | preprocess | 31 | 42 | 31 | 31 | 10cadf56e5726958dbbe806ad77a0c19980e60bf | bigcode/the-stack | train |
616591c8394adfdc5e8a442a | train | function | def calculate_baseline_law_matching(from_file: Optional[str]):
datasets = LawMatchingDatasets.load_from_csv(from_file)
results = []
for train_set, test_set in datasets.folds:
x_train, y_train = preprocess(train_set)
x_test, y_test = preprocess(test_set)
classifier.fit(x_train, y_tra... | def calculate_baseline_law_matching(from_file: Optional[str]):
| datasets = LawMatchingDatasets.load_from_csv(from_file)
results = []
for train_set, test_set in datasets.folds:
x_train, y_train = preprocess(train_set)
x_test, y_test = preprocess(test_set)
classifier.fit(x_train, y_train)
predictions = classifier.predict(x_test)
re... | vectorizer.fit_transform(texts)
for i in range(0, vectors.shape[0], 2):
x_set.append(cosine_similarity(vectors[i], vectors[i + 1])[0])
return x_set, y_set
def calculate_baseline_law_matching(from_file: Optional[str]):
| 64 | 64 | 155 | 13 | 50 | DFKI-NLP/covid19-law-matching | training/baseline_law_matching.py | Python | calculate_baseline_law_matching | calculate_baseline_law_matching | 45 | 60 | 45 | 45 | 46b5a353a32d2f0fea4d4da4cafc50af27f97166 | bigcode/the-stack | train |
c7ac60968ed4233efefb49e3 | train | function | def _tokenizer(text):
doc = nlp(text)
return [
token.text
for token in doc
if not token.is_stop and not (token.text in string.punctuation)
]
| def _tokenizer(text):
| doc = nlp(text)
return [
token.text
for token in doc
if not token.is_stop and not (token.text in string.punctuation)
]
| TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import precision_score, recall_score
from preprocessing.datasets_ import LawMatchingDatasets
from utils import report_results, eval_k_fold
nlp = spacy.load("de_core_news_sm")
def _tokenizer(text):
| 64 | 64 | 44 | 6 | 58 | DFKI-NLP/covid19-law-matching | training/baseline_law_matching.py | Python | _tokenizer | _tokenizer | 17 | 23 | 17 | 17 | 3080e20c74924be84f6cd7480a3e52761a086d8e | bigcode/the-stack | train |
3c5af2b6b3160da7d13cfba8 | train | class | class CacheRegistry(object):
"""
Provide a registry for TaskCache instances related to vim buffers.
"""
def __init__(self):
# Store caches indexed by buffer number
self.caches = {}
# Remember current cache
self.current_buffer = None
def __call__(self, buffer_number... | class CacheRegistry(object):
| """
Provide a registry for TaskCache instances related to vim buffers.
"""
def __init__(self):
# Store caches indexed by buffer number
self.caches = {}
# Remember current cache
self.current_buffer = None
def __call__(self, buffer_number = None):
"""
... | __iter__(self):
for line in self.data:
yield line
def __len__(self):
return len(self.data)
def append(self, data, position=None):
if position is None:
self.data.append(data)
else:
self.data.insert(position, data)
class CacheRegistry(object):... | 67 | 67 | 226 | 5 | 62 | samgriesemer/taskwiki | taskwiki/cache.py | Python | CacheRegistry | CacheRegistry | 58 | 99 | 58 | 58 | ab4388acf29b513cbe4467e43b8e1af8ae47d379 | bigcode/the-stack | train |
2b7219468af999e8fa194ccb | train | class | class BufferProxy(object):
def __init__(self, number):
self.data = []
self.buffer_number = number
def obtain(self):
self.data = util.get_buffer(self.buffer_number)[:]
def push(self):
with util.current_line_preserved():
buffer = util.get_buffer(self.buffer_numbe... | class BufferProxy(object):
| def __init__(self, number):
self.data = []
self.buffer_number = number
def obtain(self):
self.data = util.get_buffer(self.buffer_number)[:]
def push(self):
with util.current_line_preserved():
buffer = util.get_buffer(self.buffer_number)
# Only set th... | import vim # pylint: disable=F0401
import re
import six
from taskwiki import preset
from taskwiki import viewport
from taskwiki import regexp
from taskwiki import store
from taskwiki import short
from taskwiki import util
from taskwiki import errors
class BufferProxy(object):
| 65 | 72 | 241 | 5 | 59 | samgriesemer/taskwiki | taskwiki/cache.py | Python | BufferProxy | BufferProxy | 14 | 55 | 14 | 15 | 9551ebe43e11a90bffe5a27bff0021375c2e3f7e | bigcode/the-stack | train |
6371e2d4270104960d0ee5ef | train | class | class TaskCache(object):
"""
A cache that holds all the tasks in the given buffer and prevents
multiple redundant taskwarrior calls.
"""
def __init__(self, buffer_number):
# Determine defaults
default_rc = util.get_var('taskwiki_taskrc_location') or '~/.taskrc'
default_data ... | class TaskCache(object):
| """
A cache that holds all the tasks in the given buffer and prevents
multiple redundant taskwarrior calls.
"""
def __init__(self, buffer_number):
# Determine defaults
default_rc = util.get_var('taskwiki_taskrc_location') or '~/.taskrc'
default_data = util.get_var('taskwiki_... | =None):
if position is None:
self.data.append(data)
else:
self.data.insert(position, data)
class CacheRegistry(object):
"""
Provide a registry for TaskCache instances related to vim buffers.
"""
def __init__(self):
# Store caches indexed by buffer numbe... | 256 | 256 | 1,547 | 5 | 251 | samgriesemer/taskwiki | taskwiki/cache.py | Python | TaskCache | TaskCache | 102 | 316 | 102 | 102 | b0c072b09717d1aaaa11d9fda0baf49662fd6ce7 | bigcode/the-stack | train |
210795358f69699d078a7a6b | train | function | def test_gtractInvertBSplineTransform_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
inputReferenceVolume=dict(argstr='--inputReferenceVolume %s',
),
inputTransform=dict... | def test_gtractInvertBSplineTransform_inputs():
| input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
inputReferenceVolume=dict(argstr='--inputReferenceVolume %s',
),
inputTransform=dict(argstr='--inputTransform %s',
),
landma... | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..gtract import gtractInvertBSplineTransform
def test_gtractInvertBSplineTransform_inputs():
| 46 | 64 | 205 | 10 | 35 | sebastientourbier/nipype | nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py | Python | test_gtractInvertBSplineTransform_inputs | test_gtractInvertBSplineTransform_inputs | 6 | 34 | 6 | 6 | 86416cd1091d76713a6dfdb302283ae94ae93ff6 | bigcode/the-stack | train |
e02368155484f6127fe2a7d6 | train | function | def test_gtractInvertBSplineTransform_outputs():
output_map = dict(outputTransform=dict(),
)
outputs = gtractInvertBSplineTransform.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metake... | def test_gtractInvertBSplineTransform_outputs():
| output_map = dict(outputTransform=dict(),
)
outputs = gtractInvertBSplineTransform.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| ,
),
)
inputs = gtractInvertBSplineTransform.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_gtractInvertBSplineTransform_outputs():
| 64 | 64 | 70 | 10 | 53 | sebastientourbier/nipype | nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py | Python | test_gtractInvertBSplineTransform_outputs | test_gtractInvertBSplineTransform_outputs | 37 | 44 | 37 | 37 | 93ceb8c3881ac8976f202bbadd5df4ec77508b44 | bigcode/the-stack | train |
34b00c564e64696e24319fbd | train | class | class Institute(models.Model):
"""
Institute model
"""
field_choice = AcademicField.objects.all()
code = models.CharField(_('Code composante'), max_length=3)
is_on_duty = models.BooleanField(_('En service'), default=True)
label = models.CharField(_('Libellé composante'), max_length=85)
... | class Institute(models.Model):
| """
Institute model
"""
field_choice = AcademicField.objects.all()
code = models.CharField(_('Code composante'), max_length=3)
is_on_duty = models.BooleanField(_('En service'), default=True)
label = models.CharField(_('Libellé composante'), max_length=85)
field = models.ForeignKey(Acade... | from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.core.exceptions import ValidationError
from mecc.apps.adm.models import MeccUser
class AcademicField(models.Model):
"""
Academic field model
"""
name = models.CharFi... | 91 | 123 | 413 | 5 | 85 | unistra/eva | mecc/apps/institute/models.py | Python | Institute | Institute | 18 | 64 | 18 | 18 | e80620fa1271c1ace03d31b68e5c20e5a45f0586 | bigcode/the-stack | train |
aba53dca3d6802e71a3b8408 | train | class | class AcademicField(models.Model):
"""
Academic field model
"""
name = models.CharField(_('Domaine'), max_length=70)
def __str__(self):
return self.name
| class AcademicField(models.Model):
| """
Academic field model
"""
name = models.CharField(_('Domaine'), max_length=70)
def __str__(self):
return self.name
| from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.core.exceptions import ValidationError
from mecc.apps.adm.models import MeccUser
class AcademicField(models.Model):
| 50 | 64 | 42 | 6 | 43 | unistra/eva | mecc/apps/institute/models.py | Python | AcademicField | AcademicField | 8 | 15 | 8 | 8 | 55f70f5e60193802221c6d4652b5d575b25c9cb5 | bigcode/the-stack | train |
a8b441456050066561f98dd1 | train | class | class TestShowMPLSLSPNameExtensive(unittest.TestCase):
"""
Unit test for:
* show mpls lsp name {name} extensive
"""
device = Device(name='aDevice')
maxDiff = None
empty_output = {'execute.return_value': ''}
golden_output_1 = {'execute.return_value': '''
Ingress LSP: 0 sessions
... | class TestShowMPLSLSPNameExtensive(unittest.TestCase):
| """
Unit test for:
* show mpls lsp name {name} extensive
"""
device = Device(name='aDevice')
maxDiff = None
empty_output = {'execute.return_value': ''}
golden_output_1 = {'execute.return_value': '''
Ingress LSP: 0 sessions
Total 0 displayed, Up 0, Down 0
Egress LSP: 0 ... | .194.66'
}, {
'address': '10.49.194.12'
}, {
'address': '255.255.255.255'
}, {
'address': '10.4.1.1'
}, {
'addre... | 256 | 256 | 1,673 | 14 | 242 | nujo/genieparser | src/genie/libs/parser/junos/tests/test_show_mpls.py | Python | TestShowMPLSLSPNameExtensive | TestShowMPLSLSPNameExtensive | 187 | 357 | 187 | 187 | 988e1becd414d2aaab49bbc62f341f8a8b724ceb | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.