file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
index.ts
import * as chalk from 'chalk'; import * as path from 'path'; import { IHookEngine, fsReadJsonFile } from '@ionic/cli-utils'; import { serve } from './serve/index'; export const name = '__NAME__'; export const version = '__VERSION__'; export const preferGlobal = false; export function registerHooks(hooks: IHookEngi...
const getIonic1Version = async (): Promise<string | undefined> => { const ionicVersionFilePath = path.resolve(env.project.directory, 'www', 'lib', 'ionic', 'version.json'); // TODO try { const ionicVersionJson = await fsReadJsonFile(ionicVersionFilePath); return ionicVersionJson['vers...
{ return []; }
conditional_block
index.ts
import * as chalk from 'chalk'; import * as path from 'path'; import { IHookEngine, fsReadJsonFile } from '@ionic/cli-utils'; import { serve } from './serve/index'; export const name = '__NAME__'; export const version = '__VERSION__'; export const preferGlobal = false; export function
(hooks: IHookEngine) { hooks.register(name, 'command:docs', async () => { return 'https://ionicframework.com/docs/v1/'; }); hooks.register(name, 'command:info', async ({ env }) => { if (!env.project.directory) { return []; } const getIonic1Version = async (): Promise<string | undefined> =>...
registerHooks
identifier_name
index.ts
import * as chalk from 'chalk'; import * as path from 'path'; import { IHookEngine, fsReadJsonFile } from '@ionic/cli-utils'; import { serve } from './serve/index'; export const name = '__NAME__'; export const version = '__VERSION__'; export const preferGlobal = false; export function registerHooks(hooks: IHookEngi...
const ionic1Version = await getIonic1Version(); return [ { type: 'local-packages', name: 'Ionic Framework', version: ionic1Version ? `ionic1 ${ionic1Version}` : 'unknown' }, { type: 'local-packages', name, version }, ]; }); hooks.register(name, 'command:serve', async (args) => { retur...
{ hooks.register(name, 'command:docs', async () => { return 'https://ionicframework.com/docs/v1/'; }); hooks.register(name, 'command:info', async ({ env }) => { if (!env.project.directory) { return []; } const getIonic1Version = async (): Promise<string | undefined> => { const ionicV...
identifier_body
index.ts
import * as chalk from 'chalk'; import * as path from 'path'; import { IHookEngine, fsReadJsonFile } from '@ionic/cli-utils'; import { serve } from './serve/index'; export const name = '__NAME__'; export const version = '__VERSION__'; export const preferGlobal = false; export function registerHooks(hooks: IHookEngi...
return 'https://ionicframework.com/docs/v1/'; }); hooks.register(name, 'command:info', async ({ env }) => { if (!env.project.directory) { return []; } const getIonic1Version = async (): Promise<string | undefined> => { const ionicVersionFilePath = path.resolve(env.project.directory, 'w...
random_line_split
keypad.rs
// keypad.rs --- // // Filename: keypad.rs // Author: Jules <archjules> // Created: Wed Mar 22 17:07:36 2017 (+0100) // Last-Updated: Wed Mar 22 17:17:14 2017 (+0100) // By: Jules <archjules> // pub struct Keypad { a_button: bool, b_button: bool, select: bool, start: bool, right: bool,...
} } pub fn get_keyinput(&self) -> u16 { (self.a_button as u16) | ((self.b_button as u16) << 1) | ((self.select as u16) << 2) | ((self.start as u16) << 3) | ((self.right as u16) << 4) | ((self.left as u16) << 5) | ((self.up as u16) << 6) | ...
down: false, r_button: false, l_button: false,
random_line_split
keypad.rs
// keypad.rs --- // // Filename: keypad.rs // Author: Jules <archjules> // Created: Wed Mar 22 17:07:36 2017 (+0100) // Last-Updated: Wed Mar 22 17:17:14 2017 (+0100) // By: Jules <archjules> // pub struct Keypad { a_button: bool, b_button: bool, select: bool, start: bool, right: bool,...
pub fn get_keyinput(&self) -> u16 { (self.a_button as u16) | ((self.b_button as u16) << 1) | ((self.select as u16) << 2) | ((self.start as u16) << 3) | ((self.right as u16) << 4) | ((self.left as u16) << 5) | ((self.up as u16) << 6) | ((self.down as ...
{ Keypad { a_button: false, b_button: false, select: false, start: false, right: false, left: false, up: false, down: false, r_button: false, l_button: false, } }
identifier_body
keypad.rs
// keypad.rs --- // // Filename: keypad.rs // Author: Jules <archjules> // Created: Wed Mar 22 17:07:36 2017 (+0100) // Last-Updated: Wed Mar 22 17:17:14 2017 (+0100) // By: Jules <archjules> // pub struct Keypad { a_button: bool, b_button: bool, select: bool, start: bool, right: bool,...
() -> Keypad { Keypad { a_button: false, b_button: false, select: false, start: false, right: false, left: false, up: false, down: false, r_button: false, l_button: false, } } ...
new
identifier_name
drop-order.rs
// run-pass //! Test that let bindings and destructuring assignments have consistent drop orders #![feature(destructuring_assignment)] #![allow(unused_variables, unused_assignments)] use std::cell::RefCell; thread_local! { static DROP_ORDER: RefCell<Vec<usize>> = RefCell::new(Vec::new()); } struct DropRecorder...
() { let expected_drop_order = vec![1, 4, 5, 3, 2]; // Check the drop order for let bindings: { let _ = DropRecorder(1); let _val = DropRecorder(2); let (x, _) = (DropRecorder(3), DropRecorder(4)); drop(DropRecorder(5)); } DROP_ORDER.with(|d| { assert_eq!(&*d....
main
identifier_name
drop-order.rs
// run-pass //! Test that let bindings and destructuring assignments have consistent drop orders #![feature(destructuring_assignment)] #![allow(unused_variables, unused_assignments)] use std::cell::RefCell; thread_local! { static DROP_ORDER: RefCell<Vec<usize>> = RefCell::new(Vec::new()); }
} fn main() { let expected_drop_order = vec![1, 4, 5, 3, 2]; // Check the drop order for let bindings: { let _ = DropRecorder(1); let _val = DropRecorder(2); let (x, _) = (DropRecorder(3), DropRecorder(4)); drop(DropRecorder(5)); } DROP_ORDER.with(|d| { asser...
struct DropRecorder(usize); impl Drop for DropRecorder { fn drop(&mut self) { DROP_ORDER.with(|d| d.borrow_mut().push(self.0)); }
random_line_split
convert.py
file extension mapped to the converter function # imported from /converters. CONVERTERS = { "conllubio": conllu_to_docs, "conllu": conllu_to_docs, "conll": conllu_to_docs, "ner": conll_ner_to_docs, "iob": iob_to_docs, "json": json_to_docs, } # File types that can be written to stdout FILE_TY...
locs.append(path) # It's good to sort these, in case the ordering messes up cache. locs.sort() return locs def verify_cli_args( msg: Printer, input_path: Union[str, Path], output_dir: Union[str, Path], file_type: FileTypes, converter: str, ner_map: Optional[Path], ): ...
if not path.is_dir(): return [path] paths = [path] locs = [] seen = set() for path in paths: if str(path) in seen: continue seen.add(str(path)) if path.parts[-1].startswith("."): continue elif path.is_dir(): paths.extend(path.it...
identifier_body
convert.py
file extension mapped to the converter function # imported from /converters. CONVERTERS = { "conllubio": conllu_to_docs, "conllu": conllu_to_docs, "conll": conllu_to_docs, "ner": conll_ner_to_docs, "iob": iob_to_docs, "json": json_to_docs, } # File types that can be written to stdout FILE_TY...
""" Convert files into json or DocBin format for training. The resulting .spacy file can be used with the train command and other experiment management functions. If no output_dir is specified and the output format is JSON, the data is written to stdout, so you can pipe them forward to a JSON f...
ner_map: Optional[Path] = Opt(None, "--ner-map", "-nm", help="NER tag mapping (as JSON-encoded dict of entity types)", exists=True), lang: Optional[str] = Opt(None, "--lang", "-l", help="Language (if tokenizer required)"), concatenate: bool = Opt(None, "--concatenate", "-C", help="Concatenate output to a si...
random_line_split
convert.py
extension mapped to the converter function # imported from /converters. CONVERTERS = { "conllubio": conllu_to_docs, "conllu": conllu_to_docs, "conll": conllu_to_docs, "ner": conll_ner_to_docs, "iob": iob_to_docs, "json": json_to_docs, } # File types that can be written to stdout FILE_TYPES_S...
(str, Enum): json = "json" spacy = "spacy" @app.command("convert") def convert_cli( # fmt: off input_path: str = Arg(..., help="Input file or directory", exists=True), output_dir: Path = Arg("-", help="Output directory. '-' for stdout.", allow_dash=True, exists=True), file_type: FileTypes = Op...
FileTypes
identifier_name
convert.py
file extension mapped to the converter function # imported from /converters. CONVERTERS = { "conllubio": conllu_to_docs, "conllu": conllu_to_docs, "conll": conllu_to_docs, "ner": conll_ner_to_docs, "iob": iob_to_docs, "json": json_to_docs, } # File types that can be written to stdout FILE_TY...
seen.add(str(path)) if path.parts[-1].startswith("."): continue elif path.is_dir(): paths.extend(path.iterdir()) elif converter == "json" and not path.parts[-1].endswith("json"): continue elif converter == "conll" and not path.parts[-1].endswi...
continue
conditional_block
01-run.py
#!/usr/bin/env python3 """Test behaviour of the test running and the term program interaction.""" import sys import pexpect from testrunner import run def _shellping(child, timeout=1): """Issue a 'shellping' command. Raises a pexpect exception on failure. :param timeout: timeout for the answer """ ...
else: # This one should fail _shellping(child) def _test_no_local_echo(child): """Verify that there is not local echo while testing.""" msg = 'true this should not be echoed' child.sendline(msg) res = child.expect_exact([pexpect.TIMEOUT, msg], timeout=1) assert res == 0, "Ther...
try: _shellping(child) except pexpect.TIMEOUT: pass else: break
conditional_block
01-run.py
#!/usr/bin/env python3 """Test behaviour of the test running and the term program interaction.""" import sys import pexpect from testrunner import run def _shellping(child, timeout=1): """Issue a 'shellping' command. Raises a pexpect exception on failure. :param timeout: timeout for the answer """ ...
(child, numtries=5): """Wait until the shell is ready by using 'shellping'.""" for _ in range(numtries - 1): try: _shellping(child) except pexpect.TIMEOUT: pass else: break else: # This one should fail _shellping(child) def _test_...
_wait_shell_ready
identifier_name
01-run.py
#!/usr/bin/env python3 """Test behaviour of the test running and the term program interaction.""" import sys import pexpect from testrunner import run def _shellping(child, timeout=1): """Issue a 'shellping' command. Raises a pexpect exception on failure. :param timeout: timeout for the answer """ ...
# The node should still answer after the previous one _shellping(child) if __name__ == "__main__": sys.exit(run(testfunc))
_wait_shell_ready(child) # Verify there is no local and remote echo as it is disabled _test_no_local_echo(child)
random_line_split
01-run.py
#!/usr/bin/env python3 """Test behaviour of the test running and the term program interaction.""" import sys import pexpect from testrunner import run def _shellping(child, timeout=1): """Issue a 'shellping' command. Raises a pexpect exception on failure. :param timeout: timeout for the answer """ ...
def testfunc(child): """Run some tests to verify the board under test behaves correctly. It currently tests: * local echo """ child.expect_exact("Running 'tests_tools' application") _wait_shell_ready(child) # Verify there is no local and remote echo as it is disabled _test_no_loca...
"""Verify that there is not local echo while testing.""" msg = 'true this should not be echoed' child.sendline(msg) res = child.expect_exact([pexpect.TIMEOUT, msg], timeout=1) assert res == 0, "There should have been a timeout and not match stdin"
identifier_body
oneOfArray.ts
/* The MIT License Copyright (c) 2017-2019 EclipseSource Munich https://github.com/eclipsesource/jsonforms Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, inc...
$schema: 'http://json-schema.org/draft-07/schema#', definitions: { address: { type: 'object', properties: { street_address: { type: 'string' }, city: { type: 'string' }, state: { type: 'string' } }, required: ['street_address', 'city', 'state'] }, user: {...
import { registerExamples } from '../register'; export const schema = {
random_line_split
surnametab.py
origmap, key=lambda x: glocale.sort_key(self.cmborigmap[x])) for key in keys: if key != no.get_custom(): self.cmborig.append(row=[key, self.cmborigmap[key]]) additional = self.dbstate.db.get_origin_types() if additional: for type in additional: ...
""" Handles the key being pressed. Here we make sure tab moves to next or previous value in row on TAB """ if not EmbeddedList.key_pressed(self, obj, event): if event.type == Gdk.EventType.KEY_PRESS and event.keyval in (_TAB,): if no_match_primary_mask(event.g...
identifier_body
surnametab.py
# #------------------------------------------------------------------------- class SurnameTab(EmbeddedList): _HANDLE_COL = 5 _DND_TYPE = DdTargets.SURNAME _MSG = { 'add' : _('Create and add a new surname'), 'del' : _('Remove the selected surname'), 'edit' : _('Edit the select...
""" node = self.model.get_iter(path) text = new_text.translate(INVISIBLE).strip() self.model.set_value(node, colnr, text) self.update() def on_orig_edited(self, cellr, path, new_text, colnr): """ An edit is finished in the origin type column. For
""" Edit is happening. The model is updated and the surname objects updated. colnr must be the column in the model.
random_line_split
surnametab.py
_column(column) # toggle box for primary colno += 1 name = self._column_toggle[0] renderer = Gtk.CellRendererToggle() renderer.set_property('activatable', True) renderer.set_property('radio', True) renderer.connect( 'toggled', self.on_prim_toggled, self._column_to...
if path < len(self.obj.get_surname_list()): newpath = Gtk.TreePath((path+1,)) self.curr_celle.editing_done() self.selection.select_path(newpath) self.tree.set_cursor_on_cell(newpath, focus_column=self.co...
conditional_block
surnametab.py
# #------------------------------------------------------------------------- class SurnameTab(EmbeddedList): _HANDLE_COL = 5 _DND_TYPE = DdTargets.SURNAME _MSG = { 'add' : _('Create and add a new surname'), 'del' : _('Remove the selected surname'), 'edit' : _('Edit the select...
(self, dbstate, uistate, track, name, on_change=None, top_label='<b>%s</b>' % _("Multiple Surnames") ): self.obj = name self.on_change = on_change self.curr_col = -1 self.curr_cellr = None self.curr_celle = None EmbeddedList.__init__(self, dbstate, uista...
__init__
identifier_name
estimateintrons.py
#!/usr/bin/env python import argparse import os import sqlite3 from Bio import SeqIO, SeqRecord, Seq from Bio.Align.Applications import ClustalwCommandline from Bio.Blast import NCBIXML from Bio.Blast.Applications import NcbiblastnCommandline as bn from Bio import AlignIO AT_DB_FILE = 'AT.db' BLAST_EXE = '~/opt/ncbi...
res_cur = c.execute('SELECT CDS, FULL_SEQ from seq ' 'WHERE ID=?', (sid,)) cds, full_seq = res_cur.fetchone() if cds=='': print('There is no matching CDS') exit() # Check sequence polarity. sidcds = '{0}-CDS'.format(sid) sidseq = '{0}-SEQ'.format(sid) ...
"""Infer Splicing Sites from a FASTA file full of EST sequences""" with open('forblast','w') as forblastfh: forblastfh.write(str(user_seq.seq)) blastn_cline = bn(cmd=BLAST_EXE, query='forblast', db=BLAST_DB, evalue='1e-10', outfmt=5, num_descriptions='1'...
identifier_body
estimateintrons.py
#!/usr/bin/env python import argparse import os import sqlite3 from Bio import SeqIO, SeqRecord, Seq from Bio.Align.Applications import ClustalwCommandline from Bio.Blast import NCBIXML from Bio.Blast.Applications import NcbiblastnCommandline as bn from Bio import AlignIO AT_DB_FILE = 'AT.db' BLAST_EXE = '~/opt/ncbi...
(seq): """Return a list with tuples containing all gap positions and length. seq is a string.""" gaps = [] indash = False for i, c in enumerate(seq): if indash is False and c == '-': c_ini = i indash = True dashn = 0 elif indash is True and c ==...
allgaps
identifier_name
estimateintrons.py
#!/usr/bin/env python import argparse import os import sqlite3 from Bio import SeqIO, SeqRecord, Seq from Bio.Align.Applications import ClustalwCommandline from Bio.Blast import NCBIXML from Bio.Blast.Applications import NcbiblastnCommandline as bn from Bio import AlignIO AT_DB_FILE = 'AT.db' BLAST_EXE = '~/opt/ncbi...
id = sidseq, name='', description='') else: seqCDS = SeqRecord.SeqRecord( Seq.Seq(cds).reverse_complement(), id = sidcds, name='', description='') fullseq = SeqRe...
random_line_split
estimateintrons.py
#!/usr/bin/env python import argparse import os import sqlite3 from Bio import SeqIO, SeqRecord, Seq from Bio.Align.Applications import ClustalwCommandline from Bio.Blast import NCBIXML from Bio.Blast.Applications import NcbiblastnCommandline as bn from Bio import AlignIO AT_DB_FILE = 'AT.db' BLAST_EXE = '~/opt/ncbi...
elif indash is True and c != '-': indash = False gaps.append((c_ini, dashn+1)) return gaps def iss(user_seq): """Infer Splicing Sites from a FASTA file full of EST sequences""" with open('forblast','w') as forblastfh: forblastfh.write(str(user_seq.seq)) bl...
dashn += 1
conditional_block
testing.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang (letang.jeremy@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitati...
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SO...
// copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
random_line_split
test_realizer_arbitrary_reordering.py
import unittest import tagging class TestRealizerArbitraryReordering(unittest.TestCase): """ Tests for the realizer with arbitrary reordering enabled. """ def test_realize_output_in_order(self): """ Test for when source tokens occur in the same relative orde...
self.assertEqual(expected, result) if __name__ == '__main__': unittest.main()
random_line_split
test_realizer_arbitrary_reordering.py
import unittest import tagging class TestRealizerArbitraryReordering(unittest.TestCase): """ Tests for the realizer with arbitrary reordering enabled. """ def test_realize_output_in_order(self): """ Test for when source tokens occur in the same relative orde...
unittest.main()
conditional_block
test_realizer_arbitrary_reordering.py
import unittest import tagging class TestRealizerArbitraryReordering(unittest.TestCase):
def test_realize_output_out_of_order(self): """ Test for when the source tokens do not occur in the same relative order in the target string """ editing_task = tagging.EditingTask(["word1 word2 <::::> word3 "]) tags_str = ['KEEP|1', 'KEEP|0', 'KE...
""" Tests for the realizer with arbitrary reordering enabled. """ def test_realize_output_in_order(self): """ Test for when source tokens occur in the same relative order in the target string """ editing_task = tagging.EditingTask(["wo...
identifier_body
test_realizer_arbitrary_reordering.py
import unittest import tagging class
(unittest.TestCase): """ Tests for the realizer with arbitrary reordering enabled. """ def test_realize_output_in_order(self): """ Test for when source tokens occur in the same relative order in the target string """ editing_task =...
TestRealizerArbitraryReordering
identifier_name
1____Serial_Device_Settings_Change_Check.py
from ImageScripter import * from elan import * raise ValueError('fff') Viewer.Start() Viewer.CloseAndClean() Configurator.Start() Configurator.inputoutput.Click() addNewComDev(ComType = "Standard Connection",HardwareType = "Serial Port",Comport = '0') addNewDevice(Configurator.genericserialdevices,"Generic Serial De...
#################### Configurator.serialone.RightClickType('t') Configurator.system.Click() Configurator.RestartHard() Configurator.Start() Configurator.inputoutput.RealClick() ############################################TEST CODE sleep(3) Configurator.atatat2.RightClickType('d') HlConfig.PushButton.Click('Yes') Con...
Configurator.atatat2.RightClickTypeThenPress('aa','enter') Add.PushButton.Click('OK') Configurator.Edit.SetText(0,str(i)) Configurator.Edit.SetText(2,str(i)) Configurator.ComboBox.SelectAllWithIndex('1') Configurator.apply.Click()
conditional_block
1____Serial_Device_Settings_Change_Check.py
from ImageScripter import * from elan import * raise ValueError('fff') Viewer.Start() Viewer.CloseAndClean() Configurator.Start() Configurator.inputoutput.Click() addNewComDev(ComType = "Standard Connection",HardwareType = "Serial Port",Comport = '0') addNewDevice(Configurator.genericserialdevices,"Generic Serial De...
Configurator.atatat2.RightClickType('d') HlConfig.PushButton.Click('Yes') Configurator.atatat2.WaitVanish() Configurator.system.Click() Configurator.Reset()
Configurator.Start() Configurator.inputoutput.RealClick() ############################################TEST CODE sleep(3)
random_line_split
plugin.js
widget plugin to: * - require a data-entity-type and a data-entity-uuid attribute (which Drupal * uses to track where images are being used) * - use a Drupal-native dialog (that is in fact just an alterable Drupal form * like any other) instead of CKEditor's own dialogs. * * @see \Drupal\editor\Form\EditorIm...
editor.fire('saveSnapshot'); // Pass `true` so DocumentFragment will also be returned. var container = widget.wrapper.getParent(true); var image = widget.parts.image; // Set the updated widget data, after the necessary conversions from // the d...
{ widget.focus(); }
conditional_block
plugin.js
2 widget plugin to: * - require a data-entity-type and a data-entity-uuid attribute (which Drupal * uses to track where images are being used) * - use a Drupal-native dialog (that is in fact just an alterable Drupal form * like any other) instead of CKEditor's own dialogs. * * @see \Drupal\editor\Form\EditorI...
if (element.name !== 'img') { return; } // Don't initialize on pasted fake objects. else if (element.attributes['data-cke-realelement']) { return; } // Parse the data-entity-type attribute. data['data-entity-type'] = element....
// have a data-entity-type and a data-entity-uuid attribute. widgetDefinition.upcast = function (element, data) {
random_line_split
cndtr.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distribute...
cndtr.set_ndt(5); assert_eq!(cndtr.0, 5); } // TODO: Tests for out of range values? }
assert_eq!(cndtr.0, 65535);
random_line_split
cndtr.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distribute...
(u32); impl CNDTR { /* Bits 31:16 Reserved, must be kept at reset value. * Bits 15:0 NDT[15:0]: Number of data to transfer * * Number of data to be transferred (0 up to 65535). * * This register can only be written when the channel is disabled. * Once the channel is enabled, this re...
CNDTR
identifier_name
models.py
atch, on_delete=models.CASCADE) revision = models.ForeignKey(SeriesRevision, on_delete=models.CASCADE) order = models.IntegerField() class Meta: unique_together = [('revision', 'patch'), ('revision', 'order')] ordering = ['order'] class Event(models.Model): name = models.CharField(max...
_patch_post_change_callback
identifier_name
models.py
_2_unicode_compatible class Tag(models.Model): name = models.CharField(max_length=20) pattern = models.CharField(max_length=50, help_text='A simple regex to match the tag in the content of ' 'a message. Will be used with MULTILINE and IGNORECASE ' 'flags. ...
return qs.extra(select=select, select_params=select_params) class PatchManager(models.Manager): use_for_related_fields = True def get_queryset(self): return PatchQuerySet(self.model, using=self.db) def with_tag_counts(self, project): return self.get_queryset().with_tag_counts(p...
select[tag.attr_name] = ( "coalesce(" "(SELECT count FROM patchwork_patchtag " "WHERE patchwork_patchtag.patch_id=patchwork_patch.id " "AND patchwork_patchtag.tag_id=%s), 0)") select_params.append(tag.id)
conditional_block
models.py
in table column headers') @property def attr_name(self): return 'tag_%d_count' % self.id def __str__(self): return self.name class Meta: ordering = ['abbrev'] class PatchTag(models.Model): patch = models.ForeignKey('Patch', on_delete=models.CASCADE) tag = models.For...
return reverse('series', kwargs={'series': self.pk})
identifier_body
models.py
_2_unicode_compatible class Tag(models.Model): name = models.CharField(max_length=20) pattern = models.CharField(max_length=50, help_text='A simple regex to match the tag in the content of ' 'a message. Will be used with MULTILINE and IGNORECASE ' 'flags. ...
order = models.IntegerField() class Meta: unique_together = [('bundle', 'patch')] ordering = ['order'] SERIES_DEFAULT_NAME = "Series without cover letter" class TestState: STATE_PENDING = 0 STATE_INFO = 1 STATE_SUCCESS = 2 STATE_WARNING = 3 STATE_FAILURE = 4 STATE_CH...
random_line_split
screen_error_message.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Offline message screen implementation. */ login.createScreen('ErrorMessageScreen', 'error-message', function() { // Link whic...
, /** * Sets current UI state of the screen. * @param {string} ui_state New UI state of the screen. * @private */ setUIState_: function(ui_state) { this.classList.remove(this.ui_state); this.ui_state = ui_state; this.classList.add(this.ui_state); if (ui_state ==...
{ var buttons = []; var powerwashButton = this.ownerDocument.createElement('button'); powerwashButton.id = 'error-message-restart-and-powerwash-button'; powerwashButton.textContent = loadTimeData.getString('localStateErrorPowerwashButton'); powerwashButton.classList.add('show-with...
identifier_body
screen_error_message.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Offline message screen implementation. */ login.createScreen('ErrorMessageScreen', 'error-message', function() { // Link whic...
'</a>'); $('error-guest-signin-link').onclick = function() { chrome.send('launchIncognito'); }; $('error-offline-login').innerHTML = loadTimeData.getStringF( 'offlineLogin', '<a id="error-offline-login-link" class="signin-link" href="#">', '</a>'); ...
$('error-guest-signin').innerHTML = loadTimeData.getStringF( 'guestSignin', '<a id="error-guest-signin-link" class="signin-link" href="#">',
random_line_split
screen_error_message.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Offline message screen implementation. */ login.createScreen('ErrorMessageScreen', 'error-message', function() { // Link whic...
() { var buttons = []; var powerwashButton = this.ownerDocument.createElement('button'); powerwashButton.id = 'error-message-restart-and-powerwash-button'; powerwashButton.textContent = loadTimeData.getString('localStateErrorPowerwashButton'); powerwashButton.classList.add('show-w...
buttons
identifier_name
fast_forward.rs
use std::io; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::super::{RequestType, Request}; use ::proto::{self, Deserialize, Serialize}; #[derive(Debug, Clone)] pub enum FastForward { TrackBoundary = 0, } impl Deserialize for FastForward { fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Re...
} impl Serialize for FastForwardError { fn write(&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> { try!(proto::write_empty_struct(buf)); Ok(()) } }
{ try!(proto::read_empty_struct(buf)); Ok(FastForwardError) }
identifier_body
fast_forward.rs
use std::io; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::super::{RequestType, Request}; use ::proto::{self, Deserialize, Serialize}; #[derive(Debug, Clone)] pub enum FastForward { TrackBoundary = 0, } impl Deserialize for FastForward { fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Re...
(&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> { try!(proto::write_empty_struct(buf)); Ok(()) } }
write
identifier_name
fast_forward.rs
use std::io; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::super::{RequestType, Request}; use ::proto::{self, Deserialize, Serialize}; #[derive(Debug, Clone)] pub enum FastForward { TrackBoundary = 0, } impl Deserialize for FastForward { fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Re...
let kind = match kind { Some(kind) => kind, None => return Err(io::Error::new(io::ErrorKind::Other, "missing field: kind")), }; Ok(FastForwardRequest { kind: kind, }) } } impl Serialize for FastForwardRequest { fn write(&self, buf: &mut io::...
random_line_split
generate_lockfile.rs
use std::os; use cargo::ops; use cargo::core::MultiShell; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct
{ flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for ...
Options
identifier_name
generate_lockfile.rs
use std::os; use cargo::ops; use cargo::core::MultiShell; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the l...
{ debug!("executing; cmd=cargo-generate-lockfile; args={:?}", os::args()); shell.set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, shell) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
identifier_body
generate_lockfile.rs
use std::os; use cargo::ops; use cargo::core::MultiShell; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, }
pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(optio...
random_line_split
properties_test.js
import { defineProperty, deprecateProperty } from '..'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'defineProperty', class extends AbstractTestCase { ['@test toString'](assert)
} ); moduleFor( 'Ember.deprecateProperty', class extends AbstractTestCase { ['@test enables access to deprecated property and returns the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecati...
{ let obj = {}; defineProperty(obj, 'toString', undefined, function () { return 'FOO'; }); assert.equal(obj.toString(), 'FOO', 'should replace toString'); }
identifier_body
properties_test.js
import { defineProperty, deprecateProperty } from '..'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'defineProperty', class extends AbstractTestCase { ['@test toString'](assert) { let obj = {}; defineProperty(obj, 'toString', undefined, function () { retu...
} } ['@test enables setter to deprecated property and updates the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); expectDeprecation(); obj...
{ assert.notEqual(prop, 'baz'); }
conditional_block
properties_test.js
import { defineProperty, deprecateProperty } from '..'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'defineProperty', class extends AbstractTestCase { ['@test toString'](assert) { let obj = {}; defineProperty(obj, 'toString', undefined, function () { retu...
(assert) { assert.expect(2); let obj = { foo: 'bar', blammo: 'whammy' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); for (let prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { assert.notEqual(prop, 'baz'); ...
['@test deprecatedKey is not enumerable']
identifier_name
properties_test.js
import { defineProperty, deprecateProperty } from '..'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'defineProperty', class extends AbstractTestCase { ['@test toString'](assert) { let obj = {}; defineProperty(obj, 'toString', undefined, function () { retu...
} ); moduleFor( 'Ember.deprecateProperty', class extends AbstractTestCase { ['@test enables access to deprecated property and returns the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecatio...
}); assert.equal(obj.toString(), 'FOO', 'should replace toString'); }
random_line_split
oppia-interactive-end-exploration.component.ts
// Copyright 2021 The Oppia 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 ap...
controller: [ '$attrs', '$http', 'ContextService', 'InteractionAttributesExtractorService', 'ReadOnlyCollectionBackendApiService', 'UrlService', 'EXPLORATION_EDITOR_TAB_CONTEXT', 'EXPLORATION_SUMMARY_DATA_URL_TEMPLATE', 'PAGE_CONTEXT', function( $attrs, $http, ContextService, I...
require('services/contextual/url.service.ts'); angular.module('oppia').component('oppiaInteractiveEndExploration', { template: require('./end-exploration-interaction.component.html'), controllerAs: '$ctrl',
random_line_split
oppia-interactive-end-exploration.component.ts
// Copyright 2021 The Oppia 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 ap...
}); if (missingExpIds.length === 0) { ctrl.errorMessage = ''; } else { var listOfIds = missingExpIds.join('", "'); ctrl.errorMessage = ( 'Warning: exploration(s) with the IDs "' + listOfIds + '" will not be s...
{ missingExpIds.push(expId); }
conditional_block
InterestingPeopleWithAPI.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; import _ from 'lodash'; import User from './User'; import Loading from '../../components/Icon/Loading'; import './InterestingPeople.less'; import steemAPI...
extends Component { static propTypes = { authenticatedUser: PropTypes.shape({ name: PropTypes.string, }), followingList: PropTypes.arrayOf(PropTypes.string), }; static defaultProps = { authenticatedUser: { name: '', }, followingList: [], }; state = { users: [], l...
InterestingPeopleWithAPI
identifier_name
InterestingPeopleWithAPI.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; import _ from 'lodash'; import User from './User'; import Loading from '../../components/Icon/Loading'; import './InterestingPeople.less'; import steemAPI...
return ( <div className="InterestingPeople"> <div className="InterestingPeople__container"> <h4 className="InterestingPeople__title"> <i className="iconfont icon-group InterestingPeople__icon" /> {' '} <FormattedMessage id="interesting_people" defaultMes...
{ return <Loading />; }
conditional_block
InterestingPeopleWithAPI.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Link } from 'react-router-dom'; import _ from 'lodash'; import User from './User'; import Loading from '../../components/Icon/Loading'; import './InterestingPeople.less'; import steemAPI...
}) .catch(() => { this.setState({ noUsers: true, }); }); render() { const { users, loading, noUsers } = this.state; if (noUsers) { return <div />; } if (loading) { return <Loading />; } return ( <div className="InterestingPeople...
this.setState({ noUsers: true, }); }
random_line_split
lib.rs
/*! A Rust syntax extension for applying the `pub` visibility modifer to many items at once Right now the attribute applies to every possible child AST element that could have public visibility, including: - `use` - `static` - `fn`, both standalone and methods/associated ones - `mod` - `type`, `struct` and `enum` - `...
(self) -> bool { match self { IsFn => true, _ => false } } fn is_trait_impl(self) -> bool { match self { IsTraitImpl => true, _ => false } } fn is_type_impl(self) -> bool { match self { IsTypeImpl => true, _ => false } } fn is_extern_block(self) -> bool { match self { IsExternBlock => true, _ => false } } ...
is_fn
identifier_name
lib.rs
/*! A Rust syntax extension for applying the `pub` visibility modifer to many items at once Right now the attribute applies to every possible child AST element that could have public visibility, including: - `use` - `static` - `fn`, both standalone and methods/associated ones - `mod` - `type`, `struct` and `enum` - `...
#[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(token::intern(NAME), SyntaxExtension::Modifier(box Expand)); } struct ApplyPubFolder { parent_item_variant: ItemVariant } struct Expand; impl ItemModifier for Expand { fn expand(&self, ecx: &mut ...
random_line_split
service.rs
extern crate proc_macro; use std::convert::From; use syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote,ToTokens}; use super::utils::*; struct Service<'a> { ast: &'a syn::ItemImpl, idents: Vec<syn::Ident>, idents_cap: Vec<syn::Ident>, args: Vec<Vec<syn:...
#(fn #idents(&mut self, #(#args: #args_ty),*) -> Box<Future<Output=Result<#outputs,()>>> { Box::new(self.send_request(Request::#idents_cap(#(#args),*)) .then(|response| match response { #variants, _ => er...
random_line_split
service.rs
extern crate proc_macro; use std::convert::From; use syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote,ToTokens}; use super::utils::*; struct Service<'a> { ast: &'a syn::ItemImpl, idents: Vec<syn::Ident>, idents_cap: Vec<syn::Ident>, args: Vec<Vec<syn:...
fn types(&self) -> TokenStream2 { let Self { idents_cap, args_ty, outputs, .. } = self; let (_impl_generics, ty_generics, where_clause) = self.ast.generics.split_for_impl(); // we need phantom variant for handling generics cases: R, R<A>, R<A,B>. let phantom = quote! { _Phantom(Ph...
{ let ast = &self.ast; let (types, server, client) = (self.types(), self.server(), self.client()); (quote!{ #ast pub mod service { use super::*; use libfoxlive::rpc::Service; use std::marker::PhantomData; u...
identifier_body
service.rs
extern crate proc_macro; use std::convert::From; use syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote,ToTokens}; use super::utils::*; struct Service<'a> { ast: &'a syn::ItemImpl, idents: Vec<syn::Ident>, idents_cap: Vec<syn::Ident>, args: Vec<Vec<syn:...
(ast: &'a syn::ItemImpl) -> Self { let signatures = ast.items.iter().filter_map(|item| match item { syn::ImplItem::Method(item) => Some(&item.sig), _ => None, }); let (mut idents, mut idents_cap, mut args, mut args_ty, mut outputs) = (Vec::new(), Vec::new(), ...
new
identifier_name
IconElement.js
/** * IconElement is often mixed into other classes to generate an icon. * Icons are graphics, about the size of normal text. They are used to aid the user * in locating a control or to convey information in a space-efficient way. See the * [OOUI documentation on MediaWiki] [1] for a list of icons * included in th...
* @return {string} Icon name */ OO.ui.mixin.IconElement.prototype.getIcon = function () { return this.icon; };
/** * Get the symbolic name of the icon. *
random_line_split
IconElement.js
/** * IconElement is often mixed into other classes to generate an icon. * Icons are graphics, about the size of normal text. They are used to aid the user * in locating a control or to convey information in a space-efficient way. See the * [OOUI documentation on MediaWiki] [1] for a list of icons * included in th...
.updateThemeClasses(); return this; }; /** * Get the symbolic name of the icon. * * @return {string} Icon name */ OO.ui.mixin.IconElement.prototype.getIcon = function () { return this.icon; };
this.$icon.removeClass( 'oo-ui-icon-' + this.icon ); } if ( icon ) { this.$icon.addClass( 'oo-ui-icon-' + icon ); } this.$icon.toggleClass( 'oo-ui-iconElement-noIcon', !icon ); } this.icon = icon; this
conditional_block
ImageUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {UIService, UI} from "../UI"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; interface ...
let ctx: any = canvas.getContext("2d"); let cw: number = this._container.element.clientWidth; let ch: number = this._container.element.clientHeight; ctx.fillStyle = "black"; // todo: This should be customizable by the end user ctx.fillRe...
{ return null; }
conditional_block
ImageUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {UIService, UI} from "../UI"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; interface ...
return null; } let ctx: any = canvas.getContext("2d"); let cw: number = this._container.element.clientWidth; let ch: number = this._container.element.clientHeight; ctx.fillStyle = "black"; // todo: This should be custo...
if (!node || !canvas) {
random_line_split
ImageUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {UIService, UI} from "../UI"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; interface ...
} UIService.register(ImageUI); export default ImageUI;
{ this._disposable.dispose(); }
identifier_body
ImageUI.ts
/// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" /> /// <reference path="../../node_modules/rx/ts/rx.all.d.ts" /> import * as rx from "rx"; import * as vd from "virtual-dom"; import {UIService, UI} from "../UI"; import {Node} from "../Graph"; import {Container, Navigator} from "../Viewer"; interface ...
extends UI { public static uiName: string = "image"; private canvasId: string; private _disposable: rx.IDisposable; constructor(name: string, container: Container, navigator: Navigator) { super(name, container, navigator); this.canvasId = `${container.id}-${this._name}`; } pr...
ImageUI
identifier_name
nproc.rs
#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] ...
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag( "", "all", "print the number of cores available to the system", ); opts.optopt("", "ignore", "ignore up to N cores", "N"); opts.optflag("h", "help", "display this help and exit"); opts.opt...
uumain
identifier_name
nproc.rs
#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] ...
{ num_cpus::get() }
identifier_body
nproc.rs
#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] ...
"", "all", "print the number of cores available to the system", ); opts.optopt("", "ignore", "ignore up to N cores", "N"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.p...
random_line_split
Sidebar.Settings.js
/** * @author mrdoob / http://mrdoob.com/ */ Sidebar.Settings = function ( editor ) { var config = editor.config; var signals = editor.signals; var strings = editor.strings; var container = new UI.Panel(); container.setBorderTop( '0' ); container.setPaddingTop( '20px' ); container.setPaddingBottom( '20px' )...
container.add( new Sidebar.Settings.Shortcuts( editor ) ); container.add( new Sidebar.Settings.Viewport( editor ) ); return container; };
themeRow.add( new UI.Text( strings.getKey( 'sidebar/settings/theme' ) ).setWidth( '90px' ) ); themeRow.add( theme ); container.add( themeRow );
random_line_split
Sidebar.Settings.js
/** * @author mrdoob / http://mrdoob.com/ */ Sidebar.Settings = function ( editor ) { var config = editor.config; var signals = editor.signals; var strings = editor.strings; var container = new UI.Panel(); container.setBorderTop( '0' ); container.setPaddingTop( '20px' ); container.setPaddingBottom( '20px' )...
anguage.onChange( function () { var value = this.getValue(); editor.config.setKey( 'language', value ); } ); languageRow.add( new UI.Text( strings.getKey( 'sidebar/settings/language' ) ).setWidth( '90px' ) ); languageRow.add( language ); container.add( languageRow ); // theme var options = { 'css/lig...
language.setValue( config.getKey( 'language' ) ); } l
conditional_block
appconfig.py
import os import yaml MONGO_USERNAME = os.getenv('MONGO_USERNAME', None) MONGO_PASSWORD = os.getenv('MONGO_PASSWORD', None) MONGODB_HOST = os.getenv('MONGODB_HOST', '127.0.0.1') MONGODB_PORT = int(os.getenv('MONGODB_PORT', '27017')) MONGODB_SERVERS = os.getenv('MONGODB_SERVERS') \ or '{}:{}'.format(...
'logging': { 'type': 'stream' }, 'verbosity': LOG_VERBOSITY, 'continueOnError': True }, } CONFIG_LOCATION = os.getenv('CONFIG_LOCATION')
} ],
random_line_split
preview.test.ts
import { createPreview } from '@dicebear/core'; import * as style from '../dist'; import * as fs from 'fs'; import * as path from 'path'; const data = [ [style, { seed: 'test' }, 'eyes'], [style, { seed: 'test' }, 'hair'], [style, { seed: 'test' }, 'body'], [style, { seed: 'test' }, 'mouth'], [style, { seed:...
});
expect(createPreview(...params)).toEqual(svg); });
random_line_split
preview.test.ts
import { createPreview } from '@dicebear/core'; import * as style from '../dist'; import * as fs from 'fs'; import * as path from 'path'; const data = [ [style, { seed: 'test' }, 'eyes'], [style, { seed: 'test' }, 'hair'], [style, { seed: 'test' }, 'body'], [style, { seed: 'test' }, 'mouth'], [style, { seed:...
const svg = fs.readFileSync(svgComponent, { encoding: 'utf-8' }); expect(createPreview(...params)).toEqual(svg); }); });
{ if (false === fs.existsSync(path.dirname(svgComponent))) { fs.mkdirSync(path.dirname(svgComponent), { recursive: true }); } fs.writeFileSync(svgComponent, createPreview(...params), { encoding: 'utf-8', }); }
conditional_block
Plugin.ts
import { PalringoClient } from './../PalClient'; import { Dictionary } from './../Polyfill/Dictionary'; import { Group, User, ExtendedMessage } from './../Subprofile/Subprofile'; import { PalUtils } from './../Utilities/PalUtils'; export interface IPluginOptions { aliases?: string[]; authCheck?: (user: User, g...
(client: PalringoClient, msg: ExtendedMessage) { if (!msg.isText) { return; } if (msg.text.indexOf(client.commandCharacter) != 0) { return; } var ps = PluginInstance.plugins; var msgText = msg.text.slice(client.commandCharacter.length, m...
onMessage
identifier_name
Plugin.ts
import { PalringoClient } from './../PalClient'; import { Dictionary } from './../Polyfill/Dictionary'; import { Group, User, ExtendedMessage } from './../Subprofile/Subprofile'; import { PalUtils } from './../Utilities/PalUtils'; export interface IPluginOptions { aliases?: string[]; authCheck?: (user: User, g...
item.options = options; item.oncmdex = fn; //Add the instance of plugins to the collection PluginInstance.plugins.add(command, item); } static attach(client: PalringoClient) { client.On.GroupMessage = (msg) => { PluginInstance.onMessage(client, msg); ...
//Create instance of the plugins var item = new PluginInstance(); item.command = command;
random_line_split
Plugin.ts
import { PalringoClient } from './../PalClient'; import { Dictionary } from './../Polyfill/Dictionary'; import { Group, User, ExtendedMessage } from './../Subprofile/Subprofile'; import { PalUtils } from './../Utilities/PalUtils'; export interface IPluginOptions { aliases?: string[]; authCheck?: (user: User, g...
return false; }); if (!val) { console.log('No plugin matching text'); return; } msgText = msgText.slice(val.command.length, msgText.length).trim(); if (!val.options.authCheck(msg.userProfile, msg.group)) { return; } ...
{ if (!msg.isText) { return; } if (msg.text.indexOf(client.commandCharacter) != 0) { return; } var ps = PluginInstance.plugins; var msgText = msg.text.slice(client.commandCharacter.length, msg.text.length).trim(); var val = ps.g...
identifier_body
icLogin.service.ts
import { Injectable } from '@angular/core'; import { IC_LOGIN } from './icLogin.model'; // import { Router } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; @Injectable() export class IcLoginService { userProfile: any; requestedScopes: string = 'openid profile read:ti...
(): void { this.auth0.parseHash((err, authResult) => { if (authResult && authResult.accessToken && authResult.idToken) { window.location.hash = ''; this.setSession(authResult); console.log('Success'); // this.router.navigate(['/home']); } else if (err) { // this.r...
handleAuthentication
identifier_name
icLogin.service.ts
import { Injectable } from '@angular/core'; import { IC_LOGIN } from './icLogin.model'; // import { Router } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; @Injectable() export class IcLoginService { userProfile: any; requestedScopes: string = 'openid profile read:ti...
public isAuthenticated(): boolean { // Check whether the current time is past the // access token's expiry time const expiresAt = JSON.parse(localStorage.getItem('expires_at')); return new Date().getTime() < expiresAt; } public userHasScopes(scopes: Array<string>): boolean { const grantedSc...
{ // Remove tokens and expiry time from localStorage localStorage.removeItem('access_token'); localStorage.removeItem('id_token'); localStorage.removeItem('expires_at'); localStorage.removeItem('scopes'); // Go back to the home route // this.router.navigate(['/']); }
identifier_body
icLogin.service.ts
import { Injectable } from '@angular/core'; import { IC_LOGIN } from './icLogin.model'; // import { Router } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; @Injectable() export class IcLoginService { userProfile: any; requestedScopes: string = 'openid profile read:ti...
} public logout(): void { // Remove tokens and expiry time from localStorage localStorage.removeItem('access_token'); localStorage.removeItem('id_token'); localStorage.removeItem('expires_at'); localStorage.removeItem('scopes'); // Go back to the home route // this.router.navigate(['/']...
random_line_split
icLogin.service.ts
import { Injectable } from '@angular/core'; import { IC_LOGIN } from './icLogin.model'; // import { Router } from '@angular/router'; import 'rxjs/add/operator/filter'; import * as auth0 from 'auth0-js'; @Injectable() export class IcLoginService { userProfile: any; requestedScopes: string = 'openid profile read:ti...
else if (err) { // this.router.navigate(['/home']); console.log(err); alert('Error: ${err.error}. Check the console for further details.'); } }); } private setSession(authResult): void { // Set the time that the access token will expire at const expiresAt = JSON.stringify...
{ window.location.hash = ''; this.setSession(authResult); console.log('Success'); // this.router.navigate(['/home']); }
conditional_block
namespace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[deriving(Eq, Clone)] pub enum Namespace { Null, HTML, XML, XMLNS, XLink, SVG, MathML...
match url { "http://www.w3.org/1999/xhtml" => HTML, "http://www.w3.org/XML/1998/namespace" => XML, "http://www.w3.org/2000/xmlns/" => XMLNS, "http://www.w3.org/1999/xlink" => XLink, "http://www.w3.org/2000/svg" => SVG, "http://www.w3.org/19...
pub fn from_str(url: &str) -> Namespace {
random_line_split
namespace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[deriving(Eq, Clone)] pub enum Namespace { Null, HTML, XML, XMLNS, XLink, SVG, MathML...
(url: &str) -> Namespace { match url { "http://www.w3.org/1999/xhtml" => HTML, "http://www.w3.org/XML/1998/namespace" => XML, "http://www.w3.org/2000/xmlns/" => XMLNS, "http://www.w3.org/1999/xlink" => XLink, "http://www.w3.org/2000/svg" => SVG, ...
from_str
identifier_name
namespace.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[deriving(Eq, Clone)] pub enum Namespace { Null, HTML, XML, XMLNS, XLink, SVG, MathML...
}
{ match *self { Null => "", HTML => "http://www.w3.org/1999/xhtml", XML => "http://www.w3.org/XML/1998/namespace", XMLNS => "http://www.w3.org/2000/xmlns/", XLink => "http://www.w3.org/1999/xlink", SVG => "http://www.w3.org/2000/svg", ...
identifier_body
cargo_rerast_tests.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; fn cargo_rerast(crate_root: &str) -> Command { // We can't use Assert.current_dir, because then Assert::cargo_binary doesn't work, instead we // pass the crate root as an argument and get our binary to change directories once it...
@@ -8,7 +8,7 @@ mod tests2 { #[test] fn x() { - if 1 > 42 { + if 42 < 1 { assert!(false); } } @@ -16,7 +16,7 @@ /// A well documented function. pub fn foo(a: i32, b: i32) -> i32 { - if a > b { + if b < a { 42 } else { b @@ -26,7 +26,...
.assert() .stdout(predicate::eq( r#"--- src/lib.rs +++ src/lib.rs
random_line_split
cargo_rerast_tests.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; fn cargo_rerast(crate_root: &str) -> Command { // We can't use Assert.current_dir, because then Assert::cargo_binary doesn't work, instead we // pass the crate root as an argument and get our binary to change directories once it...
() { cargo_rerast("tests/crates/invalid_cargo_toml") .args(&["-s", "file!()", "-r", "\"foo\""]) .args(&["--diff", "--color=never"]) .assert() .failure() .stderr( predicate::str::contains("cargo metadata failed") .and(predicate::str::contains("could...
test_invalid_cargo_toml
identifier_name
cargo_rerast_tests.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; fn cargo_rerast(crate_root: &str) -> Command { // We can't use Assert.current_dir, because then Assert::cargo_binary doesn't work, instead we // pass the crate root as an argument and get our binary to change directories once it...
- if 1 > 42 { + if 42 < 1 { assert!(false); } } @@ -16,7 +16,7 @@ /// A well documented function. pub fn foo(a: i32, b: i32) -> i32 { - if a > b { + if b < a { 42 } else { b @@ -26,7 +26,7 @@ #[cfg(test)] mod tests { fn bar(a: i32, b: i3...
{ cargo_rerast("tests/crates/simple") // TODO: Remove once #10 is fixed. .env("RERAST_FULL_CARGO_CLEAN", "1") .arg("-p") .arg("p0: i32, p1: i32") .arg("-s") .arg("p0 > p1") .arg("-r") .arg("p1 < p0") .arg("--diff") .arg("--color=never")...
identifier_body
dispatcher-mezzi-marker.service.fake.ts
import {Injectable} from '@angular/core'; import {of, Observable, Subject} from 'rxjs'; import {MezziMarkerService} from '../../../service/maps-service/mezzi-marker/mezzi-marker.service'; import {MezzoMarker} from '../../../../maps/maps-model/mezzo-marker.model'; @Injectable({ providedIn: 'root' }) export class D...
(): Observable<MezzoMarker> { return this.newMezzoMarker$; } onUpdateMezzoMarker(): Observable<MezzoMarker> { return this.updateMezzoMarker$; } onDeleteMezzoMarker(): Observable<MezzoMarker> { return this.deleteMezzoMarker$; } }
onNewMezzoMarker
identifier_name
dispatcher-mezzi-marker.service.fake.ts
import {Injectable} from '@angular/core'; import {of, Observable, Subject} from 'rxjs'; import {MezziMarkerService} from '../../../service/maps-service/mezzi-marker/mezzi-marker.service'; import {MezzoMarker} from '../../../../maps/maps-model/mezzo-marker.model'; @Injectable({ providedIn: 'root' }) export class D...
onNewMezzoMarker(): Observable<MezzoMarker> { return this.newMezzoMarker$; } onUpdateMezzoMarker(): Observable<MezzoMarker> { return this.updateMezzoMarker$; } onDeleteMezzoMarker(): Observable<MezzoMarker> { return this.deleteMezzoMarker$; } }
{ this.mezziMarkersService.getMezziMarkers().subscribe((mezzoMarker: MezzoMarker[]) => { this.mezziMarkers = mezzoMarker; }); return of(this.mezziMarkers); }
identifier_body
dispatcher-mezzi-marker.service.fake.ts
import {Injectable} from '@angular/core'; import {of, Observable, Subject} from 'rxjs'; import {MezziMarkerService} from '../../../service/maps-service/mezzi-marker/mezzi-marker.service'; import {MezzoMarker} from '../../../../maps/maps-model/mezzo-marker.model'; @Injectable({ providedIn: 'root' }) export class D...
return this.newMezzoMarker$; } onUpdateMezzoMarker(): Observable<MezzoMarker> { return this.updateMezzoMarker$; } onDeleteMezzoMarker(): Observable<MezzoMarker> { return this.deleteMezzoMarker$; } }
random_line_split
HUnitConnectCAG_ConnectedLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitConnectCAG_ConnectedLHS(HimesisPreConditionPatternLHS): def
(self): """ Creates the himesis graph representing the AToM3 model HUnitConnectCAG_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled = True super(HUnitConnectCAG_ConnectedLHS, self).__init__(name='HUnitConnectCAG_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges...
__init__
identifier_name
HUnitConnectCAG_ConnectedLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitConnectCAG_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitConnectCAG_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled...
self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Channel""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Channel') # Add the edges self.add_edges([ ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True # define evaluat...
self.add_node() self.vs[0]["MT_pre__attr1"] = """return True"""
random_line_split
HUnitConnectCAG_ConnectedLHS.py
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitConnectCAG_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitConnectCAG_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled...
# define evaluation methods for each match association. def constraint(self, PreNode, graph): return True
return True
identifier_body
Gridbox.tsx
import { Box, Button, Card, Checkbox, Chip, styled, Typography, } from "@material-ui/core"; import { fetchResolver } from "@penrose/components"; import { compileTrio, evalEnergy, PenroseState, prepareState, prettySubstance, RenderStatic, resample, showError, showMutations, stepUntilCon...
extends React.Component<GridboxProps, GridboxState> { constructor(props: GridboxProps) { super(props); this.state = { showDiagram: true, isSelected: false, diagramSVG: "", energy: 0, }; } computeEnergy = async (optimizedState: PenroseState) => { if (this.props.srcState) {...
Gridbox
identifier_name
Gridbox.tsx
import { Box, Button, Card, Checkbox, Chip, styled, Typography, } from "@material-ui/core"; import { fetchResolver } from "@penrose/components"; import { compileTrio, evalEnergy, PenroseState, prepareState, prettySubstance, RenderStatic, resample, showError, showMutations, stepUntilCon...
} async componentDidMount() { await this.update(); } async componentDidUpdate(prevProps: GridboxProps) { if (this.props.substance.prog !== prevProps.substance.prog) { await this.update(); } } toggleView = () => { this.setState({ showDiagram: !this.state.showDiagram }); }; chec...
{ throw res.error; }
conditional_block
Gridbox.tsx
import { Box, Button, Card, Checkbox, Chip, styled, Typography, } from "@material-ui/core"; import { fetchResolver } from "@penrose/components"; import { compileTrio, evalEnergy, PenroseState, prepareState, prettySubstance, RenderStatic, resample, showError, showMutations, stepUntilCon...
let state = resample(await prepareState(res.value)); state = resample(state); const opt = stepUntilConvergence(state); if (opt.isErr()) { console.log(showError(opt.error)); throw Error("optimization failed"); } const optimized = opt.value; cons...
// resample because initial sampling did not use the special sampling seed
random_line_split