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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7007624f10b9f127f0e11fb | train | class | class SparkScriptStepTestCase(MockBoto3TestCase):
# a lot of this is already tested in test_runner.py
def setUp(self):
super(SparkScriptStepTestCase, self).setUp()
self.fake_script = self.makefile('fake_script.py')
# _spark_submit_args() is tested elsewhere
self.start(patch(
... | class SparkScriptStepTestCase(MockBoto3TestCase):
# a lot of this is already tested in test_runner.py
| def setUp(self):
super(SparkScriptStepTestCase, self).setUp()
self.fake_script = self.makefile('fake_script.py')
# _spark_submit_args() is tested elsewhere
self.start(patch(
'mrjob.bin.MRJobBinRunner._spark_submit_args',
return_value=['<spark submit args>'])... | .start(patch(
'mrjob.bin.MRJobBinRunner._spark_submit_args',
return_value=['<spark submit args>']))
def test_jar_gets_uploaded(self):
job = MRSparkJar(['-r', 'emr', '--jar', self.fake_jar,
'--jar-main-class', 'fake.Main'])
job.sandbox()
wit... | 231 | 231 | 771 | 27 | 204 | Affirm/mrjob | tests/test_emr.py | Python | SparkScriptStepTestCase | SparkScriptStepTestCase | 2,755 | 2,854 | 2,755 | 2,757 | 626b7903569a0787fa83bc17a4b376d3d0f5cb50 | bigcode/the-stack | train |
16472e104d7c3f07f366869d | train | class | class ProgressHtmlFromTunnelTestCase(MockBoto3TestCase):
MOCK_TUNNEL_URL = 'http://foohost:12345/cluster'
def setUp(self):
super(ProgressHtmlFromTunnelTestCase, self).setUp()
self.urlopen = self.start(patch('mrjob.emr.urlopen'))
self.log = self.start(patch('mrjob.emr.log'))
... | class ProgressHtmlFromTunnelTestCase(MockBoto3TestCase):
| MOCK_TUNNEL_URL = 'http://foohost:12345/cluster'
def setUp(self):
super(ProgressHtmlFromTunnelTestCase, self).setUp()
self.urlopen = self.start(patch('mrjob.emr.urlopen'))
self.log = self.start(patch('mrjob.emr.log'))
# don't clean up our mock cluster; this causes unwanted lo... | by default, we fetch progress from the resource manager, through
# the SSH tunnel
self._launch_and_log_progress('--image-version', '2.4.9')
self.log.info.assert_called_once_with(' map 100% reduce 50%')
self.assertTrue(self._progress_html_from_tunnel.called)
self.assertFalse... | 134 | 134 | 448 | 14 | 120 | Affirm/mrjob | tests/test_emr.py | Python | ProgressHtmlFromTunnelTestCase | ProgressHtmlFromTunnelTestCase | 5,537 | 5,597 | 5,537 | 5,538 | 135c64c0d10e83a4161eb208b25f88d85f5f98bd | bigcode/the-stack | train |
3e1a4022a567752bc010abb7 | train | class | class AvailabilityZoneTestCase(MockBoto3TestCase):
MRJOB_CONF_CONTENTS = {'runners': {'emr': {
'emr_backoff': 0.01, # must be non-zero
'check_cluster_every': 0.00,
'cloud_fs_sync_secs': 0.00,
'zone': 'PUPPYLAND',
}}}
def test_availability_zone_config(self):
with se... | class AvailabilityZoneTestCase(MockBoto3TestCase):
| MRJOB_CONF_CONTENTS = {'runners': {'emr': {
'emr_backoff': 0.01, # must be non-zero
'check_cluster_every': 0.00,
'cloud_fs_sync_secs': 0.00,
'zone': 'PUPPYLAND',
}}}
def test_availability_zone_config(self):
with self.make_runner() as runner:
runner.run()... |
with self.make_runner('--image-id', 'ami-blanchin',
'--release-label', 'emr-5.6.0') as runner:
self.assertTrue(log.warning.called)
self.assertRaises(ClientError, runner.run)
class AvailabilityZoneTestCase(MockBoto3TestCase):
| 64 | 64 | 140 | 12 | 52 | Affirm/mrjob | tests/test_emr.py | Python | AvailabilityZoneTestCase | AvailabilityZoneTestCase | 807 | 823 | 807 | 808 | c37fe7979fc6768c9c067eb5801461f7965931b4 | bigcode/the-stack | train |
b32b2f0956468ac37ce54e9e | train | class | class TracUserHours(Component):
implements(ITemplateProvider, IRequestHandler)
# ITemplateProvider methods
def get_htdocs_dirs(self):
return []
def get_templates_dirs(self):
from pkg_resources import resource_filename
return [resource_filename(__name__, 'templates')]
# I... | class TracUserHours(Component):
| implements(ITemplateProvider, IRequestHandler)
# ITemplateProvider methods
def get_htdocs_dirs(self):
return []
def get_templates_dirs(self):
from pkg_resources import resource_filename
return [resource_filename(__name__, 'templates')]
# IRequestHandler methods
def m... | self.hours[milestone]
estimated_hours = hours['estimatedhours']
total_hours = hours['totalhours']
if not (estimated_hours or total_hours):
return iter([])
items = []
if estimated_hours:
if parse_version(TRAC_VERSION) < parse_ve... | 255 | 256 | 2,628 | 7 | 248 | t-kenji/trac-hours-plugin | trachours/web_ui.py | Python | TracUserHours | TracUserHours | 153 | 452 | 153 | 154 | 541a656ea0192edbd94e123635ec85ce353ae29a | bigcode/the-stack | train |
fd80a9bd1e6a07aa7db18b49 | train | class | class TracHoursRoadmapFilter(Component):
implements(ITemplateStreamFilter)
# ITemplateStreamFilter methods
def filter_stream(self, req, method, filename, stream, data):
"""
filter the stream for the roadmap (/roadmap)
and milestones /milestone/<milestone>
"""
if f... | class TracHoursRoadmapFilter(Component):
| implements(ITemplateStreamFilter)
# ITemplateStreamFilter methods
def filter_stream(self, req, method, filename, stream, data):
"""
filter the stream for the roadmap (/roadmap)
and milestones /milestone/<milestone>
"""
if filename in ('roadmap.html', 'milestone_vie... | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Jeff Hammel <jhammel@openplans.org>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
import re
import calendar
import csv
import time
from StringIO import StringIO
from ... | 241 | 256 | 908 | 9 | 231 | t-kenji/trac-hours-plugin | trachours/web_ui.py | Python | TracHoursRoadmapFilter | TracHoursRoadmapFilter | 37 | 150 | 37 | 38 | 165a12341b54ff2a46924887a6864b40e074ce17 | bigcode/the-stack | train |
0f3363b19c23e4d3cde38491 | train | class | class Decoder(nn.Module):
"""GRU-based decoder.
"""
def __init__(self,
inputs: int,
channels: int,
hiddens: List[int],
loc: int,
kernels: int,
dropout: float,
layers: int,
... | class Decoder(nn.Module):
| """GRU-based decoder.
"""
def __init__(self,
inputs: int,
channels: int,
hiddens: List[int],
loc: int,
kernels: int,
dropout: float,
layers: int,
mel: int,
... | from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .misc import Prenet
from .align import Aligner
class Decoder(nn.Module):
| 51 | 256 | 1,647 | 5 | 45 | revsic/torch-tacotron | taco/decoder.py | Python | Decoder | Decoder | 12 | 172 | 12 | 12 | dcca5ea86cf4ea270a87280ee4be3331b9f20d09 | bigcode/the-stack | train |
d51c23942e1a2409307c5014 | train | function | def command_string_to_list(move):
value = move.command
command_list = []
i = 0
save_point = 0
while (i < len(value) - 1):
if (value[i] == ":" and not (value[i+1] == ":" or value[i+1] == " ")):
j = i + 1
while(j < len(value)):
if (value[j] == ":"):
... | def command_string_to_list(move):
| value = move.command
command_list = []
i = 0
save_point = 0
while (i < len(value) - 1):
if (value[i] == ":" and not (value[i+1] == ":" or value[i+1] == " ")):
j = i + 1
while(j < len(value)):
if (value[j] == ":"):
command_list.app... | :
i += 1
if (i == len(value)):
height_level_list.append(value[save_point:i])
elif (value[i] == ":"):
height_level_list.append(value[save_point:i])
move.height_level = height_level_list
else:
move.height_level = ["... | 73 | 73 | 245 | 7 | 66 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | command_string_to_list | command_string_to_list | 324 | 354 | 324 | 324 | 7153ba3daf90d6afe053ee05e4cfb69eec5eca92 | bigcode/the-stack | train |
ed46454d6833f4a86b608f10 | train | function | def height_level_string_to_list(move):
value = move.height_level
if (value):
height_level_list = []
i = 0
save_point = i
while (i < len(value) - 1):
if (value[i] == ":"):
j = i + 1
while(j < len(value)):
if (value[j]... | def height_level_string_to_list(move):
| value = move.height_level
if (value):
height_level_list = []
i = 0
save_point = i
while (i < len(value) - 1):
if (value[i] == ":"):
j = i + 1
while(j < len(value)):
if (value[j] == ":"):
heigh... | for special_stance in special_stances]
special_states = SpecialState.objects.filter(character=character)
special_state_abbreviations = [special_state.abbreviation for special_state in special_states]
return special_stance_abbreviations + special_state_abbreviations
def height_level_string_to_list(move... | 64 | 64 | 188 | 8 | 55 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | height_level_string_to_list | height_level_string_to_list | 297 | 322 | 297 | 297 | d4503e941eca4932efe496f605ec2f7f1608f9a5 | bigcode/the-stack | train |
315287a8ef725cd6b161230b | train | function | def get_key():
base_dir = 'img/sc-inputs/'
columns = [
{
'label': "Move",
'message': mark_safe("English <strong>name</strong> of the move."),
},
{
'label': "Command",
'message': mark_safe("<strong>Input</strong> to execute move."),
... | def get_key():
| base_dir = 'img/sc-inputs/'
columns = [
{
'label': "Move",
'message': mark_safe("English <strong>name</strong> of the move."),
},
{
'label': "Command",
'message': mark_safe("<strong>Input</strong> to execute move."),
},
{
... | -detail.html', context)
# Helpers
def assign_section(section, context, move):
# don't do it like this anymore, instead use Move.objects.filter()
if (section.name == "horizontal attack"):
context['table_list'][0]['moves_list'].append(move)
elif (section.name == "vertical attack"):
contex... | 256 | 256 | 1,639 | 4 | 252 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | get_key | get_key | 110 | 286 | 110 | 110 | 26e2f889ff1055e3883b9538f61a3ef704a6ed4d | bigcode/the-stack | train |
3004717501b7b378ef2526b5 | train | function | def legend(request):
key = get_key()
context = {'inputs': key['inputs'], 'columns': key['columns'], 'title': "Legend"}
return render(request, 'soulcalibur_vi/legend.html', context)
| def legend(request):
| key = get_key()
context = {'inputs': key['inputs'], 'columns': key['columns'], 'title': "Legend"}
return render(request, 'soulcalibur_vi/legend.html', context)
| key = get_key()
context = {
'characters': characters,
'inputs': key['inputs'],
'columns': key['columns'],
'title': 'Soulcalibur VI'
}
return render(request, 'soulcalibur_vi/home.html', context)
def legend(request):
| 64 | 64 | 50 | 4 | 60 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | legend | legend | 48 | 53 | 48 | 48 | fb756ac5bedb1b54dd17a929b3ad721545e1fc16 | bigcode/the-stack | train |
f0fb38cc47c2039f3b61078e | train | function | def home(request):
characters = Character.objects.all().order_by('name')
key = get_key()
context = {
'characters': characters,
'inputs': key['inputs'],
'columns': key['columns'],
'title': 'Soulcalibur VI'
}
return render(request, 'soulcalibur_vi/home.html', contex... | def home(request):
| characters = Character.objects.all().order_by('name')
key = get_key()
context = {
'characters': characters,
'inputs': key['inputs'],
'columns': key['columns'],
'title': 'Soulcalibur VI'
}
return render(request, 'soulcalibur_vi/home.html', context)
| ":SC:", ":RE:", "RE", ":GI:",
]
# these strings can be turned into images too
height_level_smilies = [
":M:", ":H:", ":L:", ":SM:", ":SH:", ":SL:", ":TH:", ":GI:", ":SS:"
]
def home(request):
| 64 | 64 | 77 | 4 | 60 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | home | home | 34 | 46 | 34 | 34 | 6f3ff0ab30595f217d1f64e9b68c4082155f8984 | bigcode/the-stack | train |
87fd057899214aa533048860 | train | function | def assign_section(section, context, move):
# don't do it like this anymore, instead use Move.objects.filter()
if (section.name == "horizontal attack"):
context['table_list'][0]['moves_list'].append(move)
elif (section.name == "vertical attack"):
context['table_list'][1]['moves_list'].app... | def assign_section(section, context, move):
# don't do it like this anymore, instead use Move.objects.filter()
| if (section.name == "horizontal attack"):
context['table_list'][0]['moves_list'].append(move)
elif (section.name == "vertical attack"):
context['table_list'][1]['moves_list'].append(move)
elif (section.name == "kick attack"):
context['table_list'][2]['moves_list'].append(move)
el... | _section(section=move.section, context=context, move=move)
else:
context['sectionless_table'].append(move)
return render(request, 'soulcalibur_vi/character-detail.html', context)
# Helpers
def assign_section(section, context, move):
# don't do it like this anymore, instead use... | 73 | 73 | 244 | 25 | 47 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | assign_section | assign_section | 87 | 108 | 87 | 90 | 5e43d4a7f8628e25cdbe779ebe24b522f492af80 | bigcode/the-stack | train |
8f3c750c535bc08f41393a5b | train | function | def get_allowable_patterns(character):
special_stances = SpecialStance.objects.filter(character=character)
special_stance_abbreviations = [special_stance.abbreviation for special_stance in special_stances]
special_states = SpecialState.objects.filter(character=character)
special_state_abbreviations = [s... | def get_allowable_patterns(character):
| special_stances = SpecialStance.objects.filter(character=character)
special_stance_abbreviations = [special_stance.abbreviation for special_stance in special_stances]
special_states = SpecialState.objects.filter(character=character)
special_state_abbreviations = [special_state.abbreviation for special_s... | label': base_dir + 'eightWayRun.png',
'message': mark_safe("During <strong>Eight-Way-Run</strong> movement."),
},
]
return {'columns': columns, 'inputs_without_images': inputs_without_images, 'inputs': inputs}
def get_allowable_patterns(character):
| 64 | 64 | 91 | 7 | 57 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | get_allowable_patterns | get_allowable_patterns | 289 | 295 | 289 | 289 | 11311a61c48161c04413ec28409dc16215adb219 | bigcode/the-stack | train |
c15606836335f1dfe39ec043 | train | function | def detail(request, slug):
character = Character.objects.get(slug = slug)
sections = Section.objects.all().order_by('id')
moves = Move.objects.filter(character=character).order_by('id')
context = {
"name": character.name,
"image": character.image.url,
"table_list": [],
... | def detail(request, slug):
| character = Character.objects.get(slug = slug)
sections = Section.objects.all().order_by('id')
moves = Move.objects.filter(character=character).order_by('id')
context = {
"name": character.name,
"image": character.image.url,
"table_list": [],
"title": character.name... | '
}
return render(request, 'soulcalibur_vi/home.html', context)
def legend(request):
key = get_key()
context = {'inputs': key['inputs'], 'columns': key['columns'], 'title': "Legend"}
return render(request, 'soulcalibur_vi/legend.html', context)
def detail(request, slug):
| 75 | 75 | 251 | 6 | 69 | RayGar7/SaltyFramesAPI | soulcalibur_vi/views.py | Python | detail | detail | 55 | 83 | 55 | 55 | b2a76d4864739dfd89dd8146648889674a14b9d6 | bigcode/the-stack | train |
bf91002d8aecfb386d9bae0a | train | class | class ReadStatsSerializers(serializers.ModelSerializer):
""""
Serializer class for our ReadStats model
"""
article = serializers.SerializerMethodField()
class Meta:
model = ReadStats
fields = '__all__'
def get_article(self, stats):
return {
"article": s... | class ReadStatsSerializers(serializers.ModelSerializer):
| """"
Serializer class for our ReadStats model
"""
article = serializers.SerializerMethodField()
class Meta:
model = ReadStats
fields = '__all__'
def get_article(self, stats):
return {
"article": stats.article.title,
"slug": stats.article.slu... | from rest_framework import serializers
from .models import ReadStats
class ReadStatsSerializers(serializers.ModelSerializer):
| 22 | 64 | 77 | 9 | 12 | andela/ah-alpha | authors/apps/reading_stats/serializers.py | Python | ReadStatsSerializers | ReadStatsSerializers | 6 | 22 | 6 | 6 | aa65a24f40b4938c38cbfbd0c02deb90c7692658 | bigcode/the-stack | train |
28c2698d09270826d771ec97 | train | class | class OrderListTest(OrderViewTestCase):
def test_order_list(self):
response = self.client.get(reverse('purchase-order-index'))
self.assertEqual(response.status_code, 200)
| class OrderListTest(OrderViewTestCase):
| def test_order_list(self):
response = self.client.get(reverse('purchase-order-index'))
self.assertEqual(response.status_code, 200)
| ]
def setUp(self):
super().setUp()
# Create a user
User = get_user_model()
User.objects.create_user('username', 'user@email.com', 'password')
self.client.login(username='username', password='password')
class OrderListTest(OrderViewTestCase):
| 64 | 64 | 39 | 9 | 55 | Zeigren/InvenTree | InvenTree/order/test_views.py | Python | OrderListTest | OrderListTest | 40 | 45 | 40 | 41 | b53cce71115c88df91343bad7594f0d844b49de2 | bigcode/the-stack | train |
7a3df8b64c874b0085e8811d | train | class | class TestPOReceive(OrderViewTestCase):
""" Tests for receiving a purchase order """
def setUp(self):
super().setUp()
self.po = PurchaseOrder.objects.get(pk=1)
self.po.status = OrderStatus.PLACED
self.po.save()
self.url = reverse('purchase-order-receive', args=(1,))
... | class TestPOReceive(OrderViewTestCase):
| """ Tests for receiving a purchase order """
def setUp(self):
super().setUp()
self.po = PurchaseOrder.objects.get(pk=1)
self.po.status = OrderStatus.PLACED
self.po.save()
self.url = reverse('purchase-order-receive', args=(1,))
def post(self, data, validate=None):
... | 200)
data = json.loads(response.content)
self.assertTrue(data['form_valid'])
self.assertEqual(n + 1, PurchaseOrder.objects.get(pk=1).lines.count())
line = PurchaseOrderLineItem.objects.get(order=1, part=100)
self.assertEqual(line.quantity, 45)
def test_line_item_edit(self)... | 137 | 137 | 457 | 9 | 128 | Zeigren/InvenTree | InvenTree/order/test_views.py | Python | TestPOReceive | TestPOReceive | 177 | 257 | 177 | 177 | 8f3b71053b7dcef3b3eacd370a45ce6eab141567 | bigcode/the-stack | train |
ac60eee27f4287837ce37048 | train | class | class OrderViewTestCase(TestCase):
fixtures = [
'category',
'part',
'bom',
'location',
'company',
'supplier_part',
'stock',
'order',
]
def setUp(self):
super().setUp()
# Create a user
User = get_user_model()
... | class OrderViewTestCase(TestCase):
| fixtures = [
'category',
'part',
'bom',
'location',
'company',
'supplier_part',
'stock',
'order',
]
def setUp(self):
super().setUp()
# Create a user
User = get_user_model()
User.objects.create_user('username', ... | from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from InvenTree.status_codes import OrderStatus
from .models import PurchaseOrder, PurchaseOrderLineItem
import json
class OrderViewTestCase(TestCase):
| 64 | 64 | 101 | 9 | 54 | Zeigren/InvenTree | InvenTree/order/test_views.py | Python | OrderViewTestCase | OrderViewTestCase | 17 | 37 | 17 | 18 | af64c15121eb18300217d2d686ea97ed608ff716 | bigcode/the-stack | train |
9a7d62cf33e6843bf79ed07e | train | class | class POTests(OrderViewTestCase):
""" Tests for PurchaseOrder views """
def test_detail_view(self):
""" Retrieve PO detail view """
response = self.client.get(reverse('purchase-order-detail', args=(1,)))
self.assertEqual(response.status_code, 200)
keys = response.context.keys()
... | class POTests(OrderViewTestCase):
| """ Tests for PurchaseOrder views """
def test_detail_view(self):
""" Retrieve PO detail view """
response = self.client.get(reverse('purchase-order-detail', args=(1,)))
self.assertEqual(response.status_code, 200)
keys = response.context.keys()
self.assertIn('OrderStatus... | """ Unit tests for Order views (see views.py) """
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from InvenTree.status_codes import OrderStatus
from .models import PurchaseOrder, Purchase... | 223 | 256 | 1,113 | 8 | 215 | Zeigren/InvenTree | InvenTree/order/test_views.py | Python | POTests | POTests | 48 | 174 | 48 | 48 | b056bb89cd35f933d510d2c2295ec9a8fda4182f | bigcode/the-stack | train |
9afc2e871950dd5abddfa53a | train | function | def image_format_check(img_path):
"""This check the image path whether legal or not
Arguments:
img_path {path} -- image path
Returns:
bool -- if it is a valid image file, return True.
"""
suffix = img_path.split('.')[-1]
if suffix in ImgConf._VALID_IMAGE_SUFFIXES:
... | def image_format_check(img_path):
| """This check the image path whether legal or not
Arguments:
img_path {path} -- image path
Returns:
bool -- if it is a valid image file, return True.
"""
suffix = img_path.split('.')[-1]
if suffix in ImgConf._VALID_IMAGE_SUFFIXES:
return True
retur... |
from .config import ImageConf as ImgConf
import os
def image_format_check(img_path):
| 21 | 64 | 82 | 7 | 13 | tkianai/tk-cv | kt/image/utils.py | Python | image_format_check | image_format_check | 5 | 19 | 5 | 5 | 61b0883cb11a9920edfd1deb827a3a32249808b4 | bigcode/the-stack | train |
c7e7a006ff088b0b9dea1685 | train | function | def _gunzip(bs):
with gzip.GzipFile(fileobj=six.BytesIO(bs), mode="rb") as f:
return f.read()
| def _gunzip(bs):
| with gzip.GzipFile(fileobj=six.BytesIO(bs), mode="rb") as f:
return f.read()
| "text/html",
csp_scripts_sha256s=["abcd"],
)
def _gzip(bs):
out = six.BytesIO()
with gzip.GzipFile(fileobj=out, mode="wb") as f:
f.write(bs)
return out.getvalue()
def _gunzip(bs):
| 64 | 64 | 32 | 6 | 58 | qzchenwl/tensorboard | tensorboard/backend/http_util_test.py | Python | _gunzip | _gunzip | 399 | 401 | 399 | 399 | 7cd37f3f8f0f8107af42ab57aa3b8c01d9c953a1 | bigcode/the-stack | train |
6393561cc3aad40d202ffce9 | train | function | def _gzip(bs):
out = six.BytesIO()
with gzip.GzipFile(fileobj=out, mode="wb") as f:
f.write(bs)
return out.getvalue()
| def _gzip(bs):
| out = six.BytesIO()
with gzip.GzipFile(fileobj=out, mode="wb") as f:
f.write(bs)
return out.getvalue()
| ):
with self.assertRaisesRegex(
ValueError,
"^Expected whitelist domain to not contain a whitespace",
):
http_util.Respond(
q,
"<b>hello</b>",
"text/html",... | 64 | 64 | 41 | 5 | 59 | qzchenwl/tensorboard | tensorboard/backend/http_util_test.py | Python | _gzip | _gzip | 392 | 396 | 392 | 392 | 1b8f0427b28a0c3045bea214d7d3b8376afd205e | bigcode/the-stack | train |
53e32d3dfd3faae3b2d3650c | train | class | class RespondTest(tb_test.TestCase):
def testHelloWorld(self):
q = wrappers.Request(wtest.EnvironBuilder().get_environ())
r = http_util.Respond(q, "<b>hello world</b>", "text/html")
self.assertEqual(r.status_code, 200)
self.assertEqual(r.response, [six.b("<b>hello world</b>")])
... | class RespondTest(tb_test.TestCase):
| def testHelloWorld(self):
q = wrappers.Request(wtest.EnvironBuilder().get_environ())
r = http_util.Respond(q, "<b>hello world</b>", "text/html")
self.assertEqual(r.status_code, 200)
self.assertEqual(r.response, [six.b("<b>hello world</b>")])
self.assertEqual(r.headers.get("Co... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 256 | 256 | 3,599 | 8 | 247 | qzchenwl/tensorboard | tensorboard/backend/http_util_test.py | Python | RespondTest | RespondTest | 41 | 389 | 41 | 41 | d22a8efc7be76bc70e0a102ef4e75530ec3f9373 | bigcode/the-stack | train |
9fc48c12fa381a33c8c3841b | train | function | def _bitflip(bs):
# Return bytestring with all its bits flipped.
return b"".join(
struct.pack("B", 0xFF ^ struct.unpack_from("B", bs, i)[0])
for i in range(len(bs))
)
| def _bitflip(bs):
# Return bytestring with all its bits flipped.
| return b"".join(
struct.pack("B", 0xFF ^ struct.unpack_from("B", bs, i)[0])
for i in range(len(bs))
)
| ") as f:
f.write(bs)
return out.getvalue()
def _gunzip(bs):
with gzip.GzipFile(fileobj=six.BytesIO(bs), mode="rb") as f:
return f.read()
def _bitflip(bs):
# Return bytestring with all its bits flipped.
| 64 | 64 | 57 | 17 | 47 | qzchenwl/tensorboard | tensorboard/backend/http_util_test.py | Python | _bitflip | _bitflip | 404 | 409 | 404 | 405 | 6a74dfc7daf524a605c23fc0fe977af8d6b51664 | bigcode/the-stack | train |
7f762c71566f79fd2b3c3209 | train | class | class OmniGrammar(PVLGrammar):
"""A broadly permissive grammar.
This grammar does not follow a specification, but is meant to allow
the broadest possible ingestion of PVL-like text that is found.
This grammar should not be used to write out Python objects to PVL,
instead please use one of the gram... | class OmniGrammar(PVLGrammar):
| """A broadly permissive grammar.
This grammar does not follow a specification, but is meant to allow
the broadest possible ingestion of PVL-like text that is found.
This grammar should not be used to write out Python objects to PVL,
instead please use one of the grammars that follows a published
... | have a separate grammar object. Since we're at it, we might
# as well use the *_pref_keywords to indicate the CamelCase
# that ISIS folks are expecting.
group_pref_keywords = ('Group', 'End_Group')
group_keywords = {'GROUP': 'END_GROUP'}
object_pref_keywords = ('Object', 'End_Object')
object_k... | 91 | 92 | 309 | 7 | 84 | AndrewAnnex/pvl | pvl/grammar.py | Python | OmniGrammar | OmniGrammar | 221 | 245 | 221 | 221 | ec270cc7350e37b8c1ce46fe4ddeb097649e72f8 | bigcode/the-stack | train |
c8c4889b97316f9adce11e34 | train | class | class ODLGrammar(PVLGrammar):
"""This defines a PDS3 ODL grammar.
The reference for this grammar is the PDS3 Standards Reference
(version 3.8, 27 Feb 2009) Chapter 12: Object Description
Language Specification and Usage.
"""
group_pref_keywords = ('GROUP', 'END_GROUP')
object_pref_keywords... | class ODLGrammar(PVLGrammar):
| """This defines a PDS3 ODL grammar.
The reference for this grammar is the PDS3 Standards Reference
(version 3.8, 27 Feb 2009) Chapter 12: Object Description
Language Specification and Usage.
"""
group_pref_keywords = ('GROUP', 'END_GROUP')
object_pref_keywords = ('OBJECT', 'END_OBJECT')
... | ord(char)
# The vertical tab, ord('\t') = 11, is mistakenly
# shaded on page B-3 of the PVL specification.
if(o > 255 or
(o >= 0 and o <= 8) or
# o == 11 or
(o >= 14 and o <= 31) or
(o >= 127 and o <= 159)):
return False
else:
... | 109 | 109 | 365 | 8 | 100 | AndrewAnnex/pvl | pvl/grammar.py | Python | ODLGrammar | ODLGrammar | 135 | 173 | 135 | 135 | 64365fa1d16507eb10de383b46c9fe681e90e2af | bigcode/the-stack | train |
e2050073d0f099e7e9aa2412 | train | class | class ISISGrammar(PVLGrammar):
"""This defines the ISIS version of PVL.
This is valid as of ISIS 3.9, and before, at least.
The ISIS 'Pvl' object typically writes out parameter
values and keywords in CamelCase (e.g. 'Group', 'End_Group',
'CenterLatitude', etc.), but it will accept all-... | class ISISGrammar(PVLGrammar):
| """This defines the ISIS version of PVL.
This is valid as of ISIS 3.9, and before, at least.
The ISIS 'Pvl' object typically writes out parameter
values and keywords in CamelCase (e.g. 'Group', 'End_Group',
'CenterLatitude', etc.), but it will accept all-uppercase
versions.
... | -6])#{PVLGrammar._s}')
nondecimal_re = re.compile(
fr'{nondecimal_pre_re.pattern}(?P<non_decimal>[0-9|A-F|a-f]+)#')
def char_allowed(self, char):
"""Returns true if *char* is allowed in the ODL Character Set.
The ODL Character Set is limited to ASCII. This is fewer
characters ... | 157 | 157 | 525 | 7 | 149 | AndrewAnnex/pvl | pvl/grammar.py | Python | ISISGrammar | ISISGrammar | 176 | 218 | 176 | 176 | 902f30a16e2d2e1c31e4a64f3f7f747b515a3b18 | bigcode/the-stack | train |
6982f9ccfd2b55882b2bf944 | train | class | class PVLGrammar():
"""Describes a PVL grammar for use by the lexer and parser.
The reference for this grammar is the CCSDS-641.0-B-2 'Blue Book'.
:param whitespace: Tuple of characters to be recognized as PVL
White Space (used to separate syntactic elements and promote
readability, but th... | class PVLGrammar():
| """Describes a PVL grammar for use by the lexer and parser.
The reference for this grammar is the CCSDS-641.0-B-2 'Blue Book'.
:param whitespace: Tuple of characters to be recognized as PVL
White Space (used to separate syntactic elements and promote
readability, but the amount or presence... | # -*- coding: utf-8 -*-
"""Describes the language aspects of PVL dialects."""
# Copyright 2019-2020, ``pvl`` library authors.
#
# Reuse is permitted under the terms of the license.
# The AUTHORS file and the LICENSE file are at the
# top level of this library.
import re
class PVLGrammar():
| 76 | 256 | 1,509 | 5 | 70 | AndrewAnnex/pvl | pvl/grammar.py | Python | PVLGrammar | PVLGrammar | 13 | 132 | 13 | 13 | 166e542ac26a0e727b6a34c41311c3f006088983 | bigcode/the-stack | train |
391465c815102aa8b8c13fb8 | train | class | class BipartiteMatching(DPMatching):
"""Bipartite matching algorithm for IAT.
"""
def match(self, from_module: List[Union[nn.Module, List[nn.Module]]],
to_module: List[Union[nn.Module, List[nn.Module]]], *args, **kwargs) \
-> List[Tuple[nn.Module, nn.Module]]:
_, matched, ... | class BipartiteMatching(DPMatching):
| """Bipartite matching algorithm for IAT.
"""
def match(self, from_module: List[Union[nn.Module, List[nn.Module]]],
to_module: List[Union[nn.Module, List[nn.Module]]], *args, **kwargs) \
-> List[Tuple[nn.Module, nn.Module]]:
_, matched, _ = self._match_bipartite(from_module... | from typing import Tuple, List, Union
import networkx as nx
import numpy as np
import torch.nn as nn
from iatransfer.toolkit.matching.dp_matching import DPMatching
class BipartiteMatching(DPMatching):
| 50 | 176 | 588 | 9 | 40 | KamilPiechowiak/iatransfer | iatransfer/toolkit/matching/bipartite_matching.py | Python | BipartiteMatching | BipartiteMatching | 10 | 60 | 10 | 10 | 74a9fbc4f9c93badc6ecb22ff75212514db29920 | bigcode/the-stack | train |
c1a79c0c6b0146112c447c15 | train | class | class TestTablesAclSql(SQLTemplateTestBase):
scenarios = [
("Test query returns the permissions when there are permissions set up"
" on the table", dict())
]
def __init__(self):
super(TestTablesAclSql, self).__init__()
self.table_id = -1
def test_setup(self, connection... | class TestTablesAclSql(SQLTemplateTestBase):
| scenarios = [
("Test query returns the permissions when there are permissions set up"
" on the table", dict())
]
def __init__(self):
super(TestTablesAclSql, self).__init__()
self.table_id = -1
def test_setup(self, connection, cursor):
cursor.execute("GRANT SELE... | ##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2017, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
import os
from re... | 87 | 109 | 365 | 10 | 76 | jhkuang11/UniTrade | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/tests/test_tables_acl_sql.py | Python | TestTablesAclSql | TestTablesAclSql | 15 | 54 | 15 | 15 | 5dce57ebe1012d6f37bc5df1dda70c294eeaae88 | bigcode/the-stack | train |
3c8959c08028e2e4f8e96dde | train | class | class MD3Card(MDCard, FakeRectangularElevationBehavior):
pass
| class MD3Card(MDCard, FakeRectangularElevationBehavior):
| pass
| ymd.app import MDApp
from kivymd.uix.behaviors import FakeRectangularElevationBehavior
from kivymd.uix.card import MDCard
from json import loads
font_file = "assets/fonts/avenir_heavy.ttf"
class MD3Card(MDCard, FakeRectangularElevationBehavior):
| 64 | 64 | 17 | 14 | 50 | kengoon/Kvdroid | demo/kivy_ui/main.py | Python | MD3Card | MD3Card | 11 | 12 | 11 | 11 | 893334d473f2f75d9fe733dad89151766e546ef8 | bigcode/the-stack | train |
169702d687e53c5b865ea6ac | train | class | class KvDroid(MDApp):
icon = "assets/image/icon.png"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.theme_cls.primary_palette = "Blue"
self.theme_cls.primary_hue = "A700"
self.theme_cls.font_styles.update(
{
"H1": [font_file, 96, False,... | class KvDroid(MDApp):
| icon = "assets/image/icon.png"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.theme_cls.primary_palette = "Blue"
self.theme_cls.primary_hue = "A700"
self.theme_cls.font_styles.update(
{
"H1": [font_file, 96, False, -1.5],
... | from kivy import Config
Config.set("kivy", "exit_on_escape", "0")
from kivymd.app import MDApp
from kivymd.uix.behaviors import FakeRectangularElevationBehavior
from kivymd.uix.card import MDCard
from json import loads
font_file = "assets/fonts/avenir_heavy.ttf"
class MD3Card(MDCard, FakeRectangularElevationBehavior... | 97 | 104 | 349 | 8 | 88 | kengoon/Kvdroid | demo/kivy_ui/main.py | Python | KvDroid | KvDroid | 15 | 52 | 15 | 15 | d29c5d862b67622cdf4b6d1e4ef1840c5b99f5ee | bigcode/the-stack | train |
90cafd2a562e350fb9487e9f | train | class | class TestAvatarField:
def setup(self):
self.avatar_field = fields.AvatarField()
@pytest.mark.parametrize(
argnames="default,result",
argvalues=[
(None, None),
(1, 1),
(0, 0),
('', ''),
(lambda: 1, 1),
]
)
def t... | class TestAvatarField:
| def setup(self):
self.avatar_field = fields.AvatarField()
@pytest.mark.parametrize(
argnames="default,result",
argvalues=[
(None, None),
(1, 1),
(0, 0),
('', ''),
(lambda: 1, 1),
]
)
def test_get_default_method(... | import pytest
from pyavagen import fields, validators
class TestAvatarField:
| 17 | 106 | 356 | 5 | 11 | abalx/py-avatar-generator | tests/test_fields.py | Python | TestAvatarField | TestAvatarField | 6 | 60 | 6 | 6 | cb7e830cf2835ef29256b0afa9752870238d6f7b | bigcode/the-stack | train |
cd7b5bc81df0b14f41a44bd9 | train | function | def split_sentences(text):
"""Split a large string into sentences
"""
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
sentences = tokenizer.tokenize(text)
sentences = [x.replace('\n', '') for x in sentences if len(x) > 10]
return sentences
| def split_sentences(text):
| """Split a large string into sentences
"""
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
sentences = tokenizer.tokenize(text)
sentences = [x.replace('\n', '') for x in sentences if len(x) > 10]
return sentences
| freq[word] += 1
notUnique += 1
else:
freq[word] = 1
unique +=1
entropyN = int((unique / (num_words - numStop))*100)
return [entropyN,numStop,num_words]
def split_sentences(text):
| 64 | 64 | 72 | 6 | 58 | agnelvishal/newspaper | newspaper/nlp.py | Python | split_sentences | split_sentences | 179 | 187 | 179 | 179 | 376ed34142c8ea110b8d80954228de3822a586cf | bigcode/the-stack | train |
4d4491214924a78797a3fff4 | train | function | def score(sentences, titleWords, keywords):
"""Score sentences based on different features
"""
senSize = len(sentences)
ranks = Counter()
for i, s in enumerate(sentences):
sentence = split_words(s)
titleFeature = title_score(titleWords, sentence)
sentenceLength = length_score... | def score(sentences, titleWords, keywords):
| """Score sentences based on different features
"""
senSize = len(sentences)
ranks = Counter()
for i, s in enumerate(sentences):
sentence = split_words(s)
titleFeature = title_score(titleWords, sentence)
sentenceLength = length_score(len(sentence))
sentencePosition = s... | ranks = score(sentences, titleWords, keys).most_common(max_sents)
for rank in ranks:
summaries.append(rank[0])
summaries.sort(key=lambda summary: summary[0])
return [summary[1] for summary in summaries]
def score(sentences, titleWords, keywords):
| 64 | 64 | 192 | 10 | 54 | agnelvishal/newspaper | newspaper/nlp.py | Python | score | score | 57 | 74 | 57 | 57 | c050a8c95e20aea1daf735beab8d22662bcd9f78 | bigcode/the-stack | train |
942e3df1df14dbfa54e709b1 | train | function | def dbs(words, keywords):
if (len(words) == 0):
return 0
summ = 0
first = []
second = []
for i, word in enumerate(words):
if word in keywords:
score = keywords[word]
if first == []:
first = [i, score]
else:
second =... | def dbs(words, keywords):
| if (len(words) == 0):
return 0
summ = 0
first = []
second = []
for i, word in enumerate(words):
if word in keywords:
score = keywords[word]
if first == []:
first = [i, score]
else:
second = first
fir... | 0
if (len(words) == 0):
return 0
for word in words:
if word in keywords:
score += keywords[word]
return (1.0 / math.fabs(len(words)) * score) / 10.0
def dbs(words, keywords):
| 64 | 64 | 161 | 7 | 56 | agnelvishal/newspaper | newspaper/nlp.py | Python | dbs | dbs | 87 | 106 | 87 | 87 | 230828726a7051288d62208bc0c5eb59fe55c92a | bigcode/the-stack | train |
81d7bc66dd279f9e98860a2f | train | function | def title_score(title, sentence):
if title:
title = [x for x in title if x not in stopwords]
count = 0.0
for word in sentence:
if (word not in stopwords and word in title):
count += 1.0
return count / max(len(title), 1)
else:
return 0
| def title_score(title, sentence):
| if title:
title = [x for x in title if x not in stopwords]
count = 0.0
for word in sentence:
if (word not in stopwords and word in title):
count += 1.0
return count / max(len(title), 1)
else:
return 0
| sentences = tokenizer.tokenize(text)
sentences = [x.replace('\n', '') for x in sentences if len(x) > 10]
return sentences
def length_score(sentence_len):
return 1 - math.fabs(ideal - sentence_len) / ideal
def title_score(title, sentence):
| 64 | 64 | 81 | 7 | 56 | agnelvishal/newspaper | newspaper/nlp.py | Python | title_score | title_score | 194 | 203 | 194 | 194 | 20fa583ffc7c00d94e17c07beb6bd1b62544102f | bigcode/the-stack | train |
b93812ab060e3b404532f971 | train | function | def load_stopwords(language):
"""
Loads language-specific stopwords for keyword selection
"""
global stopwords
# stopwords for nlp in English are not the regular stopwords
# to pass the tests
# can be changed with the tests
if language == 'en':
stopwordsFile = settings.NLP_STOPW... | def load_stopwords(language):
| """
Loads language-specific stopwords for keyword selection
"""
global stopwords
# stopwords for nlp in English are not the regular stopwords
# to pass the tests
# can be changed with the tests
if language == 'en':
stopwordsFile = settings.NLP_STOPWORDS_EN
else:
stop... | -Yang'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014, Lucas Ou-Yang'
import re
import math
from os import path
from collections import Counter
from . import settings
ideal = 20.0
stopwords = set()
def load_stopwords(language):
| 64 | 64 | 138 | 6 | 58 | agnelvishal/newspaper | newspaper/nlp.py | Python | load_stopwords | load_stopwords | 22 | 37 | 22 | 22 | 2fb35ccecf1e24afc889c4397534accfa1148cf3 | bigcode/the-stack | train |
c53d5dbfa303e37cff47dbe5 | train | function | def length_score(sentence_len):
return 1 - math.fabs(ideal - sentence_len) / ideal
| def length_score(sentence_len):
| return 1 - math.fabs(ideal - sentence_len) / ideal
|
"""
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
sentences = tokenizer.tokenize(text)
sentences = [x.replace('\n', '') for x in sentences if len(x) > 10]
return sentences
def length_score(sentence_len):
| 64 | 64 | 23 | 6 | 57 | agnelvishal/newspaper | newspaper/nlp.py | Python | length_score | length_score | 190 | 191 | 190 | 190 | 27da9e4d864a636f1910cb78e41e93068dbfe99a | bigcode/the-stack | train |
96e755aa4d328a29283bfb16 | train | function | def entropy(text):
"""Used to calculate the entropy of words in a text.
"""
text = split_words(text)
numStop = 0
textNo=[]
# of words before removing blacklist words
if text:
num_words = len(text)
for x in text:
if x not in stopwords:
textNo.append(x)
... | def entropy(text):
| """Used to calculate the entropy of words in a text.
"""
text = split_words(text)
numStop = 0
textNo=[]
# of words before removing blacklist words
if text:
num_words = len(text)
for x in text:
if x not in stopwords:
textNo.append(x)
else:
... | , y in keywords)
for k in keywords:
articleScore = keywords[k] * 1.0 / max(num_words, 1)
keywords[k] = articleScore * 1.5 + 1
return dict(keywords)
else:
return dict()
def entropy(text):
| 64 | 64 | 174 | 4 | 60 | agnelvishal/newspaper | newspaper/nlp.py | Python | entropy | entropy | 152 | 177 | 152 | 152 | 6a18eb07962093a2d6f38a732dcf4ad265368382 | bigcode/the-stack | train |
1cd3b2758bbd4ebab79f69df | train | function | def sbs(words, keywords):
score = 0.0
if (len(words) == 0):
return 0
for word in words:
if word in keywords:
score += keywords[word]
return (1.0 / math.fabs(len(words)) * score) / 10.0
| def sbs(words, keywords):
| score = 0.0
if (len(words) == 0):
return 0
for word in words:
if word in keywords:
score += keywords[word]
return (1.0 / math.fabs(len(words)) * score) / 10.0
| scores from four categories
totalScore = (titleFeature*1.5 + frequency*2.0 +
sentenceLength*1.0 + sentencePosition*1.0)/4.0
ranks[(i, s)] = totalScore
return ranks
def sbs(words, keywords):
| 64 | 64 | 70 | 7 | 56 | agnelvishal/newspaper | newspaper/nlp.py | Python | sbs | sbs | 77 | 84 | 77 | 77 | 848b6a8a295881cb967df232244baaa7cbc67ba2 | bigcode/the-stack | train |
86682da3297289e709b5da91 | train | function | def keywords(text):
"""Get the top 10 keywords and their frequency scores ignores blacklisted
words in stopwords, counts the number of occurrences of each word, and
sorts them in reverse natural order (so descending) by number of
occurrences.
"""
NUM_KEYWORDS = 10
text = split_words(text)
... | def keywords(text):
| """Get the top 10 keywords and their frequency scores ignores blacklisted
words in stopwords, counts the number of occurrences of each word, and
sorts them in reverse natural order (so descending) by number of
occurrences.
"""
NUM_KEYWORDS = 10
text = split_words(text)
# of words before ... | + 1.0)) * summ)
def split_words(text):
"""Split a string into array of words
"""
try:
text = re.sub(r'[^\w ]', '', text) # strip special chars
return [x.strip('.').lower() for x in text.split()]
except TypeError:
return None
def keywords(text):
| 77 | 77 | 259 | 4 | 72 | agnelvishal/newspaper | newspaper/nlp.py | Python | keywords | keywords | 119 | 150 | 119 | 119 | ff359d1778af1c9f2b3421b0c7a201cd998de578 | bigcode/the-stack | train |
a26ff4c34ff5bc6bec44a5c4 | train | function | def sentence_position(i, size):
"""Different sentence positions indicate different
probability of being an important sentence.
"""
normalized = i * 1.0 / size
if (normalized > 1.0):
return 0
elif (normalized > 0.9):
return 0.15
elif (normalized > 0.8):
return 0.04
... | def sentence_position(i, size):
| """Different sentence positions indicate different
probability of being an important sentence.
"""
normalized = i * 1.0 / size
if (normalized > 1.0):
return 0
elif (normalized > 0.9):
return 0.15
elif (normalized > 0.8):
return 0.04
elif (normalized > 0.7):
... | if x not in stopwords]
count = 0.0
for word in sentence:
if (word not in stopwords and word in title):
count += 1.0
return count / max(len(title), 1)
else:
return 0
def sentence_position(i, size):
| 68 | 68 | 228 | 7 | 60 | agnelvishal/newspaper | newspaper/nlp.py | Python | sentence_position | sentence_position | 206 | 234 | 206 | 206 | 595d972f979e82754fdb345718463fbe93ebb66a | bigcode/the-stack | train |
d48c10de0c2796b3f820514d | train | function | def summarize(url='', title='', text='', max_sents=5):
if not text or not title or max_sents <= 0:
return []
summaries = []
sentences = split_sentences(text)
keys = keywords(text)
titleWords = split_words(title)
# Score sentences, and use the top 5 or max_sents sentences
ranks = sc... | def summarize(url='', title='', text='', max_sents=5):
| if not text or not title or max_sents <= 0:
return []
summaries = []
sentences = split_sentences(text)
keys = keywords(text)
titleWords = split_words(title)
# Score sentences, and use the top 5 or max_sents sentences
ranks = score(sentences, titleWords, keys).most_common(max_sents)... | WORDS_DIR,\
'stopwords-{}.txt'.format(language))
with open(stopwordsFile, 'r', encoding='utf-8') as f:
stopwords.update(set([w.strip() for w in f.readlines()]))
def summarize(url='', title='', text='', max_sents=5):
| 63 | 64 | 129 | 14 | 49 | agnelvishal/newspaper | newspaper/nlp.py | Python | summarize | summarize | 40 | 54 | 40 | 40 | 8fca54d18e20faa5e64cd0e37ecfc1bae65f6449 | bigcode/the-stack | train |
62ddf4c782a8dc0f0bdb6b9d | train | function | def split_words(text):
"""Split a string into array of words
"""
try:
text = re.sub(r'[^\w ]', '', text) # strip special chars
return [x.strip('.').lower() for x in text.split()]
except TypeError:
return None
| def split_words(text):
| """Split a string into array of words
"""
try:
text = re.sub(r'[^\w ]', '', text) # strip special chars
return [x.strip('.').lower() for x in text.split()]
except TypeError:
return None
| (first[1] * second[1]) / (dif ** 2)
# Number of intersections
k = len(set(keywords.keys()).intersection(set(words))) + 1
return (1 / (k * (k + 1.0)) * summ)
def split_words(text):
| 64 | 64 | 64 | 5 | 59 | agnelvishal/newspaper | newspaper/nlp.py | Python | split_words | split_words | 109 | 116 | 109 | 109 | b87e6ccc2f3cd6038b492da1958c3fca52427f13 | bigcode/the-stack | train |
bdd46dc50263bd094b00bf75 | train | class | @represents(UML.AcceptEventAction)
class AcceptEventActionItem(ElementPresentation, Named):
def __init__(self, diagram, id=None):
super().__init__(diagram, id, width=50, height=30)
self.shape = Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
... | @represents(UML.AcceptEventAction)
class AcceptEventActionItem(ElementPresentation, Named):
| def __init__(self, diagram, id=None):
super().__init__(diagram, id, width=50, height=30)
self.shape = Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
EditableText(text=lambda: self.subject.name or ""),
style={"padding": (4, 1... | _to(width - d, 0)
cr.line_to(width, height / 2)
cr.line_to(width - d, height)
cr.line_to(0, height)
cr.close_path()
stroke(context)
@represents(UML.AcceptEventAction)
class AcceptEventActionItem(ElementPresentation, Named):
| 66 | 66 | 223 | 19 | 47 | milotype/gaphor | gaphor/UML/actions/action.py | Python | AcceptEventActionItem | AcceptEventActionItem | 62 | 90 | 62 | 63 | 148e1d27a9a3720a54f234c7f727197216e5f710 | bigcode/the-stack | train |
3ef7d6f6eb331063c8f2598f | train | class | @represents(UML.Action)
class ActionItem(ElementPresentation, Named):
def __init__(self, diagram, id=None):
super().__init__(diagram, id, width=50, height=30)
self.shape = Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
EditableText(text... | @represents(UML.Action)
class ActionItem(ElementPresentation, Named):
| def __init__(self, diagram, id=None):
super().__init__(diagram, id, width=50, height=30)
self.shape = Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
EditableText(text=lambda: self.subject.name or ""),
style={
... | .presentation import ElementPresentation, Named
from gaphor.diagram.shapes import Box, EditableText, Text, draw_border, stroke
from gaphor.diagram.support import represents
from gaphor.UML.modelfactory import stereotypes_str
@represents(UML.Action)
class ActionItem(ElementPresentation, Named):
| 64 | 64 | 137 | 15 | 48 | milotype/gaphor | gaphor/UML/actions/action.py | Python | ActionItem | ActionItem | 10 | 28 | 10 | 11 | 17b70b8be3594d42642e4ecb9ff5763c9c5ca846 | bigcode/the-stack | train |
c6bdb30a2b1de589004b398d | train | class | @represents(UML.SendSignalAction)
class SendSignalActionItem(ElementPresentation, Named):
def __init__(self, diagram, id=None):
super().__init__(diagram, id, width=50, height=30)
self.shape = Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
... | @represents(UML.SendSignalAction)
class SendSignalActionItem(ElementPresentation, Named):
| def __init__(self, diagram, id=None):
super().__init__(diagram, id, width=50, height=30)
self.shape = Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
EditableText(text=lambda: self.subject.name or ""),
style={"padding": (4, 2... | 4, 12),
"border-radius": 15,
},
draw=draw_border,
)
self.watch("subject[NamedElement].name")
self.watch("subject.appliedStereotype.classifier.name")
@represents(UML.SendSignalAction)
class SendSignalActionItem(ElementPresentation, Named):
| 68 | 68 | 227 | 19 | 49 | milotype/gaphor | gaphor/UML/actions/action.py | Python | SendSignalActionItem | SendSignalActionItem | 31 | 59 | 31 | 32 | e152659ea39c47262d1143c3126c1be09e59da67 | bigcode/the-stack | train |
901fc11e2bff6eb0bbd77df0 | train | function | def _get_repo_path():
dir_path = Path(__file__).resolve()
repo_dir = dir_path.parents[2]
return repo_dir
| def _get_repo_path():
| dir_path = Path(__file__).resolve()
repo_dir = dir_path.parents[2]
return repo_dir
| import gc
import os
import json
import csv
import time
import math
import logging
import requests
import numpy as np
import pandas as pd
from pathlib import Path
from dotenv import load_dotenv
from configparser import ConfigParser
def _get_repo_path():
| 59 | 64 | 31 | 6 | 52 | naik-jay/initial-repo | src/pipelines/utilities.py | Python | _get_repo_path | _get_repo_path | 17 | 20 | 17 | 17 | d0d496910cf1fc9557d909f33d15d66f42a1d601 | bigcode/the-stack | train |
fed4d9cfc169fd9234fd5b52 | train | function | def _get_sql_query(file_name):
REPO_DIR = _get_repo_path()
with open(f'{REPO_DIR}/dags/sql/{file_name}.sql') as f:
query_template = f.read()
return query_template
| def _get_sql_query(file_name):
| REPO_DIR = _get_repo_path()
with open(f'{REPO_DIR}/dags/sql/{file_name}.sql') as f:
query_template = f.read()
return query_template
| _creds(name):
REPO_DIR = _get_repo_path()
credentials_env = f"{REPO_DIR}/src/.env"
# env
load_dotenv(dotenv_path=credentials_env)
creds = os.getenv(f"{name}")
return creds
def _get_sql_query(file_name):
| 64 | 64 | 51 | 8 | 55 | naik-jay/initial-repo | src/pipelines/utilities.py | Python | _get_sql_query | _get_sql_query | 34 | 40 | 34 | 35 | cf4e1c4f6264274858cd94c5ab94f49f353312c1 | bigcode/the-stack | train |
bb963f45c11f112fa7bb0bd7 | train | function | def _get_sql_2_df(file_name):
sql_query = _get_sql_query(file_name)
conn= _get_db_connection()
df = pd.read_sql(sql_query, conn)
return df | def _get_sql_2_df(file_name):
| sql_query = _get_sql_query(file_name)
conn= _get_db_connection()
df = pd.read_sql(sql_query, conn)
return df | creds
def _get_sql_query(file_name):
REPO_DIR = _get_repo_path()
with open(f'{REPO_DIR}/dags/sql/{file_name}.sql') as f:
query_template = f.read()
return query_template
def _get_sql_2_df(file_name):
| 64 | 64 | 44 | 11 | 52 | naik-jay/initial-repo | src/pipelines/utilities.py | Python | _get_sql_2_df | _get_sql_2_df | 42 | 47 | 42 | 43 | 48adebe1fec7c99d0abe7e6e20baa16b87e56590 | bigcode/the-stack | train |
c5e9e97d8e6a52221783c9ba | train | function | def _get_creds(name):
REPO_DIR = _get_repo_path()
credentials_env = f"{REPO_DIR}/src/.env"
# env
load_dotenv(dotenv_path=credentials_env)
creds = os.getenv(f"{name}")
return creds
| def _get_creds(name):
| REPO_DIR = _get_repo_path()
credentials_env = f"{REPO_DIR}/src/.env"
# env
load_dotenv(dotenv_path=credentials_env)
creds = os.getenv(f"{name}")
return creds
| as pd
from pathlib import Path
from dotenv import load_dotenv
from configparser import ConfigParser
def _get_repo_path():
dir_path = Path(__file__).resolve()
repo_dir = dir_path.parents[2]
return repo_dir
# utility functions:
def _get_creds(name):
| 64 | 64 | 59 | 7 | 57 | naik-jay/initial-repo | src/pipelines/utilities.py | Python | _get_creds | _get_creds | 23 | 31 | 23 | 24 | 12b678aae2e9ce0c3ab91ec020ceb5f23cdabd06 | bigcode/the-stack | train |
8e2aba68d8ecd00b4b68ee5e | train | function | def recvall(s, n):
"""Receive n bytes from a socket, or fail."""
rv = bytearray()
while n > 0:
d = s.recv(n)
if not d:
raise IOError('Unexpected end of stream')
rv.extend(d)
n -= len(d)
return rv
| def recvall(s, n):
| """Receive n bytes from a socket, or fail."""
rv = bytearray()
while n > 0:
d = s.recv(n)
if not d:
raise IOError('Unexpected end of stream')
rv.extend(d)
n -= len(d)
return rv
| ("TestFramework.socks5")
# Protocol constants
class Command:
CONNECT = 0x01
class AddressType:
IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
# Utility functions
def recvall(s, n):
| 64 | 64 | 68 | 7 | 56 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | recvall | recvall | 24 | 33 | 24 | 24 | 6c06705d3414ccfc3a554dc648d102d331db2011 | bigcode/the-stack | train |
25011643b8f0dd57e4834cc9 | train | class | class Command:
CONNECT = 0x01
| class Command:
| CONNECT = 0x01
| under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Dummy Socks5 server for testing."""
import socket
import threading
import queue
import logging
logger = logging.getLogger("TestFramework.socks5")
# Protocol constants
class Command:
| 64 | 64 | 11 | 3 | 60 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | Command | Command | 15 | 16 | 15 | 15 | 68299124b7419054d0caeb541520931147a11e0d | bigcode/the-stack | train |
d115e59e245c890188ce0a4b | train | class | class AddressType:
IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
| class AddressType:
| IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
| COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Dummy Socks5 server for testing."""
import socket
import threading
import queue
import logging
logger = logging.getLogger("TestFramework.socks5")
# Protocol constants
class Command:
CONNECT = 0x01
class AddressType:
| 64 | 64 | 31 | 4 | 59 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | AddressType | AddressType | 18 | 21 | 18 | 18 | 6e15793fd2a5010b357b65628737e35062f3953a | bigcode/the-stack | train |
de3df8cfd29466775239e348 | train | class | class Socks5Configuration():
"""Proxy configuration."""
def __init__(self):
self.addr = None # Bind address (must be set)
self.af = socket.AF_INET # Bind address family
self.unauth = False # Support unauthenticated
self.auth = False # Support authentication
| class Socks5Configuration():
| """Proxy configuration."""
def __init__(self):
self.addr = None # Bind address (must be set)
self.af = socket.AF_INET # Bind address family
self.unauth = False # Support unauthenticated
self.auth = False # Support authentication
| a socket, or fail."""
rv = bytearray()
while n > 0:
d = s.recv(n)
if not d:
raise IOError('Unexpected end of stream')
rv.extend(d)
n -= len(d)
return rv
# Implementation classes
class Socks5Configuration():
| 64 | 64 | 66 | 5 | 58 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | Socks5Configuration | Socks5Configuration | 36 | 42 | 36 | 36 | ea4bc71e19c57a0840e2a9ffccf578c9068f762b | bigcode/the-stack | train |
5babc39a2cba84d2a8f7bf2d | train | class | class Socks5Server():
def __init__(self, conf):
self.conf = conf
self.s = socket.socket(conf.af)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind(conf.addr)
self.s.listen(5)
self.running = False
self.thread = None
self.queue = q... | class Socks5Server():
| def __init__(self, conf):
self.conf = conf
self.s = socket.socket(conf.af)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind(conf.addr)
self.s.listen(5)
self.running = False
self.thread = None
self.queue = queue.Queue() # report ... | port, username, password)
self.serv.queue.put(cmdin)
logger.info('Proxy: %s', cmdin)
# Fall through to disconnect
except Exception as e:
logger.exception("socks5 request handling failed.")
self.serv.queue.put(e)
finally:
self.conn.... | 70 | 70 | 235 | 5 | 65 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | Socks5Server | Socks5Server | 126 | 159 | 126 | 126 | a27dd17af4c85f42a1b69a079e665b3f53d062dc | bigcode/the-stack | train |
71ddab7bfb25a70c49a2d313 | train | class | class Socks5Connection():
def __init__(self, serv, conn):
self.serv = serv
self.conn = conn
def handle(self):
"""Handle socks5 request according to RFC192."""
try:
# Verify socks version
ver = recvall(self.conn, 1)[0]
if ver != 0x05:
... | class Socks5Connection():
| def __init__(self, serv, conn):
self.serv = serv
self.conn = conn
def handle(self):
"""Handle socks5 request according to RFC192."""
try:
# Verify socks version
ver = recvall(self.conn, 1)[0]
if ver != 0x05:
raise IOError('Inva... | ."""
def __init__(self):
self.addr = None # Bind address (must be set)
self.af = socket.AF_INET # Bind address family
self.unauth = False # Support unauthenticated
self.auth = False # Support authentication
class Socks5Command():
"""Information about an incoming socks5 command... | 204 | 204 | 683 | 5 | 199 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | Socks5Connection | Socks5Connection | 56 | 124 | 56 | 56 | 8120fe40747c227be80c599406e7f1d848ee600f | bigcode/the-stack | train |
40e283eb91938f305ef6329d | train | class | class Socks5Command():
"""Information about an incoming socks5 command."""
def __init__(self, cmd, atyp, addr, port, username, password):
self.cmd = cmd # Command (one of Command.*)
self.atyp = atyp # Address type (one of AddressType.*)
self.addr = addr # Address
self.port = port... | class Socks5Command():
| """Information about an incoming socks5 command."""
def __init__(self, cmd, atyp, addr, port, username, password):
self.cmd = cmd # Command (one of Command.*)
self.atyp = atyp # Address type (one of AddressType.*)
self.addr = addr # Address
self.port = port # Port to connect to
... | Proxy configuration."""
def __init__(self):
self.addr = None # Bind address (must be set)
self.af = socket.AF_INET # Bind address family
self.unauth = False # Support unauthenticated
self.auth = False # Support authentication
class Socks5Command():
| 64 | 64 | 142 | 5 | 58 | Phonemetra/TurboCoin | test/functional/test_framework/socks5.py | Python | Socks5Command | Socks5Command | 44 | 54 | 44 | 44 | d064369c0886df94963659cf0be5da2efaf11a34 | bigcode/the-stack | train |
8dbfef8297f8dadddd708040 | train | class | class InductorMilHdbk217FResultPanel(MilHdbk217FResultPanel):
"""Displays Inductor assessment results attribute data.
The Inductor assessment result view displays all the assessment results
for the selected inductor. This includes, currently, results for
MIL-HDBK-217FN2 parts count and part stress met... | class InductorMilHdbk217FResultPanel(MilHdbk217FResultPanel):
| """Displays Inductor assessment results attribute data.
The Inductor assessment result view displays all the assessment results
for the selected inductor. This includes, currently, results for
MIL-HDBK-217FN2 parts count and part stress methods. The attributes of an
Inductor assessment result vie... | # -*- coding: utf-8 -*-
#
# ramstk.views.gtk3.hardware.components.inductor.py is part of the RAMSTK
# Project.
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Inductor Results Panel."""
# Standard Library Imports
from typing import Any, D... | 165 | 256 | 981 | 21 | 143 | TahaEntezari/ramstk | src/ramstk/views/gtk3/milhdbk217f/components/inductor.py | Python | InductorMilHdbk217FResultPanel | InductorMilHdbk217FResultPanel | 19 | 164 | 19 | 19 | 3a04cdf681f3a846147cc5e4c857ea820e6fe54e | bigcode/the-stack | train |
cd80f7a4895e8360e1215d77 | train | function | def update_cart(request, item_id):
"""This view lets the user update the quantity of an item in their cart"""
item = get_object_or_404(Product, pk=item_id)
quantity = int(request.POST.get('quantity'))
size = None
if 'item_size' in request.POST:
size = request.POST['item_size']
cart = req... | def update_cart(request, item_id):
| """This view lets the user update the quantity of an item in their cart"""
item = get_object_or_404(Product, pk=item_id)
quantity = int(request.POST.get('quantity'))
size = None
if 'item_size' in request.POST:
size = request.POST['item_size']
cart = request.session.get('cart', {})
i... | .keys()):
cart[item_id] += quantity
messages.success(request, f'Added {quantity}x {item.friendly_name}'
f' to your cart. You now have {cart[item_id]} of'
f' {item.friendly_name} in your cart')
else:
cart[item_id] = qua... | 121 | 121 | 405 | 8 | 113 | lbacon17/lb-fitness | cart/views.py | Python | update_cart | update_cart | 52 | 94 | 52 | 52 | 4d691dfcbfaafd8ef6d9d973ebf328cb9b7283b0 | bigcode/the-stack | train |
11c298740f63ece188431a18 | train | function | def add_item_to_cart(request, item_id):
"""This view lets the user add an item to their shopping cart"""
item = get_object_or_404(Product, pk=item_id)
quantity = int(request.POST.get('quantity'))
redirect_url = request.POST.get('redirect_url')
size = None
if 'item_size' in request.POST:
... | def add_item_to_cart(request, item_id):
| """This view lets the user add an item to their shopping cart"""
item = get_object_or_404(Product, pk=item_id)
quantity = int(request.POST.get('quantity'))
redirect_url = request.POST.get('redirect_url')
size = None
if 'item_size' in request.POST:
size = request.POST['item_size']
car... | from django.shortcuts import (
render, redirect, reverse, get_object_or_404, HttpResponse)
from django.contrib import messages
from shop.models import Product
from members.models import Member
def load_cart(request):
"""This view render's the user's cart contents"""
return render(request, 'cart/cart.html'... | 75 | 117 | 390 | 10 | 65 | lbacon17/lb-fitness | cart/views.py | Python | add_item_to_cart | add_item_to_cart | 13 | 49 | 13 | 13 | efd817492846b26466d007d1dd08a869dc278219 | bigcode/the-stack | train |
5fbf999b9a3ff219528d77cb | train | function | def remove_item_from_cart(request, item_id):
"""This view lets the user delete an item from their shopping cart"""
try:
item = get_object_or_404(Product, pk=item_id)
size = None
if 'item_size' in request.POST:
size = request.POST['item_size']
cart = request.session.ge... | def remove_item_from_cart(request, item_id):
| """This view lets the user delete an item from their shopping cart"""
try:
item = get_object_or_404(Product, pk=item_id)
size = None
if 'item_size' in request.POST:
size = request.POST['item_size']
cart = request.session.get('cart', {})
if size:
d... | {cart[item_id]}.')
else:
cart.pop(item_id)
messages.success(request, f'{item.friendly_name} was removed from '
'your cart.')
request.session['cart'] = cart
return redirect(reverse('load_cart'))
def remove_item_from_cart(request, item_id):
| 64 | 65 | 219 | 10 | 54 | lbacon17/lb-fitness | cart/views.py | Python | remove_item_from_cart | remove_item_from_cart | 97 | 123 | 97 | 97 | 2318e19ceaecacc14655e46a23e77dd44a0758ac | bigcode/the-stack | train |
e6bab8208c2ec342ef314770 | train | function | def load_cart(request):
"""This view render's the user's cart contents"""
return render(request, 'cart/cart.html')
| def load_cart(request):
| """This view render's the user's cart contents"""
return render(request, 'cart/cart.html')
| from django.shortcuts import (
render, redirect, reverse, get_object_or_404, HttpResponse)
from django.contrib import messages
from shop.models import Product
from members.models import Member
def load_cart(request):
| 44 | 64 | 26 | 5 | 38 | lbacon17/lb-fitness | cart/views.py | Python | load_cart | load_cart | 8 | 10 | 8 | 8 | 329cdf4480aa18c56c1ef8d0026ad7987fbaab33 | bigcode/the-stack | train |
f568ba64f6eefd78401e209e | train | function | def load_model(pickle_path: str, transformer_dir: str = 'transformer', max_len: int = 512, multi_class: bool = True):
"""
Load a Keras model that uses a Transformer layer.
:param pickle_path: path to pickle file containing learned weights from the last layer
:param transformer_dir: directory of saved m... | def load_model(pickle_path: str, transformer_dir: str = 'transformer', max_len: int = 512, multi_class: bool = True):
| """
Load a Keras model that uses a Transformer layer.
:param pickle_path: path to pickle file containing learned weights from the last layer
:param transformer_dir: directory of saved model
:param max_len: maximum length of encoded sequence
:param multi_class: if True, final layer is multiclass... | model.get_layer(index=3).get_weights()
pickle.dump(sigmoid, open(os.path.join(transformer_dir, 'sigmoid.pickle'), 'wb'))
def load_model(pickle_path: str, transformer_dir: str = 'transformer', max_len: int = 512, multi_class: bool = True):
| 66 | 67 | 224 | 33 | 33 | dnsosa/drug-lit-contradictory-claims | src/contradictory_claims/models/train_model.py | Python | load_model | load_model | 97 | 116 | 97 | 97 | 58277eeefcfa12a3d5a21f669de76115f7c5a216 | bigcode/the-stack | train |
19340a25866b3fe4800bf842 | train | function | def regular_encode(texts: list, tokenizer: transformers.AutoTokenizer, maxlen: int = 512):
"""
Encode sentences for input to Transformer models.
:param texts: list of strings to be encoded
:param tokenizer: tokenizer for encoding
:param maxlen: max number of characters of input string being encoded... | def regular_encode(texts: list, tokenizer: transformers.AutoTokenizer, maxlen: int = 512):
| """
Encode sentences for input to Transformer models.
:param texts: list of strings to be encoded
:param tokenizer: tokenizer for encoding
:param maxlen: max number of characters of input string being encoded
:return: numpy array of encoded strings
"""
# TODO: Intersphinx link to transf... | .keras.models import Model
from tensorflow.keras.optimizers import Adam
from transformers import AutoModel, AutoModelWithLMHead, AutoTokenizer, TFAutoModel
from wandb.keras import WandbCallback
def regular_encode(texts: list, tokenizer: transformers.AutoTokenizer, maxlen: int = 512):
| 64 | 64 | 174 | 22 | 41 | dnsosa/drug-lit-contradictory-claims | src/contradictory_claims/models/train_model.py | Python | regular_encode | regular_encode | 22 | 40 | 22 | 22 | 52821a2e89df7646ebb2b10d5d675fa017dd2006 | bigcode/the-stack | train |
95d5abc0abeb66f5ab48ad91 | train | function | def save_model(model, timed_dir_name: bool = True, transformer_dir: str = 'output/transformer'):
"""
Save a Keras model that uses a Transformer layer.
:param model: end-to-end Transformer model
:param timed_dir_name: if True, save model to a directory where date is recorded
:param transformer_dir: ... | def save_model(model, timed_dir_name: bool = True, transformer_dir: str = 'output/transformer'):
| """
Save a Keras model that uses a Transformer layer.
:param model: end-to-end Transformer model
:param timed_dir_name: if True, save model to a directory where date is recorded
:param transformer_dir: directory to save model
:return:
"""
if timed_dir_name:
now = datetime.dateti... | .compile(Adam(lr=1e-6), loss='binary_crossentropy',
metrics=[tf.keras.metrics.Recall(), tf.keras.metrics.Precision(), 'accuracy'])
return model
def save_model(model, timed_dir_name: bool = True, transformer_dir: str = 'output/transformer'):
| 64 | 64 | 195 | 24 | 39 | dnsosa/drug-lit-contradictory-claims | src/contradictory_claims/models/train_model.py | Python | save_model | save_model | 75 | 94 | 75 | 75 | 8cb4a20668f61327ba89e7fd9c5443664a526c64 | bigcode/the-stack | train |
a99f26f29d7b1377f047190d | train | function | def train_model(multi_nli_train_x: np.ndarray,
multi_nli_train_y: np.ndarray,
multi_nli_test_x: np.ndarray,
multi_nli_test_y: np.ndarray,
med_nli_train_x: np.ndarray,
med_nli_train_y: np.ndarray,
med_nli_test_x: np.ndarray,
... | def train_model(multi_nli_train_x: np.ndarray,
multi_nli_train_y: np.ndarray,
multi_nli_test_x: np.ndarray,
multi_nli_test_y: np.ndarray,
med_nli_train_x: np.ndarray,
med_nli_train_y: np.ndarray,
med_nli_test_x: np.ndarray,
... | """
Train the Transformer model.
:param multi_nli_train_x: MultiNLI training sentence pairs
:param multi_nli_train_y: MultiNLI training labels
:param multi_nli_test_x: MultiNLI test sentence pairs
:param multi_nli_test_y: MultiNLI test labels
:param med_nli_train_x: MedNLI training sentence... | 'rb'))
if multi_class:
model.get_layer('softmax').set_weights(sigmoid)
else:
model.get_layer('sigmoid').set_weights(sigmoid)
return model
def train_model(multi_nli_train_x: np.ndarray,
multi_nli_train_y: np.ndarray,
multi_nli_test_x: np.ndarray,
... | 256 | 256 | 1,771 | 215 | 40 | dnsosa/drug-lit-contradictory-claims | src/contradictory_claims/models/train_model.py | Python | train_model | train_model | 119 | 279 | 119 | 141 | 30306be43b8970c4bee314b61c65a414e4de60a6 | bigcode/the-stack | train |
ddc4558456793030f654394a | train | function | def build_model(transformer, max_len: int = 512, multi_class: bool = True): # noqa: D205
"""
Build an end-to-end Transformer model. Requires a transformer of type TFAutoBert.
https://www.kaggle.com/xhlulu/jigsaw-tpu-distilbert-with-huggingface-and-keras
:param transformer: Transformer model
:param... | def build_model(transformer, max_len: int = 512, multi_class: bool = True): # noqa: D205
| """
Build an end-to-end Transformer model. Requires a transformer of type TFAutoBert.
https://www.kaggle.com/xhlulu/jigsaw-tpu-distilbert-with-huggingface-and-keras
:param transformer: Transformer model
:param max_len: maximum length of encoded sequence
:param multi_class: if True, final layer ... | docs/source/conf.py?
enc_di = tokenizer.batch_encode_plus(texts,
return_attention_mask=False,
return_token_type_ids=False,
pad_to_max_length=True,
# se... | 101 | 102 | 343 | 28 | 73 | dnsosa/drug-lit-contradictory-claims | src/contradictory_claims/models/train_model.py | Python | build_model | build_model | 43 | 72 | 43 | 43 | d3aa41533c8349d60b14d9bcd649fab869881072 | bigcode/the-stack | train |
d0a8e6f62c72ac38d09d6a92 | train | class | class ResourceGuardProxyOperations(object):
"""ResourceGuardProxyOperations 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... | class ResourceGuardProxyOperations(object):
| """ResourceGuardProxyOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.recove... | # 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 ... | 224 | 256 | 3,007 | 7 | 217 | praveenkuttappan/azure-sdk-for-python | sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/operations/_resource_guard_proxy_operations.py | Python | ResourceGuardProxyOperations | ResourceGuardProxyOperations | 25 | 307 | 25 | 25 | 062deadc6024eb16aa363dc366cacc35a356a5aa | bigcode/the-stack | train |
364b8832cab619a6681103a1 | train | function | def set_cxx_flags_clib_hook(build_clib, build_info):
cc = build_clib.compiler
new_args = []
new_link_args = []
std_flag = get_cxx_std_flag(cc)
if std_flag is not None:
new_args.append(std_flag)
if sys.platform == 'darwin':
# Set min macOS version
min_macos_flag = '-mmac... | def set_cxx_flags_clib_hook(build_clib, build_info):
| cc = build_clib.compiler
new_args = []
new_link_args = []
std_flag = get_cxx_std_flag(cc)
if std_flag is not None:
new_args.append(std_flag)
if sys.platform == 'darwin':
# Set min macOS version
min_macos_flag = '-mmacosx-version-min=10.9'
if has_flag(cc, min_mac... | version
min_macos_flag = '-mmacosx-version-min=10.9'
if has_flag(cc, min_macos_flag):
args.append(min_macos_flag)
ext.extra_link_args.append(min_macos_flag)
def set_cxx_flags_clib_hook(build_clib, build_info):
| 64 | 64 | 144 | 15 | 49 | avivajpeyi/scipy | scipy/_build_utils/compiler_helper.py | Python | set_cxx_flags_clib_hook | set_cxx_flags_clib_hook | 87 | 104 | 87 | 87 | 5f3a369a7f89bcf9205b976e7dbb1b5a6726ee10 | bigcode/the-stack | train |
07d5f66fb77af1fbaeed9fa8 | train | function | def get_cxx_std_flag(compiler):
"""Detects compiler flag for c++14, c++11, or None if not detected"""
# GNU C compiler documentation uses single dash:
# https://gcc.gnu.org/onlinedocs/gcc/Standards.html
# but silently understands two dashes, like --std=c++11 too.
# Other GCC compatible compilers,... | def get_cxx_std_flag(compiler):
| """Detects compiler flag for c++14, c++11, or None if not detected"""
# GNU C compiler documentation uses single dash:
# https://gcc.gnu.org/onlinedocs/gcc/Standards.html
# but silently understands two dashes, like --std=c++11 too.
# Other GCC compatible compilers, like Intel C Compiler on Linux ... | output_dir=temp_dir, extra_postargs=flags)
except CompileError:
return False
return True
def has_flag(compiler, flag, ext=None):
"""Returns True if the compiler supports the given flag"""
return try_compile(compiler, flags=[flag], ext=ext)
def get_cxx_std_flag(compiler):
| 71 | 71 | 237 | 9 | 62 | avivajpeyi/scipy | scipy/_build_utils/compiler_helper.py | Python | get_cxx_std_flag | get_cxx_std_flag | 39 | 62 | 39 | 39 | 6cf4d7ddafd353d42235f4f785b98e94141f8bf1 | bigcode/the-stack | train |
24e9b29fc49097eed4d4da09 | train | function | def try_add_flag(args, compiler, flag, ext=None):
"""Appends flag to the list of arguments if supported by the compiler"""
if try_compile(compiler, flags=args+[flag], ext=ext):
args.append(flag)
| def try_add_flag(args, compiler, flag, ext=None):
| """Appends flag to the list of arguments if supported by the compiler"""
if try_compile(compiler, flags=args+[flag], ext=ext):
args.append(flag)
| flag in flags:
if flag is None:
return None
if has_flag(compiler, flag):
return flag
from numpy.distutils import log
log.warn('Could not detect c++ standard flag')
return None
def try_add_flag(args, compiler, flag, ext=None):
| 64 | 64 | 50 | 13 | 50 | avivajpeyi/scipy | scipy/_build_utils/compiler_helper.py | Python | try_add_flag | try_add_flag | 65 | 68 | 65 | 65 | e4740bd0d63b739f66d95ec1e3db6251b853e412 | bigcode/the-stack | train |
7d07579013c1b0d63044d988 | train | function | def has_flag(compiler, flag, ext=None):
"""Returns True if the compiler supports the given flag"""
return try_compile(compiler, flags=[flag], ext=ext)
| def has_flag(compiler, flag, ext=None):
| """Returns True if the compiler supports the given flag"""
return try_compile(compiler, flags=[flag], ext=ext)
| main'+ext)
with open(fname, 'w') as f:
f.write(code)
try:
compiler.compile([fname], output_dir=temp_dir, extra_postargs=flags)
except CompileError:
return False
return True
def has_flag(compiler, flag, ext=None):
| 64 | 64 | 38 | 11 | 52 | avivajpeyi/scipy | scipy/_build_utils/compiler_helper.py | Python | has_flag | has_flag | 34 | 36 | 34 | 34 | 162fd9e58a3121549e315594d4a8e1a025669a17 | bigcode/the-stack | train |
0e8167024d8f4e1ae361b304 | train | function | def set_cxx_flags_hook(build_ext, ext):
"""Sets basic compiler flags for compiling C++11 code"""
cc = build_ext._cxx_compiler
args = ext.extra_compile_args
std_flag = get_cxx_std_flag(cc)
if std_flag is not None:
args.append(std_flag)
if sys.platform == 'darwin':
# Set min macO... | def set_cxx_flags_hook(build_ext, ext):
| """Sets basic compiler flags for compiling C++11 code"""
cc = build_ext._cxx_compiler
args = ext.extra_compile_args
std_flag = get_cxx_std_flag(cc)
if std_flag is not None:
args.append(std_flag)
if sys.platform == 'darwin':
# Set min macOS version
min_macos_flag = '-mma... | return None
def try_add_flag(args, compiler, flag, ext=None):
"""Appends flag to the list of arguments if supported by the compiler"""
if try_compile(compiler, flags=args+[flag], ext=ext):
args.append(flag)
def set_cxx_flags_hook(build_ext, ext):
| 64 | 64 | 132 | 11 | 53 | avivajpeyi/scipy | scipy/_build_utils/compiler_helper.py | Python | set_cxx_flags_hook | set_cxx_flags_hook | 70 | 84 | 70 | 70 | d98f2c780845365c8d80545cec3f65fe29667d99 | bigcode/the-stack | train |
67fc9346c80894fde9ad78d6 | train | function | def try_compile(compiler, code=None, flags=[], ext=None):
"""Returns True if the compiler is able to compile the given code"""
from distutils.errors import CompileError
from numpy.distutils.fcompiler import FCompiler
if code is None:
if isinstance(compiler, FCompiler):
code = " ... | def try_compile(compiler, code=None, flags=[], ext=None):
| """Returns True if the compiler is able to compile the given code"""
from distutils.errors import CompileError
from numpy.distutils.fcompiler import FCompiler
if code is None:
if isinstance(compiler, FCompiler):
code = " program main\n return\n end"
else:
... | """
Helpers for detection of compiler features
"""
import tempfile
import os
import sys
from numpy.distutils.system_info import dict_append
def try_compile(compiler, code=None, flags=[], ext=None):
| 42 | 64 | 187 | 14 | 27 | avivajpeyi/scipy | scipy/_build_utils/compiler_helper.py | Python | try_compile | try_compile | 9 | 31 | 9 | 9 | a63cb89a279522e373bbb50194a535d6d750f4cc | bigcode/the-stack | train |
f3dff657bc01cd45dd3a9a48 | train | class | @testing_utils.skipIfCircleCI
class TestBB2Fid(unittest.TestCase):
"""
Test retrieval methods for BB2 with FiD.
"""
# BASIC Methods
def test_retrieval_all(self):
_test_bb2_fid(KnowledgeAccessMethod.ALL)
def test_retrieval_search_only(self):
_test_bb2_fid(KnowledgeAccessMethod.S... | @testing_utils.skipIfCircleCI
class TestBB2Fid(unittest.TestCase):
| """
Test retrieval methods for BB2 with FiD.
"""
# BASIC Methods
def test_retrieval_all(self):
_test_bb2_fid(KnowledgeAccessMethod.ALL)
def test_retrieval_search_only(self):
_test_bb2_fid(KnowledgeAccessMethod.SEARCH_ONLY)
def test_retrieval_memory_only(self):
_tes... | KnowledgeAccessMethod.CLASSIFY,
query_generator_model_file=SEARCH_QUERY_MODEL,
)
def test_retrieval_none(self):
_test_bb2_rag(KnowledgeAccessMethod.NONE, n_docs=1)
@testing_utils.skipIfCircleCI
class TestBB2Fid(unittest.TestCase):
| 64 | 64 | 179 | 18 | 46 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2Fid | TestBB2Fid | 91 | 114 | 91 | 92 | d32f4b5e2004173c3bdf5ecc65fc5a2b5a1a527e | bigcode/the-stack | train |
98f2cb178d0a1f5d3a29ad38 | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2AdditionalTruncation(unittest.TestCase):
"""
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_mode... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2AdditionalTruncation(unittest.TestCase):
| """
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='token',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='searc... | search_server=SEARCH_SERVER,
query_generator_beam_size=3,
query_generator_beam_min_length=2,
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2AdditionalTruncation(unittest.TestCase):
| 64 | 64 | 136 | 37 | 27 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2AdditionalTruncation | TestBB2AdditionalTruncation | 206 | 224 | 206 | 208 | f2c16fb680d17317cde8c3ede1eea0c42f823ca5 | bigcode/the-stack | train |
79657ad92b4a0bf415144481 | train | class | @unittest.skipUnless(TRANSFORMER_INSTALLED, "Needs transformer, not installed.")
class TestBB2ZooModel(unittest.TestCase):
"""
Test Zoo Model.
"""
def test_zoo_model(self):
_test_bb2_fid(
KnowledgeAccessMethod.CLASSIFY,
n_docs=3,
batchsize=1,
task... | @unittest.skipUnless(TRANSFORMER_INSTALLED, "Needs transformer, not installed.")
class TestBB2ZooModel(unittest.TestCase):
| """
Test Zoo Model.
"""
def test_zoo_model(self):
_test_bb2_fid(
KnowledgeAccessMethod.CLASSIFY,
n_docs=3,
batchsize=1,
task='wizard_of_internet',
model_file=ZOO_BB2,
rag_retriever_type='dpr',
indexer_type='comp... | search_server=SEARCH_SERVER,
insert_gold_docs=True,
task='wizard_of_internet',
memory_decoder_model_file=PERSONA_SUMMARY_MODEL,
)
@unittest.skipUnless(TRANSFORMER_INSTALLED, "Needs transformer, not installed.")
class TestBB2ZooModel(unittest.TestCase):
| 64 | 64 | 215 | 29 | 35 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2ZooModel | TestBB2ZooModel | 270 | 298 | 270 | 271 | 11955d05b4e1c5d3d9f0eef8d1532438742524fb | bigcode/the-stack | train |
302db080c9847d75156d1f71 | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2Search(unittest.TestCase):
"""
Test Search functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='token',
... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2Search(unittest.TestCase):
| """
Test Search functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='token',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='search_... | rag_model_type='turn',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2Search(unittest.TestCase):
| 64 | 64 | 113 | 34 | 30 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2Search | TestBB2Search | 147 | 163 | 147 | 149 | f5ae3d5b0275221f0e735a02ecee4c49d9b79f27 | bigcode/the-stack | train |
bbf632d2bebe0f0bc74faace | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2MemoryDecoder(unittest.TestCase):
"""
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type=... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2MemoryDecoder(unittest.TestCase):
| """
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='sequence',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='se... | iever_type='search_engine',
search_server=SEARCH_SERVER,
insert_gold_docs=True,
task='wizard_of_internet',
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2MemoryDecoder(unittest.TestCase):
| 64 | 64 | 142 | 35 | 29 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2MemoryDecoder | TestBB2MemoryDecoder | 248 | 267 | 248 | 250 | d6cd7c007cb007d4462ae2fbdb9aab9b892624ab | bigcode/the-stack | train |
8cc3d0d5b0a24b83b388f8c5 | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2RagTurn(unittest.TestCase):
"""
Test RAG Turn functionality.
"""
def test_rag_turn(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2RagTurn(unittest.TestCase):
| """
Test RAG Turn functionality.
"""
def test_rag_turn(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='turn',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
)
| _encoders(self):
_test_bb2_fid(
KnowledgeAccessMethod.ALL, share_search_and_memory_query_encoder=True
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2RagTurn(unittest.TestCase):
| 64 | 64 | 101 | 36 | 28 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2RagTurn | TestBB2RagTurn | 130 | 144 | 130 | 132 | 4a7e1699b7299997b72a9e0f740303bd488342f7 | bigcode/the-stack | train |
b4222cfa776fa9a4bee8b9c7 | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2RagSequence(unittest.TestCase):
"""
Test RAG Sequence functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_typ... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2RagSequence(unittest.TestCase):
| """
Test RAG Sequence functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='sequence',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type... | query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='search_engine',
search_server=SEARCH_SERVER,
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2RagSequence(unittest.TestCase):
| 64 | 64 | 117 | 36 | 28 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2RagSequence | TestBB2RagSequence | 166 | 182 | 166 | 168 | 9d8d83499540ce4cad1399feb8ddca2c31a2e3e1 | bigcode/the-stack | train |
95aabd695fc23a2f6391ddaf | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestLongTermMemory(unittest.TestCase):
"""
Test LongTermMemory functionality.
"""
def test_shared_encoders(self):
_test_bb2_fid(
KnowledgeAccessMethod.ALL, share_search_and... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestLongTermMemory(unittest.TestCase):
| """
Test LongTermMemory functionality.
"""
def test_shared_encoders(self):
_test_bb2_fid(
KnowledgeAccessMethod.ALL, share_search_and_memory_query_encoder=True
)
| )
def test_retrieval_none(self):
_test_bb2_fid(KnowledgeAccessMethod.NONE, n_docs=1)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestLongTermMemory(unittest.TestCase):
| 64 | 64 | 77 | 34 | 30 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestLongTermMemory | TestLongTermMemory | 117 | 127 | 117 | 119 | 47e7b658378374937af808242fc351d2c88fb97b | bigcode/the-stack | train |
110cee05c102aab888986049 | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2QGenParams(unittest.TestCase):
"""
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='to... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2QGenParams(unittest.TestCase):
| """
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='token',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='searc... | query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='search_engine',
search_server=SEARCH_SERVER,
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2QGenParams(unittest.TestCase):
| 64 | 64 | 136 | 36 | 28 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2QGenParams | TestBB2QGenParams | 185 | 203 | 185 | 187 | 4d05acd2bfca80d97b3370300c9e6b21c0d79ece | bigcode/the-stack | train |
8c77e44c4a035f71779e266c | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2GoldDocs(unittest.TestCase):
"""
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='sequ... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2GoldDocs(unittest.TestCase):
| """
Test RAG Turn functionality.
"""
def test_rag(self):
_test_bb2_rag(
KnowledgeAccessMethod.CLASSIFY,
rag_model_type='sequence',
n_docs=3,
batchsize=1,
query_generator_model_file=SEARCH_QUERY_MODEL,
rag_retriever_type='se... | _engine',
search_server=SEARCH_SERVER,
query_generator_truncate=24,
memory_retriever_truncate=24,
)
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2GoldDocs(unittest.TestCase):
| 64 | 64 | 130 | 35 | 29 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2GoldDocs | TestBB2GoldDocs | 227 | 245 | 227 | 229 | 332607455daf734b71604f798aef3a2f564666d9 | bigcode/the-stack | train |
5072f859e0bc837607ba26ab | train | class | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2Rag(unittest.TestCase):
"""
Test retrieval methods for BB2 with RAG.
"""
def test_retrieval_all(self):
_test_bb2_rag(KnowledgeAccessMethod.ALL)
def test_retrieval_search_on... | @testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2Rag(unittest.TestCase):
| """
Test retrieval methods for BB2 with RAG.
"""
def test_retrieval_all(self):
_test_bb2_rag(KnowledgeAccessMethod.ALL)
def test_retrieval_search_only(self):
_test_bb2_rag(KnowledgeAccessMethod.SEARCH_ONLY)
def test_retrieval_memory_only(self):
_test_bb2_rag(KnowledgeA... | '] = retrieval_method.value
opt.update(dict(kwargs))
testing_utils.eval_model(opt, skip_test=True)
torch.cuda.empty_cache()
@testing_utils.skipUnlessGPU
@unittest.skipIf(LOCAL, "Skipping Test because its slow and mem intensive")
class TestBB2Rag(unittest.TestCase):
| 64 | 64 | 191 | 35 | 29 | twstewart42/ParlAI | tests/nightly/gpu/test_bb2.py | Python | TestBB2Rag | TestBB2Rag | 65 | 88 | 65 | 67 | b9bd7064109f8a9f7641f66b6eb174c0a5f25a48 | bigcode/the-stack | train |
d8c2dbdd30feb54951b307d3 | train | function | def test_FiducialRegistration_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
fixedLandmarks=dict(argstr='--fixedLandmarks %s...',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
movingLandmarks=dict(argstr='--movin... | def test_FiducialRegistration_inputs():
| input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
fixedLandmarks=dict(argstr='--fixedLandmarks %s...',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
movingLandmarks=dict(argstr='--movingLandmarks %s...',
),
outputMess... | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from .....testing import assert_equal
from ..specialized import FiducialRegistration
def test_FiducialRegistration_inputs():
| 42 | 64 | 213 | 9 | 32 | Conxz/nipype | nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py | Python | test_FiducialRegistration_inputs | test_FiducialRegistration_inputs | 6 | 35 | 6 | 6 | 00e838a12d72b56975c365098a6a5acb4dabe9f7 | bigcode/the-stack | train |
9e24bc2d14803c4b6b16d2e2 | train | function | def test_FiducialRegistration_outputs():
output_map = dict(saveTransform=dict(),
)
outputs = FiducialRegistration.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey), v... | def test_FiducialRegistration_outputs():
| output_map = dict(saveTransform=dict(),
)
outputs = FiducialRegistration.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey), value
| s',
),
)
inputs = FiducialRegistration.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_FiducialRegistration_outputs():
| 64 | 64 | 69 | 9 | 54 | Conxz/nipype | nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py | Python | test_FiducialRegistration_outputs | test_FiducialRegistration_outputs | 38 | 45 | 38 | 38 | 82fb34855dc14c23bd53f9e4abd35681ff864704 | bigcode/the-stack | train |
5c5613324266bd3d5a0ef2e9 | train | class | class MandateNonSepaDirectDebit(DataObject):
__payment_product705_specific_data = None
__payment_product730_specific_data = None
@property
def payment_product705_specific_data(self):
"""
| Object containing specific data for Direct Debit UK
Type: :class:`ingenico.conne... | class MandateNonSepaDirectDebit(DataObject):
| __payment_product705_specific_data = None
__payment_product730_specific_data = None
@property
def payment_product705_specific_data(self):
"""
| Object containing specific data for Direct Debit UK
Type: :class:`ingenico.connect.sdk.domain.token.definitions.token_non_sepa... | # -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.data_object import DataObject
from ingenico.connect.sdk.domain.token.definitions.token_non_sepa_direct_debit_payment_product705_specific_data i... | 133 | 158 | 528 | 11 | 121 | festicket/connect-sdk-python3 | ingenico/connect/sdk/domain/token/definitions/mandate_non_sepa_direct_debit.py | Python | MandateNonSepaDirectDebit | MandateNonSepaDirectDebit | 11 | 62 | 11 | 12 | 972da80236dc903033564e2e17241253b12d84a6 | bigcode/the-stack | train |
5632fe2366f46fdac0de580d | train | class | class HeatmapGenerator:
"""Generate heatmaps for bottom-up models.
Args:
num_joints (int): Number of keypoints
output_size (int): Size of feature map
sigma (int): Sigma of the heatmaps.
use_udp (bool): To use unbiased data processing.
Paper ref: Huang et al. The Devi... | class HeatmapGenerator:
| """Generate heatmaps for bottom-up models.
Args:
num_joints (int): Number of keypoints
output_size (int): Size of feature map
sigma (int): Sigma of the heatmaps.
use_udp (bool): To use unbiased data processing.
Paper ref: Huang et al. The Devil is in the Details: Del... | (float): Current scale
min_scale (float): Minimal scale
Returns:
tuple: A tuple containing image info.
- image_resized (tuple): size of resize image
- center (np.ndarray): center of image
- scale (np.ndarray): scale
"""
size_resized, _, _ = _get_multi_scale_size(im... | 210 | 210 | 703 | 5 | 204 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | HeatmapGenerator | HeatmapGenerator | 129 | 192 | 129 | 129 | 70df46fa415c4b5814de2cb2e8904b90e0a7319f | bigcode/the-stack | train |
8a0a144ec26bad5bfccbe134 | train | class | @PIPELINES.register_module()
class BottomUpRandomFlip:
"""Data augmentation with random image flip for bottom-up.
Args:
flip_prob (float): Probability of flip.
"""
def __init__(self, flip_prob=0.5):
self.flip_prob = flip_prob
def __call__(self, results):
"""Perform data au... | @PIPELINES.register_module()
class BottomUpRandomFlip:
| """Data augmentation with random image flip for bottom-up.
Args:
flip_prob (float): Probability of flip.
"""
def __init__(self, flip_prob=0.5):
self.flip_prob = flip_prob
def __call__(self, results):
"""Perform data augmentation with random image flip."""
image, ma... | 0 and dst[2] > 0:
self._accumulate_paf_map_(pafs[2 * idx:2 * idx + 2],
src[:2], dst[:2], count)
pafs[2 * idx:2 * idx + 2] /= np.maximum(count, 1)
return pafs
@PIPELINES.register_module()
class BottomUpRandomFlip:
| 84 | 84 | 283 | 12 | 71 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | BottomUpRandomFlip | BottomUpRandomFlip | 326 | 357 | 326 | 327 | 78b954082adecea5a58fb74f4f26426e106a381e | bigcode/the-stack | train |
5ec7e61e44edcf376b7603cc | train | class | @PIPELINES.register_module()
class BottomUpRandomAffine:
"""Data augmentation with random scaling & rotating.
Args:
rot_factor (int): Rotating to [-rotation_factor, rotation_factor]
scale_factor (float): Scaling to [1-scale_factor, 1+scale_factor]
scale_type: wrt ``long`` or ``short`` l... | @PIPELINES.register_module()
class BottomUpRandomAffine:
| """Data augmentation with random scaling & rotating.
Args:
rot_factor (int): Rotating to [-rotation_factor, rotation_factor]
scale_factor (float): Scaling to [1-scale_factor, 1+scale_factor]
scale_type: wrt ``long`` or ``short`` length of the image.
trans_factor: Translation fac... | def __init__(self, flip_prob=0.5):
self.flip_prob = flip_prob
def __call__(self, results):
"""Perform data augmentation with random image flip."""
image, mask, joints = results['img'], results['mask'], results[
'joints']
self.flip_index = results['ann_info']['flip_in... | 256 | 256 | 1,546 | 12 | 243 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | BottomUpRandomAffine | BottomUpRandomAffine | 360 | 505 | 360 | 361 | 690677446cbb8b918c690f54a489e351560659d4 | bigcode/the-stack | train |
641acb42cd6aebae1894c567 | train | class | @PIPELINES.register_module()
class BottomUpGeneratePAFTarget:
"""Generate multi-scale heatmaps and part affinity fields (PAF) target for
bottom-up. Paper ref: Cao et al. Realtime Multi-Person 2D Human Pose
Estimation using Part Affinity Fields (CVPR 2017).
Args:
limb_width (int): Limb width of ... | @PIPELINES.register_module()
class BottomUpGeneratePAFTarget:
| """Generate multi-scale heatmaps and part affinity fields (PAF) target for
bottom-up. Paper ref: Cao et al. Realtime Multi-Person 2D Human Pose
Estimation using Part Affinity Fields (CVPR 2017).
Args:
limb_width (int): Limb width of part affinity fields
"""
def __init__(self, limb_widt... | _list[scale_id])
target_list.append(target_t.astype(np.float32))
mask_list[scale_id] = mask_list[scale_id].astype(np.float32)
joints_list[scale_id] = joints_t.astype(np.int32)
results['img'], results['masks'], results[
'joints'] = img, mask_list, joints_list
... | 103 | 103 | 345 | 14 | 88 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | BottomUpGeneratePAFTarget | BottomUpGeneratePAFTarget | 601 | 644 | 601 | 602 | ea5458e9ed3a1858f0e02cd477c1b1bb332046c3 | bigcode/the-stack | train |
ec9da0d7a70bb1b5dda5a8ec | train | function | def _resize_align_multi_scale_udp(image, input_size, current_scale, min_scale):
"""Resize the images for multi-scale training.
Args:
image: Input image
input_size (int): Size of the image input
current_scale (float): Current scale
min_scale (float): Minimal scale
Returns:
... | def _resize_align_multi_scale_udp(image, input_size, current_scale, min_scale):
| """Resize the images for multi-scale training.
Args:
image: Input image
input_size (int): Size of the image input
current_scale (float): Current scale
min_scale (float): Minimal scale
Returns:
tuple: A tuple containing image info.
- image_resized (tuple): s... | (
image, input_size, current_scale, min_scale)
trans = get_affine_transform(center, scale, 0, size_resized)
image_resized = cv2.warpAffine(image, trans, size_resized)
return image_resized, center, scale
def _resize_align_multi_scale_udp(image, input_size, current_scale, min_scale):
| 77 | 77 | 257 | 18 | 58 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | _resize_align_multi_scale_udp | _resize_align_multi_scale_udp | 96 | 126 | 96 | 96 | be102087fff0b3ffbf3aa5ff444496c9952ba135 | bigcode/the-stack | train |
d38ad7f6eab7bbcb7f22c2c0 | train | class | class PAFGenerator:
"""Generate part affinity fields.
Args:
output_size (int): Size of feature map.
limb_width (int): Limb width of part affinity fields.
skeleton (list[list]): connections of joints.
"""
def __init__(self, output_size, limb_width, skeleton):
self.output... | class PAFGenerator:
| """Generate part affinity fields.
Args:
output_size (int): Size of feature map.
limb_width (int): Limb width of part affinity fields.
skeleton (list[list]): connections of joints.
"""
def __init__(self, output_size, limb_width, skeleton):
self.output_size = output_size
... | points: K
max number of people in an image: M
Args:
joints (np.ndarray[NxKx3])
Returns:
visible_kpts (np.ndarray[MxKx2]).
"""
visible_kpts = np.zeros((self.max_num_people, self.num_joints, 2),
dtype=np.float32)
... | 230 | 230 | 767 | 5 | 224 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | PAFGenerator | PAFGenerator | 245 | 323 | 245 | 245 | 848bf7be9e011974dd2956a0ae85ea36d83ad558 | bigcode/the-stack | train |
27208e317d0f0c21611a3e2a | train | class | @PIPELINES.register_module()
class BottomUpGetImgSize:
"""Get multi-scale image sizes for bottom-up, including base_size and
test_scale_factor. Keep the ratio and the image is resized to
`results['ann_info']['image_size']×current_scale`.
Args:
test_scale_factor (List[float]): Multi scale
... | @PIPELINES.register_module()
class BottomUpGetImgSize:
| """Get multi-scale image sizes for bottom-up, including base_size and
test_scale_factor. Keep the ratio and the image is resized to
`results['ann_info']['image_size']×current_scale`.
Args:
test_scale_factor (List[float]): Multi scale
current_scale (int): default 1
use_udp (bool)... | output_size in heatmap_size
]
return paf_generator
def __call__(self, results):
"""Generate multi-scale part affinity fields for bottom-up."""
if self.skeleton is None:
assert results['ann_info']['skeleton'] is not None
self.skeleton = results['ann_info']['s... | 202 | 202 | 675 | 13 | 188 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | BottomUpGetImgSize | BottomUpGetImgSize | 647 | 709 | 647 | 648 | 8205a7ef25c19e2a39ac68954c22f3fa10d7595e | bigcode/the-stack | train |
397674f751fb9dc11a48fd28 | train | function | def _resize_align_multi_scale(image, input_size, current_scale, min_scale):
"""Resize the images for multi-scale training.
Args:
image: Input image
input_size (int): Size of the image input
current_scale (float): Current scale
min_scale (float): Minimal scale
Returns:
... | def _resize_align_multi_scale(image, input_size, current_scale, min_scale):
| """Resize the images for multi-scale training.
Args:
image: Input image
input_size (int): Size of the image input
current_scale (float): Current scale
min_scale (float): Minimal scale
Returns:
tuple: A tuple containing image info.
- image_resized (tuple): s... | else:
center = np.array([round(w / 2.0), round(h / 2.0)])
return (w_resized, h_resized), center, np.array([scale_w, scale_h])
def _resize_align_multi_scale(image, input_size, current_scale, min_scale):
| 64 | 64 | 186 | 17 | 47 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | _resize_align_multi_scale | _resize_align_multi_scale | 71 | 93 | 71 | 71 | b9b922c7064ea60c029ba98169fb541f62e7dc3a | bigcode/the-stack | train |
99bc4317e26862223ba5ddaf | train | class | @PIPELINES.register_module()
class BottomUpGenerateTarget:
"""Generate multi-scale heatmap target for bottom-up.
Args:
sigma (int): Sigma of heatmap Gaussian
max_num_people (int): Maximum number of people in an image
use_udp (bool): To use unbiased data processing.
Paper ref... | @PIPELINES.register_module()
class BottomUpGenerateTarget:
| """Generate multi-scale heatmap target for bottom-up.
Args:
sigma (int): Sigma of heatmap Gaussian
max_num_people (int): Maximum number of people in an image
use_udp (bool): To use unbiased data processing.
Paper ref: Huang et al. The Devil is in the Details: Delving into
... | heatmap_generator
def __call__(self, results):
"""Generate multi-scale heatmap target for bottom-up."""
heatmap_generator = \
self._generate(results['ann_info']['num_joints'],
results['ann_info']['heatmap_size'])
target_list = list()
joints_li... | 139 | 139 | 465 | 12 | 126 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | BottomUpGenerateTarget | BottomUpGenerateTarget | 548 | 598 | 548 | 549 | 6f1615a7b4fde4706a1bb75c071cd0cea5af5ccf | bigcode/the-stack | train |
85aca184d8b4a951069e8d57 | train | class | @PIPELINES.register_module()
class BottomUpGenerateHeatmapTarget:
"""Generate multi-scale heatmap target for bottom-up.
Args:
sigma (int): Sigma of heatmap Gaussian
max_num_people (int): Maximum number of people in an image
use_udp (bool): To use unbiased data processing.
Pa... | @PIPELINES.register_module()
class BottomUpGenerateHeatmapTarget:
| """Generate multi-scale heatmap target for bottom-up.
Args:
sigma (int): Sigma of heatmap Gaussian
max_num_people (int): Maximum number of people in an image
use_udp (bool): To use unbiased data processing.
Paper ref: Huang et al. The Devil is in the Details: Delving into
... | _input = self._get_affine_matrix(center, scale,
(self.input_size,
self.input_size), aug_rot)[:2]
image = cv2.warpAffine(image, mat_input, (self.input_size.item(),
... | 95 | 95 | 319 | 14 | 80 | SummerVideoAnalysis/mmpose | mmpose/datasets/pipelines/bottom_up_transform.py | Python | BottomUpGenerateHeatmapTarget | BottomUpGenerateHeatmapTarget | 508 | 545 | 508 | 509 | bf44821420b84711128aeb18f59544d92bdaf6be | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.