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
app-store.purchase-handler.ts
import {PurchaseHandler} from "./purchase-handler"; import {ProductData, productDataMap} from "./products"; import * as appleReceiptVerify from "node-apple-receipt-verify"; import {APP_STORE_SHARED_SECRET} from "./constants"; import {IapRepository} from "./iap.repository"; import {firestore} from "firebase-admin/lib/fi...
export class AppStorePurchaseHandler extends PurchaseHandler { constructor(private iapRepository: IapRepository) { super(); appleReceiptVerify.config({ verbose: false, secret: APP_STORE_SHARED_SECRET, extended: true, environment: ["sandbox"], // Optional, defaults to ['production'], ...
originalTransactionId: string; } }
random_line_split
donors-list-controller.js
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * ...
{ Donors.get(function (data) { $scope.donors = data.donors; }); $scope.editDonor = function (id, donationCount) { var data = {query: $scope.query}; navigateBackService.setData(data); sharedSpace.setCountOfDonations(donationCount); $location.path('edit/' + id); }; }
identifier_body
donors-list-controller.js
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * ...
($scope, sharedSpace, $location, navigateBackService, Donors) { Donors.get(function (data) { $scope.donors = data.donors; }); $scope.editDonor = function (id, donationCount) { var data = {query: $scope.query}; navigateBackService.setData(data); sharedSpace.setCountOfDonations(donation...
DonorListController
identifier_name
donors-list-controller.js
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * ...
var data = {query: $scope.query}; navigateBackService.setData(data); sharedSpace.setCountOfDonations(donationCount); $location.path('edit/' + id); }; }
$scope.editDonor = function (id, donationCount) {
random_line_split
authors.js
$(function() { var resultCache = []; var allItems = $(".index .item"); $("#filter_text").keyup(function(){ var searchString = $(this).val(); allItems.addClass('visibility_hidden'); var items; if (resultCache[searchString] === undefined)
else { items = resultCache[searchString]; } items.removeClass('visibility_hidden'); $("#numberFiltered").text(items.length); $("#numberFilteredText").text(items.length == 1 ? $T("author") : $T("authors")); }); $(".material_icon").each(function() { $(this).q...
{ items = $(".index .item .text").textContains(searchString).parent().parent(); resultCache[searchString] = items; }
conditional_block
authors.js
$("#filter_text").keyup(function(){ var searchString = $(this).val(); allItems.addClass('visibility_hidden'); var items; if (resultCache[searchString] === undefined) { items = $(".index .item .text").textContains(searchString).parent().parent(); resultCache[s...
$(function() { var resultCache = []; var allItems = $(".index .item");
random_line_split
controller.py
from .model import NetworkModel from .view import NetworkView from PyQt5.QtWidgets import QAction, QMenu from PyQt5.QtGui import QCursor, QDesktopServices from PyQt5.QtCore import pyqtSlot, QUrl, QObject from duniterpy.api import bma from duniterpy.documents import BMAEndpoint class NetworkController(QObject): ""...
def __init__(self, parent, view, model): """ Constructor of the navigation component :param sakia.gui.network.view.NetworkView: the view :param sakia.gui.network.model.NetworkModel model: the model """ super().__init__(parent) self.view = view self.m...
The network panel """
random_line_split
controller.py
from .model import NetworkModel from .view import NetworkView from PyQt5.QtWidgets import QAction, QMenu from PyQt5.QtGui import QCursor, QDesktopServices from PyQt5.QtCore import pyqtSlot, QUrl, QObject from duniterpy.api import bma from duniterpy.documents import BMAEndpoint class NetworkController(QObject): ""...
@pyqtSlot() def open_node_in_browser(self): node = self.sender().data() bma_endpoints = [e for e in node.endpoints if isinstance(e, BMAEndpoint)] if bma_endpoints: conn_handler = next(bma_endpoints[0].conn_handler()) peering_url = bma.API(conn_handler, bma.netwo...
node = self.sender().data() self.model.unset_root_node(node)
identifier_body
controller.py
from .model import NetworkModel from .view import NetworkView from PyQt5.QtWidgets import QAction, QMenu from PyQt5.QtGui import QCursor, QDesktopServices from PyQt5.QtCore import pyqtSlot, QUrl, QObject from duniterpy.api import bma from duniterpy.documents import BMAEndpoint class NetworkController(QObject): ""...
(self, point): index = self.view.table_network.indexAt(point) valid, node = self.model.table_model_data(index) if self.model.app.parameters.expert_mode: menu = QMenu() open_in_browser = QAction(self.tr("Open in browser"), self) open_in_browser.triggered.connec...
node_context_menu
identifier_name
controller.py
from .model import NetworkModel from .view import NetworkView from PyQt5.QtWidgets import QAction, QMenu from PyQt5.QtGui import QCursor, QDesktopServices from PyQt5.QtCore import pyqtSlot, QUrl, QObject from duniterpy.api import bma from duniterpy.documents import BMAEndpoint class NetworkController(QObject): ""...
@pyqtSlot() def set_root_node(self): node = self.sender().data() self.model.add_root_node(node) @pyqtSlot() def unset_root_node(self): node = self.sender().data() self.model.unset_root_node(node) @pyqtSlot() def open_node_in_browser(self): node = self....
menu = QMenu() open_in_browser = QAction(self.tr("Open in browser"), self) open_in_browser.triggered.connect(self.open_node_in_browser) open_in_browser.setData(node) menu.addAction(open_in_browser) # Show the context menu. menu.exec_(QCursor.pos()...
conditional_block
dropbox.py
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the ...
product_ids = product_pool.search([ ('connector_id.wordpress', '=', True), ]) # Check elements: #error = [] # Error database #warning = [] # Warning database #info = [] # Info database #log = [] # Log database #log_sym = [] # Log database for symlinks #product_odoo = {} # Only if new file (check how): dropbox...
) # Pool used: product_pool = odoo.model('product.product.web.server')
random_line_split
dropbox.py
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the ...
os.system('chmod 777 "%s" -R' % dropbox_path) for filename in current_files: os.rm(filename) # file_modify = get_modify_date(fullname) # os.system('mkdir -p "%s"' % product_folder) print 'End operation' # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
image_id = image.id code = image.album_id.code samba_relative_path = image.album_id.path # TODO dropbox_path filename = product.filename origin = os.path.(samba_relative_path, filename) destination = os.path.(dropbox_root_path, '%s.%s' % (code, filename)) ...
conditional_block
dropbox.py
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the ...
# ----------------------------------------------------------------------------- # ODOO operation: # ----------------------------------------------------------------------------- odoo = erppeek.Client( 'http://%s:%s' % ( odoo_server, odoo_port), db=odoo_database, ...
''' Return modify date for file ''' modify_date = datetime.fromtimestamp( os.stat(fullname).st_mtime).strftime('%Y-%m-%d') return modify_date
identifier_body
dropbox.py
############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the ...
(fullname): ''' Return modify date for file ''' modify_date = datetime.fromtimestamp( os.stat(fullname).st_mtime).strftime('%Y-%m-%d') return modify_date # ----------------------------------------------------------------------------- # ODOO operation: # -------...
get_modify_date
identifier_name
timezone.service.ts
import { Injectable } from '@angular/core'; import moment from 'moment-timezone'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { default as timezone } from '../data/timezone.json'; import { HttpRequestService } from './http-request.service'; import { ResourceEndpoints } from '../type...
(timestamp: number | null, timeZone: string): any { if (!timestamp) { return moment.tz(timeZone); } return moment(timestamp).tz(timeZone); } /** * Gets the resolved UNIX timestamp from a local data time with time zone. */ getResolvedTimestamp(localDateTime: string, timeZone: string, field...
getMomentInstance
identifier_name
timezone.service.ts
import { Injectable } from '@angular/core'; import moment from 'moment-timezone'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { default as timezone } from '../data/timezone.json'; import { HttpRequestService } from './http-request.service'; import { ResourceEndpoints } from '../type...
getTimeZone(): Observable<TimeZones> { return this.httpRequestService.get(ResourceEndpoints.TIMEZONE); } formatToString(timestamp: number, timeZone: string, format: string): string { return moment(timestamp).tz(timeZone).format(format); } getMomentInstance(timestamp: number | null, timeZone: strin...
{ return this.badZones[tz]; }
identifier_body
timezone.service.ts
import { Injectable } from '@angular/core'; import moment from 'moment-timezone'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { default as timezone } from '../data/timezone.json'; import { HttpRequestService } from './http-request.service'; import { ResourceEndpoints } from '../type...
this.guessedTimezone = moment.tz.guess(); } /** * Gets the timezone database version. */ getTzVersion(): string { return this.tzVersion; } /** * Gets the mapping of time zone ID to offset values. */ getTzOffsets(): Record<string, number> { return this.tzOffsets; } /** * Gue...
random_line_split
bitflags.rs
// Copyright 2014 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 ...
#[test] fn test_remove(){ let mut e1 = FlagA | FlagB; let e2 = FlagA | FlagC; e1.remove(e2); assert!(e1 == FlagB); } #[test] fn test_operators() { let e1 = FlagA | FlagC; let e2 = FlagB | FlagC; assert!((e1 | e2) == FlagABC); // union ...
{ let mut e1 = FlagA; let e2 = FlagA | FlagB; e1.insert(e2); assert!(e1 == e2); }
identifier_body
bitflags.rs
// Copyright 2014 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 ...
//! - `insert`: inserts the specified flags in-place //! - `remove`: removes the specified flags in-place #![macro_escape] #[macro_export] macro_rules! bitflags( ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+ }) => ( #[deriving(Eq...
random_line_split
bitflags.rs
// Copyright 2014 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 ...
(){ assert_eq!(Flags::empty().bits(), 0x00000000); assert_eq!(FlagA.bits(), 0x00000001); assert_eq!(FlagABC.bits(), 0x00000111); } #[test] fn test_is_empty(){ assert!(Flags::empty().is_empty()); assert!(!FlagA.is_empty()); assert!(!FlagABC.is_empty()); } ...
test_bits
identifier_name
status-window.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { ColyseusGameService } from '../colyseus.game.service'; import { values, extend } from 'lodash'; import { LocalStorage } from 'ngx-webstorage'; import { timer } from 'rxjs'; @Component({ selector: 'app-status-window', templateUrl: './sta...
@LocalStorage() public isMPPercent: boolean; public effects = []; private effect$: any; public get player() { return this.colyseusGame.character; } get healthPercent(): number { if(!this.player) return 0; return Math.floor(this.player.hp.__current / this.player.hp.maximum * 100); } ...
public isXPPercent: boolean; @LocalStorage() public isHPPercent: boolean;
random_line_split
status-window.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { ColyseusGameService } from '../colyseus.game.service'; import { values, extend } from 'lodash'; import { LocalStorage } from 'ngx-webstorage'; import { timer } from 'rxjs'; @Component({ selector: 'app-status-window', templateUrl: './sta...
(): any[] { if(!this.player) return []; return values(this.player.effects); } constructor(public colyseusGame: ColyseusGameService) { } ngOnInit() { this.effect$ = timer(0, 1000).subscribe(() => { this.recalculateEffects(); }); } ngOnDestroy() { this.effect$.unsubscribe(); } ...
allEffects
identifier_name
status-window.component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { ColyseusGameService } from '../colyseus.game.service'; import { values, extend } from 'lodash'; import { LocalStorage } from 'ngx-webstorage'; import { timer } from 'rxjs'; @Component({ selector: 'app-status-window', templateUrl: './sta...
get xpPercent(): number { if(!this.player) return 0; const baseXp = this.player.calcLevelXP(this.player.level); const neededXp = this.player.calcLevelXP(this.player.level + 1); return Math.floor(Math.min(100, (this.player.exp - baseXp) / (neededXp - baseXp) * 100)); } get axpPercent(): number ...
{ if(!this.player) return 0; // show full bar even if 0/0 if(this.player.mp.maximum === 0) return 100; return Math.floor(this.player.mp.__current / this.player.mp.maximum * 100); }
identifier_body
test_user_registered.py
from django.test import TestCase from django.contrib.auth.models import User from django.http import HttpRequest from .factories import UserReferrerFactory, UserFactory, CampaignFactory from referral_module import constants from referral_module import models def make_cookie_file(user_referrer): cookie_file = '{...
(self): real_user_campaign_key = self.user_referrer.campaign.key # First check with fake campaign key self.user_referrer.campaign.key = 77777 # random data request = get_request(user_referrer=self.user_referrer) self.assertEqual( models.Referrer.objects.count(), ...
test_illegal_referrer_data
identifier_name
test_user_registered.py
from django.test import TestCase from django.contrib.auth.models import User from django.http import HttpRequest from .factories import UserReferrerFactory, UserFactory, CampaignFactory from referral_module import constants from referral_module import models def make_cookie_file(user_referrer): cookie_file = '{...
def test_unreferred_user_registered(self): request = HttpRequest() models.associate_registered_user_with_referral("", user=self.user, request=request) # new user is in the database user_in_db = User.objects.get(username=self.user.username) self.assertEqual(user_in_db.usern...
reward_before_new_user = self.user_referrer.reward request = get_request(user_referrer=self.user_referrer) models.associate_registered_user_with_referral("", user=self.user, request=request) # referrer user sign as referrer to the new user referrer_db = models.Referrer.objects.get(user_...
identifier_body
test_user_registered.py
from django.test import TestCase from django.contrib.auth.models import User from django.http import HttpRequest from .factories import UserReferrerFactory, UserFactory, CampaignFactory from referral_module import constants from referral_module import models def make_cookie_file(user_referrer): cookie_file = '{...
def test_user_registered_with_referrer_user(self): reward_before_new_user = self.user_referrer.reward request = get_request(user_referrer=self.user_referrer) models.associate_registered_user_with_referral("", user=self.user, request=request) # referrer user sign as referrer to the n...
random_line_split
gen_events.py
#!/usr/bin/python ''' This script is used to generate a set of random-ish events to simulate log data from a Juniper Netscreen FW. It was built around using netcat to feed data into Flume for ingestion into a Hadoop cluster. Once you have Flume configured you would use the following command to populate data: ./g...
sleep(0.3) fo.close()
random_line_split
gen_events.py
#!/usr/bin/python ''' This script is used to generate a set of random-ish events to simulate log data from a Juniper Netscreen FW. It was built around using netcat to feed data into Flume for ingestion into a Hadoop cluster. Once you have Flume configured you would use the following command to populate data: ./g...
fo.close()
proto_index = random.randint(0,1) protocol = protocols[proto_index] src_port_index = random.randint(0,13) dest_port_index = random.randint(0,13) src_port = common_ports[src_port_index] dest_port = common_ports[dest_port_index] action_index = random.randint(0,3) action = action_list[action_in...
conditional_block
statement_flow.ts
import {expect} from "chai"; import {Registry} from "../../src/registry"; import {MemoryFile} from "../../src/files/memory_file"; import {LanguageServer} from "../../src"; describe("LSP, statement flow", () => { it("basic", async () => { const abap = ` CLASS zcl_foobar DEFINITION PUBLIC CREATE PUBLIC. ...
ENDMETHOD. METHOD method2. DATA foo. IF 2 = 1. WRITE 'sdf'. ENDIF. ENDMETHOD. ENDCLASS. `; const file = new MemoryFile("zcl_foobar.clas.abap", abap); const reg = new Registry().addFile(file); await reg.parseAsync(); const dump = new LanguageSer...
METHODS method2. ENDCLASS. CLASS zcl_foobar IMPLEMENTATION. METHOD method1. WRITE 'sdf'.
random_line_split
construct-translation-ids.service.spec.ts
// Copyright 2020 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 //
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License....
random_line_split
ModalExportWallets.spec.js
import Vue from 'vue' import Vuelidate from 'vuelidate' import { shallowMount } from '@vue/test-utils' import useI18nGlobally from '../../__utils__/i18n' import ModalExportWallets from '@/components/Modal/ModalExportWallets' import StringMixin from '@/mixins/strings' import WalletMixin from '@/mixins/wallet' Vue.use(V...
$store: { getters: { 'delegate/byAddress': jest.fn(), 'wallet/contactsByProfileId': () => [], 'wallet/byProfileId': () => wallets, 'ledger/wallets': () => ledgerWallets } } } }) } it('should render modal', () => { con...
session_network: { knownWallets: {} },
random_line_split
tokenizer.rs
//! A whitespace and comment preserving lexer designed for use in both the compiler frontend //! and IDEs. //! //! The output of the tokenizer is lightweight, and only contains information about the //! type of a [Token] and where it occurred in the source. use std::ops::Range; use itertools::Itertools; use logos::Le...
} impl<'a> Iterator for Tokenizer<'a> { type Item = (TokenKind, Range<usize>); fn next(&mut self) -> Option<Self::Item> { if self.seen_eof { return None; } let ty = self.lexer.token; let range = self.lexer.range(); self.lexer.advance(); if ty == T...
random_line_split
tokenizer.rs
//! A whitespace and comment preserving lexer designed for use in both the compiler frontend //! and IDEs. //! //! The output of the tokenizer is lightweight, and only contains information about the //! type of a [Token] and where it occurred in the source. use std::ops::Range; use itertools::Itertools; use logos::Le...
{ let types: Vec<TokenKind> = tokenize("test abc 123") .into_iter() .map(|t| t.into()) .collect(); assert_eq!( vec![ TokenKind::Name, TokenKind::Whitespace, TokenKind::Name, TokenKind::Whitespace, TokenKind::Integer, ...
identifier_body
tokenizer.rs
//! A whitespace and comment preserving lexer designed for use in both the compiler frontend //! and IDEs. //! //! The output of the tokenizer is lightweight, and only contains information about the //! type of a [Token] and where it occurred in the source. use std::ops::Range; use itertools::Itertools; use logos::Le...
<'a> { lexer: Lexer<TokenKind, &'a str>, seen_eof: bool, } impl<'a> Tokenizer<'a> { fn new(text: &'a str) -> Self { Tokenizer { lexer: TokenKind::lexer(text), seen_eof: false, } } } impl<'a> Iterator for Tokenizer<'a> { type Item = (TokenKind, Range<usize>);...
Tokenizer
identifier_name
frame.py
from collections import deque from lcdui import common from lcdui.ui import widget import array import time class Frame(object): def __init__(self, ui): self._ui = ui self._widgets = {} self._position = {} self._span = {} self._screen_buffer = ScreenBuffer(self.rows(), self.cols()) self.onI...
def addItem(self, key, value): self._items.append((key, value)) self._rebuildMenu() def scrollUp(self): if self._cursor_pos == 0: return self._cursor_pos -= 1 self._updateWindowPos() self._rebuildMenu() def scrollDown(self): if (self._cursor_pos + 1) == len(self._items): ...
random_line_split
frame.py
from collections import deque from lcdui import common from lcdui.ui import widget import array import time class Frame(object): def __init__(self, ui): self._ui = ui self._widgets = {} self._position = {} self._span = {} self._screen_buffer = ScreenBuffer(self.rows(), self.cols()) self.onI...
(Frame): def __init__(self, ui): Frame.__init__(self, ui) self._inner_frames = deque() self._display_time = {} self._last_rotate = None def AddWidget(self, widget_obj, name, row=0, col=0, span=None): raise NotImplementedError def GetWidget(self, name): raise NotImplementedError def Re...
MultiFrame
identifier_name
frame.py
from collections import deque from lcdui import common from lcdui.ui import widget import array import time class Frame(object): def __init__(self, ui): self._ui = ui self._widgets = {} self._position = {} self._span = {} self._screen_buffer = ScreenBuffer(self.rows(), self.cols()) self.onI...
if (self._window_pos + self._window_size) < len(self._items): self._item_widgets[-1].set_postfix('|' + symbol_down) def _updateWindowPos(self): self._window_pos = self._cursor_pos - (self._cursor_pos % self._window_size) def setTitle(self, title): prefix = '' symbol_back = self._ui.GetSymb...
self._item_widgets[0].set_postfix('|' + symbol_up)
conditional_block
frame.py
from collections import deque from lcdui import common from lcdui.ui import widget import array import time class Frame(object): def __init__(self, ui): self._ui = ui self._widgets = {} self._position = {} self._span = {} self._screen_buffer = ScreenBuffer(self.rows(), self.cols()) self.onI...
def _updateWindowPos(self): self._window_pos = self._cursor_pos - (self._cursor_pos % self._window_size) def setTitle(self, title): prefix = '' symbol_back = self._ui.GetSymbol(common.SYMBOL.FRAME_BACK) if self._show_back: postfix = '_' + symbol_back + '_' else: postfix = '' a...
items = self._items[self._window_pos:self._window_pos+self._window_size] num_blank = self._window_size - len(items) symbol_up = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_UP) symbol_down = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_DOWN) symbol_cursor = self._ui.GetSymbol(common.SYMBOL.MENU_CURSOR) ...
identifier_body
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize...
"-i, --interactive 'Use the interactive version instead of outputting to stdout' [INPUT] 'Specifies the input file to use'").get_matches(); if let Some(file_path) = matches.value_of("INPUT") { if matches.is_present("interactive") { rustbox_output(&file_path); ...
random_line_split
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize...
fn string_repeat(s: &str, n: usize) -> String { std::iter::repeat(s).take(n).collect::<String>() } fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String { match trimming_offset { None => { format!("{:01$x}: ", offset, width) } Some(trimming_string) => { ...
{ format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3) }
identifier_body
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize...
0xFF => { print!("## ") } _ => { print!("{:02X} ", b) } } } let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None }; let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong pri...
{ print!(" ") }
conditional_block
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize...
le_path: &str) { let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = EditorState { open_file: None, read_only: false }; // rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!"); ...
tbox_output(fi
identifier_name
index.tsx
/* * 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/. * */ import * as React from 'react'; import { findIndex } from 'lodash'; import { AbilityButtonInfo } from 'hud...
extends React.Component<AbilityQueueProps, AbilityQueueState> { private eventHandles: {[id: string]: EventHandle} = {}; constructor(props: AbilityQueueProps) { super(props); this.state = { queuedAbilities: {}, }; } public render() { return ( <AbilityQueueList queuedAbilities={this....
AbilityQueue
identifier_name
index.tsx
/* * 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/. * */ import * as React from 'react'; import { findIndex } from 'lodash'; import { AbilityButtonInfo } from 'hud...
if (track & AbilityTrack.Mind) { return AbilityTrack[AbilityTrack.Mind]; } return AbilityTrack[AbilityTrack.None]; } } export default AbilityQueue;
{ return AbilityTrack[AbilityTrack.Voice]; }
conditional_block
index.tsx
/* * 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/. * */ import * as React from 'react'; import { findIndex } from 'lodash'; import { AbilityButtonInfo } from 'hud...
} public componentDidMount() { camelotunchained.game.store.onUpdated(this.initAbilityButtonEvents); } public componentWillUnmount() { Object.keys(this.eventHandles).forEach((eventKey) => { // Clear events this.eventHandles[eventKey].clear(); delete this.eventHandles[eventKey]; })...
random_line_split
index.tsx
/* * 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/. * */ import * as React from 'react'; import { findIndex } from 'lodash'; import { AbilityButtonInfo } from 'hud...
public componentDidMount() { camelotunchained.game.store.onUpdated(this.initAbilityButtonEvents); } public componentWillUnmount() { Object.keys(this.eventHandles).forEach((eventKey) => { // Clear events this.eventHandles[eventKey].clear(); delete this.eventHandles[eventKey]; }); ...
{ return ( <AbilityQueueList queuedAbilities={this.state.queuedAbilities} /> ); }
identifier_body
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn ...
Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y))) } pub fn list() -> Result<Vec<String>, String> { ensure_history_exists(); let mut result = Vec::new(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { for y in arr.iter() { ...
let new_entry = remember::serialize(req, resp); arr.insert(0, new_entry); }
random_line_split
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn ...
, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); Ok(output.to_string()) } else { Err(format!("Failed to load history file {}", HISTORY_FILE)) } }
{}
conditional_block
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn ...
pub fn list() -> Result<Vec<String>, String> { ensure_history_exists(); let mut result = Vec::new(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { for y in arr.iter() { let method = try!(yaml_util::get_value_as_string(&y,...
{ ensure_history_exists(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { // Trim the history, -1 so that our request fits under the limit if arr.len() > HISTORY_LIMIT - 1 { while arr.len() > HISTORY_LIMIT - 1 { ...
identifier_body
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn
() { if !Path::new(HISTORY_FILE).exists() { file::ensure_dir_exists(HISTORY_DIR); file::write_file(HISTORY_FILE, "[]"); } } pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> { ensure_history_exists(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_...
ensure_history_exists
identifier_name
models.py
from __future__ import absolute_import, unicode_literals from datetime import datetime import json import random import pytz from smartmin.models import SmartModel from temba import TembaClient from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from...
(self): user = self.administrators.filter(is_active=True).first() if user: org_user = user org_user.set_org(self) return org_user def get_temba_client(self): host = getattr(settings, 'SITE_API_HOST', None) agent = getattr(settings, 'SITE_API_USER_...
get_user
identifier_name
models.py
from __future__ import absolute_import, unicode_literals from datetime import datetime import json import random import pytz from smartmin.models import SmartModel from temba import TembaClient from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from...
User.get_user_orgs = get_user_orgs def get_org_group(obj): org_group = None org = obj.get_org() if org: org_group = org.get_user_org_group(obj) return org_group User.get_org_group = get_org_group USER_GROUPS = (('A', _("Administrator")), ('E', _("Editor")), (...
if user.is_superuser: return Org.objects.all() user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all() return user_orgs.distinct()
identifier_body
models.py
from __future__ import absolute_import, unicode_literals from datetime import datetime import json import random import pytz from smartmin.models import SmartModel from temba import TembaClient from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from...
districts = districts_by_state[osm_id] districts.append(boundary) # mini function to convert a list of boundary objects to geojson def to_geojson(boundary_list): features = [dict(type='Feature', geometry=dict(type=b.geometry.type,...
osm_id = boundary.parent if osm_id not in districts_by_state: districts_by_state[osm_id] = []
random_line_split
models.py
from __future__ import absolute_import, unicode_literals from datetime import datetime import json import random import pytz from smartmin.models import SmartModel from temba import TembaClient from django.conf import settings from django.contrib.auth.models import User, Group from django.core.cache import cache from...
districts = districts_by_state[osm_id] districts.append(boundary) # mini function to convert a list of boundary objects to geojson def to_geojson(boundary_list): features = [dict(type='Feature', geometry=dict(type=b.geometry.typ...
districts_by_state[osm_id] = []
conditional_block
demo.js
/*global console*/ var AutoCompleteView = require('../ampersand-autocomplete-view'); var FormView = require('ampersand-form-view'); var Model = require('ampersand-state').extend({ props: { mbid: 'string', name: 'string', listeners: 'string' }, derived: { id: function() { return this.name; ...
document.addEventListener('DOMContentLoaded', function () { var baseView = new BaseView({el: document.body }); baseView.on('all', function (name, field) { console.log('Got event', name, field.value, field.valid); }); baseView.render(); });
random_line_split
demo.js
/*global console*/ var AutoCompleteView = require('../ampersand-autocomplete-view'); var FormView = require('ampersand-form-view'); var Model = require('ampersand-state').extend({ props: { mbid: 'string', name: 'string', listeners: 'string' }, derived: { id: function() { return this.name; ...
} }); /* var collection = new Collection([ { id: 'red', title: 'Red' }, { id: 'yellow', title: 'Yellow' }, { id: 'blue', title: 'Blue' }, { id: 'rat', title: 'Rat' } ]); */ var BaseView = FormView.extend({ fields: function () { return [ new AutoCompleteView({ name: 'autocomplete', ...
{ return response.results.artistmatches.artist; }
conditional_block
postMessage.js
/* Module handles message posting. */ 'use strict'; const AWS = require('aws-sdk'), Joi = require('joi'), config = require('../environments/config'), dynamodb = new AWS.DynamoDB({ region: 'us-east-1' }); /* Joi validation object */ const postMessageValidate = Joi.object().keys({ UserName: Joi...
}); }; module.exports = { postMessageParams, config: { handler: postMessage, description: 'Allow user to post a message.', tags: ['api'], validate: { query: postMessageValidate } } };
console.log('ERR: ' + err); resp({Error: err}).code(400); } else { resp({mete: {status: "Success"}, data: data}).code(200); }
random_line_split
postMessage.js
/* Module handles message posting. */ 'use strict'; const AWS = require('aws-sdk'), Joi = require('joi'), config = require('../environments/config'), dynamodb = new AWS.DynamoDB({ region: 'us-east-1' }); /* Joi validation object */ const postMessageValidate = Joi.object().keys({ UserName: Joi...
}); }; module.exports = { postMessageParams, config: { handler: postMessage, description: 'Allow user to post a message.', tags: ['api'], validate: { query: postMessageValidate } } };
{ resp({mete: {status: "Success"}, data: data}).code(200); }
conditional_block
all_62.js
var searchData= [ ['backtrace',['backtrace',['../class_logger.html#a5deb9b10c43285287a9113f280ee8fab',1,'Logger']]],
['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_t_mail_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]], ['basicauth',['BasicAuth',['../class_bas...
['baseexception',['BaseException',['../class_base_exception.html',1,'']]], ['baseexception_2ephp',['BaseException.php',['../_base_exception_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]], ['basic_2ephp',['Basic.php',['../_paginator_2_basic_8php.html',1,'']]],
random_line_split
Calculator.py
# Numbers 数字 print(2 + 2) # 4 print(50 - 5*6) # 20 print((50 - 5*6) / 4) # 5.0 print(8/5) # 1.6 print(17 / 3) # 5.666666666666667 float print(17 // 3) # 5 取整 print(17 % 3) # 2 取模 print(5*3+2) # 17 先乘除,后加减 print(2+5*3) # 17 先乘除,后加减 pri...
tax = 12.5 / 100 price = 100.50 print(price * tax) # print(price+_); #在控制台可行,但是在本文件中不行,提示ameError: name '_' is not defined # round(_, 2) #在控制台可行,但是在本文件中不行,提示ameError: name '_' is not defined print("--华丽的分割线--") # Strings 字符串 print('spam eggs') print( 'doesn\'t') # \' 会进行转义 print("doesn't") ...
# n # n 没有定义 NameError: name 'n' is not defined print(4 * 3.75 - 1)
random_line_split
models.py
from django.db import models from django.conf import settings from django.contrib.auth.models import User, Group
DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public') class Store(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(max_length=128) query_endpoint = models.URLField() update_endpoint = models.URLField(null=True, blank=True) graph_store_endpoint = mo...
from .endpoint import Endpoint
random_line_split
models.py
from django.db import models from django.conf import settings from django.contrib.auth.models import User, Group from .endpoint import Endpoint DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public') class Store(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(m...
(self, *args, **kwargs): return Endpoint(self.query_endpoint).query(*args, **kwargs) class Meta: permissions = (('administer_store', 'can administer'), ('query_store', 'can query'), ('update_store', 'can update')) class UserPrivileges(models.Model): ...
query
identifier_name
models.py
from django.db import models from django.conf import settings from django.contrib.auth.models import User, Group from .endpoint import Endpoint DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public') class Store(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(m...
user = models.ForeignKey(User, null=True, blank=True) group = models.ForeignKey(Group, null=True, blank=True) allow_concurrent_queries = models.BooleanField() disable_throttle = models.BooleanField() throttle_threshold = models.FloatField(null=True, blank=True) deny_threshold = models.FloatField(nu...
identifier_body
extract_symbols.py
#!/usr/bin/env python # Copyright (c) 2014, Bo Tian <tianbo@gmail.com> # 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, ...
fin.close() fout.close() if __name__ == "__main__": main()
symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yahoo finance. fout.write(symbol + '\n')
conditional_block
extract_symbols.py
#!/usr/bin/env python # Copyright (c) 2014, Bo Tian <tianbo@gmail.com> # 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, ...
def extract_symbols(input_file, output_file): fin = open(input_file, 'r') fout = open(output_file, 'w') for line in fin: if '|' in line: cols = line.split('|') if not '$' in cols[1]: # Skip preferred shares, warrant etc. symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yah...
args = sys.argv print str(args) extract_symbols(args[1], args[2])
identifier_body
extract_symbols.py
#!/usr/bin/env python # Copyright (c) 2014, Bo Tian <tianbo@gmail.com> # 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, ...
(input_file, output_file): fin = open(input_file, 'r') fout = open(output_file, 'w') for line in fin: if '|' in line: cols = line.split('|') if not '$' in cols[1]: # Skip preferred shares, warrant etc. symbol = cols[1].replace('.', '-') # e.g., BRK.B -> BRK-B for Yahoo finance. f...
extract_symbols
identifier_name
extract_symbols.py
#!/usr/bin/env python # Copyright (c) 2014, Bo Tian <tianbo@gmail.com> # 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, ...
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OT...
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
random_line_split
query_string.py
import urllib from django import template from django.utils.safestring import mark_safe register = template.Library() @register.tag def query_string(parser, token): """ Allows to manipulate the query string of a page by adding and removing keywords. If a given value is a context variable it will resolve...
(self, add, remove): self.add = add self.remove = remove def render(self, context): p = {} for k, v in context["request"].GET.items(): p[k] = v return get_query_string(p, self.add, self.remove, context) def get_query_string(p, new_params, remove, context): ...
__init__
identifier_name
query_string.py
import urllib from django import template from django.utils.safestring import mark_safe register = template.Library() @register.tag def query_string(parser, token): """ Allows to manipulate the query string of a page by adding and removing keywords. If a given value is a context variable it will resolve...
if string: string = str(string) if ',' not in string: # ensure at least one ',' string += ',' for arg in string.split(','): arg = arg.strip() if arg == '': continue kw, val = arg.split('=', 1) kwargs[kw]...
kwargs = {}
random_line_split
query_string.py
import urllib from django import template from django.utils.safestring import mark_safe register = template.Library() @register.tag def query_string(parser, token): """ Allows to manipulate the query string of a page by adding and removing keywords. If a given value is a context variable it will resolve...
for k, v in new_params.items(): if k in p and v is None: del p[k] elif v is not None: p[k] = v for k, v in p.items(): try: p[k] = template.Variable(v).resolve(context) except: p[k] = v return mark_safe('?' + '&amp;'.join([u'%...
del p[k]
conditional_block
query_string.py
import urllib from django import template from django.utils.safestring import mark_safe register = template.Library() @register.tag def query_string(parser, token): """ Allows to manipulate the query string of a page by adding and removing keywords. If a given value is a context variable it will resolve...
def render(self, context): p = {} for k, v in context["request"].GET.items(): p[k] = v return get_query_string(p, self.add, self.remove, context) def get_query_string(p, new_params, remove, context): """ Add and remove query parameters. From `django.contrib.admin`. ...
self.add = add self.remove = remove
identifier_body
extern-return-TwoU32s.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 ...
} pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU32s(); assert_eq!(y.one, 10); assert_eq!(y.two, 20); } }
pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s;
random_line_split
extern-return-TwoU32s.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 ...
{ one: u32, two: u32 } #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s; } pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU32s(); assert_eq!(y.one, 10); assert_eq!(y.two, 20); } }
TwoU32s
identifier_name
htmlselectelement.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/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use...
// Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_g...
{ let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) }
identifier_body
htmlselectelement.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/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use...
else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_p...
{ el.check_ancestors_disabled_state_for_form_control(); }
conditional_block
htmlselectelement.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/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use...
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, ...
// Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add
random_line_split
htmlselectelement.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/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use...
(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"...
Add
identifier_name
qmp_basic_rhel6.py
import logging from autotest.client.shared import error def run(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. IMPORTANT NOTES: o Most tests depend heavily on QMP'...
def test_good_input_obj(monitor): """ Basic success tests for issuing QMP commands. """ # NOTE: We don't use the cmd_qmp() method here because the command # object is in a 'random' order resp = monitor.cmd_obj({"execute": "query-version"}) check_success_resp...
resp = monitor.cmd_obj(cmd) check_error_resp(resp, "QMPBadInputObject", {"expected": "object"})
conditional_block
qmp_basic_rhel6.py
import logging from autotest.client.shared import error def run(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. IMPORTANT NOTES: o Most tests depend heavily on QMP'...
doesn't get called. """ for item in (True, [], 1, "foo"): resp = monitor.cmd_obj({"execute": "eject", "arguments": item}) check_error_resp(resp, "QMPBadInputObjectMember", {"member": "arguments", "expected": "object"}) def test_bad_execut...
choice, any command that accepts arguments will do, as the command
random_line_split
qmp_basic_rhel6.py
import logging from autotest.client.shared import error def run(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. IMPORTANT NOTES: o Most tests depend heavily on QMP'...
def input_object_suite(monitor): """ Check the input object format, as described in the QMP specfication section '2.3 Issuing Commands'. { "execute": json-string, "arguments": json-object, "id": json-value } """ test_good_input_obj(monitor) test_bad_input_o...
""" Basic success tests for issuing QMP commands. """ # NOTE: We don't use the cmd_qmp() method here because the command # object is in a 'random' order resp = monitor.cmd_obj({"execute": "query-version"}) check_success_resp(resp) resp = monitor.cmd_obj({"argumen...
identifier_body
qmp_basic_rhel6.py
import logging from autotest.client.shared import error def run(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. IMPORTANT NOTES: o Most tests depend heavily on QMP'...
(qmp_dict, key): if not isinstance(qmp_dict, dict): raise error.TestFail("qmp_dict is not a dict (it's '%s')" % type(qmp_dict)) if key not in qmp_dict: raise error.TestFail("'%s' key doesn't exist in dict ('%s')" % ...
fail_no_key
identifier_name
NavButton.js
import React, { Component, PropTypes } from 'react'; /*** Third Party Components ***/ import Dialog from 'react-toolbox/lib/dialog'; import { Button, IconButton } from 'react-toolbox/lib/button'; import Icon from 'react-fa'; import style from './style.scss'; class NavButton extends Component { constructor(props)...
}; handleClose = () => { this.setState({ open: false }); }; render() { return ( <div className={`${style.root} ${this.props.className}`} > <IconButton className={style.navBars} neutral={false} onClick={this.handleOpen}> ...
this.setState({ open: true });
random_line_split
NavButton.js
import React, { Component, PropTypes } from 'react'; /*** Third Party Components ***/ import Dialog from 'react-toolbox/lib/dialog'; import { Button, IconButton } from 'react-toolbox/lib/button'; import Icon from 'react-fa'; import style from './style.scss'; class NavButton extends Component { constructor(props)...
() { return ( <div className={`${style.root} ${this.props.className}`} > <IconButton className={style.navBars} neutral={false} onClick={this.handleOpen}> <Icon name={this.state.open ? 'times-circle-o' : 'bars'} /> </IconBut...
render
identifier_name
NavButton.js
import React, { Component, PropTypes } from 'react'; /*** Third Party Components ***/ import Dialog from 'react-toolbox/lib/dialog'; import { Button, IconButton } from 'react-toolbox/lib/button'; import Icon from 'react-fa'; import style from './style.scss'; class NavButton extends Component { constructor(props)...
} export default NavButton;
{ return ( <div className={`${style.root} ${this.props.className}`} > <IconButton className={style.navBars} neutral={false} onClick={this.handleOpen}> <Icon name={this.state.open ? 'times-circle-o' : 'bars'} /> </IconButton...
identifier_body
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Tok...
() { init(); debug!("Starting TEST_CLOSE_ON_DROP"); let mut poll = Poll::new().unwrap(); // == Create & setup server socket let mut srv = TcpListener::bind(any_local_address()).unwrap(); let addr = srv.local_addr().unwrap(); poll.registry() .register(&mut srv, SERVER, Interest::REA...
close_on_drop
identifier_name
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Tok...
} } assert!(handler.state == AfterRead, "actual={:?}", handler.state); }
{ handler.handle_write(&mut poll, event.token()); }
conditional_block
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Tok...
} #[test] pub fn close_on_drop() { init(); debug!("Starting TEST_CLOSE_ON_DROP"); let mut poll = Poll::new().unwrap(); // == Create & setup server socket let mut srv = TcpListener::bind(any_local_address()).unwrap(); let addr = srv.local_addr().unwrap(); poll.registry() .register...
{ match tok { SERVER => panic!("received writable for token 0"), CLIENT => { debug!("client connected"); poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } _ =...
identifier_body
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Tok...
// == Create & setup client socket let mut sock = TcpStream::connect(addr).unwrap(); poll.registry() .register(&mut sock, CLIENT, Interest::WRITABLE) .unwrap(); // == Create storage for events let mut events = Events::with_capacity(1024); // == Setup test handler let mut ...
poll.registry() .register(&mut srv, SERVER, Interest::READABLE) .unwrap();
random_line_split
angryProfessor.js
// Problem - https://www.hackerrank.com/challenges/angry-professor function processData(input) { var lines = input.split('\n'), numberTestCases = parseInt(lines.shift()); for (var i = 0; i < numberTestCases*2; i += 2) { var leastNumber = lines[i].split(' ')[1], studentsArrival = li...
} } } processData("10\n"+ "10 4\n" + "-93 -86 49 -62 -90 -63 40 72 11 67\n" + "10 10\n" + "23 -35 -2 58 -67 -56 -42 -73 -19 37\n" + "10 9\n" + "13 91 56 -62 96 -5 -84 -36 -46 -13\n" + "10 8\n" + "45 67 64 -50 -8 78 84 -51 99 60\n" + "10 7\n" + "26 94 -95 34 67 -97 17 52 1 86\n" + "10 2\n" + "19 29 -17...
random_line_split
angryProfessor.js
// Problem - https://www.hackerrank.com/challenges/angry-professor function processData(input) { var lines = input.split('\n'), numberTestCases = parseInt(lines.shift()); for (var i = 0; i < numberTestCases*2; i += 2)
} processData("10\n"+ "10 4\n" + "-93 -86 49 -62 -90 -63 40 72 11 67\n" + "10 10\n" + "23 -35 -2 58 -67 -56 -42 -73 -19 37\n" + "10 9\n" + "13 91 56 -62 96 -5 -84 -36 -46 -13\n" + "10 8\n" + "45 67 64 -50 -8 78 84 -51 99 60\n" + "10 7\n" + "26 94 -95 34 67 -97 17 52 1 86\n" + "10 2\n" + "19 29 -17 -71 -75 -27 -5...
{ var leastNumber = lines[i].split(' ')[1], studentsArrival = lines[i + 1].split(' '), arrivedInTime = 0; studentsArrival.forEach(function(time) { if (time <= 0) { arrivedInTime++; } }); if (leastNumber <= arrivedInTime) {...
conditional_block
angryProfessor.js
// Problem - https://www.hackerrank.com/challenges/angry-professor function processData(input)
processData("10\n"+ "10 4\n" + "-93 -86 49 -62 -90 -63 40 72 11 67\n" + "10 10\n" + "23 -35 -2 58 -67 -56 -42 -73 -19 37\n" + "10 9\n" + "13 91 56 -62 96 -5 -84 -36 -46 -13\n" + "10 8\n" + "45 67 64 -50 -8 78 84 -51 99 60\n" + "10 7\n" + "26 94 -95 34 67 -97 17 52 1 86\n" + "10 2\n" + "19 29 -17 -71 -75 -27 -56 ...
{ var lines = input.split('\n'), numberTestCases = parseInt(lines.shift()); for (var i = 0; i < numberTestCases*2; i += 2) { var leastNumber = lines[i].split(' ')[1], studentsArrival = lines[i + 1].split(' '), arrivedInTime = 0; studentsArrival.forEach(function(...
identifier_body
angryProfessor.js
// Problem - https://www.hackerrank.com/challenges/angry-professor function
(input) { var lines = input.split('\n'), numberTestCases = parseInt(lines.shift()); for (var i = 0; i < numberTestCases*2; i += 2) { var leastNumber = lines[i].split(' ')[1], studentsArrival = lines[i + 1].split(' '), arrivedInTime = 0; studentsArrival.forEach(f...
processData
identifier_name
transaction-relay.component.ts
import {Component, Output, Injectable, OnInit, Input, OnChanges} from '@angular/core'; import {CommonModelRelayService, Filter} from "../common/common-model-relay.service"; import {Transaction} from "./transaction"; import {TransactionReqService} from "./transaction-req.service"; import {CommonRelayComponent} from "../...
super(relay); } ngOnInit(): void { this.filter(this.filterField); this.refresh(); } //TODO change name sendFilter() { this.filter(this.filterField); } }
constructor(relay: TransactionModelRelayService) {
random_line_split
transaction-relay.component.ts
import {Component, Output, Injectable, OnInit, Input, OnChanges} from '@angular/core'; import {CommonModelRelayService, Filter} from "../common/common-model-relay.service"; import {Transaction} from "./transaction"; import {TransactionReqService} from "./transaction-req.service"; import {CommonRelayComponent} from "../...
(svc: TransactionReqService) { super(svc); } } @Component({ selector: 'transaction-relay', template: `<div *ngIf="false"> Transactions: {{transactions | async | json}}</div>` }) export class TransactionRelayComponent extends CommonRelayComponent<Transaction> implements OnInit { @Input('filter') filterFiel...
constructor
identifier_name
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask.ext.script import Manager, Shell, Server from flask.ext.migrate import MigrateCommand from foobar.app import create_app from foobar.user.models import User from foobar.settings import DevConfig, ProdConfig from foobar.datab...
HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User} @manager.command...
app = create_app(DevConfig)
conditional_block
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask.ext.script import Manager, Shell, Server from flask.ext.migrate import MigrateCommand from foobar.app import create_app from foobar.user.models import User from foobar.settings import DevConfig, ProdConfig from foobar.datab...
def test(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server()) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run...
@manager.command
random_line_split
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask.ext.script import Manager, Shell, Server from flask.ext.migrate import MigrateCommand from foobar.app import create_app from foobar.user.models import User from foobar.settings import DevConfig, ProdConfig from foobar.datab...
(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User} @manager.command def test(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code ma...
_make_context
identifier_name
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask.ext.script import Manager, Shell, Server from flask.ext.migrate import MigrateCommand from foobar.app import create_app from foobar.user.models import User from foobar.settings import DevConfig, ProdConfig from foobar.datab...
@manager.command def test(): """Run the tests.""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server()) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand) if __name__ == '__main_...
"""Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User}
identifier_body
lib.rs
// Copyright (C) 2020 Natanael Mojica <neithanmo@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later versio...
env!("BUILD_REL_DATE") );
random_line_split
lib.rs
// Copyright (C) 2020 Natanael Mojica <neithanmo@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later versio...
(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { filter::register(plugin)?; Ok(()) } gst_plugin_define!( csound, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), ...
plugin_init
identifier_name