file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
reflector.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/. */
//! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::root::DomRoot;
use do... |
impl DomObject for Reflector {
fn reflector(&self) -> &Self {
self
}
}
/// A trait to initialize the `Reflector` for a DOM object.
pub trait MutDomObject: DomObject {
/// Initializes the Reflector
fn init_reflector(&mut self, obj: *mut JSObject);
}
impl MutDomObject for Reflector {
fn ini... | random_line_split | |
reflector.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/. */
//! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::root::DomRoot;
use do... | (&self) -> HandleObject {
// We're rooted, so it's safe to hand out a handle to object in Heap
unsafe { self.object.handle() }
}
/// Initialize the reflector. (May be called only once.)
pub fn set_jsobject(&mut self, object: *mut JSObject) {
assert!(self.object.get().is_null());
... | get_jsobject | identifier_name |
reflector.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/. */
//! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::root::DomRoot;
use do... |
}
| {
self.set_jsobject(obj)
} | identifier_body |
app.js | angular.module('app', [ 'ngRoute', 'ui.select' ])
// Routes
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/:steamId/trade-offers', {
templateUrl: 'trade-offers.html',
controller:... | templateUrl: 'trade-offer.html',
controller: 'TradeOfferController'
})
.when('/trade-offer-status', {
templateUrl: 'trade-offer-status.html',
controller: 'TradeOfferStatusController'
})
.otherwise({
redirectTo: '/'
});
})
// Controllers
.controll... | })
.when('/:steamId/trade-offer/:tradeOfferId', {
| random_line_split |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
n... | return [];
}
async copyFont(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return await this.copyBlob(platform, from, to + '.ttf', options);
}
} | return [];
}
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
| random_line_split |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
n... |
}
async copyImage(platform: string, from: string, to: string, options: any, cache: any): Promise<Array<string>> {
return [];
}
async copySound(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyVideo(platform: string, from: string, to: str... | {
if (this.sources[i] === path) {
this.sources.splice(i, 1);
return;
}
} | conditional_block |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
n... | (platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyVideo(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<str... | copySound | identifier_name |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
n... |
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyFont(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return await this.copyBlob(platform, from, to + '.ttf', options);
}
}
| {
return [];
} | identifier_body |
switch.js | /*
name: Switch
version: 0.1
description: On-off iPhone style switch button.
license: MooTools MIT-Style License (http://mootools.net/license.txt)
copyright: Valerio Proietti (http://mad4milk.net)
authors: Valerio Proietti (http://mad4milk.net)
requires: MooTools 1.2.5, Touch 0.1+ (http://github.com/kamicane/moo... |
this.sides.style.backgroundPosition = a;
},
toggle: function () {
this.change(this.button.offsetLeft > this.half ? false : true);
},
change: function (a, b) {
if (typeof a == "string") {
a = a.toInt();
}
if (this.animating) {
return this;
... | {
a = "0 " + b * 4 + "px";
} | conditional_block |
switch.js | name: Switch
version: 0.1
description: On-off iPhone style switch button.
license: MooTools MIT-Style License (http://mootools.net/license.txt)
copyright: Valerio Proietti (http://mad4milk.net)
authors: Valerio Proietti (http://mad4milk.net)
requires: MooTools 1.2.5, Touch 0.1+ (http://github.com/kamicane/mootoo... | /* | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
# Copyright (C) 2007 Osmo Salomaa
#
# 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 pr... |
"""User-activatable actions for :class:`gaupol.Application`."""
from gaupol.actions.audio import * # noqa
from gaupol.actions.edit import * # noqa
from gaupol.actions.file import * # noqa
from gaupol.actions.help import * # noqa
from gaupol.actions.projects import * # noqa
from gaupol.actions.text ... | #
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero Genera... |
function end(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 1 && mode == 0) {
qm.sendNext("What? You don't want the potion?");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendYesNo("Hm... Your ex... | {
status++;
if (mode != 1) {
if(type == 2 && mode == 0) {
qm.sendOk("Hm... You don't think that would help? Think about it. It could help, you know...");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendNext("Welcome, hero! What's that? You want to know how I... | identifier_body |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero Genera... | }
if (status == 0)
qm.sendYesNo("Hm... Your expression tells me that the exercise didn't jog any memories. But don't you worry. They'll come back, eventually. Here, drink this potion and power up!\r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0#\r\n#v2000022# 10 #t2000022#\r\n#v2000023# 10 #t2000023#\r\n\r\n#fUI/UIWindow.... | qm.dispose();
return;
} | random_line_split |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero Genera... | (mode, type, selection) {
status++;
if (mode != 1) {
if(type == 2 && mode == 0) {
qm.sendOk("Hm... You don't think that would help? Think about it. It could help, you know...");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendNext("Welcome, hero! What's that... | start | identifier_name |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero Genera... |
} | {
if(qm.isQuestCompleted(21012))
qm.dropMessage(1,"Unknown Error");
else if(qm.canHold(2000022) && qm.canHold(2000023)){
qm.gainExp(57);
qm.gainItem(2000022, 10);
qm.gainItem(2000023, 10);
qm.forceCompleteQuest();
qm.sendOk("#b(Even i... | conditional_block |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We ... | }
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChangeListeners,
_navigator: typeof navigator !== 'undefined' ? navigator : null,
mozAddonManager: config.get('server')
? {}
: (navigator: MozNav... | random_line_split | |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We ... |
}
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChangeListeners,
_navigator: typeof navigator !== 'undefined' ? navigator : null,
mozAddonManager: config.get('server')
? {}
: (navigator: MozNa... | {
case 401:
return NotAuthorizedPage;
case 404:
return NotFoundPage;
case 500:
default:
return ServerErrorPage;
} | identifier_body |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We ... | return (
<NestedStatus code={200}>
<ScrollToTop>
<Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} />
<ErrorPage getErrorComponent={getErrorPage}>
<Routes />
</ErrorPage>
</ScrollToTop>
</NestedStatus>
);
}
}
export const map... | defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox Android (%(locale)s)'),
i18nValues,
);
titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes.
... | conditional_block |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We ... | (status) {
case 401:
return NotAuthorizedPage;
case 404:
return NotFoundPage;
case 500:
default:
return ServerErrorPage;
}
}
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChang... | switch | identifier_name |
defaults-de_DE.js | /*!
* Bootstrap-select v1.13.15 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== unde... | multipleSeparator: ', '
};
})(jQuery);
}));
//# sourceMappingURL=defaults-de_DE.js.map | ];
},
selectAllText: 'Alles auswählen',
deselectAllText: 'Nichts auswählen',
| random_line_split |
defaults-de_DE.js | /*!
* Bootstrap-select v1.13.15 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== unde... |
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Bitte wählen...',
noneResultsText: 'Keine Ergebnisse für {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} Element ausgewählt' : '{0} Elemente ausgewählt... | {
factory(root["jQuery"]);
} | conditional_block |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
*****************... |
def evaluation_test( self, mComposition, mLabel ):
# $CURRENT_DATE evaluation
mLabel.setText( "__$CURRENT_DATE__" )
assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )
# $CURRENT_DATE() evaluation
mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
... | TEST_DATA_DIR = unitTestDataPath()
vectorFileInfo = QFileInfo( TEST_DATA_DIR + "/france_parts.shp")
mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )
QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )
# create composition wi... | identifier_body |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
*****************... | unittest.main() | conditional_block | |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
*****************... | ( self, mComposition, mLabel, mVectorLayer ):
provider = mVectorLayer.dataProvider()
fi = provider.getFeatures( QgsFeatureRequest() )
feat = QgsFeature()
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
mLabel.setText( "[%\"NAME_1\"||'_ok'%]")
... | feature_evaluation_test | identifier_name |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
*****************... |
def feature_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
provider = mVectorLayer.dataProvider()
fi = provider.getFeatures( QgsFeatureRequest() )
feat = QgsFeature()
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
mLabel.setT... |
# expression evaluation (without associated feature)
mLabel.setText( "__[%\"NAME_1\"%][%21*2%]__" )
assert mLabel.displayText() == "__[NAME_1]42__" | random_line_split |
sweetalert-tests.ts | /// <reference path="sweetalert.d.ts" />
// A basic message
swal("Here's a message!");
// A title with a text under
swal("Here's a message!", "It's pretty, isn't it?");
// A success message!
swal("Good job!", "You clicked the button!", "success");
// A warning message, with a function attached to the "Confirm"-butt... | title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
... | swal({ | random_line_split |
sweetalert-tests.ts | /// <reference path="sweetalert.d.ts" />
// A basic message
swal("Here's a message!");
// A title with a text under
swal("Here's a message!", "It's pretty, isn't it?");
// A success message!
swal("Good job!", "You clicked the button!", "success");
// A warning message, with a function attached to the "Confirm"-butt... | else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
// A message with a custom icon
swal({
title: "Sweet!",
text: "Here's a custom image.",
imageUrl: "images/thumbs-up.jpg"
});
// An HTML message
swal({
title: "HTML <small>Title</small>!",
text: "A c... | {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} | conditional_block |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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 Licens... | f get_uri_error(uri):
"""Return error for fetching the URL or None if it works."""
if uri.startswith("https://nonexisting.weblate.org/"):
return "Non existing test URL"
cache_key = f"uri-check-{uri}"
cached = cache.get(cache_key)
if cached is True:
LOGGER.debug("URL check for %s, cac... | = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
de | identifier_body |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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 Licens... | agent = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
def get_uri_error(uri):
"""Return error for fetching the URL or None if... |
def request(method, url, headers=None, **kwargs): | random_line_split |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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 Licens... | od, url, headers=None, **kwargs):
agent = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
def get_uri_error(uri):
"""Return err... | st(meth | identifier_name |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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 Licens... | result = str(error)
cache.set(cache_key, result, 3600)
return result
| n None
| conditional_block |
main.rs | use std::env;
struct LwzDict {
words: Vec<String>
}
impl LwzDict {
pub fn | (&mut self, s: &str) {
if s.len() < 1 {
return;
}
let next = match self.find(s) {
Some(c) => {
self.words.push(
format!("{}{}", c, s)
);
s[c.len()..s.len()]
},
None => {
... | add_chain | identifier_name |
main.rs | use std::env;
struct LwzDict {
words: Vec<String>
}
impl LwzDict {
pub fn add_chain(&mut self, s: &str) {
if s.len() < 1 {
return;
}
let next = match self.find(s) {
Some(c) => {
self.words.push(
format!("{}{}", c, s) | s[1..s.len()]
}
};
self.add_chain(&next);
}
fn find(&self, s: &str) -> Option<String> {
for word in self.words {
if(word == s) {
Some(word.clone())
}
}
None
}
}
impl From<String> for LwzDict {
... | );
s[c.len()..s.len()]
},
None => {
self.words.push(s[0..1].to_string()); | random_line_split |
main.rs | use std::env;
struct LwzDict {
words: Vec<String>
}
impl LwzDict {
pub fn add_chain(&mut self, s: &str) |
fn find(&self, s: &str) -> Option<String> {
for word in self.words {
if(word == s) {
Some(word.clone())
}
}
None
}
}
impl From<String> for LwzDict {
fn from(from: String) -> Self {
}
}
fn main() {
let sentence = env::args().nth(1).... | {
if s.len() < 1 {
return;
}
let next = match self.find(s) {
Some(c) => {
self.words.push(
format!("{}{}", c, s)
);
s[c.len()..s.len()]
},
None => {
self.words.pus... | identifier_body |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myDateTimeInput') myDateTimeInput; jqxDateT... | }
} | } | random_line_split |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myDateTimeInput') myDateTimeInput; jqxDateT... | ber = event.args.index;
switch (index) {
case 0:
this.myDateTimeInput.culture('cs-CZ');
break;
case 1:
this.myDateTimeInput.culture('de-DE');
break;
case 2:
this.myDateTimeInput.culture('en-CA');
... | identifier_body | |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myDateTimeInput') myDateTimeInput; jqxDateT... | let index: number = event.args.index;
switch (index) {
case 0:
this.myDateTimeInput.culture('cs-CZ');
break;
case 1:
this.myDateTimeInput.culture('de-DE');
break;
case 2:
this.myDateTimeInput... | : void {
| identifier_name |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program ... | logging.getLogger("dnf").log(DDEBUG, msg)
_LIBDNF_TO_DNF_LOGLEVEL_MAPPING = {
libdnf.utils.Logger.Level_CRITICAL: CRITICAL,
libdnf.utils.Logger.Level_ERROR: ERROR,
libdnf.utils.Logger.Level_WARNING: WARNING,
libdnf.utils.Logger.Level_NOTICE: INFO,
libdnf.utils.Logger.Level_INFO: INFO,
... | msg = 'timer: %s: %d ms' % (self.what, diff * 1000) | random_line_split |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program ... |
return 1
_VERBOSE_VAL_MAPPING = {
0 : SUPERCRITICAL,
1 : logging.INFO,
2 : logging.INFO, # the default
3 : logging.DEBUG,
4 : logging.DEBUG,
5 : logging.DEBUG,
6 : logging.DEBUG, # verbose value
}
def _cfg_verbose_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
ret... | return 0 | conditional_block |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program ... |
class _MaxLevelFilter(object):
def __init__(self, max_level):
self.max_level = max_level
def filter(self, record):
if record.levelno >= self.max_level:
return 0
return 1
_VERBOSE_VAL_MAPPING = {
0 : SUPERCRITICAL,
1 : logging.INFO,
2 : logging.INFO, # the defa... | """Method decorator turning the method into noop on second or later calls."""
def noop(*_args, **_kwargs):
pass
def swan_song(self, *args, **kwargs):
func(self, *args, **kwargs)
setattr(self, func.__name__, noop)
return swan_song | identifier_body |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program ... | (*_args, **_kwargs):
pass
def swan_song(self, *args, **kwargs):
func(self, *args, **kwargs)
setattr(self, func.__name__, noop)
return swan_song
class _MaxLevelFilter(object):
def __init__(self, max_level):
self.max_level = max_level
def filter(self, record):
if ... | noop | identifier_name |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy; | const VERSION: &'static str = "1.7.1";
fn main() {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() {
let mut data = ... | use flate2::bufread::GzDecoder;
use tar::Archive;
| random_line_split |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy;
use flate2::bufread::GzDecoder;
use tar::Archive;
const VERSION: &'static str = "1.7.1";
fn | () {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() {
let mut data = Vec::new();
let mut handle = Easy::new(... | main | identifier_name |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy;
use flate2::bufread::GzDecoder;
use tar::Archive;
const VERSION: &'static str = "1.7.1";
fn main() | {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() {
let mut data = Vec::new();
let mut handle = Easy::new();
... | identifier_body | |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy;
use flate2::bufread::GzDecoder;
use tar::Archive;
const VERSION: &'static str = "1.7.1";
fn main() {
... |
prost_build::Config::new()
.service_generator(Box::new(krpc_build::KrpcServiceGenerator))
.compile_protos(
&[
dir.join("src/kudu/client/client.proto"),
dir.join("src/kudu/consensus/metadata.proto"),
dir.join("src/kudu/master/master.proto"... | {
let mut data = Vec::new();
let mut handle = Easy::new();
handle
.url(&format!(
"https://github.com/apache/kudu/archive/{}.tar.gz",
VERSION
)).expect("failed to configure Kudu tarball URL");
handle
.follow_location(tru... | conditional_block |
deleteFile.json.js | //This script is to delete a resource within the node
var deleteFile = exports;
deleteFile.handle = function(req, res, pathInfo, resource) {
const filename = pathInfo.parameters.name || pathInfo.parameters.filename;
if (filename == undefined)
{
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
... | res.end();
}).fail(function() {
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
res.write("The resource [" + filename + "] does not exists within [" + resource.path + "]");
res.end();
});
}
}; | res.writeHead(200, {"Content-Type": "application/json; charset=utf-8"});
res.write(JSON.stringify(fileList)); | random_line_split |
deleteFile.json.js | //This script is to delete a resource within the node
var deleteFile = exports;
deleteFile.handle = function(req, res, pathInfo, resource) {
const filename = pathInfo.parameters.name || pathInfo.parameters.filename;
if (filename == undefined)
|
else if (!resource.isAuthorized("delete"))
{
res.writeHead(401, {"Content-Type": "text/plain; charset=utf-8"});
res.write("User is not authorized to delete here files and resources.");
res.end();
}
else
{
resource.fileExists(filename).then(function() {
return resource.deleteFile(filename);
}).then(fu... | {
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
res.write("The url-parameter [name] is not set. This parameter defines the filename within the selected resource.");
res.end();
} | conditional_block |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from ... |
return self.status == pyven.constants.STATUS[0]
def process(self):
raise NotImplementedError('Step process method not implemented')
def report_status(self):
if self.status == pyven.constants.STATUS[0]:
return Success()
elif self.status == pyven.constant... | self.status = pyven.constants.STATUS[1] | conditional_block |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from ... |
@staticmethod
def log_delimiter(path=None):
Logger.get().info('===================================')
def step(function):
def _intern(self):
Step.log_delimiter()
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : STARTING')
ok = fu... | self.verbose = verbose
self.name = None
self.checker = None
self.status = pyven.constants.STATUS[2] | identifier_body |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from ... | def title(self):
return Title(self.name) | random_line_split | |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from ... | (path=None):
Logger.get().info('===================================')
def step(function):
def _intern(self):
Step.log_delimiter()
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : STARTING')
ok = function(self)
if ok:
... | log_delimiter | identifier_name |
generate-mod.rs | // Modules generated by transparent proc macros still acts as barriers for names (issue #50504).
// aux-build:generate-mod.rs
extern crate generate_mod;
struct FromOutside;
generate_mod::check!(); //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `Outer` in t... | ;
}
#[derive(generate_mod::CheckDeriveLint)] // OK, lint is suppressed
struct W;
fn main() {}
| InnerZ | identifier_name |
generate-mod.rs | // Modules generated by transparent proc macros still acts as barriers for names (issue #50504).
// aux-build:generate-mod.rs
| struct FromOutside;
generate_mod::check!(); //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `Outer` in this scope
#[generate_mod::check_attr] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `Outer... | extern crate generate_mod;
| random_line_split |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful... | msg = "UNKNOWN_TYPE"
if msg is not None:
logging.info("should be sending data")
self.send_single_user(msg)
def send_single_user(self, message):
"""
Send message to single user
"""
for user_host_name, protocol in self.users.iteri... | elif message_words[0] == "DEBUG_LOG":
common_file.com_file_save_data(
'./log_debug/Debug', bz2.decompress(message_words[1]), False, True, '.log')
else:
logging.error("UNKNOWN TYPE: %s", message_words[0])
| random_line_split |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful... | """
Send message to all users
"""
for user_host_name, protocol in self.users.iteritems():
if self.users[user_host_name].user_verified == 1:
logging.info('send all: %s', message)
protocol.sendString(message.encode("utf8")) | identifier_body | |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful... | (self, data):
"""
Message received from client
"""
msg = None
message_words = data.split(' ')
logging.info('GOT Data: %s', data)
logging.info('Message: %s', message_words[0])
if message_words[0] == "VALIDATE":
# have to create the self... | stringReceived | identifier_name |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful... | if self.users[user_host_name].user_verified == 1:
logging.info('send all: %s', message)
protocol.sendString(message.encode("utf8")) | conditional_block | |
functions.ts | 'use strict';
export var t = function appendText(e: HTMLElement, text: string, doc: HTMLDocument) {
return e.appendChild(doc.createTextNode(text));
}
export var tst = function appendTest() {
/* global window */
return window.document.body && (window.document.body.insertAdjacentElement);
} | e.appendChild(node);
return node;
}
export var aens = function alternateAppendNs(e: HTMLElement, name: string, ns: string, doc: HTMLDocument) {
var node = doc.createElementNS(ns, name);
e.appendChild(node);
return node;
}
export var e = function appendElement(e: HTMLElement, name: string, doc: HTMLDocument) {
var... | export var ae = function alternateAppend(e:HTMLElement, name: string, doc: HTMLDocument) {
var node = doc.createElement(name); | random_line_split |
21.rs | use std::fs::File;
use std::io::prelude::*;
use std::iter;
mod intcode;
use intcode::*;
#[derive(Debug, Clone)]
enum DroidResult {
Fail(String),
Success(i64)
}
fn get_input() -> std::io::Result<String> {
let mut file = File::open("21.txt")?;
let mut contents = String::new();
file.read_to_string(&mut conten... | # E and F are not holes
OR E T
AND F T
# )
OR T J
OR H J
# (
# There's a hole in ABC
NOT A T
NOT T T
AND B T
AND C T
NOT T T
# and D is not a hole
AND D T
# )
AND T J
RUN
";
let result = run_springdroid(&mut ProgramS... | # ( | random_line_split |
21.rs | use std::fs::File;
use std::io::prelude::*;
use std::iter;
mod intcode;
use intcode::*;
#[derive(Debug, Clone)]
enum DroidResult {
Fail(String),
Success(i64)
}
fn | () -> std::io::Result<String> {
let mut file = File::open("21.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn run_springdroid(state: &mut ProgramState, script: &str) -> DroidResult {
let inputs = script.lines()
.map(|line| line.trim())
.filter(|line| ... | get_input | identifier_name |
21.rs | use std::fs::File;
use std::io::prelude::*;
use std::iter;
mod intcode;
use intcode::*;
#[derive(Debug, Clone)]
enum DroidResult {
Fail(String),
Success(i64)
}
fn get_input() -> std::io::Result<String> {
let mut file = File::open("21.txt")?;
let mut contents = String::new();
file.read_to_string(&mut conten... | ,
_ => {
DroidResult::Fail(
outputs.iter()
.map(|&c| c as u8 as char)
.fold(String::new(), |mut acc, c| {
acc.push(c);
acc
})
)
}
}
}
fn main() {
let input = get_input().unwrap();
let program = input.split(',')
.filter_map(|x| x.trim().p... | {
DroidResult::Success(x)
} | conditional_block |
dont_promote_unstable_const_fn.rs | // Copyright 2018 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 ... | () {
let _: &'static u32 = &meh(); //~ ERROR does not live long enough
let x: &'static _ = &std::time::Duration::from_millis(42).subsec_millis();
//~^ ERROR does not live long enough
}
| main | identifier_name |
dont_promote_unstable_const_fn.rs | // Copyright 2018 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 ... | let x: &'static _ = &std::time::Duration::from_millis(42).subsec_millis();
//~^ ERROR does not live long enough
} | random_line_split | |
dont_promote_unstable_const_fn.rs | // Copyright 2018 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 ... | //~ ERROR `foo` is not yet stable as a const fn
fn a() {
let _: &'static u32 = &foo(); //~ ERROR does not live long enough
}
fn main() {
let _: &'static u32 = &meh(); //~ ERROR does not live long enough
let x: &'static _ = &std::time::Duration::from_millis(42).subsec_millis();
//~^ ERROR does not liv... | { foo() } | identifier_body |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.n... | var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrix... | var pt = svg.createSVGPoint(); | random_line_split |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.n... | {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else {
return findParentSVG(parentNode);
}
} | identifier_body | |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.n... | (node) {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else {
return findParentSVG(parentNode);
}
}
| findParentSVG | identifier_name |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.n... |
}
| {
return findParentSVG(parentNode);
} | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... |
Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move|| {
for i in 0..nmsgs {
q.push(i);
... | {} | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... |
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
... | {
Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
} | identifier_body |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | (&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
... | pop | identifier_name |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
}
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None)... |
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> { | random_line_split |
chips-autocomplete-example.ts | import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import ... |
}
selected(event: MatAutocompleteSelectedEvent): void {
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fr... | {
this.fruits.splice(index, 1);
} | conditional_block |
chips-autocomplete-example.ts | import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import ... | (event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
remov... | add | identifier_name |
record.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2018, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|--------------------------------------------------... | */
export
type MutableChange<S extends Schema> = {
[N in keyof S['fields']]?: S['fields'][N]['ChangeType'];
};
/**
* @internal
*
* A type alias for the record mutable patch type.
*/
export
type MutablePatch<S extends Schema> = {
[N in keyof S['fields']]?: S['fields'][N]['PatchType'];... | random_line_split | |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundCo... |
function removeAllQueViews(window) {
for( var i = 0; i < queViewArray.length; i++) {
var _queView = queViewArray[i];
window.remove(_queView);
}
}
function highlightHao(index) {
var _queView = queViewArray[index];
_queView.backgroundColor = "#900";
}
module.exports = FirstView;
| {
var queIndex = options["queIndex"];
var queHeight = options["queHeight"] * 90 / 100;
var backgroundColor = options["backgroundColor"];
var _queView = Ti.UI.createView({
top: queHeight * queIndex,
height: queHeight,
width: "100%",
borderColor: backgroundColor,
borderWidth: 5,
borderR... | identifier_body |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundCo... | else if (queIndex == 6) { // if que == 6, xin hao dong
// xin hao dong
var haoDong = Math.floor(Math.random() * 6);
highlightHao(haoDong);
// reverse que lai, doc tu duoi len
queWholeValue.reverse();
// add hao dong vao queWholeValue
queWholeValue.push(haoDong);
c... | {
var queValue = Math.random() >= 0.5 ? 1 : 0;
console.log(queValue);
queWholeValue.push(queValue);
var options = {
queIndex: queIndex,
queHeight: queHeight,
backgroundColor: mainBackgroundColor
}
var queView = createQueView(queValue, options);
se... | conditional_block |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundCo... | (index) {
var _queView = queViewArray[index];
_queView.backgroundColor = "#900";
}
module.exports = FirstView;
| highlightHao | identifier_name |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundCo... | top: 10,
right: 10,
width: 50,
height: 50,
zIndex: 999
});
self.add(resetButtonView);
var queIndex = 0;
pushButtonView.addEventListener("click", function(e) {
if (queIndex < 6) {
var queValue = Math.random() >= 0.5 ? 1 : 0;
console.log(queValue);
queWholeValue.push(queVal... | image: "/images/reset.jpg", | random_line_split |
login.test.js | import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import {
fetchLogin,
testing,
} from './login';
const mockStore = configureMockStore([thunk]);
beforeEach(() => {
fetchMock.restore();
});
test('fetch login with success', done => {
fetchM... | done();
});
});
test('fetch login failure', done => {
fetchMock.post(`${testing.base_url}/auth/login/`, {
status: 401,
body: {},
});
const store = mockStore();
const expectedActions = [
testing.fetchLoginFailure(),
];
const email = "mario.rossi@email.com";
const password = "pippo";... | const password = "pippo";
return store.dispatch(fetchLogin(email, password))
.then(() => {
expect(store.getActions()).toEqual(expectedActions); | random_line_split |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self... |
def description(self):
return 'Starts monitoring file on disk'
class StopTailF(sublime_plugin.TextCommand):
'''
Stop monitoring file command.
'''
def run(self, edit):
TAILF_VIEWS.remove(self.view.id())
# restore view to previous state
self.view.set_read_only(False... | return | conditional_block |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self... | return
else:
file_stat = os.stat(self.view.file_name())
new_size = file_stat[stat.ST_SIZE]
new_mod_time = file_stat[stat.ST_MTIME]
if (new_mod_time > self.prev_mod_time or
new_size != ... | if self.view.file_name() is None:
sublime.error_message('File not save on disk') | random_line_split |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self... |
class TailFEventListener(sublime_plugin.EventListener):
'''
Listener that removes files from monitored files once file is
about to be closed.
'''
def on_pre_close(self, view):
if view.id() in TAILF_VIEWS:
TAILF_VIEWS.remove(view.id())
| read_only = self.view.is_read_only()
self.view.set_read_only(False)
with io.open(self.view.file_name(), 'r', encoding='utf-8-sig') as f:
content = f.read()
whole_file = sublime.Region(0, self.view.size())
self.view.replace(edit, whole_file, content)
self.view.... | identifier_body |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def | (self, *args, **kwargs):
super(TailF, self).__init__(*args, **kwargs)
self.prev_file_size = -1
self.prev_mod_time = -1
def run(self, edit):
self.view.set_read_only(True)
t = threading.Thread(target=self.thread_handler)
TAILF_VIEWS.add(self.view.id())
self.vie... | __init__ | identifier_name |
lib.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/. */
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#!... | () {}
pub fn init_service_workers(sw_senders: SWManagerSenders) {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
proxyhandler::init();
// Create the global vtables used ... | perform_platform_specific_initialization | identifier_name |
lib.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/. */
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#!... | #[macro_use]
extern crate bitflags;
extern crate bluetooth_traits;
extern crate byteorder;
extern crate canvas_traits;
extern crate caseless;
extern crate cookie as cookie_rs;
extern crate core;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate deny_public_fields;
extern crate devtools_traits;
extern crate... | extern crate atomic_refcell;
extern crate audio_video_metadata; | random_line_split |
lib.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/. */
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#!... | {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
} | identifier_body | |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.comp... | (self):
return self._name
@property
def icon(self):
return SENSOR_TYPES[self.type][2]
@property
def state(self):
""" Returns the state of the device. """
return self._state
@property
def unit_of_measurement(self):
""" Unit of measurement of this entity,... | name | identifier_name |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.comp... | config.get(CONF_PASSWORD, None))
if not authorization:
_LOGGER.error(
"Connection error "
"Please check your settings for NatAtmo API.")
return False
data = NetAtmoData(authorization)
dev = []
try:
# Iterate each ... | authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
config.get(CONF_SECRET_KEY, None),
config.get(CONF_USERNAME, None), | random_line_split |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.comp... |
elif self.type == 'noise':
self._state = data['Noise']
elif self.type == 'co2':
self._state = data['CO2']
elif self.type == 'pressure':
self._state = round(data['Pressure'], 1)
class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """
d... | self._state = data['Humidity'] | conditional_block |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.comp... |
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Call the NetAtmo API to update the data. """
import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600)
| """ Return all module available on the API as a list. """
self.update()
return self.data.keys() | identifier_body |
proto.spec.ts | import Long from "long";
import { ClientTransaction } from "../../src/byzcoin";
import { DataBody, DataHeader, TxResult } from "../../src/byzcoin/proto";
import {
AddTxRequest, CreateGenesisBlock,
} from "../../src/byzcoin/proto/requests";
import Darc from "../../src/darc/darc";
describe("ByzCoin Proto Tests", () ... |
expect(new CreateGenesisBlock()).toBeDefined();
});
it("should handle add tx request messages", () => {
const req = new AddTxRequest({ skipchainID: Buffer.from([1, 2, 3]) });
expect(req.skipchainID).toEqual(Buffer.from([1, 2, 3]));
expect(new AddTxRequest()).toBeDefined();
... | expect(req.blockInterval.toNumber()).toBe(1);
expect(req.maxBlockSize).toBe(42); | random_line_split |
target-apply.ts | import * as clc from "cli-color";
import { Command } from "../command";
import { logger } from "../logger";
import * as requireConfig from "../requireConfig";
import * as utils from "../utils";
import { FirebaseError } from "../error";
export default new Command("target:apply <type> <name> <resources...>")
.descrip... | );
for (const change of changes) {
utils.logWarning(
`Previous target ${clc.bold(change.target)} removed from ${clc.bold(change.resource)}`
);
}
logger.info();
logger.info(`Updated: ${name} (${options.rc.target(options.project, type, name).join(",")})`);
}); | utils.logSuccess(
`Applied ${type} target ${clc.bold(name)} to ${clc.bold(resources.join(", "))}` | random_line_split |
target-apply.ts | import * as clc from "cli-color";
import { Command } from "../command";
import { logger } from "../logger";
import * as requireConfig from "../requireConfig";
import * as utils from "../utils";
import { FirebaseError } from "../error";
export default new Command("target:apply <type> <name> <resources...>")
.descrip... |
const changes = options.rc.applyTarget(options.project, type, name, resources);
utils.logSuccess(
`Applied ${type} target ${clc.bold(name)} to ${clc.bold(resources.join(", "))}`
);
for (const change of changes) {
utils.logWarning(
`Previous target ${clc.bold(change.target)} remove... | {
throw new FirebaseError(
`Must have an active project to set deploy targets. Try ${clc.bold("firebase use --add")}`
);
} | conditional_block |
input_state.rs | use std::vec::Vec;
use operation::{ Operation, Direction, };
pub struct InputState {
pub left: bool,
pub right: bool,
pub up: bool,
pub down: bool,
pub enter: bool,
pub cancel: bool,
}
impl InputState {
pub fn new() -> InputState {
InputState {
left: false, right: fals... |
if self.cancel { states.push(Operation::Cancel); }
states
}
}
| { states.push(Operation::Enter); } | conditional_block |
input_state.rs | use std::vec::Vec;
use operation::{ Operation, Direction, };
pub struct InputState {
pub left: bool,
pub right: bool,
pub up: bool,
pub down: bool,
pub enter: bool,
pub cancel: bool,
}
impl InputState {
pub fn new() -> InputState {
InputState {
left: false, right: fals... | (&mut self, op: Operation) -> &mut Self {
self.update(op, false)
}
fn update(&mut self, op: Operation, value: bool) -> &mut Self {
match op {
Operation::Move(dir) => match dir {
Direction::Left => self.left = value,
Direction::Right => self.right = va... | release | identifier_name |
input_state.rs | use std::vec::Vec; | use operation::{ Operation, Direction, };
pub struct InputState {
pub left: bool,
pub right: bool,
pub up: bool,
pub down: bool,
pub enter: bool,
pub cancel: bool,
}
impl InputState {
pub fn new() -> InputState {
InputState {
left: false, right: false, up: false, down: ... | random_line_split | |
spatial_reference.rs | extern crate gdal; |
fn run() -> Result<(), gdal::errors::Error> {
let spatial_ref1 = SpatialRef::from_proj4(
"+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
)?;
println!(
"Spatial ref from proj4 to wkt:\n{:?}\n",
spatial_ref1.to_wkt()?
);
let spatial_r... |
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry; | random_line_split |
spatial_reference.rs | extern crate gdal;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
fn | () -> Result<(), gdal::errors::Error> {
let spatial_ref1 = SpatialRef::from_proj4(
"+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
)?;
println!(
"Spatial ref from proj4 to wkt:\n{:?}\n",
spatial_ref1.to_wkt()?
);
let spatial_ref2 = S... | run | identifier_name |
spatial_reference.rs | extern crate gdal;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
fn run() -> Result<(), gdal::errors::Error> |
fn main() {
run().unwrap();
}
| {
let spatial_ref1 = SpatialRef::from_proj4(
"+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
)?;
println!(
"Spatial ref from proj4 to wkt:\n{:?}\n",
spatial_ref1.to_wkt()?
);
let spatial_ref2 = SpatialRef::from_wkt("GEOGCS[\"WGS 84\"... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.