file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
create-app.component.ts
import { UserService } from './../../shared/services/user.service'; import { Links, RuntimeImage } from './../../shared/models/constants'; import { Component, OnInit, OnDestroy, Input, Injector } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { CustomFormControl } from './../../co...
}, location: 'local', kind: 'functionapp' }; this._globalStateService.setBusyState(); this._cacheService.putArm(id, null, body).subscribe( r => { this._globalStateService.clearBusyState(); const siteObj: ArmObj<Site...
{ const nameControl = <CustomFormControl>this.group.controls['name']; const name = nameControl.value; if (!name) { nameControl._msRunValidation = true; nameControl.updateValueAndValidity(); return; } const id = `/subscriptions/${this.group.con...
identifier_body
daemons.js
"use strict"; var collName = "daemons"; const async = require("async"); const soajsLib = require("soajs.core.libs"); var methods = { "findEntries": function (soajs, model, opts, cb) { opts.collection = collName; model.findEntries(soajs, opts, (err, records)=>{ if (err){ return cb(err); } if (records...
}); }, "removeEntry": function (soajs, model, opts, cb) { opts.collection = collName; model.removeEntry(soajs, opts, cb); }, "updateEntry": function (soajs, model, opts, cb) { opts.collection = collName; model.updateEntry(soajs, opts, cb); }, "unsanitize": function (record, cb) { let sanitizedVersion ...
methods.unsanitize(record, cb);
random_line_split
daemons.js
"use strict"; var collName = "daemons"; const async = require("async"); const soajsLib = require("soajs.core.libs"); var methods = { "findEntries": function (soajs, model, opts, cb) { opts.collection = collName; model.findEntries(soajs, opts, (err, records)=>{ if (err){ return cb(err); } if (records...
} }; module.exports = methods;
{ return cb(null, record); }
conditional_block
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(fnbox)] #![feature(fs_time)] #![feature(mpsc_select)] #![feature(plugin)] #![fe...
pub mod about_loader; pub mod bluetooth_thread; pub mod chrome_loader; pub mod connector; pub mod cookie; pub mod cookie_storage; pub mod data_loader; pub mod file_loader; pub mod filemanager_thread; pub mod hsts; pub mod http_loader; pub mod image_cache_thread; pub mod mime_classifier; pub mod pub_domains; pub mod res...
extern crate webrender_traits; extern crate websocket;
random_line_split
valve_acl.py
"""Compose ACLs on ports.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # Licensed under the Apache Lic...
try: acl_match = valve_of.match_from_dict(acl_match_dict) except TypeError: raise InvalidConfigError('invalid type in ACL') if acl_act: acl_inst.append(valve_of.apply_actions(acl_act)) return (acl_match, acl_inst, acl_cookie, acl_ofmsgs) def build_acl_ofmsgs(acls, acl_table, ...
acl_match_dict['vlan_vid'] = valve_of.vid_present(vlan_vid)
conditional_block
valve_acl.py
"""Compose ACLs on ports.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # Licensed under the Apache Lic...
def build_output_actions(output_dict): """Implement actions to alter packet/output.""" output_actions = [] output_port = None ofmsgs = [] # rewrite any VLAN headers first always vlan_actions = rewrite_vlan(output_dict) if vlan_actions: output_actions.extend(vlan_actions) if 's...
"""Implement actions to rewrite VLAN headers.""" vlan_actions = [] if 'pop_vlans' in output_dict: for _ in range(output_dict['pop_vlans']): vlan_actions.append(valve_of.pop_vlan()) # if vlan tag is specified, push it. if 'vlan_vid' in output_dict: vlan_actions.extend(push_vla...
identifier_body
valve_acl.py
"""Compose ACLs on ports.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # Licensed under the Apache Lic...
(vlan_vid): """Push a VLAN tag with optional selection of eth type.""" vid = vlan_vid vlan_eth_type = None if isinstance(vlan_vid, dict): vid = vlan_vid['vid'] if 'eth_type' in vlan_vid: vlan_eth_type = vlan_vid['eth_type'] if vlan_eth_type is None: return valve_o...
push_vlan
identifier_name
valve_acl.py
"""Compose ACLs on ports.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # Licensed under the Apache Lic...
vlan_actions.append( valve_of.set_vlan_vid(output_dict['swap_vid'])) # or, if a list, push them all (all with type Q). elif 'vlan_vids' in output_dict: for vlan_vid in output_dict['vlan_vids']: vlan_actions.extend(push_vlan(vlan_vid)) return vlan_actions def build_o...
# if vlan tag is specified, push it. if 'vlan_vid' in output_dict: vlan_actions.extend(push_vlan(output_dict['vlan_vid'])) # swap existing VID elif 'swap_vid' in output_dict:
random_line_split
app-load.service.ts
import { Injectable } from '@angular/core'; import { plugins } from '../../../plugins'; import { CommonAppConfig } from '../../site/common/common.config'; import { AppConfig, SearchableModelEntry, ModelEntry } from '../../site/base/app-config'; import { CollectionStringModelMapperService } from './collectionStringModel...
{ /** * Constructor. * * @param modelMapper * @param mainMenuService * @param searchService */ public constructor( private modelMapper: CollectionStringModelMapperService, private mainMenuService: MainMenuService, private searchService: SearchService ) ...
AppLoadService
identifier_name
app-load.service.ts
import { Injectable } from '@angular/core'; import { plugins } from '../../../plugins'; import { CommonAppConfig } from '../../site/common/common.config'; import { AppConfig, SearchableModelEntry, ModelEntry } from '../../site/base/app-config'; import { CollectionStringModelMapperService } from './collectionStringModel...
this.mainMenuService.registerEntries(config.mainMenuEntries); } }); } private isSearchableModelEntry(entry: ModelEntry | SearchableModelEntry): entry is SearchableModelEntry { if ((<SearchableModelEntry>entry).searchOrder !== undefined) { // We need to do...
this.searchService.registerModel(entry.collectionString, entry.model, entry.searchOrder); } }); } if (config.mainMenuEntries) {
random_line_split
app-load.service.ts
import { Injectable } from '@angular/core'; import { plugins } from '../../../plugins'; import { CommonAppConfig } from '../../site/common/common.config'; import { AppConfig, SearchableModelEntry, ModelEntry } from '../../site/base/app-config'; import { CollectionStringModelMapperService } from './collectionStringModel...
return true; } return false; } }
{ throw Error( `Wrong configuration for ${ entry.collectionString }: you gave a searchOrder, but the model is not searchable.` ); }
conditional_block
app-load.service.ts
import { Injectable } from '@angular/core'; import { plugins } from '../../../plugins'; import { CommonAppConfig } from '../../site/common/common.config'; import { AppConfig, SearchableModelEntry, ModelEntry } from '../../site/base/app-config'; import { CollectionStringModelMapperService } from './collectionStringModel...
}
{ if ((<SearchableModelEntry>entry).searchOrder !== undefined) { // We need to double check, because Typescipt cannot check contructors. If typescript could differentiate // between (ModelConstructor<BaseModel>) and (new (...args: any[]) => (BaseModel & Searchable)), we would not have ...
identifier_body
LanguageSettings.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
(self, e, l): errstr = 'Could not find translation for language "%s"' % l wx.the_app.logger.error(errstr, exc_info=e) errstr = errstr + '\n%s: %s' % (str(e[0]), unicode(e[1].args[0])) self.set_error(errstr) def refit(self): self.box_sizer.Layout() self.sizer.Layout(...
set_language_failed
identifier_name
LanguageSettings.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
# other sizers self.box_sizer.Add(self.choice, flag=wx.GROW|wx.ALL, border=SPACING) self.box_sizer.Add(restart, flag=wx.BOTTOM|wx.LEFT|wx.RIGHT, border=SPACING) self.box_sizer.Add(self.bottom_error, flag=wx.BOTTOM|wx.LEFT|wx.RIGHT, border=SPACING) # clear out bottom error ...
self.choice.SetSelection(0)
conditional_block
LanguageSettings.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
self.choice = wx.Choice(self, choices=self.language_names) self.Bind(wx.EVT_CHOICE, self.set_language, self.choice) restart = wx.StaticText(self, -1, "You must restart %s for the\nlanguage " "setting to take effect." % app_name) ...
languages.insert(0, '') self.languages = languages
random_line_split
LanguageSettings.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
def clear_error(self): index = self.box_sizer.GetItem(self.bottom_error) if index: self.box_sizer.Detach(self.bottom_error) self.bottom_error.SetLabel('') self.refit() def set_error(self, errstr): index = self.box_sizer.GetItem(self.bottom_error) if...
self.clear_error() wx.MessageBox("You must restart %s for the language " "setting to take effect." % app_name, "%s translation" % app_name, style=wx.ICON_INFORMATION)
identifier_body
ReadyButton.tsx
} from 'context/InputContext'; import { MatchmakingContext, MatchmakingContextState } from 'context/MatchmakingContext'; import { WarbandContext, WarbandContextState } from 'context/WarbandContext'; import { Button } from '../../Button'; import { ErrorComponent } from '../../Error'; import { formatTime } from '../../....
if (matchmakingContext.isEntered && !warbandContextState.groupID) { return ( <Button type='primary' styles={`${ReadyButtonStyle}`} disabled={this.state.disabled} text={ inputContext.isConsole ? <ConsoleButton> <ButtonIcon ...
{ return ( // We found a match! <Button type='primary' styles={`${ReadyButtonStyle}`} disabled={true} text={ inputContext.isConsole ? <ConsoleButton> <ButtonIcon className='icon-xb-a'></ButtonIcon> Found! </C...
conditional_block
ReadyButton.tsx
State } from 'context/InputContext'; import { MatchmakingContext, MatchmakingContextState } from 'context/MatchmakingContext'; import { WarbandContext, WarbandContextState } from 'context/WarbandContext'; import { Button } from '../../Button'; import { ErrorComponent } from '../../Error'; import { formatTime } from '.....
extends React.Component<SearchingTimerStateProps,{}> { constructor(props: SearchingTimerStateProps) { super(props); } public render() { return ( <SearchingTimerText> Searching {formatTime(this.props.matchmakingContext.timeSearching)} </SearchingTimerText> ); } } class ReadyBut...
SearchingTimer
identifier_name
ReadyButton.tsx
State } from 'context/InputContext'; import { MatchmakingContext, MatchmakingContextState } from 'context/MatchmakingContext'; import { WarbandContext, WarbandContextState } from 'context/WarbandContext'; import { Button } from '../../Button'; import { ErrorComponent } from '../../Error'; import { formatTime } from '.....
onClick={this.onClick} /> ); } return ( <Button type='primary' styles={`${ReadyButtonStyle}`} disabled={this.state.disabled} text={ inputContext.isConsole ? <ConsoleButton> <ButtonIcon className='icon-xb-a'></ButtonIc...
</ConsoleButton> : 'Ready' }
random_line_split
relacher_gouvernail.py
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
ception=None): """Retourne le matelot le plus apte à accomplir la volonté.""" navire = self.navire equipage = navire.equipage gouvernail = self.navire.gouvernail if gouvernail is None or gouvernail.tenu is None: return None personnage = gouvernail.tenu ...
atelots(self, ex
identifier_name
relacher_gouvernail.py
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
ersonnage = gouvernail.tenu matelot = equipage.get_matelot_depuis_personnage(personnage) return matelot def executer(self, matelot): """Exécute la volonté.""" if matelot is None: self.terminer() return navire = self.navire ordres = [] ...
p
conditional_block
relacher_gouvernail.py
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
matelot = equipage.get_matelot_depuis_personnage(personnage) return matelot def executer(self, matelot): """Exécute la volonté.""" if matelot is None: self.terminer() return navire = self.navire ordres = [] matelot.invalider_ordres("v...
""Classe représentant une volonté. Cette volonté demande simplement au matelot qui tient le gouvernail de le relâcher. Comme la plupart des volontés, le matelot est encouragé à retourner dans sa salle d'affectation après coup. """ cle = "relacher_gouvernail" ordre_court = re.compile(r"^rg$", ...
identifier_body
relacher_gouvernail.py
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
def choisir_matelots(self, exception=None): """Retourne le matelot le plus apte à accomplir la volonté.""" navire = self.navire equipage = navire.equipage gouvernail = self.navire.gouvernail if gouvernail is None or gouvernail.tenu is None: return None pe...
ordre_long = re.compile(r"^relacher\s+gouvernail?$", re.I)
random_line_split
io.k8s.api.scheduling.v1beta1.ts
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0
* 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. */ import { KubernetesObject } from 'kpt-functions'; import * as api...
* * Unless required by applicable law or agreed to in writing, software
random_line_split
io.k8s.api.scheduling.v1beta1.ts
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
(desc: PriorityClassList) { this.apiVersion = PriorityClassList.apiVersion; this.items = desc.items.map((i) => new PriorityClass(i)); this.kind = PriorityClassList.kind; this.metadata = desc.metadata; } } export function isPriorityClassList(o: any): o is PriorityClassList { return ( o && o....
constructor
identifier_name
trait-safety-ok.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.
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Simple smoke test that unsafe traits can be compiled etc. unsafe trait Foo { fn...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
trait-safety-ok.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 ...
() { let x: isize = 22; assert_eq!(22, take_foo(&x)); }
main
identifier_name
trait-safety-ok.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 ...
} fn take_foo<F:Foo>(f: &F) -> isize { f.foo() } fn main() { let x: isize = 22; assert_eq!(22, take_foo(&x)); }
{ *self }
identifier_body
header.js
const { massiveHide } = require('../coreFunctions'); const header = { init: () => { constructor(); setupLogo(); }, }; const constructor = () => { headerContainer = body.find('#header'); const breadcrumbContainer = body.find('.bread-container') const hideElements = [ headerContainer.find('#stati...
</a> <div class="mo-login-container"> <a href="https://acesso.uol.com.br/login.html?skin=forum-jogos&dest=REDIR|mlocal.forum.jogos.uol.com.br" class="mo-login-button fa fa-user fa-2x"></a> </div> `; headerContainer.append(logoContainer); } module.exports = header;
const setupLogo = () => { const logoContainer = ` <a href="/vale-tudo_f_57" class="mo-logo-container"> <div class="mo-logo-image sprite-vtMini"></div> <div class="mo-logo-text">VT Mobile</div>
random_line_split
wtforms_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012, 2013 CERN. ## ## Invenio 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 2 of the ## License, or (at your opt...
return False class FilterTextField(TextField): alias = None def __init__(self, *args, **kwargs): self.alias = kwargs.get('alias') if 'alias' in kwargs: del kwargs['alias'] super(TextField, self).__init__(*args, **kwargs) if not self.raw_data: self...
return True
conditional_block
wtforms_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012, 2013 CERN.
## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU...
## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as
random_line_split
wtforms_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012, 2013 CERN. ## ## Invenio 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 2 of the ## License, or (at your opt...
class InvenioBaseForm(Form, SessionSecureForm): SECRET_KEY = CFG_SITE_SECRET_KEY TIME_LIMIT = datetime.timedelta(minutes=20) def __init__(self, *args, **kwargs): super(InvenioBaseForm, self).__init__(*args, csrf_context=session, **kwargs) def add_fields(self, name, field): self.__se...
return [field.name for field in self if hasattr(field, 'required')]
identifier_body
wtforms_utils.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012, 2013 CERN. ## ## Invenio 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 2 of the ## License, or (at your opt...
(self, *args, **kwargs): self.alias = kwargs.get('alias') if 'alias' in kwargs: del kwargs['alias'] super(TextField, self).__init__(*args, **kwargs) if not self.raw_data: self.raw_data = [] def _value(self): if self.raw_data: return self.r...
__init__
identifier_name
limited_heap.rs
use min_max_heap::{IntoIter, MinMaxHeap}; use std::iter::IntoIterator; use super::weighted::WeightedItem; /// A heap that only allows a constant amount of items. It will keep the items /// with the highest priority. #[derive(Clone)] pub struct LimitedHeap<I, W> where W: Ord, { heap: MinMaxHeap<WeightedItem<I,...
pub fn pop(&mut self) -> Option<I> { self.0.pop() } pub fn clear(&mut self) { self.0.clear() } pub fn len(&self) -> usize { self.0.len() } pub fn peek(&self) -> Option<&I> { self.0.peek() } } im...
{ let priority = element.get_weight(); self.0.push(element, priority) }
identifier_body
limited_heap.rs
use min_max_heap::{IntoIter, MinMaxHeap}; use std::iter::IntoIterator; use super::weighted::WeightedItem; /// A heap that only allows a constant amount of items. It will keep the items /// with the highest priority. #[derive(Clone)] pub struct LimitedHeap<I, W> where W: Ord, { heap: MinMaxHeap<WeightedItem<I,...
(self) -> Self::IntoIter { self.heap.into_iter().into() } }
into_iter
identifier_name
limited_heap.rs
use min_max_heap::{IntoIter, MinMaxHeap}; use std::iter::IntoIterator; use super::weighted::WeightedItem; /// A heap that only allows a constant amount of items. It will keep the items /// with the highest priority. #[derive(Clone)] pub struct LimitedHeap<I, W> where W: Ord, { heap: MinMaxHeap<WeightedItem<I,...
Some(self.heap.push_pop_min(WeightedItem(element, priority)).0) } } pub fn pop(&mut self) -> Option<I> { self.heap.pop_max().map(|wi| wi.0) } pub fn clear(&mut self) { self.heap.clear(); } pub fn len(&self) -> usize { self.heap.len() } pub ...
pub fn push(&mut self, element: I, priority: W) -> Option<I> { if self.capacity > self.heap.len() { self.heap.push(WeightedItem(element, priority)); None } else {
random_line_split
limited_heap.rs
use min_max_heap::{IntoIter, MinMaxHeap}; use std::iter::IntoIterator; use super::weighted::WeightedItem; /// A heap that only allows a constant amount of items. It will keep the items /// with the highest priority. #[derive(Clone)] pub struct LimitedHeap<I, W> where W: Ord, { heap: MinMaxHeap<WeightedItem<I,...
else { Some(self.heap.push_pop_min(WeightedItem(element, priority)).0) } } pub fn pop(&mut self) -> Option<I> { self.heap.pop_max().map(|wi| wi.0) } pub fn clear(&mut self) { self.heap.clear(); } pub fn len(&self) -> usize { self.heap.len() } ...
{ self.heap.push(WeightedItem(element, priority)); None }
conditional_block
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载后的漫画整理模块 ==================== 请参考注释部分的整理步骤。 """ from __future__ import print_function, unicode_literals import os, re import shutil import random, string from hcomic.lib.filetool.files import WinDir, FileCollection from hcomic.lib.filetool.winzip import zip_everyt...
if len(res) == 1: return True return False def organize(src, dst): """将漫画归档到某一个目录下。 """ # check input if not (os.path.exists(src) and os.path.isdir(src)): raise Exception("'%s' doens't exist or not a directory" % src) src = os.path.abspath(src) if not (os....
zip_everything_in_a_folder(dir_path, dir_path + ".cbz") logger.show("Complete!", 1) def comic_archive_filter(winfile): """漫画文件过滤器。 """ if winfile.ext == ".cbz": res = re.findall(r"\[\d+P\]", winfile.fname)
identifier_body
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载后的漫画整理模块 ==================== 请参考注释部分的整理步骤。 """ from __future__ import print_function, unicode_literals import os, re import shutil import random, string from hcomic.lib.filetool.files import WinDir, FileCollection from hcomic.lib.filetool.winzip import zip_everyt...
logger.show("Remove non image and rename image ...") for abspath in FileCollection.yield_all_top_file_path(workspace): if abspath.endswith(".html") or abspath.endswith(".htm"): os.remove(abspath) for dir_path in FileCollection.yield_all_top_dir_path(workspace): remove_non_im...
- 对于网页另存为的图片, 使用 ``ctime`` (create time) - 对于已经排序好的图片, 使用 ``fname`` (file name) """
random_line_split
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载后的漫画整理模块 ==================== 请参考注释部分的整理步骤。 """ from __future__ import print_function, unicode_literals import os, re import shutil import random, string from hcomic.lib.filetool.files import WinDir, FileCollection from hcomic.lib.filetool.winzip import zip_everyt...
efix = "".join(random.sample(string.ascii_letters, 8)) counter = 0 for winfile in fc.iterfiles(): counter += 1 winfile.rename(new_fname=prefix + str(counter).zfill(4)) counter = 0 for winfile in fc.iterfiles(): counter += 1 winfile.rename(new_fname=str(count...
by) pr
identifier_name
manage.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载后的漫画整理模块 ==================== 请参考注释部分的整理步骤。 """ from __future__ import print_function, unicode_literals import os, re import shutil import random, string from hcomic.lib.filetool.files import WinDir, FileCollection from hcomic.lib.filetool.winzip import zip_everyt...
dall(r"\[\d+P\]", winfile.fname) if len(res) == 1: return True return False def organize(src, dst): """将漫画归档到某一个目录下。 """ # check input if not (os.path.exists(src) and os.path.isdir(src)): raise Exception("'%s' doens't exist or not a directory" % src) src = os.path.a...
file.ext == ".cbz": res = re.fin
conditional_block
test_LONG_image2.py
""" @brief test log(time=200s) """ import os import unittest import math import warnings from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor from ensae_teaching_cs.special.image.image_synthese_base import Vecteur, Couleur, Source, Repere from ensae_teach...
if __name__ == "__main__": wait_event(pygame) if __name__ == "__main__": unittest.main()
screen = pygame.display.set_mode(s.dim) screen.fill((255, 255, 255)) s.construit_image(screen, pygame=pygame, fLOG=fLOG) pygame.image.save(screen, os.path.join(temp, "scene_bette.png"))
random_line_split
test_LONG_image2.py
""" @brief test log(time=200s) """ import os import unittest import math import warnings from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor from ensae_teaching_cs.special.image.image_synthese_base import Vecteur, Couleur, Source, Repere from ensae_teach...
s.ajoute_source(Source(Vecteur(-12.5, 1, 6), Couleur(0.2, 0.2, 0.2))) s.ajoute_objet(Rectangle(Vecteur(-12.4, 0.99, 5.9), Vecteur(-12.6, 0.99, 5.9), Vecteur(-12.6, 0.99, 6.1), None, Couleur(0, 0, 0))) if is_travis_or_appveyor() == "travis": warnings...
def test_scene_image(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") temp = get_temp_folder(__file__, "temp_scene_bette") image = os.path.join(temp, "..", "data", "bette_davis.png") s = ScenePhong(Repere(), math.pi / ...
identifier_body
test_LONG_image2.py
""" @brief test log(time=200s) """ import os import unittest import math import warnings from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor from ensae_teaching_cs.special.image.image_synthese_base import Vecteur, Couleur, Source, Repere from ensae_teach...
unittest.main()
conditional_block
test_LONG_image2.py
""" @brief test log(time=200s) """ import os import unittest import math import warnings from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor from ensae_teaching_cs.special.image.image_synthese_base import Vecteur, Couleur, Source, Repere from ensae_teach...
(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") temp = get_temp_folder(__file__, "temp_scene_bette") image = os.path.join(temp, "..", "data", "bette_davis.png") s = ScenePhong(Repere(), math.pi / 1.5, 400, 200) ...
test_scene_image
identifier_name
0003_rename_deleted_field.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-06-27 20:29 from __future__ import unicode_literals from django.db import migrations import osf.utils.fields class Migration(migrations.Migration):
operations = [ migrations.RenameField( model_name='nodesettings', new_name='is_deleted', old_name='deleted', ), migrations.RenameField( model_name='usersettings', new_name='is_deleted', old_name='deleted', ), ...
dependencies = [ ('addons_onedrive', '0002_auto_20171121_1426'), ]
random_line_split
0003_rename_deleted_field.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-06-27 20:29 from __future__ import unicode_literals from django.db import migrations import osf.utils.fields class Migration(migrations.Migration):
migrations.AddField( model_name='usersettings', name='deleted', field=osf.utils.fields.NonNaiveDateTimeField(blank=True, null=True), ), ]
dependencies = [ ('addons_onedrive', '0002_auto_20171121_1426'), ] operations = [ migrations.RenameField( model_name='nodesettings', new_name='is_deleted', old_name='deleted', ), migrations.RenameField( model_name='usersettings', ...
identifier_body
0003_rename_deleted_field.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-06-27 20:29 from __future__ import unicode_literals from django.db import migrations import osf.utils.fields class
(migrations.Migration): dependencies = [ ('addons_onedrive', '0002_auto_20171121_1426'), ] operations = [ migrations.RenameField( model_name='nodesettings', new_name='is_deleted', old_name='deleted', ), migrations.RenameField( ...
Migration
identifier_name
lookup.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
(mut self, key: NodeKey) -> super::Result<Option<Q::Item>> { let mut hash = self.hash; // this loop iterates through non-inline nodes. for depth in 0.. { let node_data = match self.db.get(&hash) { Some(value) => value, None => { re...
look_up
identifier_name
lookup.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
; node_data = children[idx as usize]; } _ => return Ok(None), } // check if new node data is inline or hash. let r = Rlp::new(node_data); if r.is_data() && r.size() == 32 { ...
{ 1 }
conditional_block
lookup.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
loop { match Node::decoded(node_data) { Node::Leaf(k, value) => { return Ok(match k == key { true => Some(self.query.decode(value)), false => None, ...
{ let mut hash = self.hash; // this loop iterates through non-inline nodes. for depth in 0.. { let node_data = match self.db.get(&hash) { Some(value) => value, None => { return Err(Box::new(match depth { ...
identifier_body
lookup.rs
// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // 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. // Th...
_ => AVLError::IncompleteDatabase(hash), })); } }; self.query.record(&hash, &node_data, depth); // this loop iterates through all inline children (usually max 1) // witho...
return Err(Box::new(match depth { 0 => AVLError::InvalidStateRoot(hash),
random_line_split
fake_async.ts
/**
* found in the LICENSE file at https://angular.io/license */ import {discardPeriodicTasks, fakeAsync, tick} from '@angular/core/testing'; // #docregion basic describe('this test', () => { it('looks async but is synchronous', <any>fakeAsync((): void => { let flag = false; setTimeout(() => { flag = t...
* @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be
random_line_split
rest_api_server.py
import time import json import random from flask import Flask, request, current_app, abort from functools import wraps from cloudbrain.utils.metadata_info import (map_metric_name_to_num_channels, get_supported_devices, get_metrics_...
""" # return last 5 microseconds if start not specified. default_start_timestamp = int(time.time() * 1000000 - 5) device_id = request.args.get('device_id', None) device_name = request.args.get('device_name', None) metric = request.args.get('metric', None) start = int(request.args.get('start...
@support_jsonp def data(): """ GET metric data :return:
random_line_split
rest_api_server.py
import time import json import random from flask import Flask, request, current_app, abort from functools import wraps from cloudbrain.utils.metadata_info import (map_metric_name_to_num_channels, get_supported_devices, get_metrics_...
if __name__ == "__main__": app.run(host="0.0.0.0", port=WEBSERVER_PORT)
"""Retrieve all aggregates for a specific tag and user""" device_type = request.args.get('device_type', None) metrics = request.args.getlist('metrics', None) if device_type is None and len(metrics) == 0: device_types = get_supported_devices() for device_type in device_types: me...
identifier_body
rest_api_server.py
import time import json import random from flask import Flask, request, current_app, abort from functools import wraps from cloudbrain.utils.metadata_info import (map_metric_name_to_num_channels, get_supported_devices, get_metrics_...
(f): """Wraps JSONified output for JSONP""" @wraps(f) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + str(f()) + ')' return current_app.response_class(content, ...
support_jsonp
identifier_name
rest_api_server.py
import time import json import random from flask import Flask, request, current_app, abort from functools import wraps from cloudbrain.utils.metadata_info import (map_metric_name_to_num_channels, get_supported_devices, get_metrics_...
if not device_id: return "missing param: device_id", 500 # data_records = _get_mock_data(device_name, metric) data_records = dao.get_data(device_name, device_id, metric, start) return json.dumps(data_records) def _get_mock_data(device_name, metric): metric_to_num_channels = map_metric_...
return "missing param: metric", 500
conditional_block
users.profile.server.controller.js
'use strict'; // 定义模块依赖 var _ = require('lodash'), mkdirp = require('mkdirp'), fs = require('fs'), path = require('path'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), mongoose = require('mongoose'), User = mongoose.model('User'); /** * 更...
* @param {Object} res 用户得到的HTTP响应 */ exports.changeProfilePicture = function(req, res) { // 获取当前登录用户对象 var user = req.user; // 上传用户头像并更新信息 if (user) { // 图片保存路径 var filepath = 'uploads/profile/' + req.files.file.name; // 确保图片保存的目录存在 mkdirp(path.dirname('./' + filepath),...
* @param {Object} req 用户发起的HTTP请求
random_line_split
users.profile.server.controller.js
'use strict'; // 定义模块依赖 var _ = require('lodash'), mkdirp = require('mkdirp'), fs = require('fs'), path = require('path'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), mongoose = require('mongoose'), User = mongoose.model('User'); /** * 更...
conditional_block
javascript-eval.ts
Evaluate a line of code with the scope containing only a jquery wrapped element and whatever is available on window. Obviously not "safe", but maybe safer/cleaner than nothing. */ // element type = jquery wrapped element export function javascript_eval(line: string, element: any): string { let requirejs: any; let ...
/*
random_line_split
javascript-eval.ts
/* Evaluate a line of code with the scope containing only a jquery wrapped element and whatever is available on window. Obviously not "safe", but maybe safer/cleaner than nothing. */ // element type = jquery wrapped element export function javascript_eval(line: string, element: any): string
try { eval(line); } catch (err) { console.warn(`Jupyter Eval Error: ${err} -- evaluating "${line}"`); return `${err}`; } return ""; }
{ let requirejs: any; let require: any; require = requirejs = () => console.warn( // TODO: replace "CoCalc"? "require is not available in CoCalc; if you need a Javascript library, please email help@cocalc.com." ); require = require = requirejs = requirejs; require = require; // Same as bel...
identifier_body
javascript-eval.ts
/* Evaluate a line of code with the scope containing only a jquery wrapped element and whatever is available on window. Obviously not "safe", but maybe safer/cleaner than nothing. */ // element type = jquery wrapped element export function
(line: string, element: any): string { let requirejs: any; let require: any; require = requirejs = () => console.warn( // TODO: replace "CoCalc"? "require is not available in CoCalc; if you need a Javascript library, please email help@cocalc.com." ); require = require = requirejs = requirejs...
javascript_eval
identifier_name
test_config.py
# coding=utf-8 """Test configuration of toolbox.""" import importlib import os import pytest from snntoolbox.bin.utils import update_setup from snntoolbox.utils.utils import import_configparser with open(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'req...
@pytest.mark.parametrize('required_module', requirements) def test_imports_from_requirements(required_module): assert importlib.import_module(required_module) # Todo: Add configuration that is expected to pass. _in_and_out = [ ({}, False), ({'paths': {'path_wd': os.path.dirname(__file__), ...
requirements.append(s.rstrip('\n').split('==')[0])
conditional_block
test_config.py
# coding=utf-8 """Test configuration of toolbox.""" import importlib import os import pytest from snntoolbox.bin.utils import update_setup from snntoolbox.utils.utils import import_configparser with open(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'req...
({}, False), ({'paths': {'path_wd': os.path.dirname(__file__), 'dataset_path': os.path.dirname(__file__), 'filename_ann': '98.96'}}, False) ] @pytest.mark.parametrize('params, expect_pass', _in_and_out) def test_updating_settings(params, expect_pass, _path_wd): configpa...
# Todo: Add configuration that is expected to pass. _in_and_out = [
random_line_split
test_config.py
# coding=utf-8 """Test configuration of toolbox.""" import importlib import os import pytest from snntoolbox.bin.utils import update_setup from snntoolbox.utils.utils import import_configparser with open(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'req...
# Todo: Add configuration that is expected to pass. _in_and_out = [ ({}, False), ({'paths': {'path_wd': os.path.dirname(__file__), 'dataset_path': os.path.dirname(__file__), 'filename_ann': '98.96'}}, False) ] @pytest.mark.parametrize('params, expect_pass', _in_and_out) ...
assert importlib.import_module(required_module)
identifier_body
test_config.py
# coding=utf-8 """Test configuration of toolbox.""" import importlib import os import pytest from snntoolbox.bin.utils import update_setup from snntoolbox.utils.utils import import_configparser with open(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'req...
(params, expect_pass, _path_wd): configparser = import_configparser() config = configparser.ConfigParser() config.read_dict(params) configpath = os.path.join(str(_path_wd), 'config') with open(configpath, 'w') as file: config.write(file) if expect_pass: assert update_setup(config...
test_updating_settings
identifier_name
board.ts
/// <reference path="typings/angularjs/angular.d.ts" /> /// <reference path="task.ts" /> import T = require("task"); export class
{ BoardID: number; Name: string; ColorCode: string; Tasks: T.Task[]; Filter: number; Menu: boolean; selectLast: () => any; } export interface BoardScope extends ng.IScope{ boards: Board[]; taskMoved: (taskID: number, boardID: number) => any; deleteTask: (task: T.Task, board: B...
Board
identifier_name
board.ts
/// <reference path="typings/angularjs/angular.d.ts" /> /// <reference path="task.ts" /> import T = require("task"); export class Board {
BoardID: number; Name: string; ColorCode: string; Tasks: T.Task[]; Filter: number; Menu: boolean; selectLast: () => any; } export interface BoardScope extends ng.IScope{ boards: Board[]; taskMoved: (taskID: number, boardID: number) => any; deleteTask: (task: T.Task, board: Boar...
random_line_split
tshirt-design.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'; import { Contest } from '../../../../models/contest'; import { ContestsService } from '../../../../services/contests.service'; import { AuthService } from '../../../../services/auth.servi...
{ return this.authService.isDesigner(); } isEmailConfirmed() { // TODO add these checks to every form return sessionStorage.getItem('emailConfirmed') == CryptoJS.SHA3('true').toString(); } }
Designer()
identifier_name
tshirt-design.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'; import { Contest } from '../../../../models/contest'; import { ContestsService } from '../../../../services/contests.service'; import { AuthService } from '../../../../services/auth.servi...
backToList() { this.router.navigate(['/paskelbti-konkursa']); } logErrors(errors) { console.log(errors); } addContest(value) { this.isLoading = true; //console.log(value); this.contestsService.addContest(value) .subscribe(contest => { //console.log('contest added'); ...
{ window.scrollTo(0,0); this.contest.category = "Marškinėliai"; }
identifier_body
tshirt-design.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'; import { Contest } from '../../../../models/contest'; import { ContestsService } from '../../../../services/contests.service'; import { AuthService } from '../../../../services/auth.servi...
//console.log(value); this.contestsService.addContest(value) .subscribe(contest => { //console.log('contest added'); //console.log(contest); this.isLoading = false; this.notificationsService.success('Paskelbta', 'Konkursas paskelbtas', {timeOut: 3000, showProgressBar: false...
this.isLoading = true;
random_line_split
urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'CryptoKnocker.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admi...
url(r'^management/keys/changeKey$', "management.views.changeKey"), url(r'^management/getPorts/$', "management.views.getPorts"), url(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}) )
url(r'^management/registration/$', "management.views.registration"), url(r'^management/keys/$', "management.views.manageKeys"),
random_line_split
lib.rs
extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use quote::ToTokens; use syn; //########################################## // #[derive] mode macros #[proc_macro_derive(HelloMacro)] pub fn hello_macro_derive(input: TokenStream) -> TokenStream { // Construct a representation of Rust code as...
(_attr: TokenStream, item: TokenStream) -> TokenStream { // syn::ItemStruct requires feature "full" let input = syn::parse_macro_input!(item as syn::ItemStruct); let name = &input.ident; let result = match input.fields { syn::Fields::Named(ref fields) => { let fields = &fields.name...
struct_extension
identifier_name
lib.rs
extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use quote::ToTokens; use syn; //########################################## // #[derive] mode macros #[proc_macro_derive(HelloMacro)] pub fn hello_macro_derive(input: TokenStream) -> TokenStream { // Construct a representation of Rust code as...
}
{ assert_eq!(2 + 2, 4); }
identifier_body
lib.rs
extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use quote::ToTokens; use syn; //########################################## // #[derive] mode macros #[proc_macro_derive(HelloMacro)] pub fn hello_macro_derive(input: TokenStream) -> TokenStream { // Construct a representation of Rust code as...
let r = quote! { fn hello_macro() -> String { #input.to_owned() } }; r.into() } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
random_line_split
main.rs
flag_list: bool, flag_version: bool, flag_verbose: u32, flag_quiet: Option<bool>, flag_color: Option<String>, arg_command: String, arg_args: Vec<String>, flag_locked: bool, flag_frozen: bool, } const USAGE: &'static str = " Cargo inspired build system for C based projects Usage: ...
random_line_split
main.rs
flag_quiet: Option<bool>, flag_color: Option<String>, arg_command: String, arg_args: Vec<String>, flag_locked: bool, flag_frozen: bool, } const USAGE: &'static str = " Cargo inspired build system for C based projects Usage: craft <command> [<args>...] craft [options] Options: -h, --h...
(config: &Config, command: &String) -> CraftResult<Option<Vec<String>>> { let alias_name = format!("alias.{}", command); let mut result = Ok(None); match config.get_string(&alias_name) { Ok(value) => { if let Some(record) = value { let alias_commands = record.val ...
aliased_command
identifier_name
main.rs
flag_quiet: Option<bool>, flag_color: Option<String>, arg_command: String, arg_args: Vec<String>, flag_locked: bool, flag_frozen: bool, } const USAGE: &'static str = " Cargo inspired build system for C based projects Usage: craft <command> [<args>...] craft [options] Options: -h, --h...
fn aliased_command(config: &Config, command: &String) -> CraftResult<Option<Vec<String>>> { let alias_name = format!("alias.{}", command); let mut result = Ok(None); match config.get_string(&alias_name) { Ok(value) => { if let Some(record) = value { let alias_commands =...
{ macro_rules! cmd { ($name:ident) => (if args[1] == stringify!($name).replace("_", "-") { config.shell().set_verbosity(Verbosity::Verbose); let r = craft::call_main_without_stdin($name::execute, config, $name::USAGE, ...
identifier_body
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
'sequence': 14, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'summary': 'Allow to define purchase prices on different currencies using\ replenishment cost field', "description": """ Sale Exceptions Ingore Approve Directly ======================================= Whe...
random_line_split
index.d.ts
/*
* * 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 t...
* @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors.
random_line_split
L10nTextField.tsx
import * as React from "react"; import TextField, { StandardTextFieldProps } from "@material-ui/core/TextField"; import { useState } from "react"; import theOneLocalizationManager from "../lib/localizationManager/localizationManager"; import "./RequestStringDialog.less"; interface IProps extends StandardTextFieldProps...
return <TextField {...props} label={labelContent} />; };
{ const stringLabel: string = props.label; setPrevL10nKey(props.l10nKeyForLabel); theOneLocalizationManager .asyncGetText(props.l10nKeyForLabel, stringLabel, undefined) .done(result => { setLabelContent(result); }); }
conditional_block
L10nTextField.tsx
import * as React from "react"; import TextField, { StandardTextFieldProps } from "@material-ui/core/TextField"; import { useState } from "react"; import theOneLocalizationManager from "../lib/localizationManager/localizationManager"; import "./RequestStringDialog.less"; interface IProps extends StandardTextFieldProps...
props.label && typeof props.label === "string" ) { const stringLabel: string = props.label; setPrevL10nKey(props.l10nKeyForLabel); theOneLocalizationManager .asyncGetText(props.l10nKeyForLabel, stringLabel, undefined) .done(result => { ...
if ( props.l10nKeyForLabel != prevL10nKey &&
random_line_split
DialogExampleLayout.tsx
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
</ButtonTransparent> </> } > {children} </DialogLayout> ) }
<Button onClick={closeModal}>Done Reading</Button> <ButtonTransparent color="neutral" onClick={closeModal}> Finish Later
random_line_split
views.py
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import onenote import bitbucket # sample repo_uuid = 3d316876-a913-4b20-b183-d57e919f96dc BASE_URL = "https://afternoon-waters-2404.herokuapp.com" # DEV_URL = "https://classnotes-varunagrawal.c9.io" # Create your views h...
(request): if 'repo_uuid' in request.COOKIES: repo_uuid = request.COOKIES['repo_uuid'] books = onenote.get_notebooks(repo_uuid) context = {'notebooks': books} # print(notebooks return render(request, 'notebooks.html', context)#("List of Notebooks\n{0}".format(str(notebooks))) ...
notebooks
identifier_name
views.py
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import onenote import bitbucket # sample repo_uuid = 3d316876-a913-4b20-b183-d57e919f96dc BASE_URL = "https://afternoon-waters-2404.herokuapp.com" # DEV_URL = "https://classnotes-varunagrawal.c9.io" # Create your views h...
repo_uuid = None if 'repo_uuid' in request.COOKIES: repo_uuid = request.COOKIES['repo_uuid'] page = onenote.get_page_content(request.GET["id"], repo_uuid) # context = { 'page': page } # return render(request, 'page.html', context) return HttpResponse(str(page))
identifier_body
views.py
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import onenote import bitbucket # sample repo_uuid = 3d316876-a913-4b20-b183-d57e919f96dc BASE_URL = "https://afternoon-waters-2404.herokuapp.com" # DEV_URL = "https://classnotes-varunagrawal.c9.io" # Create your views h...
sections = onenote.get_sections(request.GET["id"], request.GET["name"], repo_uuid) context = {'sections': sections} # return HttpResponse(sections["value"]) return render(request, 'sections.html', context) def pages(request): if 'repo_uuid' in request.COOKIES: repo_uuid = reques...
repo_uuid = request.COOKIES['repo_uuid']
conditional_block
views.py
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import onenote import bitbucket # sample repo_uuid = 3d316876-a913-4b20-b183-d57e919f96dc BASE_URL = "https://afternoon-waters-2404.herokuapp.com" # DEV_URL = "https://classnotes-varunagrawal.c9.io" # Create your views h...
'microsoft_login': microsoft_login_url, 'need_ms_signin': need_ms_signin} response = render(request, 'index.html', context) response.set_cookie('repo_uuid', repo_uuid) return response def ms_sign_in(request): print("Redirecting user") redirect_to = "https://login.live....
need_ms_signin = onenote.get_auth_token(request) is None need_atlassian_signin = not bitbucket.is_logged_in(repo_uuid) context = {'bitbucket_login': bitbucket_login_url, 'need_atlassian_signin': need_atlassian_signin,
random_line_split
stepper.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directionality} from '@angular/cdk/bidi'; import {BooleanInput} from '@angular/cdk/coercion'; import { CdkS...
(@Inject(forwardRef(() => MatStepper)) stepper: MatStepper, @SkipSelf() private _errorStateMatcher: ErrorStateMatcher, @Optional() @Inject(STEPPER_GLOBAL_OPTIONS) stepperOptions?: StepperOptions) { super(stepper, stepperOptions); } /** Custom error state matcher that additionally ch...
constructor
identifier_name
stepper.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directionality} from '@angular/cdk/bidi'; import {BooleanInput} from '@angular/cdk/coercion'; import { CdkS...
}); } static ngAcceptInputType_editable: BooleanInput; static ngAcceptInputType_optional: BooleanInput; static ngAcceptInputType_completed: BooleanInput; static ngAcceptInputType_hasError: BooleanInput; } @Component({ selector: 'mat-horizontal-stepper', exportAs: 'matHorizontalStepper', templateU...
{ this.animationDone.emit(); }
conditional_block
stepper.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directionality} from '@angular/cdk/bidi'; import {BooleanInput} from '@angular/cdk/coercion'; import { CdkS...
selector: 'mat-horizontal-stepper', exportAs: 'matHorizontalStepper', templateUrl: 'stepper-horizontal.html', styleUrls: ['stepper.css'], inputs: ['selectedIndex'], host: { 'class': 'mat-stepper-horizontal', '[class.mat-stepper-label-position-end]': 'labelPosition == "end"', '[class.mat-stepper-...
@Component({
random_line_split
parameters.ts
import { PaymentMethod } from '../../../data/global'; import { PaymentData } from '../../../data/payments/data';
interface ContextParameters { orderId: string; testmode?: boolean; } export type CreateParameters = ContextParameters & Pick<PaymentData, 'mandateId' | 'applicationFee'> & { /** * Normally, a payment method screen is shown. However, when using this parameter, you can choose a specific payment method an...
random_line_split
search.controller.js
(function() { 'use strict'; angular.module('columbyApp') .controller('SearchCtrl', function($log,$rootScope, $scope, SearchSrv) { /* ---------- SETUP ----------------------------------------------------------------------------- */ $scope.contentLoading = true; $scope.search = {}; $rootScope.t...
else { $scope.search.message = 'Type at least 3 characters.'; } }; /* ---------- INIT ---------------------------------------------------------------------------- */ if ($rootScope.searchTerm){ $scope.search.searchTerm = $rootScope.searchTerm; $log.debug($scope.search.searchTerm...
{ $scope.search.message = 'Searching for: ' + $scope.search.searchTerm; SearchSrv.query({ text: $scope.search.searchTerm, limit: $scope.pagination.itemsPerPage }).then(function (response) { $scope.search.hits = response; $scope.search.message = null; ...
conditional_block
search.controller.js
(function() { 'use strict'; angular.module('columbyApp') .controller('SearchCtrl', function($log,$rootScope, $scope, SearchSrv) { /* ---------- SETUP ----------------------------------------------------------------------------- */ $scope.contentLoading = true; $scope.search = {}; $rootScope.t...
}, function(err){ $scope.search.message = 'Error: ' + err.data.message; }); } else { $scope.search.message = 'Type at least 3 characters.'; } }; /* ---------- INIT ---------------------------------------------------------------------------- */ if ($rootScope....
$scope.pagination.datasets.numPages = response.datasets.count / $scope.pagination.itemsPerPage; $scope.pagination.accounts.numPages = response.accounts.count / $scope.pagination.itemsPerPage; $scope.pagination.tags.numPages = response.tags.count / $scope.pagination.itemsPerPage;
random_line_split
base.py
"""Base test class for nbconvert""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import io import os import glob import shlex import shutil import sys import unittest import nbconvert from subprocess import Popen, PIPE import nose.tools as nt from nbformat imp...
(self, path): nb = v4.new_notebook() with io.open(path, 'w', encoding='utf-8') as f: write(nb, f, 4) def copy_files_to(self, copy_filenames, dest='.'): "Copy test files into the destination directory" if not os.path.isdir(dest): os.makedirs(dest) file...
create_empty_notebook
identifier_name
base.py
"""Base test class for nbconvert""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import io import os import glob import shlex import shutil import sys import unittest import nbconvert from subprocess import Popen, PIPE import nose.tools as nt from nbformat imp...
if tabs_are_spaces: a = a.replace('\t', ' ') b = b.replace('\t', ' ') if ignore_spaces: a = a.replace(' ', '') b = b.replace(' ', '') if fuzzy_spacing: a = self.recursive_replace(a, ' ', ' ') b = self.recursive_replace(...
a = a.replace('\n', ' ') b = b.replace('\n', ' ')
conditional_block
base.py
"""Base test class for nbconvert""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import io import os import glob import shlex import shutil import sys import unittest import nbconvert from subprocess import Popen, PIPE import nose.tools as nt from nbformat imp...
text = text.replace(search, replacement) return text def create_temp_cwd(self, copy_filenames=None): temp_dir = TemporaryWorkingDirectory() #Copy the files if requested. if copy_filenames is not None: self.copy_files_to(copy_filenames, dest=temp_dir.name) ...
""" Performs a recursive replacement operation. Replaces all instances of a search string in a text string with a replacement string until the search string no longer exists. Recursion is needed because the replacement string may generate additional search strings. For example...
identifier_body
base.py
"""Base test class for nbconvert""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import io import os import glob import shlex import shutil import sys import unittest import nbconvert from subprocess import Popen, PIPE import nose.tools as nt from nbformat imp...
""" for i in range(0, len(a), chunk_size): chunk_a = a[i:i + chunk_size] chunk_b = b[i:i + chunk_size] nt.assert_equal(chunk_a, chunk_b, "[offset: %i]\n%r != \n%r" % ( i, chunk_a, chunk_b)) if len(a) > len(b): nt.fail("Length doesn't match (%i > %i). Extra text:\...
"""assert that large strings are equal Zooms in on first chunk that differs, to give better info than vanilla assertEqual for large text blobs.
random_line_split
kzip_sys.rs
// Copyright 2020 The Kythe 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 appli...
#[doc = " \\brief Deallocates KzipWriter."] #[doc = ""] #[doc = " Must be called once KzipWriter is no longer needed."] pub fn KzipWriter_Delete(writer: *mut KzipWriter); } extern "C" { #[doc = " \\brief Closes the writer."] #[doc = " Must be called before destroying the object."] pub fn Kzi...
encoding: i32, create_status: *mut i32, ) -> *mut KzipWriter; } extern "C" {
random_line_split
kzip_sys.rs
// Copyright 2020 The Kythe 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 appli...
{ _unused: [u8; 0], } extern "C" { #[doc = " \\brief Creates a new kzip writer."] #[doc = " \\param path The path to the file to create."] #[doc = " \\param path_len the string length of path, required due to the C API."] #[doc = " \\param encoding The compilation unit encoding, either"] #[doc ...
KzipWriter
identifier_name
db.rs
", (&real_name, &name, &true), )?; fid = result.last_insert_id().unwrap(); } { if CONFIG.general.link_files { conn.exec_drop( "INSERT INTO `query_files` (qid,fid) VALUES(?,?)", (&qid, &fid), )?; } } Ok(fi...
fn get_db_create_sql<'a>() -> Vec<String> { let raw_sql = include_str!("../../setup.sql"); let reg = regex::Regex::new(r"(/\*(.|\s)*?\*/)").unwrap(); // https://regex101.com/r/bG6aF2/6, replace `\/` with `/` let raw_sql =
/// Returns a vector of table setup sql #[cfg(test)]
random_line_split