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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8f19e59cc40e5e8a288f407a | train | function | def main():
issue = """# Issue
I can't see any difference in the Panel specific implementation of the Plotly and Holoviews pages.
Still only the Holoviews page shows! The Plotly page does not!"""
home = pn.pane.Markdown(issue, name="Issue")
holoviews = holoviews_page()
plotly = plotly_page()
page_... | def main():
| issue = """# Issue
I can't see any difference in the Panel specific implementation of the Plotly and Holoviews pages.
Still only the Holoviews page shows! The Plotly page does not!"""
home = pn.pane.Markdown(issue, name="Issue")
holoviews = holoviews_page()
plotly = plotly_page()
page_outlet = pn.... | .layout.width = 1000
return fig
def plotly_page(*args, **kwargs) -> pn.Column:
fig = plotly_fig()
return pn.Column(pn.pane.Markdown("# Plotly"), fig, name="Plotly", sizing_mode="stretch_both",)
def main():
| 64 | 64 | 186 | 3 | 61 | philippjfr/awesome-panel | scripts/issues/issue840_plotly_does_not_show.py | Python | main | main | 74 | 94 | 74 | 74 | d2ff988697ca5e4e9f8de45b7dbd135dae743ebf | bigcode/the-stack | train |
b2ffe07772663af4aadaf34a | train | function | def navigation_button(page, page_outlet):
button = pn.widgets.Button(name=page.name)
def navigate_to_page(event):
page_outlet.clear()
page_outlet.append(page)
button.on_click(navigate_to_page)
return button
| def navigation_button(page, page_outlet):
| button = pn.widgets.Button(name=page.name)
def navigate_to_page(event):
page_outlet.clear()
page_outlet.append(page)
button.on_click(navigate_to_page)
return button
| as hv
import hvplot.pandas
import pandas as pd
import param
from plotly import express as px
import panel as pn
pn.extension("plotly") # Hack: See https://github.com/holoviz/panel/issues/840
def navigation_button(page, page_outlet):
| 64 | 64 | 53 | 9 | 54 | philippjfr/awesome-panel | scripts/issues/issue840_plotly_does_not_show.py | Python | navigation_button | navigation_button | 12 | 20 | 12 | 12 | a26eebf09e9ba467edac39db0eb6cc0e91d05634 | bigcode/the-stack | train |
d1f5e79977b1d2d28e181dec | train | class | class AlignDlib:
"""
Use `dlib's landmark estimation <http://blog.dlib.net/2014/08/real-time-face-pose-estimation.html>`_ to align faces.
The alignment preprocess faces for input into a neural network.
Faces are resized to the same size (such as 96x96) and transformed
to make landmarks (such as the... | class AlignDlib:
| """
Use `dlib's landmark estimation <http://blog.dlib.net/2014/08/real-time-face-pose-estimation.html>`_ to align faces.
The alignment preprocess faces for input into a neural network.
Faces are resized to the same size (such as 96x96) and transformed
to make landmarks (such as the eyes and nose) a... | 0.805236879972),
(0.576410514055, 0.835436670169), (0.525398405766, 0.841706377792),
(0.47641545769, 0.837505914975), (0.41379548902, 0.810045601727),
(0.380084785646, 0.749979603086), (0.477955996282, 0.74513234612),
(0.523389793327, 0.748924302636), (0.571057789237, 0.74332894691),
(0.672409137852... | 256 | 256 | 1,112 | 5 | 251 | gokceuludogan/FaceIdentificationInArtwork | align.py | Python | AlignDlib | AlignDlib | 61 | 188 | 61 | 61 | 0be452acd4138c95e315fbd02a064e2548f584af | bigcode/the-stack | train |
c1581661e0c48cf98fcf78e8 | train | class | class TestRequirements(unittest.TestCase):
def test_aiotruenas_client_synced(self) -> None:
manifest_version = [
r[1] for r in self._get_manifest_data() if r[0] == CLIENT_LIBRARY
]
requirements_dev_version = [
r[1] for r in self._get_requirements_dev_data() if r[0] ==... | class TestRequirements(unittest.TestCase):
| def test_aiotruenas_client_synced(self) -> None:
manifest_version = [
r[1] for r in self._get_manifest_data() if r[0] == CLIENT_LIBRARY
]
requirements_dev_version = [
r[1] for r in self._get_requirements_dev_data() if r[0] == CLIENT_LIBRARY
]
self.asse... | "
MANIFEST_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"..",
"custom_components",
"truenas",
"manifest.json",
)
REQUIREMENTS_DEV_FILE = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "requirements-dev.txt"
)
class TestRequirements(unittest.TestCase):
| 78 | 78 | 261 | 7 | 71 | sdwilsh/hass-freenas | tests/test_requirements.py | Python | TestRequirements | TestRequirements | 21 | 48 | 21 | 21 | 19d242656f5d438d48ec81c8274c07f4cfc95f2d | bigcode/the-stack | train |
14218aca5c050a1868ec18ca | train | function | @skip("https://github.com/threefoldtech/jumpscaleX_core/issues/493")
def test_tmux():
"""
kosmos -p 'j.servers.myjobs.test("tmux")'
"""
myjobs._test_setup()
assert len(myjobs.workers.find()) == 0
myjobs.workers_tmux_start(2)
assert len(myjobs.workers.find()) == 2
found = False
tim... | @skip("https://github.com/threefoldtech/jumpscaleX_core/issues/493")
def test_tmux():
| """
kosmos -p 'j.servers.myjobs.test("tmux")'
"""
myjobs._test_setup()
assert len(myjobs.workers.find()) == 0
myjobs.workers_tmux_start(2)
assert len(myjobs.workers.find()) == 2
found = False
timeend = j.data.time.epoch + 20
while not found and j.data.time.epoch < timeend:
... | import gevent
from Jumpscale import j
import time
myjobs = j.servers.myjobs
skip = j.baseclasses.testtools._skip
@skip("https://github.com/threefoldtech/jumpscaleX_core/issues/493")
def test_tmux():
| 58 | 153 | 513 | 25 | 32 | gneumann333/jumpscaleX_core | JumpscaleCore/servers/myjobs/tests/8_tmux.py | Python | test_tmux | test_tmux | 12 | 73 | 12 | 13 | 39228b4027b29b182e774f42f63d2305726d53c4 | bigcode/the-stack | train |
49d5dc2604e24414235877d6 | train | class | class Line(Element):
_description = [
("elements", "", "List of elements", ()),
("element_names", "", "List of element names", ()),
]
_extra = []
def __len__(self):
assert len(self.elements) == len(self.element_names)
return len(self.elements)
def to_dict(self, keep... | class Line(Element):
| _description = [
("elements", "", "List of elements", ()),
("element_names", "", "List of element names", ()),
]
_extra = []
def __len__(self):
assert len(self.elements) == len(self.element_names)
return len(self.elements)
def to_dict(self, keepextra=False):
... | import numpy as np
from .base_classes import Element
from . import elements
from .particles import Particles
from .loader_sixtrack import _expand_struct
from .loader_mad import iter_from_madx_sequence
from .closed_orbit import linearize_around_closed_orbit
from .closed_orbit import healy_symplectify
from .linear_norm... | 107 | 256 | 4,537 | 4 | 103 | carlidel/pysixtrack | pysixtrack/line.py | Python | Line | Line | 18 | 584 | 18 | 18 | eefb36c8b9c5c033d886e05986a186e326394dc1 | bigcode/the-stack | train |
d80f166e254665d852965ae4 | train | class | class PrintEpoch(keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
global current_epoch, first_epoch_start
#remaining_epochs = epochs - epoch
current_epoch = epoch
print('current epoch ' + str(current_epoch))
global epoch_begin_time
epoch_begin_ti... | class PrintEpoch(keras.callbacks.Callback):
| def on_epoch_begin(self, epoch, logs=None):
global current_epoch, first_epoch_start
#remaining_epochs = epochs - epoch
current_epoch = epoch
print('current epoch ' + str(current_epoch))
global epoch_begin_time
epoch_begin_time = time.time()
if epoch == startin... | .node, 10002, message)
sys.exit()
signal.signal(signal.SIGTERM, terminateProcess)
#################################################################################
logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name
tensorboard_callback = TensorBoard(log_dir=logdir)#, update_freq='ba... | 83 | 83 | 277 | 8 | 74 | boringlee24/keras_old | examples/pwr_run/checkpointing/final/no_threshold/job62.py | Python | PrintEpoch | PrintEpoch | 179 | 206 | 179 | 179 | 50f1145acdcf2a22d33537b513c016d0150b4265 | bigcode/the-stack | train |
48499889ebc56fa7230cb062 | train | function | def terminateProcess(signalNumber, frame):
# first record the wasted epoch time
global epoch_begin_time
if epoch_begin_time == 0:
epoch_waste_time = 0
else:
epoch_waste_time = int(time.time() - epoch_begin_time)
message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 1... | def terminateProcess(signalNumber, frame):
# first record the wasted epoch time
| global epoch_begin_time
if epoch_begin_time == 0:
epoch_waste_time = 0
else:
epoch_waste_time = int(time.time() - epoch_begin_time)
message = job_name + ' waste ' + str(epoch_waste_time) # 'job50 waste 100'
if epoch_waste_time > 0:
send_signal.send(args.node, 10002, message)... | optimizer=Adam(lr=args_lr),
metrics=['accuracy'])
#model.summary()
print(model_type)
#pdb.set_trace()
current_epoch = 0
################### connects interrupt signal to the process #####################
def terminateProcess(signalNumber, frame):
# first record the wasted epoch tim... | 64 | 64 | 208 | 17 | 46 | boringlee24/keras_old | examples/pwr_run/checkpointing/final/no_threshold/job62.py | Python | terminateProcess | terminateProcess | 145 | 167 | 145 | 146 | 19c1b3dcfafe792047f95659c077871b99fab81d | bigcode/the-stack | train |
5f5d1ed1905ff4e9e5a048ca | train | class | @httprettified
class StatsSendTest(StatsClientTest):
def test_stats_sending(self):
self.stats_server = "http://127.0.0.1:22"
self.postman = Postman(
stats_server=self.stats_server,
vnc_client=self.vnc_client,
logger=init_logger(
log_level=logging.... | @httprettified
class StatsSendTest(StatsClientTest):
| def test_stats_sending(self):
self.stats_server = "http://127.0.0.1:22"
self.postman = Postman(
stats_server=self.stats_server,
vnc_client=self.vnc_client,
logger=init_logger(
log_level=logging.DEBUG, log_file="tests_stats.txt"))
self.vnc_c... | ]}
send_freq = self.scheduler._get_updated_send_freq()
self.assertEqual(send_freq, timedelta(days=1))
def test_get_updated_send_freq_swithched_off(self):
self.vnc_client.tags_list.return_value = {"tags":
[{"fq_name": ["test"]}]}
sen... | 96 | 96 | 322 | 15 | 81 | Dmitry-Eremeev/contrail-controller | src/stats/stats/tests/test_common.py | Python | StatsSendTest | StatsSendTest | 45 | 75 | 45 | 47 | 7b904ed8395a0d49ca001c036f1a66108b946887 | bigcode/the-stack | train |
94bac4e7f83f714a7b34a62d | train | class | class StatsClientTest(TestCase):
def setUp(self):
self.vnc_client = Mock()
| class StatsClientTest(TestCase):
| def setUp(self):
self.vnc_client = Mock()
| from mock import Mock
from unittest import TestCase
from datetime import timedelta
import logging
from httpretty import httprettified, register_uri, POST, last_request
from stats.main import Scheduler, Postman, Stats, init_logger
class StatsClientTest(TestCase):
| 57 | 64 | 21 | 7 | 49 | Dmitry-Eremeev/contrail-controller | src/stats/stats/tests/test_common.py | Python | StatsClientTest | StatsClientTest | 9 | 11 | 9 | 9 | 3a8f7771c0d78df8ab04b5f94f381b092feb2566 | bigcode/the-stack | train |
9d584a5a2e53edbcd336ffb6 | train | class | class UpdatedSendFreqTest(StatsClientTest):
def setUp(self):
super(UpdatedSendFreqTest, self).setUp()
self.vnc_client.tags_list.return_value = {"tags": []}
self.scheduler = Scheduler(self.vnc_client, state="test")
def test_get_updated_send_freq_monthly(self):
self.vnc_client.tag... | class UpdatedSendFreqTest(StatsClientTest):
| def setUp(self):
super(UpdatedSendFreqTest, self).setUp()
self.vnc_client.tags_list.return_value = {"tags": []}
self.scheduler = Scheduler(self.vnc_client, state="test")
def test_get_updated_send_freq_monthly(self):
self.vnc_client.tags_list.return_value = {"tags": [
... | from mock import Mock
from unittest import TestCase
from datetime import timedelta
import logging
from httpretty import httprettified, register_uri, POST, last_request
from stats.main import Scheduler, Postman, Stats, init_logger
class StatsClientTest(TestCase):
def setUp(self):
self.vnc_client = Mock()
c... | 81 | 84 | 281 | 10 | 71 | Dmitry-Eremeev/contrail-controller | src/stats/stats/tests/test_common.py | Python | UpdatedSendFreqTest | UpdatedSendFreqTest | 14 | 42 | 14 | 14 | 9bdc70c5946eea7fb70f46a0d71f8e7ffa86580a | bigcode/the-stack | train |
db333a8cc2926a4fe37ac3ed | train | function | def send_templated_email(subject, template_name, context,
recipients, sender=None, bcc=None,
fail_silently=True, files=None):
"""
send_templated_mail() is a wrapper around Django's e-mail routines that
allows us to easily send multipart (text/plain & text/ht... | def send_templated_email(subject, template_name, context,
recipients, sender=None, bcc=None,
fail_silently=True, files=None):
| """
send_templated_mail() is a wrapper around Django's e-mail routines that
allows us to easily send multipart (text/plain & text/html) e-mails using
templates that are stored in the database. This lets the admin provide
both a text and a HTML template for each message.
template_name is the slu... | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template import Context, loader
from django.utils.html import strip_tags
def send_templated_email(subject, template_name, context,
recipients, sender=None, bcc=None,
fail_si... | 65 | 131 | 439 | 33 | 31 | timgates42/django-leonardo | leonardo/utils/emails.py | Python | send_templated_email | send_templated_email | 7 | 66 | 7 | 9 | ff8e2a2ac9973b5e29720ebd598c1521bf7f0e3f | bigcode/the-stack | train |
08b16a31c8040d7570baa97f | train | function | def solve():
squares = [str(i**2).zfill(2) for i in range(1, 10)]
def test(cube1, cube2):
for cube in [cube1, cube2]:
if "6" in cube:
cube.append("9")
if "9" in cube:
cube.append("6")
for square in squares:
x, y = square
... | def solve():
| squares = [str(i**2).zfill(2) for i in range(1, 10)]
def test(cube1, cube2):
for cube in [cube1, cube2]:
if "6" in cube:
cube.append("9")
if "9" in cube:
cube.append("6")
for square in squares:
x, y = square
if (x n... | # Cube digit pairs
from itertools import combinations
def solve():
| 13 | 102 | 340 | 3 | 9 | wephy/project-euler | python/p090.py | Python | solve | solve | 6 | 39 | 6 | 6 | 0816359666dc00785bb1881e68424c6b39c13206 | bigcode/the-stack | train |
76f6924547e9041d1adde969 | train | class | class Launcher(LoggingConfigurable):
"""Object for encapsulating launching an image for a user"""
hub_api_token = Unicode(help="The API token for the Hub")
hub_url = Unicode(help="The URL of the Hub")
async def api_request(self, url, *args, **kwargs):
"""Make an API request to JupyterHub"""
... | class Launcher(LoggingConfigurable):
| """Object for encapsulating launching an image for a user"""
hub_api_token = Unicode(help="The API token for the Hub")
hub_url = Unicode(help="The URL of the Hub")
async def api_request(self, url, *args, **kwargs):
"""Make an API request to JupyterHub"""
headers = kwargs.setdefault('he... | """
Launch an image with a temporary user via JupyterHub
"""
import base64
import json
import random
import re
import string
from urllib.parse import urlparse
import uuid
from tornado.log import app_log
from tornado import web, gen
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError
from traitlets.c... | 208 | 256 | 937 | 7 | 200 | adl/binderhub | binderhub/launcher.py | Python | Launcher | Launcher | 28 | 147 | 28 | 28 | 5edc89916874a76b77b4c29020e82e915112efbe | bigcode/the-stack | train |
96cd3ed9461bd6ef7b165bdd | train | class | class TestMode64(unittest.TestCase):
Derefs = ["RAX", "RCX", "RDX", "RBX", "RBP", "RSI", "RDI"]
DerefsInfo = [Regs.RAX, Regs.RCX, Regs.RDX, Regs.RBX, Regs.RBP, Regs.RSI, Regs.RDI]
def test_none(self):
self.assertFalse(len(I64("cdq").inst.operands) > 0)
def test_imm8(self):
I64("int 0x55").check_imm(0, 0x5... | class TestMode64(unittest.TestCase):
| Derefs = ["RAX", "RCX", "RDX", "RBX", "RBP", "RSI", "RDI"]
DerefsInfo = [Regs.RAX, Regs.RCX, Regs.RDX, Regs.RBX, Regs.RBP, Regs.RSI, Regs.RDI]
def test_none(self):
self.assertFalse(len(I64("cdq").inst.operands) > 0)
def test_imm8(self):
I64("int 0x55").check_imm(0, 0x55, 8)
def test_imm16(self):
I64("... | eref(1, self.IndicesInfo[i[0]], self.BasesInfo[j[0]], 8)
self.assertFalse(a.inst.operands[1].dispSize != 8)
self.assertFalse(a.inst.operands[1].disp != 0x55)
if s != 1:
self.assertFalse(a.inst.operands[1].scale != s)
def test_sib_disp32(self):
for i in enumerate(self.Indices):
for j in... | 256 | 256 | 5,891 | 8 | 248 | akx/distorm | examples/tests/test_distorm3.py | Python | TestMode64 | TestMode64 | 673 | 993 | 673 | 673 | 22391a51971c2b21d452c28ed4947a5d81d24354 | bigcode/the-stack | train |
894b8135d65054a4b8ec8ba3 | train | class | class TestInvalid(unittest.TestCase):
def align(self):
for i in range(15):
IB32("90")
def test_filter_mem(self):
#cmpxchg8b eax
IB32("0fc7c8")
self.align()
def test_drop_prefixes(self):
# Drop prefixes when we encountered an instruction that couldn't be decoded.
IB32("666764ffff")
self.al... | class TestInvalid(unittest.TestCase):
| def align(self):
for i in range(15):
IB32("90")
def test_filter_mem(self):
#cmpxchg8b eax
IB32("0fc7c8")
self.align()
def test_drop_prefixes(self):
# Drop prefixes when we encountered an instruction that couldn't be decoded.
IB32("666764ffff")
self.align()
def test_zzz_must_be_last_drop_... | .unusedPrefixesMask, 2)
self.assertEqual(IB64("48660f10c0").inst.unusedPrefixesMask, 1)
self.assertEqual(IB64("664f0f10c0").inst.unusedPrefixesMask, 0)
class TestInvalid(unittest.TestCase):
| 64 | 64 | 127 | 7 | 57 | akx/distorm | examples/tests/test_distorm3.py | Python | TestInvalid | TestInvalid | 1,596 | 1,610 | 1,596 | 1,596 | a9e90b2fe80474445ca8f329645433b325dada21 | bigcode/the-stack | train |
8c6eb7e11e8cfe5468136905 | train | class | class TestPrefixes(unittest.TestCase):
Derefs16 = ["BX + SI", "BX + DI", "BP + SI", "BP + DI", "SI", "DI", "BP", "BX"]
Derefs32 = ["EAX", "ECX", "EDX", "EBX", "EBP", "ESI", "EDI"]
Bases = ["EAX", "ECX", "EDX", "EBX", "ESP", "ESI", "EDI"]
def test_without_seg(self):
self.assertEqual(I64("and [rip+0X5247], ch"... | class TestPrefixes(unittest.TestCase):
| Derefs16 = ["BX + SI", "BX + DI", "BP + SI", "BP + DI", "SI", "DI", "BP", "BX"]
Derefs32 = ["EAX", "ECX", "EDX", "EBX", "EBP", "ESI", "EDI"]
Bases = ["EAX", "ECX", "EDX", "EBX", "ESP", "ESI", "EDI"]
def test_without_seg(self):
self.assertEqual(I64("and [rip+0X5247], ch").inst.segment, REG_NONE)
self.assert... | .check_type_size(0,distorm3.OPERAND_IMMEDIATE, 8)
a.check_addr_size(16)
a = I32("loopz 0x50")
a.check_type_size(0,distorm3.OPERAND_IMMEDIATE, 8)
a.check_addr_size(32)
a = I64("loopz 0x50")
a.check_type_size(0,distorm3.OPERAND_IMMEDIATE, 8)
a.check_addr_size(64)
a = I16("db 0x67\n loopz 0x50")
... | 256 | 256 | 1,713 | 7 | 249 | akx/distorm | examples/tests/test_distorm3.py | Python | TestPrefixes | TestPrefixes | 1,488 | 1,594 | 1,488 | 1,488 | 3f8da039d03c1789051bbae4cdf20e3ca1209c8c | bigcode/the-stack | train |
fdaef38d21de2978bd4f66f0 | train | function | def ABS64(x):
return x
| def ABS64(x):
| return x
| 0):
return InstBin(bin, Decode32Bits, features)
def I64(instText, features = 0):
return Inst(instText, Decode64Bits, 0, features)
def IB64(bin, features = 0):
return InstBin(bin, Decode64Bits, features)
def ABS64(x):
| 64 | 64 | 8 | 5 | 59 | akx/distorm | examples/tests/test_distorm3.py | Python | ABS64 | ABS64 | 154 | 155 | 154 | 154 | 33fd94060874eea94f89f47e999298f2092a158c | bigcode/the-stack | train |
85a281fc27689ac3aeadb18b | train | function | def I64(instText, features = 0):
return Inst(instText, Decode64Bits, 0, features)
| def I64(instText, features = 0):
| return Inst(instText, Decode64Bits, 0, features)
| Bits, instNo, features)
def I32(instText, features = 0):
return Inst(instText, Decode32Bits, 0, features)
def IB32(bin, features = 0):
return InstBin(bin, Decode32Bits, features)
def I64(instText, features = 0):
| 64 | 64 | 25 | 11 | 53 | akx/distorm | examples/tests/test_distorm3.py | Python | I64 | I64 | 148 | 149 | 148 | 148 | 4bce54613cd6745e52a1b553e5933a64c881e572 | bigcode/the-stack | train |
11e609f0d1397ac1df8ec2dd | train | function | def initfiles():
for i in ["bin16", "bin32", "bin64"]:
fbin.append(open("build\\linux\\"+i, "wb"))
| def initfiles():
| for i in ["bin16", "bin32", "bin64"]:
fbin.append(open("build\\linux\\"+i, "wb"))
| ].address, 5)
self.assertEqual(a[5].mnemonic, "DEC")
self.assertEqual(a[5].size, 1)
def GetNewSuite(className):
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(className))
return suite
def initfiles():
| 64 | 64 | 36 | 4 | 59 | akx/distorm | examples/tests/test_distorm3.py | Python | initfiles | initfiles | 1,673 | 1,675 | 1,673 | 1,673 | 08094e5635acf4cbb787a099ccd7685874ebc416 | bigcode/the-stack | train |
96f0e53d443eee93a01c1270 | train | function | def I32(instText, features = 0):
return Inst(instText, Decode32Bits, 0, features)
| def I32(instText, features = 0):
| return Inst(instText, Decode32Bits, 0, features)
| , 2: 64}[(self.inst.rawFlags >> 10) & 3], sz)
def I16(instText, instNo = 0, features = 0):
return Inst(instText, Decode16Bits, instNo, features)
def I32(instText, features = 0):
| 64 | 64 | 25 | 11 | 53 | akx/distorm | examples/tests/test_distorm3.py | Python | I32 | I32 | 142 | 143 | 142 | 142 | 34c0f2b2177a01bcdd4035fa34a77f53a4e9881e | bigcode/the-stack | train |
058ec60d77e605b526a68172 | train | class | class TestMode32(unittest.TestCase):
Derefs = ["EAX", "ECX", "EDX", "EBX", "EBP", "ESI", "EDI"]
DerefsInfo = [Regs.EAX, Regs.ECX, Regs.EDX, Regs.EBX, Regs.EBP, Regs.ESI, Regs.EDI]
def test_none(self):
self.assertFalse(len(I32("cdq").inst.operands) > 0)
def test_imm8(self):
I32("int 0x55").check_imm(0, 0x5... | class TestMode32(unittest.TestCase):
| Derefs = ["EAX", "ECX", "EDX", "EBX", "EBP", "ESI", "EDI"]
DerefsInfo = [Regs.EAX, Regs.ECX, Regs.EDX, Regs.EBX, Regs.EBP, Regs.ESI, Regs.EDI]
def test_none(self):
self.assertFalse(len(I32("cdq").inst.operands) > 0)
def test_imm8(self):
I32("int 0x55").check_imm(0, 0x55, 8)
def test_imm16(self):
I32("... | .DerefsInfo[i[0]][1], self.DerefsInfo[i[0]][0], 16)
else:
a.check_simple_deref(0, self.DerefsInfo[i[0]][0], 16)
self.assertFalse(a.inst.operands[0].dispSize != 8)
self.assertFalse(a.inst.operands[0].disp != 0x55)
def test_modrm_disp16(self):
texts = ["ADD [%s + 0x3322], AX" % i for i in self.Deref... | 256 | 256 | 4,769 | 8 | 248 | akx/distorm | examples/tests/test_distorm3.py | Python | TestMode32 | TestMode32 | 389 | 671 | 389 | 389 | fdfa8c4badf13bb999fcdf824084d25c97ba9d72 | bigcode/the-stack | train |
c0d1d5af9663f674a5389ab2 | train | class | class TestMode16(unittest.TestCase):
Derefs = ["BX + SI", "BX + DI", "BP + SI", "BP + DI", "SI", "DI", "BP", "BX"]
DerefsInfo = [(Regs.BX, Regs.SI), (Regs.BX, Regs.DI), (Regs.BP, Regs.SI), (Regs.BP, Regs.DI),
(Regs.SI,), (Regs.DI,), (Regs.BP,), (Regs.BX,)]
def test_none(self):
self.assertFalse(len(I16("... | class TestMode16(unittest.TestCase):
| Derefs = ["BX + SI", "BX + DI", "BP + SI", "BP + DI", "SI", "DI", "BP", "BX"]
DerefsInfo = [(Regs.BX, Regs.SI), (Regs.BX, Regs.DI), (Regs.BP, Regs.SI), (Regs.BP, Regs.DI),
(Regs.SI,), (Regs.DI,), (Regs.BP,), (Regs.BX,)]
def test_none(self):
self.assertFalse(len(I16("cbw").inst.operands) > 0)
def test_i... | )
self.assertEqual(self.inst.operands[n].base, base)
def check_type_size(self, n, t, sz):
self.assertEqual(self.inst.operands[n].type, t)
self.assertEqual(self.inst.operands[n].size, sz)
def check_addr_size(self, sz):
self.assertEqual({0: 16, 1: 32, 2: 64}[(self.inst.rawFlags >> 10) & 3], sz)
def... | 256 | 256 | 3,844 | 8 | 248 | akx/distorm | examples/tests/test_distorm3.py | Python | TestMode16 | TestMode16 | 158 | 387 | 158 | 158 | 9e0304aed4b50e6a2c35eade501d2c4076980a05 | bigcode/the-stack | train |
2bb29347dcc8bf53dacbf99b | train | class | class TestAVXOperands(unittest.TestCase):
def test_rm32(self):
#I16("vextractps eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
I32("vextractps eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
I64("vextractps eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
def test_reg32_64_m8(self):
#I16("vpextrb eax, xmm2, 3").check_reg... | class TestAVXOperands(unittest.TestCase):
| def test_rm32(self):
#I16("vextractps eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
I32("vextractps eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
I64("vextractps eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
def test_reg32_64_m8(self):
#I16("vpextrb eax, xmm2, 3").check_reg(0, Regs.EAX, 32)
I32("vpextrb eax, xmm2... | _invalid() # longer form of 0f, ae /02, invalid pp=3
IB32("c4c17877").check_mnemonic("VZEROUPPER") # longer form of 0f, 77
IB32("c4c17c77").check_mnemonic("VZEROALL") # longer form of 0f, 77
IB32("c4c97c77").check_invalid() # longer form of 0f, 77, invalid mmmmm
def test_crc32(self):
I32("crc32 eax, al").... | 256 | 256 | 2,310 | 9 | 247 | akx/distorm | examples/tests/test_distorm3.py | Python | TestAVXOperands | TestAVXOperands | 1,131 | 1,222 | 1,131 | 1,131 | 453d1eb7601338797d14e95260b20a4465b51d4e | bigcode/the-stack | train |
5d4986dc3efc11ff3a7f42d8 | train | function | def IB64(bin, features = 0):
return InstBin(bin, Decode64Bits, features)
| def IB64(bin, features = 0):
| return InstBin(bin, Decode64Bits, features)
| 32Bits, 0, features)
def IB32(bin, features = 0):
return InstBin(bin, Decode32Bits, features)
def I64(instText, features = 0):
return Inst(instText, Decode64Bits, 0, features)
def IB64(bin, features = 0):
| 64 | 64 | 21 | 10 | 54 | akx/distorm | examples/tests/test_distorm3.py | Python | IB64 | IB64 | 151 | 152 | 151 | 151 | 111553c11419b595d374a24368558b542525a3f8 | bigcode/the-stack | train |
ffa856929fa563f1b1f6cf0e | train | class | class InstBin(Test):
def __init__(self, bin, mode, features):
Test.__init__(self)
try:
bin = bin.decode("hex")
except:
bin = bytes.fromhex(bin)
#fbin[mode].write(bin)
self.insts = Decompose(0, bin, mode, features)
self.inst = self.insts[0]
def check_valid(self, instsNo = 1):
self.assert... | class InstBin(Test):
| def __init__(self, bin, mode, features):
Test.__init__(self)
try:
bin = bin.decode("hex")
except:
bin = bytes.fromhex(bin)
#fbin[mode].write(bin)
self.insts = Decompose(0, bin, mode, features)
self.inst = self.insts[0]
def check_valid(self, instsNo = 1):
self.assertNotEqual(self.inst.raw... | = open("1", "rb").read()
#if (not isinstance(s, str)):
return s
class Test(unittest.TestCase):
def __init__(self):
unittest.TestCase.__init__(self, "test_dummy")
def test_dummy(self):
self.fail("dummy")
class InstBin(Test):
| 64 | 64 | 187 | 5 | 59 | akx/distorm | examples/tests/test_distorm3.py | Python | InstBin | InstBin | 57 | 74 | 57 | 57 | afcf2f18ef0428652c2a8f4d8488334c8f494139 | bigcode/the-stack | train |
53e98e2fc75b75aca0877376 | train | class | class TestFeatures(unittest.TestCase):
def test_addr16(self):
#I16("mov [-4], bx", 0, DF_MAXIMUM_ADDR16).check_disp(0, 0xfffc, 16, 16)
pass
def test_add32(self):
pass
def test_fc(self):
pairs = [
(["INT 5", "db 0xf1", "INT 3", "INTO", "UD2"], distorm3.FlowControl.INT),
(["CALL 0x50", "CALL FAR... | class TestFeatures(unittest.TestCase):
| def test_addr16(self):
#I16("mov [-4], bx", 0, DF_MAXIMUM_ADDR16).check_disp(0, 0xfffc, 16, 16)
pass
def test_add32(self):
pass
def test_fc(self):
pairs = [
(["INT 5", "db 0xf1", "INT 3", "INTO", "UD2"], distorm3.FlowControl.INT),
(["CALL 0x50", "CALL FAR [ebx]"], distorm3.FlowControl.CALL),
... | r + "90").inst.unusedPrefixesMask, (1 << r) - 1)
def test_rexw_66(self):
self.assertEqual(IB64("6648ffc0").inst.unusedPrefixesMask, 1)
self.assertEqual(IB64("6640ffc0").inst.unusedPrefixesMask, 2)
self.assertEqual(IB64("48660f10c0").inst.unusedPrefixesMask, 1)
self.assertEqual(IB64("664f0f10c0").inst.unus... | 256 | 256 | 917 | 7 | 249 | akx/distorm | examples/tests/test_distorm3.py | Python | TestFeatures | TestFeatures | 1,612 | 1,666 | 1,612 | 1,612 | 57b810dab9f6ed7b4610b4eb577cc5d6d3c92eb7 | bigcode/the-stack | train |
64541fd9feb9ddcbed2d4638 | train | function | def GetNewSuite(className):
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(className))
return suite
| def GetNewSuite(className):
| suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(className))
return suite
| "JMP")
self.assertEqual(a[4].size, 2)
self.assertEqual(a[5].address, 5)
self.assertEqual(a[5].mnemonic, "DEC")
self.assertEqual(a[5].size, 1)
def GetNewSuite(className):
| 64 | 64 | 27 | 7 | 57 | akx/distorm | examples/tests/test_distorm3.py | Python | GetNewSuite | GetNewSuite | 1,668 | 1,671 | 1,668 | 1,668 | 9f0338f352b8362af21e25af52994f335a7133e3 | bigcode/the-stack | train |
f94f3c873ab37c0182f5d83a | train | class | class TestMisc(unittest.TestCase):
def test_lods(self):
a = I16("lodsb")
a.check_reg(0, Regs.AL, 8)
a.check_simple_deref(1, Regs.SI, 8)
self.assertEqual(a.inst.isSegmentDefault, True)
a = I32("lodsw")
a.check_reg(0, Regs.AX, 16)
a.check_simple_deref(1, Regs.ESI, 16)
self.assertEqual(a.inst.isS... | class TestMisc(unittest.TestCase):
| def test_lods(self):
a = I16("lodsb")
a.check_reg(0, Regs.AL, 8)
a.check_simple_deref(1, Regs.SI, 8)
self.assertEqual(a.inst.isSegmentDefault, True)
a = I32("lodsw")
a.check_reg(0, Regs.AX, 16)
a.check_simple_deref(1, Regs.ESI, 16)
self.assertEqual(a.inst.isSegmentDefault, True)
a = I32("lod... | ("vcvtdq2pd ymm1, [ebx]").check_simple_deref(1, Regs.EBX, 128)
I64("vcvtdq2pd xmm1, xmm12").check_reg(1, Regs.XMM12, 128)
I64("vcvtdq2pd xmm1, [rax]").check_simple_deref(1, Regs.RAX, 64)
I64("vcvtdq2pd ymm1, [rbx]").check_simple_deref(1, Regs.RBX, 128)
def test_lmem128_256(self):
I32("vlddqu xmm1, [eax]")... | 256 | 256 | 3,907 | 7 | 249 | akx/distorm | examples/tests/test_distorm3.py | Python | TestMisc | TestMisc | 1,224 | 1,486 | 1,224 | 1,224 | ead31d85872e2d6458a3e44c8bd87e4c13035672 | bigcode/the-stack | train |
a54e0f6613ec6da03bd81206 | train | class | class Registers(object):
def __init__(self):
for i in enumerate(_REGISTERS):
if len(i[1]):
setattr(self, i[1], i[0])
| class Registers(object):
| def __init__(self):
for i in enumerate(_REGISTERS):
if len(i[1]):
setattr(self, i[1], i[0])
| 14", "YMM15",
"CR0", "", "CR2", "CR3", "CR4", "", "", "", "CR8",
"DR0", "DR1", "DR2", "DR3", "", "", "DR6", "DR7"]
class Registers(object):
| 63 | 64 | 41 | 4 | 59 | akx/distorm | examples/tests/test_distorm3.py | Python | Registers | Registers | 28 | 32 | 28 | 28 | 98467319711f1e9192674de9ebd8d25f86ded5f2 | bigcode/the-stack | train |
187b6dd3c372658eac96785b | train | class | class Inst(Test):
def __init__(self, instText, mode, instNo, features):
Test.__init__(self)
modeSize = [16, 32, 64][mode]
bin = Assemble(instText, modeSize)
#print map(lambda x: hex(ord(x)), bin)
#fbin[mode].write(bin)
self.insts = Decompose(0, bin, mode, features)
self.inst = self.insts[instNo]
... | class Inst(Test):
| def __init__(self, instText, mode, instNo, features):
Test.__init__(self)
modeSize = [16, 32, 64][mode]
bin = Assemble(instText, modeSize)
#print map(lambda x: hex(ord(x)), bin)
#fbin[mode].write(bin)
self.insts = Decompose(0, bin, mode, features)
self.inst = self.insts[instNo]
def check_mnemo... | , str)):
return s
class Test(unittest.TestCase):
def __init__(self):
unittest.TestCase.__init__(self, "test_dummy")
def test_dummy(self):
self.fail("dummy")
class InstBin(Test):
def __init__(self, bin, mode, features):
Test.__init__(self)
try:
bin = bin.decode("hex")
except:
bin = b... | 234 | 234 | 780 | 4 | 230 | akx/distorm | examples/tests/test_distorm3.py | Python | Inst | Inst | 76 | 137 | 76 | 76 | 7ebcb28f90bf7982ba247ee7d3f9419dd1330c2e | bigcode/the-stack | train |
3450fc006e102b0eb8d28591 | train | function | def IB32(bin, features = 0):
return InstBin(bin, Decode32Bits, features)
| def IB32(bin, features = 0):
| return InstBin(bin, Decode32Bits, features)
| 16(instText, instNo = 0, features = 0):
return Inst(instText, Decode16Bits, instNo, features)
def I32(instText, features = 0):
return Inst(instText, Decode32Bits, 0, features)
def IB32(bin, features = 0):
| 64 | 64 | 21 | 10 | 54 | akx/distorm | examples/tests/test_distorm3.py | Python | IB32 | IB32 | 145 | 146 | 145 | 145 | d9d09f06eac89b144416491c00dda489c744292e | bigcode/the-stack | train |
a3b9a4aed72dedb17c80207c | train | function | def Assemble(text, mode):
lines = text.replace("\n", "\r\n")
if mode is None:
mode = 32
lines = ("bits %d\r\n" % mode) + lines
open("1.asm", "wb").write(lines.encode())
if mode == 64:
mode = "amd64"
else:
mode = "x86"
os.system("c:\\yasm -m%s 1.asm" % mode)
s = open("1", "rb").read()
#if (not... | def Assemble(text, mode):
| lines = text.replace("\n", "\r\n")
if mode is None:
mode = 32
lines = ("bits %d\r\n" % mode) + lines
open("1.asm", "wb").write(lines.encode())
if mode == 64:
mode = "amd64"
else:
mode = "x86"
os.system("c:\\yasm -m%s 1.asm" % mode)
s = open("1", "rb").read()
#if (not isinstance(s, str)):
ret... | DR6", "DR7"]
class Registers(object):
def __init__(self):
for i in enumerate(_REGISTERS):
if len(i[1]):
setattr(self, i[1], i[0])
Regs = Registers()
fbin = []
def Assemble(text, mode):
| 63 | 64 | 117 | 6 | 57 | akx/distorm | examples/tests/test_distorm3.py | Python | Assemble | Assemble | 36 | 49 | 36 | 36 | d2a5648c12decdbbaac474939394ffbba4c7e02b | bigcode/the-stack | train |
4f3a88ae8b3553fbdcdb8bfd | train | function | def I16(instText, instNo = 0, features = 0):
return Inst(instText, Decode16Bits, instNo, features)
| def I16(instText, instNo = 0, features = 0):
| return Inst(instText, Decode16Bits, instNo, features)
| sz)
def check_addr_size(self, sz):
self.assertEqual({0: 16, 1: 32, 2: 64}[(self.inst.rawFlags >> 10) & 3], sz)
def I16(instText, instNo = 0, features = 0):
| 64 | 64 | 31 | 17 | 47 | akx/distorm | examples/tests/test_distorm3.py | Python | I16 | I16 | 139 | 140 | 139 | 139 | 90af5737209bbde2c8c4210f757c330d46f6d34d | bigcode/the-stack | train |
8bfc1e53a4a230db559e6992 | train | class | class TestInstTable(unittest.TestCase):
""" Check that locate_inst algorithm covers all opcode-length (ol)
for the varying sizes of opcodes.
The bad tests should not find an instruction, so they should fail on purpose,
to see we don't crash the diassembler.
Also test for some end-cases with no... | class TestInstTable(unittest.TestCase):
| """ Check that locate_inst algorithm covers all opcode-length (ol)
for the varying sizes of opcodes.
The bad tests should not find an instruction, so they should fail on purpose,
to see we don't crash the diassembler.
Also test for some end-cases with nop and wait. """
def test_c7_opcode(self... | 1].dispSize != 8)
self.assertFalse(a.inst.operands[1].disp != 0x55)
if s != 1:
self.assertFalse(a.inst.operands[1].scale != s)
def test_sib_disp32(self):
for i in enumerate(self.Indices):
for j in enumerate(self.Bases):
for s in [1, 2, 4, 8]:
a = I64("sub rdx, [%s*%d + %s + 0x55aa... | 256 | 256 | 2,609 | 8 | 248 | akx/distorm | examples/tests/test_distorm3.py | Python | TestInstTable | TestInstTable | 995 | 1,129 | 995 | 995 | 618040a5f2e3dc78e0ecee91347fc49885195638 | bigcode/the-stack | train |
77a7194b9b2937ae3d4d50b2 | train | class | class Test(unittest.TestCase):
def __init__(self):
unittest.TestCase.__init__(self, "test_dummy")
def test_dummy(self):
self.fail("dummy")
| class Test(unittest.TestCase):
| def __init__(self):
unittest.TestCase.__init__(self, "test_dummy")
def test_dummy(self):
self.fail("dummy")
| 64:
mode = "amd64"
else:
mode = "x86"
os.system("c:\\yasm -m%s 1.asm" % mode)
s = open("1", "rb").read()
#if (not isinstance(s, str)):
return s
class Test(unittest.TestCase):
| 64 | 64 | 37 | 6 | 57 | akx/distorm | examples/tests/test_distorm3.py | Python | Test | Test | 51 | 55 | 51 | 51 | 607b1e4e6a9eacb0d4c3a7263d53c029c0870f36 | bigcode/the-stack | train |
8172c13707ad944702dd16fc | train | function | def _get_op(name): # pylint: disable=invalid-name
return tf.get_default_graph().get_operation_by_name(name)
| def _get_op(name): # pylint: disable=invalid-name
| return tf.get_default_graph().get_operation_by_name(name)
| vt']))
with self.test_session():
self.assertEqual(
round(expected_flop_cost), round(flop_reg.get_cost().eval()))
self.assertNearRelatively(expected_reg_term,
flop_reg.get_regularization_term().eval())
def _get_op(name): # pylint: disable=invalid-name
| 64 | 64 | 28 | 15 | 49 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | _get_op | _get_op | 548 | 549 | 548 | 548 | aa6a39d3f044609bea62c3a38b9dbc43a393f085 | bigcode/the-stack | train |
f98dabf3bbe93d59dd1ea8d1 | train | class | class GammaFlopLossTest(tf.test.TestCase):
def setUp(self):
tf.reset_default_graph()
self.BuildWithBatchNorm()
with self.test_session():
self.Init()
def BuildWithBatchNorm(self):
params = {
'trainable': True,
'normalizer_fn': layers.batch_norm,
'normalizer_params': {
... | class GammaFlopLossTest(tf.test.TestCase):
| def setUp(self):
tf.reset_default_graph()
self.BuildWithBatchNorm()
with self.test_session():
self.Init()
def BuildWithBatchNorm(self):
params = {
'trainable': True,
'normalizer_fn': layers.batch_norm,
'normalizer_params': {
'scale': True
}
}
... | Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 256 | 256 | 967 | 11 | 244 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | GammaFlopLossTest | GammaFlopLossTest | 36 | 122 | 36 | 37 | 97d7aaec0fdb2ec330580487f31376d002720080 | bigcode/the-stack | train |
35351368aaad390e01f9cdca | train | class | class GammaFlopLossWithDepthwiseConvTest(
tf.test.TestCase, GammaFlopLossWithDepthwiseConvTestBase):
"""Test flop_regularizer for a network with depthwise convolutions."""
def setUp(self):
self._depthwise_use_batchnorm = True
tf.reset_default_graph()
self.BuildWithBatchNorm()
with self.test_ses... | class GammaFlopLossWithDepthwiseConvTest(
tf.test.TestCase, GammaFlopLossWithDepthwiseConvTestBase):
| """Test flop_regularizer for a network with depthwise convolutions."""
def setUp(self):
self._depthwise_use_batchnorm = True
tf.reset_default_graph()
self.BuildWithBatchNorm()
with self.test_session():
self.Init()
def GetSession(self):
return self.test_session()
def testCost(self):
... | for them.
if self._depthwise_use_batchnorm:
gammad1 = self.name_to_var['dw1/BatchNorm/gamma']
gammad1.assign([-0.3] * 1 + [-0.9] * 2).eval()
gammad2 = self.name_to_var['dw2/BatchNorm/gamma']
gammad2.assign([0.3] * 5 + [0.9] * 10 + [-0.1] * 8).eval()
def cost(self, conv): # pylint: disab... | 256 | 256 | 921 | 28 | 227 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | GammaFlopLossWithDepthwiseConvTest | GammaFlopLossWithDepthwiseConvTest | 211 | 283 | 211 | 212 | a7d6cef6ca65c4450e7f397d94c585cf581c0e33 | bigcode/the-stack | train |
8085440454b32b6310a9ca88 | train | class | class GammaFlopLossWithDepthwiseConvNoBatchNormTest(
tf.test.TestCase, GammaFlopLossWithDepthwiseConvTestBase):
"""Test flop_regularizer for un-batchnormed depthwise convolutions.
This test is used to confirm that when depthwise convolution is not BNed, it
will not be considered towards the regularizer, but ... | class GammaFlopLossWithDepthwiseConvNoBatchNormTest(
tf.test.TestCase, GammaFlopLossWithDepthwiseConvTestBase):
| """Test flop_regularizer for un-batchnormed depthwise convolutions.
This test is used to confirm that when depthwise convolution is not BNed, it
will not be considered towards the regularizer, but it will be counted towards
the cost.
This design choice is for backward compatibility for users who did not
re... | 1e-5)
# Dw2 depthwise convolution is connected to conv2 (grouped regularizer).
conv = self.GetConv('conv2')
gamma_conv = self.GetGammaAbsValue('conv2')
dw = self.GetConv('dw2')
gamma_dw = self.GetGammaAbsValue('dw2')
gamma = np.maximum(gamma_dw, gamma_conv).sum()
expected_loss = _coeff(conv... | 199 | 199 | 666 | 31 | 168 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | GammaFlopLossWithDepthwiseConvNoBatchNormTest | GammaFlopLossWithDepthwiseConvNoBatchNormTest | 286 | 346 | 286 | 287 | 55d427557c835b5000362dc957774455fc08f4f7 | bigcode/the-stack | train |
6cca5d8b828bc76e37772738 | train | class | class GammaFlopResidualConnectionsLossTest(tf.test.TestCase):
"""Tests flop_regularizer for a network with residual connections."""
def setUp(self):
tf.reset_default_graph()
tf.set_random_seed(7)
self._threshold = 0.6
def buildModel(self, resnet_fn, block_fn):
# We use this model as a test case ... | class GammaFlopResidualConnectionsLossTest(tf.test.TestCase):
| """Tests flop_regularizer for a network with residual connections."""
def setUp(self):
tf.reset_default_graph()
tf.set_random_seed(7)
self._threshold = 0.6
def buildModel(self, resnet_fn, block_fn):
# We use this model as a test case because the slim.nets.nets module is
# used in some produc... | coeff(conv) * 10 * 18, self.cost([conv]))
def testRegularizer(self):
# Dw1 depthwise convolution is connected to the input (no regularizer).
conv = self.GetConv('dw1')
expected_loss = 0.0
self.assertNear(expected_loss, self.loss([conv]), expected_loss * 1e-5)
# Conv1 takes Dw1 as input, but it's... | 256 | 256 | 1,259 | 13 | 243 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | GammaFlopResidualConnectionsLossTest | GammaFlopResidualConnectionsLossTest | 349 | 470 | 349 | 349 | a595c5e6d2169e39c42e7081cf8becb490c9976a | bigcode/the-stack | train |
77116ddd824579153000800d | train | class | class GroupLassoFlopRegTest(tf.test.TestCase):
def assertNearRelatively(self, expected, actual):
self.assertNear(expected, actual, expected * 1e-6)
def testFlopRegularizer(self):
tf.reset_default_graph()
tf.set_random_seed(7907)
with arg_scope(
[layers.conv2d, layers.conv2d_transpose],
... | class GroupLassoFlopRegTest(tf.test.TestCase):
| def assertNearRelatively(self, expected, actual):
self.assertNear(expected, actual, expected * 1e-6)
def testFlopRegularizer(self):
tf.reset_default_graph()
tf.set_random_seed(7907)
with arg_scope(
[layers.conv2d, layers.conv2d_transpose],
weights_initializer=tf.random_normal_initia... | Coeff('unit_2/conv1') * self.numAlive('unit_2/conv1') *
np.sum(res_alive))
expected['unit_2/conv2'] = (
self.getCoeff('unit_2/conv2') * self.numAlive('unit_2/conv2') *
self.numAlive('unit_2/conv1'))
expected['unit_2/conv3'] = (
self.getCoeff('unit_2/conv3') * np.sum(res_alive) *
... | 243 | 243 | 813 | 13 | 230 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | GroupLassoFlopRegTest | GroupLassoFlopRegTest | 473 | 545 | 473 | 474 | 62f947983bae6e3e1c7279b8644ef01c1e94db61 | bigcode/the-stack | train |
eac87a1a5adcc947a7b7439d | train | class | class GammaFlopLossWithDepthwiseConvTestBase(object):
"""Test flop_regularizer for a network with depthwise convolutions."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def GetSession(self):
return
def BuildWithBatchNorm(self):
params = {
'trainable': True,
'normalizer_fn': layer... | class GammaFlopLossWithDepthwiseConvTestBase(object):
| """Test flop_regularizer for a network with depthwise convolutions."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def GetSession(self):
return
def BuildWithBatchNorm(self):
params = {
'trainable': True,
'normalizer_fn': layers.batch_norm,
'normalizer_params': {
... | NUM_CHANNELS, self.cost([conv]))
# Conv2 has 11 gammas above 0.45, and NUM_CHANNELS inputs (from the image).
conv = self.GetConv('conv2')
self.assertEqual(_coeff(conv) * 11 * NUM_CHANNELS, self.cost([conv]))
# Conv3 has 10 gammas above 0.45, and 7 + 11 inputs from conv1 and conv2.
conv = self.Get... | 256 | 256 | 975 | 13 | 243 | adam-dziedzic/tensorflow-models | research/morph_net/network_regularizers/flop_regularizer_test.py | Python | GammaFlopLossWithDepthwiseConvTestBase | GammaFlopLossWithDepthwiseConvTestBase | 125 | 208 | 125 | 125 | 63d2268b8e11d1cb977c2a9d7447949e6b6913e6 | bigcode/the-stack | train |
925887d39e446345786db926 | train | function | def nxt():
global head
head += 1
| def nxt():
| global head
head += 1
| ]
def rem_ptr():
global ptr_reg, head, memory
ptr_reg = memory[head]
def incr():
global val_reg
val_reg = str(int(val_reg)+1)
def decr():
global val_reg
val_reg = str(int(val_reg)-1)
def nxt():
| 64 | 64 | 13 | 3 | 61 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | nxt | nxt | 62 | 64 | 62 | 62 | 9aec218b94ddc735e9877e6552b435437156a8fb | bigcode/the-stack | train |
3333d9824e387426158832dc | train | function | def print_node():
global val_reg, ptr_reg
# Use curr to mark begining of current node
ptr_reg = "curr"
ref()
# Print (val,
val_reg = "("
write()
nxt()
nxt()
nxt()
nxt()
rem_val()
while val_reg != "null":
write()
nxt()
rem_val()
val_reg ... | def print_node():
| global val_reg, ptr_reg
# Use curr to mark begining of current node
ptr_reg = "curr"
ref()
# Print (val,
val_reg = "("
write()
nxt()
nxt()
nxt()
nxt()
rem_val()
while val_reg != "null":
write()
nxt()
rem_val()
val_reg = ","
write()
... | for siblings
read()
while val_reg != ")":
read()
create_sibling()
read()
# Set prev pointer for next node
ptr_reg = "prev"
ref()
# Return head to parent (if not null)
nxt()
rem_ptr()
if ptr_reg != "null":
drf()
def print_node():
| 77 | 77 | 258 | 4 | 73 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | print_node | print_node | 321 | 381 | 321 | 321 | dca375e77f6317c337e5f7f61c7c1bc65a2aa4d0 | bigcode/the-stack | train |
272805fe6fa5246dc4ec24a2 | train | function | def create_child():
global val_reg, ptr_reg
#print("Create child")
create_start()
### CHILD NODE INIT ##############
# Set parent index from prev
# "null" if parent == curr
##################################
# Get parent index in val_reg
ptr_reg = "prev"
drf()
rem_ptr()
... | def create_child():
| global val_reg, ptr_reg
#print("Create child")
create_start()
### CHILD NODE INIT ##############
# Set parent index from prev
# "null" if parent == curr
##################################
# Get parent index in val_reg
ptr_reg = "prev"
drf()
rem_ptr()
val_reg = ptr_re... | _reg != ",":
mem_val()
nxt()
read()
val_reg = "null"
mem_val()
nxt()
# Move end pointer
ptr_reg = "end"
ref()
# Return to beginning of node
ptr_reg = "curr"
drf()
"""
Assumes:
prev points to the parent node address
"""
def create_child():
| 81 | 81 | 273 | 4 | 77 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | create_child | create_child | 168 | 225 | 168 | 168 | 826a730fd4d97d23a77b3e0594ccdde2cb0c3a3a | bigcode/the-stack | train |
7d2b63b0b7a87382fe0b4193 | train | function | def create_end():
global val_reg, ptr_reg
# Move prev to curr
ptr_reg = "prev"
ref()
# Check for child
read()
if val_reg != ")":
create_child()
# Loop, checking for siblings
read()
while val_reg != ")":
read()
create_sibling()
... | def create_end():
| global val_reg, ptr_reg
# Move prev to curr
ptr_reg = "prev"
ref()
# Check for child
read()
if val_reg != ")":
create_child()
# Loop, checking for siblings
read()
while val_reg != ")":
read()
create_sibling()
read()
... | ()
nxt()
ptr_reg = val_reg
mem_ptr()
# Go back to current node
ptr_reg = "curr"
drf()
# Parse the current node's children
create_end()
"""
Assumes:
memory head is at current node
"""
def create_end():
| 64 | 64 | 127 | 4 | 60 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | create_end | create_end | 291 | 318 | 291 | 291 | 96e655335c687bb4c632f5a5de8e96cc635497d4 | bigcode/the-stack | train |
98ad27c6477d22fa16cb6271 | train | function | def ref():
global ptr_reg, head, pointers
pointers[ptr_reg] = head
| def ref():
| global ptr_reg, head, pointers
pointers[ptr_reg] = head
| val_reg = "null"
def read():
global val_reg
val_reg = next(it)
#print("Read %s" % val_reg)
def write():
global val_reg, output
#print("Write %s" % val_reg)
output += val_reg
def ref():
| 64 | 64 | 21 | 3 | 60 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | ref | ref | 30 | 32 | 30 | 30 | 7e4bd90a6f4412fca74fd26387f73b84f4754475 | bigcode/the-stack | train |
2dd46bfa537725411145fb63 | train | function | def decr():
global val_reg
val_reg = str(int(val_reg)-1)
| def decr():
| global val_reg
val_reg = str(int(val_reg)-1)
| rem_val():
global val_reg, head, memory
val_reg = memory[head]
def rem_ptr():
global ptr_reg, head, memory
ptr_reg = memory[head]
def incr():
global val_reg
val_reg = str(int(val_reg)+1)
def decr():
| 64 | 64 | 20 | 4 | 60 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | decr | decr | 58 | 60 | 58 | 58 | ad14063a842e1e2c3edd0ccdf0c201fbbfe2d564 | bigcode/the-stack | train |
c0b913423c18864ca68a0232 | train | function | def rem_ptr():
global ptr_reg, head, memory
ptr_reg = memory[head]
| def rem_ptr():
| global ptr_reg, head, memory
ptr_reg = memory[head]
| global val_reg, head, memory
memory[head] = val_reg
def mem_ptr():
global ptr_reg, head, memory
memory[head] = ptr_reg
def rem_val():
global val_reg, head, memory
val_reg = memory[head]
def rem_ptr():
| 64 | 64 | 21 | 4 | 60 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | rem_ptr | rem_ptr | 50 | 52 | 50 | 50 | 4000226b84757485ac91bcf9ab7f9ffa6ec6c93f | bigcode/the-stack | train |
eaa27835ef648c5526c39b90 | train | function | def mem_val():
global val_reg, head, memory
memory[head] = val_reg
| def mem_val():
| global val_reg, head, memory
memory[head] = val_reg
| #print("Write %s" % val_reg)
output += val_reg
def ref():
global ptr_reg, head, pointers
pointers[ptr_reg] = head
def drf():
global ptr_reg, head, pointers
head = pointers[ptr_reg]
def mem_val():
| 64 | 64 | 22 | 4 | 60 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | mem_val | mem_val | 38 | 40 | 38 | 38 | ec7597a568f61396a27bf7e0cdbc97ac3891b28d | bigcode/the-stack | train |
b790c26f1b1b193eabe163ee | train | function | def write():
global val_reg, output
#print("Write %s" % val_reg)
output += val_reg
| def write():
| global val_reg, output
#print("Write %s" % val_reg)
output += val_reg
| _child
# prev sibling if create_sibling
# curr: points to beginning of current node
ptr_reg = "null"
val_reg = "null"
def read():
global val_reg
val_reg = next(it)
#print("Read %s" % val_reg)
def write():
| 64 | 64 | 28 | 3 | 61 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | write | write | 25 | 28 | 25 | 25 | d1b9fb81371eb4409052b276760d89ddd2b5178f | bigcode/the-stack | train |
ac5a7a3b02c4afe6d45d410d | train | function | def read():
global val_reg
val_reg = next(it)
| def read():
| global val_reg
val_reg = next(it)
| of nodes created
# end: first free memory address
# prev: points to previous node
# parent if create_child
# prev sibling if create_sibling
# curr: points to beginning of current node
ptr_reg = "null"
val_reg = "null"
def read():
| 64 | 64 | 15 | 3 | 61 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | read | read | 20 | 22 | 20 | 20 | 74d90eba95a9b5d3cb0367ba5f5492e5045a4b26 | bigcode/the-stack | train |
518246094904fd06d898d21c | train | function | def rem_val():
global val_reg, head, memory
val_reg = memory[head]
| def rem_val():
| global val_reg, head, memory
val_reg = memory[head]
| global ptr_reg, head, pointers
head = pointers[ptr_reg]
def mem_val():
global val_reg, head, memory
memory[head] = val_reg
def mem_ptr():
global ptr_reg, head, memory
memory[head] = ptr_reg
def rem_val():
| 64 | 64 | 21 | 4 | 59 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | rem_val | rem_val | 46 | 48 | 46 | 46 | 7639f667d2867dcc89ba8a06a7ab61fb421a60d4 | bigcode/the-stack | train |
6a4bab312a5c41876ec5aa81 | train | function | def prv():
global head
head -= 1
| def prv():
| global head
head -= 1
|
ptr_reg = memory[head]
def incr():
global val_reg
val_reg = str(int(val_reg)+1)
def decr():
global val_reg
val_reg = str(int(val_reg)-1)
def nxt():
global head
head += 1
def prv():
| 64 | 64 | 13 | 3 | 60 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | prv | prv | 66 | 68 | 66 | 66 | 68f222c229a5cf93de75dddcabeb3fa27958f78d | bigcode/the-stack | train |
58a5d6ae5bac85babf75a951 | train | function | def mem_ptr():
global ptr_reg, head, memory
memory[head] = ptr_reg
| def mem_ptr():
| global ptr_reg, head, memory
memory[head] = ptr_reg
| global ptr_reg, head, pointers
pointers[ptr_reg] = head
def drf():
global ptr_reg, head, pointers
head = pointers[ptr_reg]
def mem_val():
global val_reg, head, memory
memory[head] = val_reg
def mem_ptr():
| 64 | 64 | 22 | 4 | 59 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | mem_ptr | mem_ptr | 42 | 44 | 42 | 42 | 6836e8f2496c0952cac0961c6f3b1d148afdfe64 | bigcode/the-stack | train |
853754b9f39d8ccf1d6d4edc | train | function | def create_start():
global val_reg, ptr_reg
### PREAMBLE #####################
# Get current index from counter
# Increment counter
# Set current pointer
# Set index pointer
##################################
# Retrieve new index
ptr_reg = "counter"
drf()
rem_val()
# I... | def create_start():
| global val_reg, ptr_reg
### PREAMBLE #####################
# Get current index from counter
# Increment counter
# Set current pointer
# Set index pointer
##################################
# Retrieve new index
ptr_reg = "counter"
drf()
rem_val()
# Increment index, save... | [" " if x == "null" else x for x in node]
i += 1
print("|%s |" % (" |".join(["%3s" % x for x in node])))
print("")
# Node: (index, parent_index, child_index, sibling_index, data)
"""
Assumes:
counter points to counter address
end points to free address
"""
def create_start():
| 89 | 89 | 299 | 4 | 85 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | create_start | create_start | 99 | 162 | 99 | 99 | 3d1e5f135567f9f1464bdea288589f029aac2f49 | bigcode/the-stack | train |
f59644aff103ee66d3354684 | train | function | def print_memory():
global memory, pointers
print("Pointers:")
for k in sorted(pointers.keys()):
print("%7s : %s" % (k, pointers[k]))
print("")
print("Counter: %s" % memory[0])
i = 1
while i < pointers["end"]:
node = memory[i:i+4]
i += 4
while memory[i] != "... | def print_memory():
| global memory, pointers
print("Pointers:")
for k in sorted(pointers.keys()):
print("%7s : %s" % (k, pointers[k]))
print("")
print("Counter: %s" % memory[0])
i = 1
while i < pointers["end"]:
node = memory[i:i+4]
i += 4
while memory[i] != "null":
n... | val_reg
val_reg = str(int(val_reg)+1)
def decr():
global val_reg
val_reg = str(int(val_reg)-1)
def nxt():
global head
head += 1
def prv():
global head
head -= 1
def print_memory():
| 64 | 64 | 164 | 4 | 59 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | print_memory | print_memory | 70 | 90 | 70 | 70 | a4932404acc797439e7e5f23500c55cf1112e5bd | bigcode/the-stack | train |
f2369614164be720f1e2d87c | train | function | def incr():
global val_reg
val_reg = str(int(val_reg)+1)
| def incr():
| global val_reg
val_reg = str(int(val_reg)+1)
| ():
global ptr_reg, head, memory
memory[head] = ptr_reg
def rem_val():
global val_reg, head, memory
val_reg = memory[head]
def rem_ptr():
global ptr_reg, head, memory
ptr_reg = memory[head]
def incr():
| 64 | 64 | 19 | 3 | 61 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | incr | incr | 54 | 56 | 54 | 54 | ebc06c69af1f4f35d4b27befe1c89ab96945918b | bigcode/the-stack | train |
56251a0cc5c94f3242dd8773 | train | function | def drf():
global ptr_reg, head, pointers
head = pointers[ptr_reg]
| def drf():
| global ptr_reg, head, pointers
head = pointers[ptr_reg]
| #print("Read %s" % val_reg)
def write():
global val_reg, output
#print("Write %s" % val_reg)
output += val_reg
def ref():
global ptr_reg, head, pointers
pointers[ptr_reg] = head
def drf():
| 64 | 64 | 21 | 4 | 59 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | drf | drf | 34 | 36 | 34 | 34 | 7593779325d8d63733f4b4b1f641f902ab69fb38 | bigcode/the-stack | train |
3ca685a13dea8a41c2eeebef | train | function | def create_sibling():
global val_reg, ptr_reg
#print("Create sibling")
create_start()
### SIBLING NODE INIT ############
# Set parent index from prev parent
##################################
# Get prev's parent index in val_reg
ptr_reg = "prev"
drf()
nxt()
rem_ptr()
v... | def create_sibling():
| global val_reg, ptr_reg
#print("Create sibling")
create_start()
### SIBLING NODE INIT ############
# Set parent index from prev parent
##################################
# Get prev's parent index in val_reg
ptr_reg = "prev"
drf()
nxt()
rem_ptr()
val_reg = ptr_reg
... | ":
drf()
nxt()
nxt()
ptr_reg = val_reg
mem_ptr()
# Go back to current node
ptr_reg = "curr"
drf()
# Parse the current node's children
create_end()
"""
Assumes:
prev points to previous sibling address
"""
def create_sibling():
| 72 | 72 | 240 | 5 | 67 | khushbooG9/nvm | src/syngen/mock_tree.py | Python | create_sibling | create_sibling | 232 | 284 | 232 | 232 | 87c8b6ddc2ba31f2b5d74f4c5a779b837b9604d2 | bigcode/the-stack | train |
12c73175a325e6aefd183ad4 | train | class | class Check(object):
"""Check parameters and raise comprehensible exceptions.
>>> from should_check import (
... Check,
... be_callable,
... be_py_enum_str,
... be_instance_of,
... be_subclass_of,
... not_be_none,
... not_contain,
... contain,
... ... | class Check(object):
| """Check parameters and raise comprehensible exceptions.
>>> from should_check import (
... Check,
... be_callable,
... be_py_enum_str,
... be_instance_of,
... be_subclass_of,
... not_be_none,
... not_contain,
... contain,
... not_be_empty,
...... | """
@copyright: 2015 - 2018 SSH Communications Security Corporation.
@author: Pauli Rikula
@license: MIT <http://www.opensource.org/licenses/mit-license.php>
"""
class Check(object):
| 44 | 256 | 1,604 | 4 | 40 | SSHcom/python-should-check | should_check/check.py | Python | Check | Check | 8 | 219 | 8 | 8 | 822ed01eba3c65fe107a2f0e0e2b8b48d1cc5ba7 | bigcode/the-stack | train |
877f738e5ee656a828b62a67 | train | class | class TxnMallTest(BitcoinTestFramework):
def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
help="Test double-spend of 1-confirmed transaction")
def setup_network(self):
# Start with split network:
... | class TxnMallTest(BitcoinTestFramework):
| def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
help="Test double-spend of 1-confirmed transaction")
def setup_network(self):
# Start with split network:
return super(TxnMallTest, self).setu... | #!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test proper accounting with a double-spend conflict
#
from test_framework.test_framework import Bitc... | 89 | 256 | 1,500 | 10 | 79 | vitruvedz/3dcoin | qa/rpc-tests/txn_doublespend.py | Python | TxnMallTest | TxnMallTest | 13 | 138 | 13 | 14 | ed6959769661f157b2f08b6e88d8e837d3b4349b | bigcode/the-stack | train |
32de5baef493b1d94bb007db | train | function | def token_match(s):
if include_rgx.search(s):
return False
elif exclude_rgx.search(s):
return True
return False
| def token_match(s):
| if include_rgx.search(s):
return False
elif exclude_rgx.search(s):
return True
return False
| 9]+)|([0-9]+[-][0-9]+)''' # dates
]
return re.compile('|'.join(include_rgx)), \
re.compile('|'.join(exclude_rgx))
include_rgx, exclude_rgx = build_token_match_rgx()
def token_match(s):
| 64 | 64 | 33 | 5 | 59 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | token_match | token_match | 297 | 302 | 297 | 297 | 43a7abf911d3fdc1fbfaae5b12d600d3407aee43 | bigcode/the-stack | train |
0441adc5c688cfa4b000728f | train | function | def load_special_cases(filelist):
"""
Load manually defined special cases (including any lexical metadata
like POS tag)
:param filelist:
:return:
"""
spacy_symbols = {'ORTH': ORTH, 'TAG': TAG, 'LEMMA': LEMMA}
for fpath in filelist:
for i, row in enumerate(open(fpath, "rU").read... | def load_special_cases(filelist):
| """
Load manually defined special cases (including any lexical metadata
like POS tag)
:param filelist:
:return:
"""
spacy_symbols = {'ORTH': ORTH, 'TAG': TAG, 'LEMMA': LEMMA}
for fpath in filelist:
for i, row in enumerate(open(fpath, "rU").read().splitlines()):
row ... | splits.append(seq)
else:
seq = doc[idxs[0]:idxs[-1] + 1]
splits.append(seq)
sents = splits
for s in sents:
yield s
###############################################################################
#
# Tokenization
#
#####################################... | 64 | 64 | 196 | 7 | 57 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | load_special_cases | load_special_cases | 212 | 235 | 212 | 212 | 25313acd741609b54768ec7b6218f2076fdc9f4c | bigcode/the-stack | train |
bad7d76288d3b228aad6386b | train | function | def get_parser(disable: List[str] = None ,
lang: str = 'en',
merge_terms: Optional[Set] = None,
max_sent_len: Optional[int] = None) -> Callable:
"""spaCy clinical text parser
Parameters
----------
disable
lang
merge_terms
max_sent_len
Return... | def get_parser(disable: List[str] = None ,
lang: str = 'en',
merge_terms: Optional[Set] = None,
max_sent_len: Optional[int] = None) -> Callable:
| """spaCy clinical text parser
Parameters
----------
disable
lang
merge_terms
max_sent_len
Returns
-------
"""
disable = ["ner", "parser", "tagger", "lemmatizer"] if not disable \
else disable
merge_terms = {} if not merge_terms else merge_terms
nlp = spacy... | parts['words']:
continue
parts['i'] = position
yield parts
def get_parser(disable: List[str] = None ,
lang: str = 'en',
merge_terms: Optional[Set] = None,
max_sent_len: Optional[int] = None) -> Callable:
| 64 | 64 | 201 | 45 | 18 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | get_parser | get_parser | 390 | 420 | 390 | 393 | 5d23434deae685e398f2e3ef43020dc6d937001b | bigcode/the-stack | train |
3d3ba1c67b94e176a5ecfdf3 | train | function | def split_on_punct(doc):
"""
Default punctuation-based SBD
:param doc:
:return:
"""
start = 0
seen_period = False
for i, word in enumerate(doc):
if seen_period and not word.is_punct:
yield doc[start:word.i]
start = word.i
seen_period = False
... | def split_on_punct(doc):
| """
Default punctuation-based SBD
:param doc:
:return:
"""
start = 0
seen_period = False
for i, word in enumerate(doc):
if seen_period and not word.is_punct:
yield doc[start:word.i]
start = word.i
seen_period = False
elif word.text in... | izer
from spacy.symbols import ORTH, LEMMA, POS, TAG
from typing import List, Set, Dict, Tuple, Optional, Union, Callable, Generator
logger = logging.getLogger(__name__)
###############################################################################
#
# Sentence Boundary Detection
#
#################################... | 64 | 64 | 111 | 7 | 57 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | split_on_punct | split_on_punct | 32 | 50 | 32 | 32 | 338a90cfc795834d4723d3975a5cc36d056690d3 | bigcode/the-stack | train |
2ad79e26fa83b3105bb02d4f | train | function | def ct_tokenizer(nlp):
"""
Clinical Note Tokenizer
- Keep prefix/suffix/infix regexes as simple as possible
- Move token complexity to special cases when possible
- token_match exceptions are can be *order dependant* so use caution
:param nlp:
:return:
"""
prefix_re = re.compile(r'... | def ct_tokenizer(nlp):
| """
Clinical Note Tokenizer
- Keep prefix/suffix/infix regexes as simple as possible
- Move token complexity to special cases when possible
- token_match exceptions are can be *order dependant* so use caution
:param nlp:
:return:
"""
prefix_re = re.compile(r'''^([\["'()*+-?/<>#%]+|... | '.join(include_rgx)), \
re.compile('|'.join(exclude_rgx))
include_rgx, exclude_rgx = build_token_match_rgx()
def token_match(s):
if include_rgx.search(s):
return False
elif exclude_rgx.search(s):
return True
return False
def ct_tokenizer(nlp):
| 72 | 72 | 240 | 7 | 64 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | ct_tokenizer | ct_tokenizer | 305 | 331 | 305 | 305 | 0e5b06ab87fce29bc1c669158dd1bca678e14a33 | bigcode/the-stack | train |
ee0a630d607b734d15827e82 | train | function | def split_on_phrase_rgx(sentences, doc, rgx, threshold=250):
"""
Split sentence on phrase regex
:param sentences:
:param doc:
:param rgx:
:param threshold:
:return:
"""
splits = []
for sent in sentences:
matches = re.findall(rgx, sent.text)
if len(sent.text) >= ... | def split_on_phrase_rgx(sentences, doc, rgx, threshold=250):
| """
Split sentence on phrase regex
:param sentences:
:param doc:
:param rgx:
:param threshold:
:return:
"""
splits = []
for sent in sentences:
matches = re.findall(rgx, sent.text)
if len(sent.text) >= threshold and matches:
offset = sent[0].idx
... | = sorted(list(set(idxs)))
for i in range(len(idxs) - 1):
splits.append(doc[idxs[i]:idxs[i + 1]])
else:
splits.append(sent)
return splits
def split_on_phrase_rgx(sentences, doc, rgx, threshold=250):
| 65 | 65 | 218 | 18 | 46 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | split_on_phrase_rgx | split_on_phrase_rgx | 78 | 108 | 78 | 78 | 58fa21103d835ee1cebc3f1ae90d54c67a0cb182 | bigcode/the-stack | train |
f73236070af82aad18095315 | train | function | def ct_sbd_rules(doc, merge_terms=None, max_sent_len=None):
"""
Split sentences if they don't meet certain char length thresholds.
This splits on 3 and 2 character whitespace tokens and bulleted lists.
:param doc:
:param threshold:
:return:
"""
merge_terms = {} if not merge_terms else m... | def ct_sbd_rules(doc, merge_terms=None, max_sent_len=None):
| """
Split sentences if they don't meet certain char length thresholds.
This splits on 3 and 2 character whitespace tokens and bulleted lists.
:param doc:
:param threshold:
:return:
"""
merge_terms = {} if not merge_terms else merge_terms
sents = [sent for sent in split_on_punct(doc... | inals:
stack[-1].extend(seq)
else:
stack.append(seq)
# replace missing indices (whitespace)
end = 0
sentences = []
stack[0] = [0] + stack[0]
for i in range(len(stack)-1):
s = list(sorted(set(stack[i] + [stack[i+1][0]])))
sentences.append(doc[min(s):ma... | 129 | 129 | 430 | 16 | 112 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | ct_sbd_rules | ct_sbd_rules | 161 | 203 | 161 | 161 | 2237694f04e835a7ffd87a23e9abfaf353a974c0 | bigcode/the-stack | train |
bafc18358826c490752ae1b8 | train | function | def build_token_match_rgx():
"""
Build accept & reject patterns for individual tokens. Preserving certain
token groupings (e.g., lab values) is useful for preventing false positives
during sentence boundary detection.
:return:
"""
# accept tokenization
include_rgx = [
r'''^[(][0... | def build_token_match_rgx():
| """
Build accept & reject patterns for individual tokens. Preserving certain
token groupings (e.g., lab values) is useful for preventing false positives
during sentence boundary detection.
:return:
"""
# accept tokenization
include_rgx = [
r'''^[(][0-9]''', # ignore s... | lexical metadata
like POS tag)
:param filelist:
:return:
"""
spacy_symbols = {'ORTH': ORTH, 'TAG': TAG, 'LEMMA': LEMMA}
for fpath in filelist:
for i, row in enumerate(open(fpath, "rU").read().splitlines()):
row = row.strip().split("\t")
if not row:
... | 256 | 256 | 921 | 7 | 249 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | build_token_match_rgx | build_token_match_rgx | 251 | 292 | 251 | 251 | 351513edbcad9041e0528c2b078efdf4a2038234 | bigcode/the-stack | train |
4c51ed2e91531972aa6ea56b | train | function | def add_special_cases(tokenizer, special_cases):
"""
Load special cases for the tokenizer.
These are largely clinical abbreviations/acronyms.
:param tokenizer:
:param special_cases:
:return:
"""
for term, attrib in load_special_cases(special_cases):
tokenizer.add_special_case(te... | def add_special_cases(tokenizer, special_cases):
| """
Load special cases for the tokenizer.
These are largely clinical abbreviations/acronyms.
:param tokenizer:
:param special_cases:
:return:
"""
for term, attrib in load_special_cases(special_cases):
tokenizer.add_special_case(term, attrib)
| value
for key, value in row.items() if key in spacy_symbols}
attribs[ORTH] = row['TERM'] if ORTH not in attribs \
else attribs[ORTH]
yield row['TERM'], [attribs]
def add_special_cases(tokenizer, special_cases):
| 64 | 64 | 71 | 10 | 54 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | add_special_cases | add_special_cases | 238 | 248 | 238 | 238 | 3a4d1531ca7d3c3e9cc0289f9ab85040c6e68de4 | bigcode/the-stack | train |
3e74ffeab4019be667ae6907 | train | function | def parse_doc(doc: spacy.tokens.Doc,
disable: Set[str] = None,
keep_whitespace: bool = False):
"""
Given a parsed document, generate a parsed Sentence object
:param doc:
:param disable:
:return:
"""
disable = {"ner", "parser", "tagger", "lemmatizer"} if not disab... | def parse_doc(doc: spacy.tokens.Doc,
disable: Set[str] = None,
keep_whitespace: bool = False):
| """
Given a parsed document, generate a parsed Sentence object
:param doc:
:param disable:
:return:
"""
disable = {"ner", "parser", "tagger", "lemmatizer"} if not disable \
else disable
for position, sent in enumerate(doc.sents):
parts = defaultdict(list)
for i,... | _re.search,
infix_finditer=infix_re.finditer,
token_match=token_match)
special_cases = [
fp.format(os.path.dirname(__file__))
for fp in ["{}/specialist_special_cases.txt", "{}/special_cases.txt"]
]
add_special_cases(tokenizer, special_case... | 108 | 108 | 362 | 28 | 80 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | parse_doc | parse_doc | 340 | 387 | 340 | 342 | 381cc390751a1a0547b37cf8b0e9be5e33aced03 | bigcode/the-stack | train |
a2ae882ceed96685ad1f1aed | train | function | def merge_sentences(doc, sents, merge_terms):
"""
Use a collection of bigrams (either from a dictionary of bigrams,
corpus association weights, etc.) to define word pairs that cannot
be split across sentences.
TODO: Clean this up!
:param doc:
:param idxs:
:param merge_terms:
:retur... | def merge_sentences(doc, sents, merge_terms):
| """
Use a collection of bigrams (either from a dictionary of bigrams,
corpus association weights, etc.) to define word pairs that cannot
be split across sentences.
TODO: Clean this up!
:param doc:
:param idxs:
:param merge_terms:
:return:
"""
# terms that can never end a se... | .add(sent.text.index(m) + offset)
idxs = [sent[0].i]
idxs += [word.i for word in sent if word.idx in m_idxs]
idxs += [sent[-1].i + 1]
idxs = sorted(list(set(idxs)))
for i in range(len(idxs) - 1):
splits.append(doc[idxs[i]:idxs[i + 1]])
... | 114 | 114 | 380 | 12 | 101 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | merge_sentences | merge_sentences | 111 | 158 | 111 | 111 | f5f5149e22317fe39137785cfa38d1d743bc5c2b | bigcode/the-stack | train |
9803ea1dbd06c711e5e9ce58 | train | function | def split_on_rgx(sentences, doc, rgx, threshold=250, sent_match=None):
"""
Match split tokens using provided regex.
:param sentences:
:param doc:
:param rgx:
:param threshold:
:return:
"""
splits = []
for sent in sentences:
if len(sent.text) >= threshold and not sent_mat... | def split_on_rgx(sentences, doc, rgx, threshold=250, sent_match=None):
| """
Match split tokens using provided regex.
:param sentences:
:param doc:
:param rgx:
:param threshold:
:return:
"""
splits = []
for sent in sentences:
if len(sent.text) >= threshold and not sent_match or \
(len(sent.text) >= threshold and sent_match(sen... | = word.i
seen_period = False
elif word.text in ['.', '!', '?']:
seen_period = True
if start < len(doc):
yield doc[start:len(doc)]
def split_on_rgx(sentences, doc, rgx, threshold=250, sent_match=None):
| 63 | 64 | 184 | 21 | 42 | raymondzmc/trove | preprocessing/pipes/tokenizers.py | Python | split_on_rgx | split_on_rgx | 53 | 74 | 53 | 53 | ff4079a77a65d8fd39e5dd2ae19d65918356a7a1 | bigcode/the-stack | train |
7bf5d357abdce55a196bc54e | train | function | def parse_spacecharge(line):
"""
Spacecharge (type -8)
if bytpe = −8, switch on/off the space-charge calculation at given location V3(m)
according to the sign of V2 (> 0 on, otherwise off).
"""
v = v_from_line(line)
d={}
d['s'] = float(v[3])
if float(v[2]) >0:
d['i... | def parse_spacecharge(line):
| """
Spacecharge (type -8)
if bytpe = −8, switch on/off the space-charge calculation at given location V3(m)
according to the sign of V2 (> 0 on, otherwise off).
"""
v = v_from_line(line)
d={}
d['s'] = float(v[3])
if float(v[2]) >0:
d['is_on'] = True
else:
... | Looks like V1 and V3 are used
dummy = 0.0
v = [ele, ele['s'], dummy, ele['s']]
return v
ELE_DEFAULTS['stop'] = {
's':0
}
#-----------------------------------------------------------------
def parse_spacecharge(line):
| 63 | 64 | 116 | 6 | 57 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | parse_spacecharge | parse_spacecharge | 1,235 | 1,251 | 1,235 | 1,235 | 0596d017c51b457cbe6878a49cbaccd93c34f715 | bigcode/the-stack | train |
073b2b52fe27a250e2f04dfe | train | function | def spacecharge_v(ele):
"""
spacecharge Impact-T style V list
"""
# Let v[0] be the original ele, so the indexing looks the same.
dummy = 0.0
if ele['is_on']:
sign = 1.0
else:
sign = -1
v = [ele, dummy, sign, ele['s'] ]
return v
| def spacecharge_v(ele):
| """
spacecharge Impact-T style V list
"""
# Let v[0] be the original ele, so the indexing looks the same.
dummy = 0.0
if ele['is_on']:
sign = 1.0
else:
sign = -1
v = [ele, dummy, sign, ele['s'] ]
return v
| v = v_from_line(line)
d={}
d['s'] = float(v[3])
if float(v[2]) >0:
d['is_on'] = True
else:
d['is_on'] = False
return d
def spacecharge_v(ele):
| 64 | 64 | 91 | 6 | 57 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | spacecharge_v | spacecharge_v | 1,253 | 1,270 | 1,253 | 1,253 | abc806d384b9d52e9af1838b89bcca30f69ebd06 | bigcode/the-stack | train |
51e2a2d4250d2123f2e75549 | train | function | def write_beam_for_restart_v(ele):
"""
write_beam_for_restart Impact-T style V list
"""
# Let v[0] be the original ele, so the indexing looks the same.
dummy = 0.0
v = [ele, dummy, dummy, ele['s']]
return v
| def write_beam_for_restart_v(ele):
| """
write_beam_for_restart Impact-T style V list
"""
# Let v[0] be the original ele, so the indexing looks the same.
dummy = 0.0
v = [ele, dummy, dummy, ele['s']]
return v
| .
"""
x = line.split()
v = v_from_line(line)
d={}
d['filename']='fort.'+x[2]+'+myid'
d['s'] = float(v[3])
return d
def write_beam_for_restart_v(ele):
| 64 | 64 | 71 | 9 | 54 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | write_beam_for_restart_v | write_beam_for_restart_v | 1,042 | 1,050 | 1,042 | 1,042 | df88292d1099d69e2358235cb376f47f982c2f41 | bigcode/the-stack | train |
ca307243f21ab70756e43334 | train | function | def is_commented(line, commentchar='!'):
sline = line.strip() # remove spaces
if len(sline) == 0:
return True
return sline[0] == commentchar
| def is_commented(line, commentchar='!'):
| sline = line.strip() # remove spaces
if len(sline) == 0:
return True
return sline[0] == commentchar
| 112:'beercan' # todo: make general
}
# TODO: ijk distribution
# Inverse
DIST_ITYPE={}
for k, v in DIST_TYPE.items():
DIST_ITYPE[v]=k
#-----------------
# Util
def is_commented(line, commentchar='!'):
| 64 | 64 | 47 | 11 | 52 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | is_commented | is_commented | 299 | 303 | 299 | 299 | 8332b25377ccae11ea06b9368679f7186fc90c37 | bigcode/the-stack | train |
54b30707974c66c2aa1aef46 | train | function | def load_fort40(filePath):
"""
Returns dict with 'initial_particles'
"""
data = parse_impact_particles(filePath)
return {'initial_particles':data}
| def load_fort40(filePath):
| """
Returns dict with 'initial_particles'
"""
data = parse_impact_particles(filePath)
return {'initial_particles':data}
| slice emittance (m*rad)
6th col: mean energy (eV)
7th col: energy spread (eV)
"""
return load_fortX(filePath, keys)
# Wrapper functions to provide keyed output
def load_fort40(filePath):
| 64 | 64 | 39 | 8 | 55 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort40 | load_fort40 | 1,787 | 1,792 | 1,787 | 1,787 | 726bcc9ecefdca60d678b8afa6f23f1336586fc9 | bigcode/the-stack | train |
5c7df0c3b9331acd7b410415 | train | function | def distrubution_type(x):
"""
Returns a named distribution type from an integer x
"""
if x in DIST_TYPE:
return DIST_TYPE[x]
# Expect Combine
x = str(x)
assert len(x) == 3
dtypes = [DIST_TYPE[int(i)] for i in x]
return '_'.join(dtypes)
| def distrubution_type(x):
| """
Returns a named distribution type from an integer x
"""
if x in DIST_TYPE:
return DIST_TYPE[x]
# Expect Combine
x = str(x)
assert len(x) == 3
dtypes = [DIST_TYPE[int(i)] for i in x]
return '_'.join(dtypes)
| {H['Nz']}
Maximum time steps: {H['Ntstep']}
Reference Frequency: {H['Bfreq']} Hz
Initial reference time: {H['Tini']} s
{restart_condition}
=================================================
"""
return summary
#-----------------
# Distribution types
def distrubution_type(x):
| 64 | 64 | 79 | 7 | 56 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | distrubution_type | distrubution_type | 255 | 268 | 255 | 255 | a7f3852f87378c19adf4f34726320530b83f9c1d | bigcode/the-stack | train |
231d8eb4876b025f96b2ae09 | train | function | def offset_beam_v(ele):
"""
offset_beam Impact-T style V list
"""
# Let v[0] be the original ele, so the indexing looks the same.
dummy = 0.0
v = [ele, dummy, ele['s']] + [ele[x] for x in ['x_offset', 'px_offset', 'y_offset','py_offset','z_offset','pz_offset' ]]
return v
| def offset_beam_v(ele):
| """
offset_beam Impact-T style V list
"""
# Let v[0] be the original ele, so the indexing looks the same.
dummy = 0.0
v = [ele, dummy, ele['s']] + [ele[x] for x in ['x_offset', 'px_offset', 'y_offset','py_offset','z_offset','pz_offset' ]]
return v
| 3 > len(v)-1:
val = 0.0
else:
## print('warning: offset_beam missing numbers. Assuming zeros', line)
val = float(v[i+3])
d[olist[i]] = val
return d
def offset_beam_v(ele):
| 64 | 64 | 95 | 7 | 56 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | offset_beam_v | offset_beam_v | 963 | 972 | 963 | 963 | e8ce2d9adf569a6775049d78c312ccf0bdd8aa75 | bigcode/the-stack | train |
1b20bef54f645b3a4e9632f8 | train | function | def load_slice_info(path, verbose=False):
"""
Loads slice data. Returns dicts:
data, units
data has keys:
initial_particles
final_particles
and each is a dict with the slice statistics arrays
"""
data = load_many_fort(path, FORT_SLICE_TYPES, verbose=verbose)... | def load_slice_info(path, verbose=False):
| """
Loads slice data. Returns dicts:
data, units
data has keys:
initial_particles
final_particles
and each is a dict with the slice statistics arrays
"""
data = load_many_fort(path, FORT_SLICE_TYPES, verbose=verbose)
units = {}
data1=data[list(d... | Replace -
if k.startswith('-'):
newkey = k[1:]
data[newkey] = -1*data.pop(k)
k=newkey
# Add to units
units[k] = u
return data, units
def load_slice_info(path, verbose=False):
| 64 | 64 | 120 | 9 | 54 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_slice_info | load_slice_info | 2,043 | 2,063 | 2,043 | 2,043 | 9ff4c1ad0188f58846850069e417b7d66960ef49 | bigcode/the-stack | train |
1aa419146c006f756e5fcbd6 | train | function | def load_fort24(filePath, keys=FORT_KEYS[24]):
'''From impact manual:
fort.24, fort.25: X and Y RMS size information
1st col: time (secs)
2nd col: z distance (m)
3rd col: centroid location (m)
4th col: RMS size (m)
5th col: Centroid momentum normalized by MC
6th col: RMS momentum normali... | def load_fort24(filePath, keys=FORT_KEYS[24]):
| '''From impact manual:
fort.24, fort.25: X and Y RMS size information
1st col: time (secs)
2nd col: z distance (m)
3rd col: centroid location (m)
4th col: RMS size (m)
5th col: Centroid momentum normalized by MC
6th col: RMS momentum normalized by MC
7th col: Twiss parameter: -<x, ga... | _x__gammabeta_x','norm_emit_x']
FORT_UNITS[24] = ['s', 'm', 'm', 'm', '1', '1', 'm', 'm' ]
def load_fort24(filePath, keys=FORT_KEYS[24]):
| 64 | 64 | 152 | 15 | 49 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort24 | load_fort24 | 1,627 | 1,639 | 1,627 | 1,627 | 029a2b4c0a09bc14627e4ed264dcf99dc08068cc | bigcode/the-stack | train |
068d9626f5fd136b1a390953 | train | function | def load_fortX(filePath, keys):
data = {}
#Load the data
fortdata = np.loadtxt(filePath, ndmin=1)
for count, key in enumerate(keys):
data[key] = fortdata[:,count]
return data
| def load_fortX(filePath, keys):
| data = {}
#Load the data
fortdata = np.loadtxt(filePath, ndmin=1)
for count, key in enumerate(keys):
data[key] = fortdata[:,count]
return data
| rows=skiprows, dtype=dtype,
ndmin=1) # to make sure that 1 particle is parsed the same as many.
return pdat
#-----------------------------------------------------------------
#-----------------------------------------------------------------
# Parsers for Impact-T fort.X output
d... | 64 | 64 | 58 | 10 | 53 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fortX | load_fortX | 1,601 | 1,607 | 1,601 | 1,601 | ad817ab3de89fd5f8849e8d5287ec5be978f6436 | bigcode/the-stack | train |
fc5d66353c6121535770e648 | train | function | def load_fort35(filePath, keys=FORT_KEYS[35] ):
"""Same as load_fort25, but in the dipole coordinate system"""
return load_fortX(filePath, keys)
| def load_fort35(filePath, keys=FORT_KEYS[35] ):
| """Same as load_fort25, but in the dipole coordinate system"""
return load_fortX(filePath, keys)
| ITS[27]
def load_fort34(filePath, keys=FORT_KEYS[34] ):
"""Same as load_fort24, but in the dipole coordinate system"""
return load_fortX(filePath, keys)
def load_fort35(filePath, keys=FORT_KEYS[35] ):
| 64 | 64 | 44 | 16 | 48 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort35 | load_fort35 | 1,739 | 1,741 | 1,739 | 1,739 | ee826435560678f256f95d19ec4dc693f295989b | bigcode/the-stack | train |
d965c16df082b5ea1dab0d4b | train | function | def load_fort60_and_70(filePath, keys=FORT_KEYS[60]):
"""
1st col: bunch length (m)
2nd col: number of macroparticles per cell
3rd col: current (A)
4th col: x slice emittance (m*rad)
5th col: y slice emittance (m*rad)
6th col: mean energy (eV)
7th col: energy spread (eV)
"""
retu... | def load_fort60_and_70(filePath, keys=FORT_KEYS[60]):
| """
1st col: bunch length (m)
2nd col: number of macroparticles per cell
3rd col: current (A)
4th col: x slice emittance (m*rad)
5th col: y slice emittance (m*rad)
6th col: mean energy (eV)
7th col: energy spread (eV)
"""
return load_fortX(filePath, keys)
| _x', 'norm_emit_y', 'mean_energy', 'sigma_energy']
FORT_UNITS[60] = ['m', '1', 'A', 'm', 'm', 'eV', 'eV']
def load_fort60_and_70(filePath, keys=FORT_KEYS[60]):
| 64 | 64 | 122 | 18 | 46 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort60_and_70 | load_fort60_and_70 | 1,768 | 1,778 | 1,768 | 1,768 | 30f961ae3306804e19949f92aa0e5b20e21183de | bigcode/the-stack | train |
bc57a82235351f7352c4864a | train | function | def load_fort28(filePath, keys=FORT_KEYS[28] ):
'''From impact manual:
fort.28: load balance and loss diagnostic
1st col: time (secs)
2nd col: z distance (m)
3rd col: min # of particles on a PE
4th col: max # of particles on a PE
5th col: total # of particles in the bunch
'''
return ... | def load_fort28(filePath, keys=FORT_KEYS[28] ):
| '''From impact manual:
fort.28: load balance and loss diagnostic
1st col: time (secs)
2nd col: z distance (m)
3rd col: min # of particles on a PE
4th col: max # of particles on a PE
5th col: total # of particles in the bunch
'''
return load_fortX(filePath, keys)
| t', 'mean_z', 'loadbalance_min_n_particle', 'loadbalance_max_n_particle','n_particle']
FORT_UNITS[28] = ['s', 'm', '1', '1', '1' ]
def load_fort28(filePath, keys=FORT_KEYS[28] ):
| 64 | 64 | 109 | 16 | 48 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort28 | load_fort28 | 1,682 | 1,691 | 1,682 | 1,682 | ea6e0496b3ec6415314fe35da9dea80504d0aaa2 | bigcode/the-stack | train |
c98432ec7a9fad1b67a45015 | train | function | def header_lines(header_dict, annotate=True):
"""
Re-forms the header dict into lines to be written to the Impact-T input file
"""
line0 = '! Impact-T input file'
lines = [line0]
for i in range(1,10):
names = HNAMES[i]
if annotate:
lines.append('!'+... | def header_lines(header_dict, annotate=True):
| """
Re-forms the header dict into lines to be written to the Impact-T input file
"""
line0 = '! Impact-T input file'
lines = [line0]
for i in range(1,10):
names = HNAMES[i]
if annotate:
lines.append('!'+ ' '.join(names))
x = ' '... | 0] as the original line, so the indexing starts at 1
"""
v = line.split('/')[0].split()[3:] # V data starts with index 4
v[0] = line # Preserve original line
return v
def header_lines(header_dict, annotate=True):
| 64 | 64 | 118 | 9 | 54 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | header_lines | header_lines | 357 | 374 | 357 | 357 | 56d278d44293113efb69548f0123ebe4a2a7acad | bigcode/the-stack | train |
73b9011618bb3f0e383d4bce | train | function | def create_names(elelist):
"""
Invent a name for elements
"""
counter = {}
for t in list(ele_type.values())+['comment', 'undocumented']:
counter[t] = 0
for e in elelist:
t = e['type']
counter[t] = counter[t]+1
e['name'] = e['type']+'_'+str(counter[t])
... | def create_names(elelist):
| """
Invent a name for elements
"""
counter = {}
for t in list(ele_type.values())+['comment', 'undocumented']:
counter[t] = 0
for e in elelist:
t = e['type']
counter[t] = counter[t]+1
e['name'] = e['type']+'_'+str(counter[t])
# Try from des... | # if e['type'] in ['change_timestep', 'offset_beam', 'spacecharge', 'stop', 'write_beam', 'write_beam_for_restart']:
continue
# s = s + e['L']
# e['s'] = s
def create_names(elelist):
| 64 | 64 | 129 | 6 | 57 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | create_names | create_names | 1,478 | 1,494 | 1,478 | 1,478 | 6e4da6c73a8f5d242e0f9ae27f02ac6b8a86d562 | bigcode/the-stack | train |
1940932e0a8d847a40706bbf | train | function | def load_fort30(filePath, keys=FORT_KEYS[30] ):
'''
fort.30: Fourth root of 4th moments of the beam distribution
1st col: time (secs) 2nd col: z distance (m) 3rd col: X (m)
4th col: Px (mc)
5th col: Y (m)
6th col: Py (mc)
7th col: Z (m)
8th col: Pz (mc)
'''
return loa... | def load_fort30(filePath, keys=FORT_KEYS[30] ):
| '''
fort.30: Fourth root of 4th moments of the beam distribution
1st col: time (secs) 2nd col: z distance (m) 3rd col: X (m)
4th col: Px (mc)
5th col: Y (m)
6th col: Py (mc)
7th col: Z (m)
8th col: Pz (mc)
'''
return load_fortX(filePath, keys)
| moment4_gammabeta_x', 'moment4_y','moment4_gammabeta_y', 'moment4_z','moment4_gammabeta_z']
FORT_UNITS[30] = FORT_UNITS[29]
def load_fort30(filePath, keys=FORT_KEYS[30] ):
| 64 | 64 | 129 | 16 | 48 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort30 | load_fort30 | 1,711 | 1,721 | 1,711 | 1,711 | 78f7f3b9da8ca33163e402a8818f8e9b7a95d25d | bigcode/the-stack | train |
b138c43f329358b45e2b2121 | train | function | def parse_rotationally_symmetric_to_3d(line):
"""
If btype = −5, switch the simulation from azimuthal symmetry to fully 3d simulation after location V3(m).
This location should be set as large negative number such as -1000.0 in order to start the 3D simulation immediately after the electron emission.
I... | def parse_rotationally_symmetric_to_3d(line):
| """
If btype = −5, switch the simulation from azimuthal symmetry to fully 3d simulation after location V3(m).
This location should be set as large negative number such as -1000.0 in order to start the 3D simulation immediately after the electron emission.
If there are multiple such lines in the input f... | 0
v = [ele, dummy, dummy, ele['s'], ele['dt']]
return v
ELE_DEFAULTS['change_timestep'] = {
's':0,
'dt':0}
#-----------------------------------------------------------------
def parse_rotationally_symmetric_to_3d(line):
| 63 | 64 | 124 | 13 | 50 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | parse_rotationally_symmetric_to_3d | parse_rotationally_symmetric_to_3d | 1,094 | 1,105 | 1,094 | 1,094 | 7e547179279af29036bd5aa2080740e1e2c85434 | bigcode/the-stack | train |
c9640de018b83510d0e9a3e8 | train | function | def fort_type(filePath):
"""
Extract the integer type of a fort.X file, where X is the type.
"""
fullpath = os.path.abspath(filePath)
p, f = os.path.split(fullpath)
s = f.split('.')
if s[0] != 'fort':
print('Error: not a fort file:', filePath)
else:
return int(s[1])
| def fort_type(filePath):
| """
Extract the integer type of a fort.X file, where X is the type.
"""
fullpath = os.path.abspath(filePath)
p, f = os.path.split(fullpath)
s = f.split('.')
if s[0] != 'fort':
print('Error: not a fort file:', filePath)
else:
return int(s[1])
| fort.X fliles in path
"""
assert os.path.isdir(path)
flist = os.listdir(path)
fortfiles=[]
for f in flist:
if f.startswith('fort.'):
fortfiles.append(os.path.join(path,f))
return fortfiles
def fort_type(filePath):
| 64 | 64 | 89 | 6 | 57 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | fort_type | fort_type | 1,830 | 1,840 | 1,830 | 1,830 | 2ee6bc19da6859bc65fb3642cafa3b4da1eac70f | bigcode/the-stack | train |
5c0c01e082879df401fab13a | train | function | def load_fort70(filePath):
"""
Returns dict with 'final_particle_slices'
"""
data = load_fort60_and_70(filePath)
return {'final_particle_slices':data}
| def load_fort70(filePath):
| """
Returns dict with 'final_particle_slices'
"""
data = load_fort60_and_70(filePath)
return {'final_particle_slices':data}
| Path)
return {'final_particles':data}
def load_fort60(filePath):
"""
Returns dict with 'initial_particle_slices'
"""
data = load_fort60_and_70(filePath)
return {'initial_particle_slices':data}
def load_fort70(filePath):
| 64 | 64 | 45 | 8 | 56 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort70 | load_fort70 | 1,808 | 1,813 | 1,808 | 1,808 | ec6645b518511e9b58140ba4203f2e8c6fd19272 | bigcode/the-stack | train |
72269ad0fef68f36f3e360ca | train | function | def parse_emfield_cartesian(line):
"""
emfield_cartesian
111: EMfldCart
Read in discrete EM field data Ex(MV/m), Ey(MV/m), Ez(MV/m), Bx(MV/m), By(MV/m), Bz(MV/m), as a function of (x,y,z).
V1: zedge
V2: rf_field_scale
V3: RF frequency
V4: theta0_deg
V5: file ID
V6: radi... | def parse_emfield_cartesian(line):
| """
emfield_cartesian
111: EMfldCart
Read in discrete EM field data Ex(MV/m), Ey(MV/m), Ez(MV/m), Bx(MV/m), By(MV/m), Bz(MV/m), as a function of (x,y,z).
V1: zedge
V2: rf_field_scale
V3: RF frequency
V4: theta0_deg
V5: file ID
V6: radius Not used yet
V... | {
'zedge':0,
'rf_field_scale':0,
'rf_frequency':0,
'theta0_deg':0,
'filename':'rfdata99',
'radius':0,
'solenoid_field_scale':0,
'x_offset':0,
'y_offset':0,
'x_rotation':0,
'y_rotation':0,
'z_rotation':0}
#---------------------------------------------------------... | 103 | 103 | 344 | 8 | 95 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | parse_emfield_cartesian | parse_emfield_cartesian | 792 | 827 | 792 | 792 | 96828cbcd007d8932d54df0f969e1e7e498bbdba | bigcode/the-stack | train |
34a02db2e1a12a8ac2eea04d | train | function | def parse_stop(line):
"""
Stop (type -99)
If bytpe = −99, stop the simulation at given location V3(m).
"""
v = v_from_line(line)
d={'s':float(v[3])}
return d
| def parse_stop(line):
| """
Stop (type -99)
If bytpe = −99, stop the simulation at given location V3(m).
"""
v = v_from_line(line)
d={'s':float(v[3])}
return d
| ['wakefield'] = {
's_begin':0,
's':0,
'method':'analytical',
'filename':'fort.99',
'iris_radius':0,
'gap':0,
'period':0
}
#-----------------------------------------------------------------
def parse_stop(line):
| 63 | 64 | 60 | 5 | 58 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | parse_stop | parse_stop | 1,201 | 1,211 | 1,201 | 1,201 | 71eec6ca7e74d1ace599f8bb26f0cb263025a623 | bigcode/the-stack | train |
d33e542810b08e88ca47064a | train | function | def parse_write_slice_info(line):
"""
If bytpe = −9, output slice-based information at given location V3(m) into file “fort.Bmpstp” using “Bnseg” slices.
"""
x = line.split()
Bnseg = int(x[1])
Bmpstp = int(x[2])
v = v_from_line(line)
d={}
d['n_slices'] = Bnseg
d['... | def parse_write_slice_info(line):
| """
If bytpe = −9, output slice-based information at given location V3(m) into file “fort.Bmpstp” using “Bnseg” slices.
"""
x = line.split()
Bnseg = int(x[1])
Bmpstp = int(x[2])
v = v_from_line(line)
d={}
d['n_slices'] = Bnseg
d['filename'] = 'fort.'+str(Bmpstp)
... | else:
sign = -1
v = [ele, dummy, sign, ele['s'] ]
return v
ELE_DEFAULTS['spacecharge'] = {
's':0,
'is_on':False
}
#-----------------------------------------------------------------
def parse_write_slice_info(line):
| 63 | 64 | 130 | 7 | 56 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | parse_write_slice_info | parse_write_slice_info | 1,279 | 1,295 | 1,279 | 1,279 | 229fc3d9cca2c43523b4e9a01198bd6ece1c9475 | bigcode/the-stack | train |
132ccd2cafb1976b2fdc22a4 | train | function | def load_fort50(filePath):
"""
Returns dict with 'final_particles'
"""
data = parse_impact_particles(filePath)
return {'final_particles':data}
| def load_fort50(filePath):
| """
Returns dict with 'final_particles'
"""
data = parse_impact_particles(filePath)
return {'final_particles':data}
| X(filePath, keys)
# Wrapper functions to provide keyed output
def load_fort40(filePath):
"""
Returns dict with 'initial_particles'
"""
data = parse_impact_particles(filePath)
return {'initial_particles':data}
def load_fort50(filePath):
| 63 | 64 | 39 | 8 | 55 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_fort50 | load_fort50 | 1,794 | 1,799 | 1,794 | 1,794 | 813552124964b7b481fe2bbf6faa5f48f6eff2dd | bigcode/the-stack | train |
158886f9d04410e666f09be7 | train | function | def header_is_good(header_dict):
"""
Sanity check of header.
"""
good = False
if header_dict['Flagmap'] != 1:
return False
if header_dict['Flagbc'] != 1:
return False
h = header_dict.copy()
# These keys must be in header
for k in ALL_HEADER_NAMES:
... | def header_is_good(header_dict):
| """
Sanity check of header.
"""
good = False
if header_dict['Flagmap'] != 1:
return False
if header_dict['Flagbc'] != 1:
return False
h = header_dict.copy()
# These keys must be in header
for k in ALL_HEADER_NAMES:
if k not in h:
pr... | .'
help['Bmass'] = 'Mass of the particles in eV.'
help['Bcharge'] = 'Particle charge in units of proton charge.'
help['Bfreq'] = 'Reference frequency in Hz.'
help['Tini'] = 'Initial reference time in seconds.'
def header_is_good(header_dict):
| 63 | 64 | 178 | 7 | 56 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | header_is_good | header_is_good | 174 | 205 | 174 | 174 | eb1752599126629aae0a5dd99a7c254090b67e97 | bigcode/the-stack | train |
2b0a42e5560ffcd7f5796788 | train | function | def load_many_fort(path, types=FORT_STAT_TYPES, verbose=False):
"""
Loads a large dict with data from many fort files.
Checks that keys do not conflict.
Default types are for typical statistical information along the simulation path.
"""
fortfiles=fort_files(path)
alldat = {}
... | def load_many_fort(path, types=FORT_STAT_TYPES, verbose=False):
| """
Loads a large dict with data from many fort files.
Checks that keys do not conflict.
Default types are for typical statistical information along the simulation path.
"""
fortfiles=fort_files(path)
alldat = {}
for f in fortfiles:
file_type = fort_type(f, verbose=Fal... | 36, 37, 38]
FORT_PARTICLE_TYPES = [40,50]
FORT_SLICE_TYPES = [60,70]
# All of these
# Not uesed: FORT_OUTPUT_TYPES = FORT_STAT_TYPES + FORT_PARTICLE_TYPES + FORT_SLICE_TYPES
def load_many_fort(path, types=FORT_STAT_TYPES, verbose=False):
| 78 | 79 | 264 | 16 | 61 | jacquelinegarrahan/lume-impact | impact/parsers.py | Python | load_many_fort | load_many_fort | 1,951 | 1,982 | 1,951 | 1,951 | 6639bf210f6b381dfeaf6f8dc8af6ebe27eb644a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.