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
DragDrop.js
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This softwar...
return false; } var position = jRoot.position(); o.lastMouseX = e.pageX || e.originalEvent.touches[0].pageX; o.lastMouseY = e.pageY || e.originalEvent.touches[0].pageY; o.root.onDragStart(position.left, position.top, o.lastMouseX, o.lastMouseY, e); $(document).on({"mousemove touchmove" : eXo.core....
{ var obj = null; DragDrop.prototype.init = function(o, oRoot) { var jObj = $(o); jObj.off("mousedown touchstart"); jObj.on("mousedown touchstart", eXo.core.DragDrop.start); o.root = oRoot && oRoot != null ? oRoot : o ; o.root.onDragStart = new Function(); o.root.onDragEnd = new Function(...
identifier_body
DragDrop.js
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This softwar...
() { var obj = null; DragDrop.prototype.init = function(o, oRoot) { var jObj = $(o); jObj.off("mousedown touchstart"); jObj.on("mousedown touchstart", eXo.core.DragDrop.start); o.root = oRoot && oRoot != null ? oRoot : o ; o.root.onDragStart = new Function(); o.root.onDragEnd = new Functi...
DragDrop
identifier_name
auth0.py
"name": None, "nickname": None, "user_id": "user_id", "email": "primary_email", "identities": "identities", "blocked": "active", } self.az_blacklisted_connections = ["Mozilla-LDAP", "Mozilla-LDAP-Dev"] self.az_whitelisted_co...
# auth0 field->cis field map self.az_cis_fields = { "created_at": "created", "given_name": "first_name", "family_name": "last_name",
random_line_split
auth0.py
login_method="github", publisher_name="auth0") # These are the users auth0 knows about self.az_users = self.fetch_az_users(user_ids) self.all_cis_user_ids = self.fetch_all_cis_user_ids(publisher) # Should we fan-out processing to multiple function calls? if user_ids is None: ...
logger.info( "After filtering out known CIS users/in auth0 blocked users, we will process {} users".format( len(user_ids_to_process_set) ) ) self.save_s3_cache({"az_users": self.az_users, "all_cis_user_ids": self.all_cis_user_ids}...
if ("blocked" in u.keys()) and (u["blocked"] is True): user_ids_to_process_set.add(u["user_id"])
conditional_block
auth0.py
([], login_method="github", publisher_name="auth0") # These are the users auth0 knows about self.az_users = self.fetch_az_users(user_ids) self.all_cis_user_ids = self.fetch_all_cis_user_ids(publisher) # Should we fan-out processing to multiple function calls? if user_ids is Non...
# This is fine for most methods, except this one... ideally the code should change in the CIS Vault when it # uses something else than DynamoDB and is able to match efficiently on other attributes if c == "firefoxaccounts": c = "oauth2|firefoxaccounts" pub...
""" Get all known CIS user ids for the whitelisted login methods This is here because CIS only returns user ids per specific login methods We also cache this """ self.s3_cache = self.get_s3_cache() if self.s3_cache is not None: self.all_cis_user_ids = self.s3...
identifier_body
auth0.py
login_method="github", publisher_name="auth0") # These are the users auth0 knows about self.az_users = self.fetch_az_users(user_ids) self.all_cis_user_ids = self.fetch_all_cis_user_ids(publisher) # Should we fan-out processing to multiple function calls? if user_ids is None: ...
(self): """ Extract a list of user_ids from a dict of auth0 users return: list of user_ids """ if self.user_ids_only is not None: return self.user_ids_only self.user_ids_only = [] for u in self.fetch_az_users(): self.user_ids_only.append(u...
get_az_user_ids
identifier_name
agent_connect_dlg.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'agent_connect_dlg.ui' # # Created: Tue Oct 12 14:22:17 2010 # by: PyQt4 UI code generator 4.7.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Di...
(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Dialog", "Agent", None, QtGui.QApplication.UnicodeUTF8)) self.disconnect_from_server.setText(QtGui.QApplication.translate...
retranslateUi
identifier_name
agent_connect_dlg.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'agent_connect_dlg.ui' # # Created: Tue Oct 12 14:22:17 2010 # by: PyQt4 UI code generator 4.7.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Di...
if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_())
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Dialog", "Agent", None, QtGui.QApplication.UnicodeUTF8)) self.disconnect_from_server.setText(QtGui.QApplication.translate("Dialog", "Disconnect C...
identifier_body
agent_connect_dlg.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'agent_connect_dlg.ui' # # Created: Tue Oct 12 14:22:17 2010 # by: PyQt4 UI code generator 4.7.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Di...
import sys app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_())
conditional_block
agent_connect_dlg.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'agent_connect_dlg.ui' # # Created: Tue Oct 12 14:22:17 2010 # by: PyQt4 UI code generator 4.7.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Dialog(object): def setupUi(self, Di...
ui.setupUi(Dialog) Dialog.show() sys.exit(app.exec_())
app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog()
random_line_split
solution.py
class Solution(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ MOD = 1000000007 paths = 0 cur = {(i, j): 1} for i in xrange(N): ...
cur = next return paths # 94 / 94 test cases passed. # Status: Accepted # Runtime: 232 ms # beats 75.36 %
next[(nx, ny)] += cnt next[(nx, ny)] %= MOD
conditional_block
solution.py
class Solution(object): def findPaths(self, m, n, N, i, j):
else: next[(nx, ny)] += cnt next[(nx, ny)] %= MOD cur = next return paths # 94 / 94 test cases passed. # Status: Accepted # Runtime: 232 ms # beats 75.36 %
""" :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ MOD = 1000000007 paths = 0 cur = {(i, j): 1} for i in xrange(N): next = collections.defaultdict(int) for (x, y), cnt in cur...
identifier_body
solution.py
class
(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ MOD = 1000000007 paths = 0 cur = {(i, j): 1} for i in xrange(N): next = colle...
Solution
identifier_name
solution.py
class Solution(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int
""" MOD = 1000000007 paths = 0 cur = {(i, j): 1} for i in xrange(N): next = collections.defaultdict(int) for (x, y), cnt in cur.iteritems(): for dx, dy in [[-1, 0], [0, 1], [1, 0], [0, -1]]: nx = x + dx ...
:type j: int :rtype: int
random_line_split
onboardingMethodPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {OnboardingDataService} from "../../../providers/onboardingDataService"; import {OnboardingFileContentPage} from "../onboardingFileContentPage/onboardingFileContentPage"; import {OnboardingMethodNodePage} from ".....
// handles page init. ngOnInit() { this.onboardingDataService.initiateGetOnboardingMethod(this.name) .then((files) => { this.items = files; }).catch((err) => { // there was an error. display it on screen. console.log(JSON.stringify(err)); doAlert(JSON.stringify(err)...
{ this.name = navParams.get("name"); }
identifier_body
onboardingMethodPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {OnboardingDataService} from "../../../providers/onboardingDataService"; import {OnboardingFileContentPage} from "../onboardingFileContentPage/onboardingFileContentPage"; import {OnboardingMethodNodePage} from ".....
this.nav.push(OnboardingFileContentPage, { path: this.name + "/" + item, name: item }); } else { this.nav.push(OnboardingMethodNodePage, { method: this.name, name: item }); } } }
random_line_split
onboardingMethodPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {OnboardingDataService} from "../../../providers/onboardingDataService"; import {OnboardingFileContentPage} from "../onboardingFileContentPage/onboardingFileContentPage"; import {OnboardingMethodNodePage} from ".....
implements OnInit { // directories and files in the repository items: string[] = null; name: string = null; // ctor constructor(private nav: NavController, private navParams: NavParams, private onboardingDataService: OnboardingDataService) { this.name = navParams.get("name"); } // handles...
OnboardingMethodPage
identifier_name
onboardingMethodPage.ts
import {Page, NavController, NavParams} from "ionic-angular"; import {OnInit} from "@angular/core"; import {OnboardingDataService} from "../../../providers/onboardingDataService"; import {OnboardingFileContentPage} from "../onboardingFileContentPage/onboardingFileContentPage"; import {OnboardingMethodNodePage} from ".....
} }
{ this.nav.push(OnboardingMethodNodePage, { method: this.name, name: item }); }
conditional_block
delete_deleted_fpds_idv.py
import logging import datetime import pandas as pd import numpy as np import os import boto3 from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.stagingModels import DetachedAwardProcurement from dataactco...
existing_item = sess.query(model.last_modified, model.detached_award_procurement_id, model.detached_award_proc_unique). \ filter_by(detached_award_proc_unique=unique_string).one_or_none() if existing_item and last_modified > existing_item.last_modified: ...
logger.info("Checking delete record {} of {}.".format(index, row_count))
conditional_block
delete_deleted_fpds_idv.py
import logging import datetime import pandas as pd import numpy as np import os import boto3 from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.stagingModels import DetachedAwardProcurement from dataactco...
(unique_key): """ Converts the unique key given by the file into the format we use for our unique key """ unique_key_array = unique_key.split(':') unique_key = unique_key_array[2] + '_-none-_' + unique_key_array[0] + '_' + unique_key_array[1] + '_-none-_-none-' return unique_key def clean_delete_data(...
convert_unique_key
identifier_name
delete_deleted_fpds_idv.py
import logging import datetime import pandas as pd import numpy as np import os import boto3 from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.stagingModels import DetachedAwardProcurement from dataactco...
return delete_list, delete_dict def delete_records(sess, delete_list, delete_dict): """ Delete the records listed and create a file for website deletion. """ # only need to delete values if there's something to delete if delete_list: sess.query(DetachedAwardProcurement). \ filte...
""" Gets all the values that actually need to be deleted from our database """ model = DetachedAwardProcurement delete_dict = {} delete_list = [] row_count = len(data.index) for index, row in data.iterrows(): unique_string = row['primary_key'] last_modified = row['delete_date'] ...
identifier_body
delete_deleted_fpds_idv.py
import logging import datetime import pandas as pd import numpy as np import os import boto3 from dataactcore.config import CONFIG_BROKER from dataactcore.interfaces.db import GlobalDB from dataactcore.logging import configure_logging from dataactcore.models.stagingModels import DetachedAwardProcurement from dataactco...
return delete_list, delete_dict def delete_records(sess, delete_list, delete_dict): """ Delete the records listed and create a file for website deletion. """ # only need to delete values if there's something to delete if delete_list: sess.query(DetachedAwardProcurement). \ filter(...
random_line_split
thread.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
import descriptors = require('vs/platform/instantiation/common/descriptors'); import instantiation = require('vs/platform/instantiation/common/instantiation'); import {IDisposable} from 'vs/base/common/lifecycle'; // --- thread service (web workers) export var IThreadService = instantiation.createDecorator<IThreadSer...
import winjs = require('vs/base/common/winjs.base');
random_line_split
thread.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} } export interface IThreadSynchronizableObject<S> { getId():string; creationDone?:()=>void; asyncCtor?:()=>winjs.Promise; getSerializableState?:()=>S; setData?:(data:S)=>void; } export enum ThreadAffinity { None = 0, Group1 = 1, Group2 = 2, Group3 = 3, Group4 = 4, Group5 = 5, Group6 = 6, Group7 =...
{ throw new Error('Duplicate Remotable identifier found'); }
conditional_block
thread.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
{ private static PROP_NAME = '$__REMOTABLE_ID'; public static Registry = { MainContext: <IRemotableCtorMap>Object.create(null), PluginHostContext: <IRemotableCtorMap>Object.create(null), WorkerContext: <IRemotableCtorAffinityMap>Object.create(null), }; public static getId(ctor: any): string { return (ct...
Remotable
identifier_name
views.py
import json from django.http import HttpResponse from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from apps.exercises.models import Attempts from apps.maps.models import Graphs from apps.ki.utils import performInference
g = get_object_or_404(Graphs, pk=gid) if not request.user.is_authenticated(): return HttpResponse(status=403) u, uc = User.objects.get_or_create(pk=request.user.pk) p = getParticipantByUID(request.user.pk, gid) if g.study_active and p is None: return HttpResponse(status=401) ...
from apps.research.utils import getParticipantByUID, studyFilter def knowledge_inference(request, gid=""): if request.method == "GET":
random_line_split
views.py
import json from django.http import HttpResponse from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from apps.exercises.models import Attempts from apps.maps.models import Graphs from apps.ki.utils import performInference from apps.research.utils import getParticipantByUID, st...
else: return HttpResponse(status=405)
g = get_object_or_404(Graphs, pk=gid) if not request.user.is_authenticated(): return HttpResponse(status=403) u, uc = User.objects.get_or_create(pk=request.user.pk) p = getParticipantByUID(request.user.pk, gid) if g.study_active and p is None: return HttpResponse(status=401) ex...
conditional_block
views.py
import json from django.http import HttpResponse from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from apps.exercises.models import Attempts from apps.maps.models import Graphs from apps.ki.utils import performInference from apps.research.utils import getParticipantByUID, st...
if request.method == "GET": g = get_object_or_404(Graphs, pk=gid) if not request.user.is_authenticated(): return HttpResponse(status=403) u, uc = User.objects.get_or_create(pk=request.user.pk) p = getParticipantByUID(request.user.pk, gid) if g.study_active and p is None: return ...
identifier_body
views.py
import json from django.http import HttpResponse from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from apps.exercises.models import Attempts from apps.maps.models import Graphs from apps.ki.utils import performInference from apps.research.utils import getParticipantByUID, st...
(request, gid=""): if request.method == "GET": g = get_object_or_404(Graphs, pk=gid) if not request.user.is_authenticated(): return HttpResponse(status=403) u, uc = User.objects.get_or_create(pk=request.user.pk) p = getParticipantByUID(request.user.pk, gid) if g.study_active...
knowledge_inference
identifier_name
models.py
import datetime from backend import db from cruds.crud_user_type_destinations.models import UserTypeDestinations from cruds.crud_users.models import Users from cruds import format_urls_in_text class WallMessages(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) date = db.Column(db.In...
return Users.query.filter_by(id=self.sender).all() def get_destinations(self): _dict = {} query = UserTypeDestinations.query.filter_by(id=self.destination).first().users_query query = str(query).replace('$', str(self.param_value)) exec(query, _dict) return _dict['use...
random_line_split
models.py
import datetime from backend import db from cruds.crud_user_type_destinations.models import UserTypeDestinations from cruds.crud_users.models import Users from cruds import format_urls_in_text class WallMessages(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) date = db.Column(db.In...
_dict = {} query = UserTypeDestinations.query.filter_by(id=self.destination).first().users_query query = str(query).replace('$', str(self.param_value)) exec(query, _dict) return _dict['users']
identifier_body
models.py
import datetime from backend import db from cruds.crud_user_type_destinations.models import UserTypeDestinations from cruds.crud_users.models import Users from cruds import format_urls_in_text class WallMessages(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) date = db.Column(db.In...
(self, fields): self.date = fields['date'] self.sender = fields['sender'] self.destination = fields['user_type_destination_id'] self.param_value = fields['parameter'] self.message = format_urls_in_text(fields['message']) def get_sender(self): return Users.query.filte...
set_fields
identifier_name
messages.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {MessageService} from "../../services/message-service"; import {Message} from "../../model/scenario"; import {MessageFilter} from "../../model/filter"; @Component({ moduleId: module.id, templateUrl: 'messages.html', styleUrls: ['messages.cs...
(): void { window.clearInterval(this.autoRefreshId); } getMessages() { this.messageService.getMessages(this.messageFilter) .subscribe( messages => this.messages = messages, error => this.errorMessage = <any>error ); } clearMessage...
ngOnDestroy
identifier_name
messages.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {MessageService} from "../../services/message-service"; import {Message} from "../../model/scenario"; import {MessageFilter} from "../../model/filter"; @Component({ moduleId: module.id, templateUrl: 'messages.html', styleUrls: ['messages.cs...
else { this.inboundState = ''; } this.getMessages(); } toggleOutbound() { this.messageFilter.directionOutbound = !this.messageFilter.directionOutbound; if (this.messageFilter.directionOutbound) { this.outboundState = 'active'; } else { ...
{ this.inboundState = 'active'; }
conditional_block
messages.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {MessageService} from "../../services/message-service"; import {Message} from "../../model/scenario"; import {MessageFilter} from "../../model/filter"; @Component({ moduleId: module.id, templateUrl: 'messages.html', styleUrls: ['messages.cs...
toggleOutbound() { this.messageFilter.directionOutbound = !this.messageFilter.directionOutbound; if (this.messageFilter.directionOutbound) { this.outboundState = 'active'; } else { this.outboundState = ''; } this.getMessages(); } initMessage...
{ this.messageFilter.directionInbound = !this.messageFilter.directionInbound; if (this.messageFilter.directionInbound) { this.inboundState = 'active'; } else { this.inboundState = ''; } this.getMessages(); }
identifier_body
messages.ts
import {Component, OnDestroy, OnInit} from "@angular/core"; import {MessageService} from "../../services/message-service"; import {Message} from "../../model/scenario"; import {MessageFilter} from "../../model/filter"; @Component({ moduleId: module.id, templateUrl: 'messages.html', styleUrls: ['messages.cs...
if (!this.messages) { return; } let hasPotentialNextPage = this.messages.length && this.messages.length == this.messageFilter.pageSize; if (hasPotentialNextPage) { this.messageFilter.pageNumber++; this.getMessages(); } } toggleInbound(...
} next() {
random_line_split
window.d.ts
import { Observable } from '../Observable'; import { OperatorFunction } from '../types'; /** * Branch out the source Observable values as a nested Observable whenever * `windowBoundaries` emits. * * <span class="informal">It's like {@link buffer}, but emits a nested Observable * instead of an array.</span> * * <...
* ```javascript * const clicks = fromEvent(document, 'click'); * const interval = interval(1000); * const result = clicks.pipe( * window(interval), * map(win => win.take(2)), // each window has at most 2 emissions * mergeAll(), // flatten the Observable-of-Observables * ); * result.subscribe...
* Observable `windowBoundaries` emits an item. Because each window is an * Observable, the output is a higher-order Observable. * * ## Example * In every window of 1 second each, emit at most 2 click events
random_line_split
parameter_number_and_kind.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() {}
main
identifier_name
parameter_number_and_kind.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(generic_associated_types)] //~^ WARNING the feature `generic_associated_types...
random_line_split
test_cloud_events.py
# -*- coding: utf-8 -*- """This module tests only cloud specific events""" import pytest import yaml from cfme.common.vm import VM from cfme.cloud.provider.azure import AzureProvider from utils import testgen from utils.generators import random_vm_name pytestmark = [ pytest.mark.tier(3) ] pytest_generate_tests =...
# # deferred delete vm request.addfinalizer(vm.delete_from_provider) def cmp_function(_, y): data = yaml.load(y) return data['resourceId'].endswith(vm.name) and data['status']['value'] == 'Succeeded' full_data_attr = {'full_data': 'will be ignored', 'cmp_func': c...
vm.create_on_provider(find_in_cfme=True, allow_skip="default") vm.refresh_relationships()
conditional_block
test_cloud_events.py
# -*- coding: utf-8 -*- """This module tests only cloud specific events""" import pytest import yaml from cfme.common.vm import VM from cfme.cloud.provider.azure import AzureProvider from utils import testgen from utils.generators import random_vm_name pytestmark = [ pytest.mark.tier(3) ] pytest_generate_tests =...
# generalize event register_event(full_data_attr, source='AZURE', event_type='virtualMachines_generalize_EndRequest') # capture event register_event(full_data_attr, source='AZURE', event_type='virtualMachines_capture_EndRequest') # capture vm image_name = vm.name resource...
""" tests that generalize and capture vm azure events are received and parsed by CFME """ mgmt = provider.mgmt vm = VM.factory(random_vm_name(context='capture'), provider) if not mgmt.does_vm_exist(vm.name): vm.create_on_provider(find_in_cfme=True, allow_skip="default") vm.refresh_...
identifier_body
test_cloud_events.py
# -*- coding: utf-8 -*- """This module tests only cloud specific events""" import pytest import yaml from cfme.common.vm import VM from cfme.cloud.provider.azure import AzureProvider from utils import testgen from utils.generators import random_vm_name pytestmark = [ pytest.mark.tier(3) ] pytest_generate_tests =...
(_, y): data = yaml.load(y) return data['resourceId'].endswith(vm.name) and data['status']['value'] == 'Succeeded' full_data_attr = {'full_data': 'will be ignored', 'cmp_func': cmp_function} # generalize event register_event(full_data_attr, source='AZURE', ...
cmp_function
identifier_name
test_cloud_events.py
# -*- coding: utf-8 -*- """This module tests only cloud specific events""" import pytest import yaml from cfme.common.vm import VM from cfme.cloud.provider.azure import AzureProvider from utils import testgen from utils.generators import random_vm_name pytestmark = [ pytest.mark.tier(3)
] pytest_generate_tests = testgen.generate([AzureProvider], scope='module') def test_manage_nsg_group(provider, setup_provider, register_event): """ tests that create/remove azure network security groups events are received and parsed by CFME """ nsg_name = random_vm_name(context='nsg') resource_...
random_line_split
createTabbedPanel.ts
import { ComposeFactory } from 'dojo-compose/compose'; import createWidget, { Widget, WidgetState, WidgetOptions } from './createWidget'; import { ContainerMixinOptions } from './mixins/createContainerMixin'; import createTabbedMixin, { TabbedMixin, TabbedState, TabbedChild } from './mixins/createTabbedMixin'; export ...
export default createTabbedPanel;
.extend({ tagName: 'dojo-panel-tabbed' }) as TabbedPanelFactory;
random_line_split
Validator.js
/** * Will traverse an object recursively and check every value * @param {Object} options * @param {Object} referenceOptions * @param {array} path | where to look for the actual option * @static */ static parse(options, referenceOptions, path) { for (let option in options) { if (op...
{ errorFound = false; allOptions = referenceOptions; let usedOptions = referenceOptions; if (subObject !== undefined) { usedOptions = referenceOptions[subObject]; } Validator.parse(options, usedOptions, []); return errorFound; }
identifier_body
Validator.js
() { } /** * Main function to be called * @param {Object} options * @param {Object} referenceOptions * @param {Object} subObject * @returns {boolean} * @static */ static validate(options, referenceOptions, subObject) { errorFound = false; allOptions = referenceOptions; let usedOp...
constructor
identifier_name
Validator.js
} } /** * Check every value. If the value is an object, call the parse function on that object. * @param {string} option * @param {Object} options * @param {Object} referenceOptions * @param {array} path | where to look for the actual option * @static */ static check(option, options,...
return str + '\n\n';
{ for (let j = 0; j < path.length - i; j++) { str += ' '; } str += '}\n' }
conditional_block
Validator.js
*/ constructor() { } /** * Main function to be called * @param {Object} options * @param {Object} referenceOptions * @param {Object} subObject * @returns {boolean} * @static */ static validate(options, referenceOptions, subObject) { errorFound = false; allOptions = referenceOpti...
/** * @ignore
random_line_split
label_parsers.rs
use crate::asm::Token; use nom::types::CompleteStr; use nom::{alphanumeric, multispace}; named!(pub label_decl<CompleteStr, Token>, ws!( do_parse!( name: alphanumeric >> tag!(":") >> opt!(multispace) >> ( Token::LabelDecl{name: name.to_string...
}
{ let result = label_ref(CompleteStr("@test")); assert!(result.is_ok()); let (_, token) = result.unwrap(); assert_eq!( token, Token::LabelRef { name: "test".to_string() } ); let result = label_ref(CompleteStr("test")); ...
identifier_body
label_parsers.rs
use crate::asm::Token; use nom::types::CompleteStr; use nom::{alphanumeric, multispace}; named!(pub label_decl<CompleteStr, Token>, ws!( do_parse!( name: alphanumeric >> tag!(":") >> opt!(multispace) >> ( Token::LabelDecl{name: name.to_string...
() { let result = label_ref(CompleteStr("@test")); assert!(result.is_ok()); let (_, token) = result.unwrap(); assert_eq!( token, Token::LabelRef { name: "test".to_string() } ); let result = label_ref(CompleteStr("test")...
test_parse_label_ref
identifier_name
label_parsers.rs
use crate::asm::Token; use nom::types::CompleteStr; use nom::{alphanumeric, multispace}; named!(pub label_decl<CompleteStr, Token>, ws!( do_parse!( name: alphanumeric >> tag!(":") >> opt!(multispace) >> ( Token::LabelDecl{name: name.to_string...
token, Token::LabelRef { name: "test".to_string() } ); let result = label_ref(CompleteStr("test")); assert!(result.is_err()); } }
random_line_split
es6ClassTest8.js
//// [es6ClassTest8.ts] function f1(x:any) {return x;} class C { constructor() { var bar:any = (function() { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } } class
{ static norm(v:Vector):Vector {return null;} static minus(v1:Vector, v2:Vector):Vector {return null;} static times(v1:Vector, v2:Vector):Vector {return null;} static cross(v1:Vector, v2:Vector):Vector {return null;} constructor(public x: number, public y: number, p...
Vector
identifier_name
es6ClassTest8.js
//// [es6ClassTest8.ts] function f1(x:any) {return x;} class C { constructor() { var bar:any = (function() { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } } class Vector { static norm(v:Vector):Vector {return null;} static minus(v1:Vector,...
constructor(public x: number, public y: number, public z: number) { } static dot(v1:Vector, v2:Vector):Vector {return null;} } class Camera { public forward: Vector; public right: Vector; public up: Vector; constructor(public pos: Vecto...
{return null;}
identifier_body
es6ClassTest8.js
//// [es6ClassTest8.ts] function f1(x:any) {return x;} class C { constructor() { var bar:any = (function() { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } } class Vector { static norm(v:Vector):Vector {return null;} static minus(v1:Vector,...
public right: Vector; public up: Vector; constructor(public pos: Vector, lookAt: Vector) { var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt,this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.u...
random_line_split
cfg.rs
use std::path::PathBuf; use std::collections::HashMap; use std::env; use util::ini::{Ini, IniParser}; pub struct ProgramConfig { config: Ini, } /// Encapsulates program config, which is stored per-prefix /// in .ini files. impl ProgramConfig { /// Try loading config file by prefix. pub fn factory(prefix:...
(&self) -> Option<String> { self.config.get("wine") } }
get_wine
identifier_name
cfg.rs
use std::path::PathBuf; use std::collections::HashMap; use std::env; use util::ini::{Ini, IniParser}; pub struct ProgramConfig { config: Ini, }
pub fn factory(prefix: &str) -> Option<Self> { let mut path = env::var_os("HOME") .and_then(|home| { home.into_string().and_then(|s| { Ok(PathBuf::from(s + "/.config/winerunner")) }).ok() }).unwrap(); path.push(format!("{}....
/// Encapsulates program config, which is stored per-prefix /// in .ini files. impl ProgramConfig { /// Try loading config file by prefix.
random_line_split
cfg.rs
use std::path::PathBuf; use std::collections::HashMap; use std::env; use util::ini::{Ini, IniParser}; pub struct ProgramConfig { config: Ini, } /// Encapsulates program config, which is stored per-prefix /// in .ini files. impl ProgramConfig { /// Try loading config file by prefix. pub fn factory(prefix:...
} /// Get env section for file, if present. pub fn get_env(&self) -> Option<HashMap<String, String>> { self.config.get_section("env") } pub fn get_wine(&self) -> Option<String> { self.config.get("wine") } }
{ None }
conditional_block
SerialConnection.py
import serial class SerialConnection: """RS-232 connection to the Agilent power supply""" def __init__(self, port='/dev/usb/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS): """Initialize the connection""" self.serial = serial.Serial(port=port, baudrate=baudrate, parity=parity...
self.write(data) res = self.readline() if res is "" : return self.question(data,cnt+1) return res def open(self): """Open the connection""" self.serial.open() def close(self): """Close the connection""" self.serial.close() def isOpen(self): """Check if the port is opene...
raise Exception("Too many empty responses to query: "%data)
conditional_block
SerialConnection.py
import serial class SerialConnection: """RS-232 connection to the Agilent power supply""" def __init__(self, port='/dev/usb/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS): """Initialize the connection""" self.serial = serial.Serial(port=port, baudrate=baudrate, parity=parity...
def question(self, data, cnt=0): """Send one query to the device and returns the answer""" if cnt>2: raise Exception("Too many empty responses to query: "%data) self.write(data) res = self.readline() if res is "" : return self.question(data,cnt+1) return res def open(self): """Open the ...
def readline(self): """Read one line from the device""" return self.serial.readline()[:-2]
random_line_split
SerialConnection.py
import serial class SerialConnection: """RS-232 connection to the Agilent power supply""" def __init__(self, port='/dev/usb/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS): """Initialize the connection""" self.serial = serial.Serial(port=port, baudrate=baudrate, parity=parity...
def open(self): """Open the connection""" self.serial.open() def close(self): """Close the connection""" self.serial.close() def isOpen(self): """Check if the port is opened.""" return self.serial.isOpen()
"""Send one query to the device and returns the answer""" if cnt>2: raise Exception("Too many empty responses to query: "%data) self.write(data) res = self.readline() if res is "" : return self.question(data,cnt+1) return res
identifier_body
SerialConnection.py
import serial class SerialConnection: """RS-232 connection to the Agilent power supply""" def __init__(self, port='/dev/usb/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS): """Initialize the connection""" self.serial = serial.Serial(port=port, baudrate=baudrate, parity=parity...
(self): """Check if the port is opened.""" return self.serial.isOpen()
isOpen
identifier_name
index.js
/** * Language Generator */ const fs = require('fs'); const exec = require('child_process').exec; function languageIsSupported(language) { try { fs.accessSync(`app/translations/${language}.json`, fs.F_OK); return true; } catch (e) { return false; } } module.exports = { description: 'Add a langua...
type: 'modify', path: '../../app/app.js', pattern: /(import\('intl\/locale-data\/jsonp\/[a-z]+\.js'\),\n)(?!.*import\('intl\/locale-data\/jsonp\/[a-z]+\.js'\),)/g, templateFile: './language/polyfill-intl-locale.hbs', }); actions.push( () => { const cmd = 'npm run extract-in...
actions.push({
random_line_split
index.js
/** * Language Generator */ const fs = require('fs'); const exec = require('child_process').exec; function
(language) { try { fs.accessSync(`app/translations/${language}.json`, fs.F_OK); return true; } catch (e) { return false; } } module.exports = { description: 'Add a language', prompts: [{ type: 'input', name: 'language', message: 'What is the language you want to add i18n support for (...
languageIsSupported
identifier_name
index.js
/** * Language Generator */ const fs = require('fs'); const exec = require('child_process').exec; function languageIsSupported(language) { try { fs.accessSync(`app/translations/${language}.json`, fs.F_OK); return true; } catch (e) { return false; } } module.exports = { description: 'Add a langua...
process.stdout.write(result); }); return 'modify translation messages'; } ); return actions; }, };
{ throw err || stderr; }
conditional_block
index.js
/** * Language Generator */ const fs = require('fs'); const exec = require('child_process').exec; function languageIsSupported(language)
module.exports = { description: 'Add a language', prompts: [{ type: 'input', name: 'language', message: 'What is the language you want to add i18n support for (e.g. "fr", "de")?', default: 'fr', validate: (value) => { if ((/.+/).test(value) && value.length === 2) { return languag...
{ try { fs.accessSync(`app/translations/${language}.json`, fs.F_OK); return true; } catch (e) { return false; } }
identifier_body
form.load.js
/** * Given a form id, this will return the form JSON object assembled by the * form's call back function. If the form fails to load, this returns false. * @param {String} form_id * @return {Object} */ function drupalgap_form_load(form_id)
var argument = arguments[index]; form_arguments.push(argument); } form_arguments.splice(0, 1); // Attach the form arguments to the form object. form.arguments = form_arguments; // If there were no arguments to pass along, call the function directly to // retrieve th...
{ try { var form = drupalgap_form_defaults(form_id); // The form's call back function will be equal to the form id. var function_name = form_id; if (function_exists(function_name)) { // Grab the form's function. var fn = window[function_name]; // Determine the language code. ...
identifier_body
form.load.js
/** * Given a form id, this will return the form JSON object assembled by the * form's call back function. If the form fails to load, this returns false. * @param {String} form_id * @return {Object} */ function drupalgap_form_load(form_id) { try { var form = drupalgap_form_defaults(form_id); // The form...
form.elements[name].options.attributes.id = id; } } } catch (error) { console.log('_drupalgap_form_load_set_element_defaults - ' + error); } }
form.elements[name].options.attributes = {}; } id = drupalgap_form_get_element_id(name, form.id); form.elements[name].id = id;
random_line_split
form.load.js
/** * Given a form id, this will return the form JSON object assembled by the * form's call back function. If the form fails to load, this returns false. * @param {String} form_id * @return {Object} */ function
(form_id) { try { var form = drupalgap_form_defaults(form_id); // The form's call back function will be equal to the form id. var function_name = form_id; if (function_exists(function_name)) { // Grab the form's function. var fn = window[function_name]; // Determine the language c...
drupalgap_form_load
identifier_name
form.load.js
/** * Given a form id, this will return the form JSON object assembled by the * form's call back function. If the form fails to load, this returns false. * @param {String} form_id * @return {Object} */ function drupalgap_form_load(form_id) { try { var form = drupalgap_form_defaults(form_id); // The form...
var argument = arguments[index]; form_arguments.push(argument); } form_arguments.splice(0, 1); // Attach the form arguments to the form object. form.arguments = form_arguments; // If there were no arguments to pass along, call the function directly to // retrieve t...
{ continue; }
conditional_block
_keyset_reader_test.py
# Copyright 2019 Google LLC # # 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 applicable law or agreed to in writing, ...
self.assertEqual(enc_keyset.keyset_info.key_info[0].type_url, 'type.googleapis.com/google.crypto.tink.AesGcmKey') def test_read_encrypted_invalid(self): reader = tink.JsonKeysetReader('not json') with self.assertRaises(core.TinkError): reader.read_encrypted() class BinaryKey...
json_encrypted_keyset = """ { "encryptedKeyset": "c29tZSBjaXBoZXJ0ZXh0IHdpdGgga2V5c2V0", "keysetInfo": { "primaryKeyId": 42, "keyInfo": [ { "typeUrl": "type.googleapis.com/google.crypto.tink.AesGcmKey", "outputPrefixType":...
identifier_body
_keyset_reader_test.py
# Copyright 2019 Google LLC # # 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 applicable law or agreed to in writing, ...
(self): reader = tink.JsonKeysetReader('not json') with self.assertRaises(core.TinkError): reader.read() def test_read_encrypted(self): # encryptedKeyset is a base64-encoding of 'some ciphertext with keyset' json_encrypted_keyset = """ { "encryptedKeyset": "c29tZSBjaXBoZXJ0ZXh...
test_read_invalid
identifier_name
_keyset_reader_test.py
# Copyright 2019 Google LLC # # 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 applicable law or agreed to in writing, ...
absltest.main()
conditional_block
_keyset_reader_test.py
# Copyright 2019 Google LLC # # 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 applicable law or agreed to in writing, ...
def test_read(self): keyset = tink_pb2.Keyset() keyset.primary_key_id = 42 key = keyset.key.add() key.key_data.type_url = 'type.googleapis.com/google.crypto.tink.AesGcmKey' key.key_data.key_material_type = tink_pb2.KeyData.SYMMETRIC key.key_data.value = b'GhCS/1+ejWpx68NfGt6ziYHd' key.outp...
random_line_split
filterField.js
'use strict'; var inheritance = require('./../../helpers/inheritance'), Field = require('./field'); var FilterField = function(){}; inheritance.inherits(Field,FilterField); FilterField.prototype.isOpen = function(){ return this.world.helper.elementGetter(this._root,this._data.elements.body).isDisplayed(); }...
}); case 'close': return _this.isOpen() .then(function(is){ if(is){ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.f...
{ return _this._root.scrollIntoView() .then(function(){ return _this._root.element(by.css('span.filter__sub-title')).click(); }) .then(function(){ r...
conditional_block
filterField.js
'use strict'; var inheritance = require('./../../helpers/inheritance'), Field = require('./field'); var FilterField = function(){}; inheritance.inherits(Field,FilterField); FilterField.prototype.isOpen = function(){ return this.world.helper.elementGetter(this._root,this._data.elements.body).isDisplayed(); }...
module.exports = FilterField;
} };
random_line_split
LineCountBear.py
from coalib.bears.LocalBear import LocalBear from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY class LineCountBear(LocalBear):
extra=file_length-max_lines_per_file)), severity=RESULT_SEVERITY.NORMAL, file=filename)
LANGUAGES = {'All'} AUTHORS = {'The coala developers'} AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} LICENSE = 'AGPL-3.0' CAN_DETECT = {'Formatting'} def run(self, filename, file, max_lines_per_file: int): """ Count the number of lines in a file and ensure that they are ...
identifier_body
LineCountBear.py
from coalib.bears.LocalBear import LocalBear from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY class LineCountBear(LocalBear): LANGUAGES = {'All'} AUTHORS = {'The coala developers'} AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} LICENSE = 'AGPL-3.0'...
(self, filename, file, max_lines_per_file: int): """ Count the number of lines in a file and ensure that they are smaller than a given size. :param max_lines_per_file: Number of lines allowed per file. """ file_length = len(file) if file_length > max_lines_per_fi...
run
identifier_name
LineCountBear.py
from coalib.bears.LocalBear import LocalBear from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY class LineCountBear(LocalBear): LANGUAGES = {'All'} AUTHORS = {'The coala developers'} AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} LICENSE = 'AGPL-3.0'...
yield Result.from_values( origin=self, message=('This file had {count} lines, which is {extra} ' 'lines more than the maximum limit specified.' .format(count=file_length, extra=file_length-max_lines_per_fi...
conditional_block
LineCountBear.py
from coalib.bears.LocalBear import LocalBear from coalib.results.Result import Result from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY class LineCountBear(LocalBear): LANGUAGES = {'All'} AUTHORS = {'The coala developers'} AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} LICENSE = 'AGPL-3.0'...
severity=RESULT_SEVERITY.NORMAL, file=filename)
'lines more than the maximum limit specified.' .format(count=file_length, extra=file_length-max_lines_per_file)),
random_line_split
Standby.py
self.prev_running_service = None if self.session.current_dialog: if self.session.current_dialog.ALLOW_SUSPEND == Screen.SUSPEND_STOPS: if localtime(time()).tm_year > 1970 and self.session.nav.getCurrentlyPlayingServiceOrGroup(): self.prev_running_service = self.session.nav.getCurrentlyPlayingServiceOr...
self.conntected=False
random_line_split
Standby.py
self.standbyTimeUnknownTimer.startLongTimer(60) elif self.session.current_dialog.ALLOW_SUSPEND == Screen.SUSPEND_PAUSES: self.paused_service = self.session.current_dialog self.paused_service.pauseService() if self.session.pipshown: from Screens.InfoBar import InfoBar InfoBar.instance and hasattr(Inf...
__onShow
identifier_name
Standby.py
self.avswitch.setInput("ENCODER") #restart last played service #unmute adc self.leaveMute() #kill me self.close(True) def setMute(self): if eDVBVolumecontrol.getInstance().isMuted(): self.wasMuted = 1 print "mute already active" else: self.wasMuted = 0 eDVBVolumecontrol.getInstance().volume...
def doStandby(self): Notifications.AddNotification(Screens.Standby.Standby2) class StandbySummary(Screen): skin = """ <screen position="0,0" size="132,64"> <widget source="global.CurrentTime" render="Label" position="0,0" size="132,64" font="Regular;40" halign="center"> <convert type="ClockToText" /> </w...
if answer: self.onClose.append(self.doStandby)
identifier_body
Standby.py
self.avswitch.setInput("ENCODER") #restart last played service #unmute adc self.leaveMute() #kill me self.close(True) def setMute(self): if eDVBVolumecontrol.getInstance().isMuted(): self.wasMuted = 1 print "mute already active" else: self.wasMuted = 0 eDVBVolumecontrol.getInstance().volume...
#set input to vcr scart if SystemInfo["ScartSwitch"]: self.avswitch.setInput("SCART") else: self.avswitch.setInput("AUX") if (getBrandOEM() in ('fulan')): open("/proc/stb/hdmi/output", "w").write("off") self.onFirstExecBegin.append(self.__onFirstExecBegin) self.onClose.append(self.__onClose) de...
from Screens.InfoBar import InfoBar InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
conditional_block
valid_calc_excavation.py
#!/usr/bin/env python # Shellscript to verify r.gwflow calculation, this calculation is based on # the example at page 167 of the following book: # author = "Kinzelbach, W. and Rausch, R.", # title = "Grundwassermodellierung", # publisher = "Gebr{\"u}der Borntraeger (Berlin, Stuttgart)", # year = "1995" # import sys im...
recharge="recharge", output="gwresult", dt=864000000000, type="unconfined", budget="water_budget")
grass.run_command("r.gwflow", "f", solver="cholesky", top="top", bottom="bottom", phead="phead", \ status="status", hc_x="hydcond", hc_y="hydcond", s="syield", \
random_line_split
item.service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {CacheableService} from './cacheable.service'; import {LoaderService} from './loader.service'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator...
return response.json(); }) .catch(this.handleError) }); } getDescriptionChain(path_parts: string[]): Observable<any> { let obs_chain: Observable<any>[] = []; for (let i = path_parts.length - 1; i > 0; i--){ let desc_path = ...
.map(response => { this.loader.finish_request();
random_line_split
item.service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {CacheableService} from './cacheable.service'; import {LoaderService} from './loader.service'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator...
return Observable.forkJoin(obs_chain); } private build_path(path_parts: string[]) { return this.base_path + '/' + path_parts.join('/') + this.extension; } private handleError(error: any): Observable<string> { this.loader.finish_request(); console.error('An error occurr...
{ let desc_path = path_parts.slice(0, i); desc_path.push('description'); obs_chain.unshift(this.getItem(desc_path)); }
conditional_block
item.service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {CacheableService} from './cacheable.service'; import {LoaderService} from './loader.service'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator...
(path_parts: string[]): Observable<any> { let obs_chain: Observable<any>[] = []; for (let i = path_parts.length - 1; i > 0; i--){ let desc_path = path_parts.slice(0, i); desc_path.push('description'); obs_chain.unshift(this.getItem(desc_path)); } retur...
getDescriptionChain
identifier_name
item.service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {CacheableService} from './cacheable.service'; import {LoaderService} from './loader.service'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator...
private build_path(path_parts: string[]) { return this.base_path + '/' + path_parts.join('/') + this.extension; } private handleError(error: any): Observable<string> { this.loader.finish_request(); console.error('An error occurred', error); return Observable.of(undefined);...
{ let obs_chain: Observable<any>[] = []; for (let i = path_parts.length - 1; i > 0; i--){ let desc_path = path_parts.slice(0, i); desc_path.push('description'); obs_chain.unshift(this.getItem(desc_path)); } return Observable.forkJoin(obs_chain); }
identifier_body
index.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict...
if (data == null) { data = null; } _scheduleAction({ action: 'signal', data: data, eventName: eventName, tstamp: signalTime }); } function startEvent(eventName, data) { var eventStartTime = Date.now(); if (eventName == null) { _throw('No event name specified'); } if (data =...
{ _throw('No event name specified'); }
conditional_block
index.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict...
if (!_enabled) { return; } var data = action.data ? ': ' + JSON.stringify(action.data) : ''; var fmtTime = new Date(action.tstamp).toLocaleTimeString(); switch (action.action) { case 'startEvent': console.log( '[' + fmtTime + '] ' + '<START> ' + action.eventName + data ...
throw err; } function _writeAction(action) {
random_line_split
index.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict...
function _writeAction(action) { if (!_enabled) { return; } var data = action.data ? ': ' + JSON.stringify(action.data) : ''; var fmtTime = new Date(action.tstamp).toLocaleTimeString(); switch (action.action) { case 'startEvent': console.log( '[' + fmtTime + '] ' + '<START> ' ...
{ var err = new Error(msg); // Strip off the call to _throw() var stack = err.stack.split('\n'); stack.splice(1, 1); err.stack = stack.join('\n'); throw err; }
identifier_body
index.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict...
(msg) { var err = new Error(msg); // Strip off the call to _throw() var stack = err.stack.split('\n'); stack.splice(1, 1); err.stack = stack.join('\n'); throw err; } function _writeAction(action) { if (!_enabled) { return; } var data = action.data ? ': ' + JSON.stringify(action.data) : ''; v...
_throw
identifier_name
main.rs
#![feature(lang_items, alloc_error_handler)] #![no_std]
use data_encoding::Encoding; #[lang = "eh_personality"] extern "C" fn eh_personality() {} struct Fd(libc::c_int); impl core::fmt::Write for Fd { fn write_str(&mut self, s: &str) -> core::fmt::Result { unsafe { libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len()); } ...
#![no_main] use core::fmt::Write;
random_line_split
main.rs
#![feature(lang_items, alloc_error_handler)] #![no_std] #![no_main] use core::fmt::Write; use data_encoding::Encoding; #[lang = "eh_personality"] extern "C" fn eh_personality()
struct Fd(libc::c_int); impl core::fmt::Write for Fd { fn write_str(&mut self, s: &str) -> core::fmt::Result { unsafe { libc::write(self.0, s.as_ptr() as *const libc::c_void, s.len()); } Ok(()) } } #[panic_handler] fn panic_handler(info: &core::panic::PanicInfo) -> ! { ...
{}
identifier_body
main.rs
#![feature(lang_items, alloc_error_handler)] #![no_std] #![no_main] use core::fmt::Write; use data_encoding::Encoding; #[lang = "eh_personality"] extern "C" fn eh_personality() {} struct Fd(libc::c_int); impl core::fmt::Write for Fd { fn write_str(&mut self, s: &str) -> core::fmt::Result { unsafe { ...
(&self, ptr: *mut u8, _: Layout) { libc::free(ptr as *mut libc::c_void) } } #[alloc_error_handler] fn foo(_: Layout) -> ! { loop {} } #[global_allocator] static GLOBAL: Malloc = Malloc; } fn test_encode(encoding: &Encoding, input: &[u8], output: &mut [u8], result: ...
dealloc
identifier_name
objectTypeHidingMembersOfExtendedObject.ts
class A { foo: string; } class B extends A { bar: string; } interface Object { data: A; [x: string]: Object; } class
{ valueOf() { } data: B; [x: string]: any; } var c: C; var r1: void = c.valueOf(); var r1b: B = c.data; var r1c = r1b['hm']; // should be 'Object' var r1d = c['hm']; // should be 'any' interface I { valueOf(): void; data: B; [x: string]: any; } var i: I; var r2: void = i.valueOf(); var r2b: ...
C
identifier_name
objectTypeHidingMembersOfExtendedObject.ts
class A { foo: string; } class B extends A { bar: string; } interface Object { data: A; [x: string]: Object; } class C { valueOf() { } data: B;
var c: C; var r1: void = c.valueOf(); var r1b: B = c.data; var r1c = r1b['hm']; // should be 'Object' var r1d = c['hm']; // should be 'any' interface I { valueOf(): void; data: B; [x: string]: any; } var i: I; var r2: void = i.valueOf(); var r2b: B = i.data; var r2c = r2b['hm']; // should be 'Object' var...
[x: string]: any; }
random_line_split
main.rs
// https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html #![allow(dead_code, unused_variables)] fn main() { //////////////////////////////////////////////////////////////////////////////// // Closures ////////////////////////////////////////////////////////////////////////...
() -> Box<Fn(i32) -> i32> { let num = 5; Box::new(move |x| x + num) } let f = factory(); let answer = f(1); assert_eq!(6, answer); }
factory
identifier_name
main.rs
// https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html #![allow(dead_code, unused_variables)] fn main() { //////////////////////////////////////////////////////////////////////////////// // Closures ////////////////////////////////////////////////////////////////////////...
//////////////////////////////////////////////////////////////////////////////// // Function pointers ans closures //fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 { // some_closure(1) //} //fn add_one(i: i32) -> i32 { // i + 1 //} //let f = add_one; //let answer...
//assert_eq!(3, answer);
random_line_split
main.rs
// https://rust-lang-ja.github.io/the-rust-programming-language-ja/1.6/book/closures.html #![allow(dead_code, unused_variables)] fn main() { //////////////////////////////////////////////////////////////////////////////// // Closures ////////////////////////////////////////////////////////////////////////...
let plus_one_v2 = |x: i32| -> i32 { x + 1 }; let plus_one_v3 = |x: i32| x + 1 ; //////////////////////////////////////////////////////////////////////////////// // Closures and their environment let num = 5; let plus_num = |x: i32| x + num; assert_eq!(10, plus_num(5)); // l...
{ x + 1 }
identifier_body