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 |
|---|---|---|---|---|
URLParser.ts | /*
* Copyright 2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in w... | }
// TODO: create interface for this param.
public build(searchTerms?: { [param: string]: string }): string {
const obj = searchTerms || {};
return (
'?' +
Object.keys(obj)
.map(k => k + '=' + obj[k])
.join('&')
);
}
private _update(replace = true): void {
if (rep... | random_line_split | |
hire-me.tsx | import { PageProps } from "gatsby";
import React, { FC } from "react";
import Layout from "../components/layout";
import SEO from "../components/seo";
const HireMePage: FC<PageProps> = ({ location }) => (
<Layout location={location}>
<SEO title="Nerd for Hire" />
<h1>Nerd for Hire</h1>
<p>
Wouldn’t it be gre... | </ul>
</p>
<h3>Website Quick Wins</h3>
<p>
<ul>
<li>Google Tag Manager installation</li>
<li>Google Analytics installation</li>
<li>Google Search console setup and configuration</li>
<li>Social media (Facebook, Twitter, etc) integration</li>
<li>Transfer your site to a new host</li>
... | <li>Web development: HTML, CSS, JavaScript</li>
</ul>
</li> | random_line_split |
menu-controller.ts | [Menu](../Menu/Menu/) API docs
* for more information on adding menu components.
*
* ```html
* <ion-menu [content]="mycontent">
* <ion-content>
* <ion-list>
* ...
* </ion-list>
* </ion-content>
* </ion-menu>
*
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* To call the contr... |
}
/**
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {boolean} Returns true if the menu is currently enabled, otherwise false.
*/
isEnabled(menuId?: string): boolean {
const menu = this.get(menuId);
return menu && menu.enabled || false;
}
/**
* Used to... | {
return !!this.getOpen();
} | conditional_block |
menu-controller.ts | the [Menu](../Menu/Menu/) API docs
* for more information on adding menu components.
*
* ```html
* <ion-menu [content]="mycontent">
* <ion-content>
* <ion-list>
* ...
* </ion-list>
* </ion-content>
* </ion-menu>
*
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* To call the c... | menu = this.menus.find(m => m.side === menuId && m.enabled);
if (menu) {
return menu;
}
// didn't find a menu side that is enabled
// so try to get the first menu side found
return this.menus.find(m => m.side === menuId) || null;
} else if (menuId) {
// the menuId... | // there could be more than one menu on the same side
// so first try to get the enabled one | random_line_split |
menu-controller.ts | Menu/Menu/) API docs
* for more information on adding menu components.
*
* ```html
* <ion-menu [content]="mycontent">
* <ion-content>
* <ion-list>
* ...
* </ion-list>
* </ion-content>
* </ion-menu>
*
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* To call the controller metho... | {
let menu: Menu;
if (menuId === 'left' || menuId === 'right') {
// there could be more than one menu on the same side
// so first try to get the enabled one
menu = this.menus.find(m => m.side === menuId && m.enabled);
if (menu) {
return menu;
}
// didn't find a men... | identifier_body | |
menu-controller.ts | [Menu](../Menu/Menu/) API docs
* for more information on adding menu components.
*
* ```html
* <ion-menu [content]="mycontent">
* <ion-content>
* <ion-list>
* ...
* </ion-list>
* </ion-content>
* </ion-menu>
*
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* To call the contr... | (shouldEnable: boolean, menuId?: string): Menu {
const menu = this.get(menuId);
if (menu) {
return menu.swipeEnable(shouldEnable);
}
}
/**
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {boolean} Returns true if the specified menu is currently open, otherwi... | swipeEnable | identifier_name |
config.js | /**
* @author Phuluong
* Feb 13, 2016
*/
/** Exports **/
module.exports = new Config();
/** Imports **/
var fs = require("fs");
var util = require(__dir + '/core/app/util');
/** Modules **/
function | () {
var configContainer = {};
/**
* Get config value by key
* @param {String} key
* @param {} defaultValue
* @returns {}
*/
this.get = function (key, defaultValue) {
var retval = defaultValue;
if (configContainer[key] != null) {
retval = configContainer[... | Config | identifier_name |
config.js | /**
* @author Phuluong
* Feb 13, 2016
*/
/** Exports **/
module.exports = new Config();
/** Imports **/
var fs = require("fs");
var util = require(__dir + '/core/app/util');
/** Modules **/
function Config() | } else if (fs.existsSync(parentPath + ".js")) {
if ((require(parentPath))[property] != null) {
retval = (require(parentPath))[property];
}
} else if (key.indexOf("package") == 0) {
ret... | {
var configContainer = {};
/**
* Get config value by key
* @param {String} key
* @param {} defaultValue
* @returns {}
*/
this.get = function (key, defaultValue) {
var retval = defaultValue;
if (configContainer[key] != null) {
retval = configContainer[key... | identifier_body |
config.js | /**
* @author Phuluong
* Feb 13, 2016
*/
/** Exports **/
module.exports = new Config();
/** Imports **/
var fs = require("fs");
var util = require(__dir + '/core/app/util');
/** Modules **/
function Config() {
var configContainer = {};
/**
* Get config value by key
* @param {String} key
* @par... | }
return retval;
};
/**
* Set config value
* @param {String} key
* @param {} value
*/
this.set = function (key, value) {
configContainer[key] = value;
};
} | if (retval == null) {
| random_line_split |
config.js | /**
* @author Phuluong
* Feb 13, 2016
*/
/** Exports **/
module.exports = new Config();
/** Imports **/
var fs = require("fs");
var util = require(__dir + '/core/app/util');
/** Modules **/
function Config() {
var configContainer = {};
/**
* Get config value by key
* @param {String} key
* @par... | else if (key.indexOf("package") == 0) {
retval = (require(__dir + "/package.json"))[property];
}
configContainer[key] = retval;
} catch (exc) {
}
}
if (retval == null) {
}
return retval;
};
... | {
if ((require(parentPath))[property] != null) {
retval = (require(parentPath))[property];
}
} | conditional_block |
WebhookStepGitLab-test.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | (props: Partial<WebhookStepGitLabProps> = {}) {
return shallow<WebhookStepGitLabProps>(<WebhookStepGitLab branchesEnabled={true} {...props} />);
}
| shallowRender | identifier_name |
WebhookStepGitLab-test.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | return shallow<WebhookStepGitLabProps>(<WebhookStepGitLab branchesEnabled={true} {...props} />);
} | expect(shallowRender()).toMatchSnapshot('default');
expect(shallowRender({ branchesEnabled: false })).toMatchSnapshot('with branches disabled');
});
function shallowRender(props: Partial<WebhookStepGitLabProps> = {}) { | random_line_split |
WebhookStepGitLab-test.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | {
return shallow<WebhookStepGitLabProps>(<WebhookStepGitLab branchesEnabled={true} {...props} />);
} | identifier_body | |
ModalOverlay.tsx | import { Box } from '@tlon/indigo-react';
import React, { useCallback, useRef } from 'react';
import { PropFunc } from '~/types/util';
interface ModalOverlayProps {
spacing?: PropFunc<typeof Box>['m'];
dismiss: () => void;
}
type Props = ModalOverlayProps & PropFunc<typeof Box>;
export const ModalOverlay = (props:... |
},
[props.dismiss, ref]
);
return (
<Box
backgroundColor="scales.black20"
left="0px"
top="0px"
width="100%"
height="100%"
position="fixed"
display="flex"
zIndex={10}
justifyContent="center"
alignItems="center"
p={spacing}
onClick=... | {
props.dismiss();
e.stopPropagation();
} | conditional_block |
ModalOverlay.tsx | import { Box } from '@tlon/indigo-react';
import React, { useCallback, useRef } from 'react';
import { PropFunc } from '~/types/util';
interface ModalOverlayProps {
spacing?: PropFunc<typeof Box>['m'];
dismiss: () => void;
}
type Props = ModalOverlayProps & PropFunc<typeof Box>;
export const ModalOverlay = (props:... | display="flex"
zIndex={10}
justifyContent="center"
alignItems="center"
p={spacing}
onClick={onClick}
onKeyDown={onKeyDown}
>
<Box ref={ref} {...rest} />
</Box>
);
}; | top="0px"
width="100%"
height="100%"
position="fixed" | random_line_split |
keypool.py | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet ... |
for key,value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
num_matched = num_matched+1
if num_matched == 0:
raise AssertionError("No objects matched %s"%(str(to_match)))
def run_tes... | continue | conditional_block |
keypool.py | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet ... | assert(len(addr) == 4)
# the next one should fail
try:
addr = nodes[0].getrawchangeaddress()
raise AssertionError('Keypool should be exhausted after three addresses')
except JSONRPCException,e:
assert(e.error['code']==-12)
def main():
import optparse
parser = optparse.... | # assert that four unique addresses were returned | random_line_split |
keypool.py | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet ... | ():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true",
help="Leave litecoinzds and test.* datadir on exit or error")
parser.add_option("--srcdir", dest="srcdir", default="..... | main | identifier_name |
keypool.py | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2017-2018 The LitecoinZ developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the wallet keypool, and interaction with wallet ... |
def run_test(nodes, tmpdir):
# Encrypt wallet and wait to terminate
nodes[0].encryptwallet('test')
litecoinzd_processes[0].wait()
# Restart node 0
nodes[0] = start_node(0, tmpdir)
# Keep creating keys
addr = nodes[0].getnewaddress()
try:
addr = nodes[0].getnewaddress()
... | """
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
"""
num_matched = 0
for item in object_array:
all_match = True
for key,value in to_match.items():
if item[key] != value:
... | identifier_body |
config.ts | const
IS_PRODUCTION = false,
API_URL = IS_PRODUCTION ? "https://my-host.com:443" : "https://localhost:443",
SOCKET_IO_URL = IS_PRODUCTION ? "https://my-host.com:443" : "https://localhost:443",
PATH_IMAGES = API_URL + "/assets/images/",
MAIL_TO = "admin@my-host.com",
BROWSER = {
isFirefox... | BROWSER,
SOCKET_IO_URL,
MAIL_TO,
DEFAULT_LANGUAGE,
DEFAULT_COUNTRY_ISO
} | API_URL,
PATH_IMAGES, | random_line_split |
knn.py | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from collections import defaultdict
import numpy as np
from .base import supervised... | def __init__(self, k=1):
self.k = k
def train(self, features, labels, normalisedlabels=False, copy_features=False):
features = np.asanyarray(features)
labels = np.asanyarray(labels)
if copy_features:
features = features.copy()
labels = labels.copy()
... | '''
| random_line_split |
knn.py | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from collections import defaultdict
import numpy as np
from .base import supervised... |
v,L = max( (v,L) for L,v in votes.items() )
return L
| votes[L] += 1 | conditional_block |
knn.py | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from collections import defaultdict
import numpy as np
from .base import supervised... | (self, features, labels, normalisedlabels=False, copy_features=False):
features = np.asanyarray(features)
labels = np.asanyarray(labels)
if copy_features:
features = features.copy()
labels = labels.copy()
features2 = np.sum(features**2, axis=1)
return kNN_... | train | identifier_name |
knn.py | # -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
from __future__ import division
from collections import defaultdict
import numpy as np
from .base import supervised... | if copy_features:
features = features.copy()
labels = labels.copy()
features2 = np.sum(features**2, axis=1)
return kNN_model(self.k, features, features2, labels)
class kNN_model(supervised_model):
def __init__(self, k, features, features2, labels):
self.k = ... | '''
k-Nearest Neighbour Classifier
Naive implementation of a k-nearest neighbour classifier.
C = kNN(k)
Attributes:
-----------
k : integer
number of neighbours to consider
'''
def __init__(self, k=1):
self.k = k
def train(self, features, labels, normalisedlabel... | identifier_body |
listWithUniqueSelection.tsx | /* tslint:disable */
import * as React from 'react'
/* tslint:enable */
import { observer } from 'mobx-react'
import { autorun, computed, observable } from 'mobx'
import { EditorModelClass } from '../editorModel'
import { MMElement } from '../wm3'
import { Editor, SelectableComp, EditorComp, ENTER_KEY } from './common'... | if (event.keyCode === ENTER_KEY) {
// ICI: also possibility to:
// - create an editor model from nothing/some string
// - create a source element from an editor model
// ?
editorModel.add(editorModel.length(), newItemUIValue.get... | {
return (src: SrcType): EditorComp => {
const editorModel = createListEditorModel(src)
const newItemUIValue = observable('')
const children = computed(() => editorModel.get().map(subEditor))
autorun(() => {
for (let child of children.get()) {
autorun(() =... | identifier_body |
listWithUniqueSelection.tsx | /* tslint:disable */
import * as React from 'react'
/* tslint:enable */
import { observer } from 'mobx-react'
import { autorun, computed, observable } from 'mobx'
import { EditorModelClass } from '../editorModel'
import { MMElement } from '../wm3'
import { Editor, SelectableComp, EditorComp, ENTER_KEY } from './common'... | (event: React.FormEvent) {
newItemUIValue.set((event.target as any).value)
}
function handleKeyUp(event: React.KeyboardEvent) {
if (event.keyCode === ENTER_KEY) {
// ICI: also possibility to:
// - create an editor model from nothing/some string
... | handleChange | identifier_name |
listWithUniqueSelection.tsx | /* tslint:disable */
import * as React from 'react'
/* tslint:enable */
import { observer } from 'mobx-react'
import { autorun, computed, observable } from 'mobx'
import { EditorModelClass } from '../editorModel'
import { MMElement } from '../wm3'
import { Editor, SelectableComp, EditorComp, ENTER_KEY } from './common'... |
})
}
})
function handleChange(event: React.FormEvent) {
newItemUIValue.set((event.target as any).value)
}
function handleKeyUp(event: React.KeyboardEvent) {
if (event.keyCode === ENTER_KEY) {
// ICI: also possibility ... | {
children.get().filter(i => i !== child).forEach(i => i.isSelected.set(false))
} | conditional_block |
listWithUniqueSelection.tsx | /* tslint:enable */
import { observer } from 'mobx-react'
import { autorun, computed, observable } from 'mobx'
import { EditorModelClass } from '../editorModel'
import { MMElement } from '../wm3'
import { Editor, SelectableComp, EditorComp, ENTER_KEY } from './common'
interface ListEditorModel<EltType> {
get(idx: ... | /* tslint:disable */
import * as React from 'react' | random_line_split | |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... | add_impls_for_keyword_enum!(StepPosition);
impl<H, V, D> TransformOrigin<H, V, D> {
/// Returns a new transform origin.
pub fn new(horizontal: H, vertical: V, depth: D) -> Self {
Self {
horizontal: horizontal,
vertical: vertical,
depth: depth,
}
}
}
impl... | random_line_split | |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... |
}
impl<Integer, Number> TimingFunction<Integer, Number> {
/// `ease`
#[inline]
pub fn ease() -> Self {
TimingFunction::Keyword(TimingKeyword::Ease)
}
}
impl<Integer, Number> ToCss for TimingFunction<Integer, Number>
where
Integer: ToCss,
Number: ToCss,
{
fn to_css<W>(&self, dest: ... | {
Self {
horizontal: horizontal,
vertical: vertical,
depth: depth,
}
} | identifier_body |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... | ,
TimingFunction::Frames(ref frames) => {
dest.write_str("frames(")?;
frames.to_css(dest)?;
dest.write_str(")")
},
}
}
}
impl TimingKeyword {
/// Returns the keyword as a quadruplet of Bezier point coordinates
/// `(x1, y1, x2,... | {
dest.write_str("steps(")?;
intervals.to_css(dest)?;
if position != StepPosition::End {
dest.write_str(", ")?;
position.to_css(dest)?;
}
dest.write_str(")")
} | conditional_block |
transform.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/. */
//! Generic types for CSS values that are related to transformations.
use std::fmt;
use style_traits::ToCss;
use ... | <Integer, Number> {
/// `linear | ease | ease-in | ease-out | ease-in-out`
Keyword(TimingKeyword),
/// `cubic-bezier(<number>, <number>, <number>, <number>)`
#[allow(missing_docs)]
CubicBezier { x1: Number, y1: Number, x2: Number, y2: Number },
/// `step-start | step-end | steps(<integer>, [ sta... | TimingFunction | identifier_name |
viewport.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! An adapter which makes widgets scrollable
use ShadowType;
use cast::GTK_VIEWPORT;
use ff... | pub fn get_shadow_type(&self) -> ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&self, ty: ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}... | let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.unwrap_pointer(), vadjustment.unwrap_pointer()) };
check_pointer!(tmp_pointer, Viewport)
}
| identifier_body |
viewport.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! An adapter which makes widgets scrollable
use ShadowType;
use cast::GTK_VIEWPORT;
use ff... | self, ty: ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!(Viewport);
impl_TraitWidget!(Viewport);
impl ::ContainerTrait for Viewport {}
impl ::BinTrait for Viewport {}
impl ::ScrollableTrait for Viewport {}
| t_shadow_type(& | identifier_name |
viewport.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! An adapter which makes widgets scrollable
use ShadowType;
use cast::GTK_VIEWPORT;
use ff... | }
pub fn get_shadow_type(&self) -> ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&self, ty: ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
... | impl Viewport {
pub fn new(hadjustment: &::Adjustment, vadjustment: &::Adjustment) -> Option<Viewport> {
let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.unwrap_pointer(), vadjustment.unwrap_pointer()) };
check_pointer!(tmp_pointer, Viewport) | random_line_split |
FlowLayout.py | #!/usr/bin/env python
"""PyQt4 port of the layouts/flowlayout example from Qt v4.x"""
from PyQt4 import QtCore, QtGui
# ------------------------------------------------------------------------
class FlowLayout(QtGui.QLayout):
"""
Standard PyQt examples FlowLayout modified to work with a scollable parent
"""
d... | app = QtGui.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit(app.exec_()) |
self.setWindowTitle("Scrolling Flow Layout")
| random_line_split |
FlowLayout.py | #!/usr/bin/env python
"""PyQt4 port of the layouts/flowlayout example from Qt v4.x"""
from PyQt4 import QtCore, QtGui
# ------------------------------------------------------------------------
class FlowLayout(QtGui.QLayout):
"""
Standard PyQt examples FlowLayout modified to work with a scollable parent
"""
d... | for n in range(random.randint(1,5)) ]).title()
widget = QtGui.QPushButton(words)
widget.setFixedHeight( 20 )
widget.setCursor( QtCore.Qt.PointingHandCursor )
widget.setCheckable( True )
self.scroller.addWidget(widget)
self.setWindowTitle("Scrolling Flow Layout")
app = QtGui.QApplic... | import sys
import random
class ExampleScroller(ScrollingFlowWidget):
def sizeHint(self):
return QtCore.QSize(500,300)
class ExampleWindow(QtGui.QWidget):
def __init__(self):
super(ExampleWindow, self).__init__()
self.scroller = ExampleScroller(self)
self.setLayout( QtGui.QVBoxLayout(self) )
s... | conditional_block |
FlowLayout.py | #!/usr/bin/env python
"""PyQt4 port of the layouts/flowlayout example from Qt v4.x"""
from PyQt4 import QtCore, QtGui
# ------------------------------------------------------------------------
class FlowLayout(QtGui.QLayout):
"""
Standard PyQt examples FlowLayout modified to work with a scollable parent
"""
d... |
def takeAt(self, index):
if index >= 0 and index < len(self.itemList):
return self.itemList.pop(index)
return None
def expandingDirections(self):
return QtCore.Qt.Orientations(QtCore.Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
height = self.doLa... | if index >= 0 and index < len(self.itemList):
return self.itemList[index]
return None | identifier_body |
FlowLayout.py | #!/usr/bin/env python
"""PyQt4 port of the layouts/flowlayout example from Qt v4.x"""
from PyQt4 import QtCore, QtGui
# ------------------------------------------------------------------------
class FlowLayout(QtGui.QLayout):
"""
Standard PyQt examples FlowLayout modified to work with a scollable parent
"""
d... | (self, parent=None):
QtGui.QScrollArea.__init__(self, parent)
def resizeEvent(self, event):
wrapper = self.findChild(QtGui.QWidget)
flow = wrapper.findChild(FlowLayout)
if wrapper and flow:
width = self.viewport().width()
height = flow.heightForWidth(width)
size = QtCore.QSize(width... | __init | identifier_name |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... | }
}
Ok(())
}
pub fn git_command(ctx: &mut Context, git: &GitInfo) -> Result<(), String>
{
try!(capsule::ensure_features(ctx, &[capsule::Git]));
let dest = PathBuf::from("/vagga/root").join(&git.path.rel());
let cache_path = try!(git_cache(&git.url));
try!(create_dir_all(&dest)
... | {
let mut cmd = Command::new("/usr/bin/git");
cmd.stdin(Stdio::null());
cmd.arg("--git-dir").arg(cache_path);
cmd.arg("--work-tree").arg(dest);
cmd.arg("reset").arg("--hard");
if let &Some(ref rev) = revision {
cmd.arg(&rev);
} else if let &Some(ref branch) = branch {
cmd.arg... | identifier_body |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... | "-exc".to_string(),
git.script.to_string()],
&workdir);
}
pub fn fetch_git_source(capsule: &mut capsule::State, settings: &Settings,
git: &GitSource)
-> Result<(), String>
{
try!(capsule::ensure(capsule, settings, &[capsule::Git]));
let cache_path = try!(git_cache(&git.url));
... | return run_command_at(ctx, &[
"/bin/sh".to_string(), | random_line_split |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... | (capsule: &mut capsule::State, settings: &Settings,
git: &GitSource)
-> Result<(), String>
{
try!(capsule::ensure(capsule, settings, &[capsule::Git]));
let cache_path = try!(git_cache(&git.url));
let dest = Path::new("/vagga/sources")
.join(cache_path.file_name().unwrap());
try!(create_d... | fetch_git_source | identifier_name |
vcs.rs | use std::fs::rename;
use std::fs::create_dir_all;
use std::path::{Path, PathBuf};
use unshare::{Command, Stdio};
use config::settings::Settings;
use config::builders::GitInfo;
use config::builders::GitInstallInfo;
use config::builders::GitSource;
use super::super::capsule;
use super::super::context::Context;
use supe... |
Ok(status) => {
return Err(format!("Command {:?} exited with code {}",
cmd, status));
}
Err(err) => {
return Err(format!("Error running {:?}: {}", cmd, err));
}
}
} else {
let tmppath = cache_path.w... | {} | conditional_block |
imageQueryParser.py | import random
class ImageQueryParser:
def __init__(self):
pass
def parse(self, query_string):
tab = query_string.split(" ")
last = tab[-1].lower()
is_random = False
index = 0
if last.startswith("-"):
if last == "-r":
is_random = True... | return ImageQuery(query_string, is_random, index)
class ImageQuery:
def __init__(self, query, is_random, index):
self.__query = query
self.__is_random = is_random
self.__index = index
def query(self):
return self.__query
def is_random(self):
return self.__... | except ValueError:
pass
query_string = " ".join(tab) | random_line_split |
imageQueryParser.py | import random
class ImageQueryParser:
def __init__(self):
pass
def parse(self, query_string):
tab = query_string.split(" ")
last = tab[-1].lower()
is_random = False
index = 0
if last.startswith("-"):
if last == "-r":
is_random = True... | if self.is_random():
return random.randrange(0, 100)
else:
i = self.__index
self.__index += 1
return i | identifier_body | |
imageQueryParser.py | import random
class ImageQueryParser:
def __init__(self):
pass
def parse(self, query_string):
tab = query_string.split(" ")
last = tab[-1].lower()
is_random = False
index = 0
if last.startswith("-"):
if last == "-r":
is_random = True... | i = self.__index
self.__index += 1
return i | conditional_block | |
imageQueryParser.py | import random
class ImageQueryParser:
def __init__(self):
pass
def parse(self, query_string):
tab = query_string.split(" ")
last = tab[-1].lower()
is_random = False
index = 0
if last.startswith("-"):
if last == "-r":
is_random = True... | (self, query, is_random, index):
self.__query = query
self.__is_random = is_random
self.__index = index
def query(self):
return self.__query
def is_random(self):
return self.__is_random
def next_index(self):
if self.is_random():
return random.ra... | __init__ | identifier_name |
setup.py | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
import skypipe
setup(
name='skypipe',
version=skypipe.VERSION,
author='Jeff Lindsay',
author_email='progrium@gmail.com',
description='Magic pipe in the sky',
long_description=open(os.path.join(os.path.dirname(__file__)... | 'skypipe': ['satellite/*']},
entry_points={
'console_scripts': [
'skypipe = skypipe.cli:run',]}
) | random_line_split | |
floating_ip_pools.py | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
#
# 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 req... | (wsgi.Controller):
"""The Floating IP Pool API controller for the OpenStack API."""
def __init__(self):
super(FloatingIPPoolsController, self).__init__()
self.network_api = neutron.API()
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@wsgi.expected_errors(())
de... | FloatingIPPoolsController | identifier_name |
floating_ip_pools.py | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
#
# 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 req... | """Return a list of pools."""
context = req.environ['nova.context']
context.can(fip_policies.BASE_POLICY_NAME)
pools = self.network_api.get_floating_ip_pools(context)
return _translate_floating_ip_pools_view(pools) | identifier_body | |
floating_ip_pools.py | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
#
# 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 req... |
def _translate_floating_ip_pools_view(pools):
return {
'floating_ip_pools': [_translate_floating_ip_view(pool)
for pool in pools]
}
class FloatingIPPoolsController(wsgi.Controller):
"""The Floating IP Pool API controller for the OpenStack API."""
def __init__(s... | def _translate_floating_ip_view(pool):
return {
'name': pool['name'] or pool['id'],
} | random_line_split |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | mut left = mut_root.left.take();
Self::flatten_failed(&mut left);
let mut right = mut_root.right.take();
Self::flatten_failed(&mut right);
// while let Some(node) = left.take() {
// left = node.borrow_mut().right.take();
// mut_root.right = Some(node);
/... | rap().borrow_mut();
let | conditional_block |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | return;
}
let mut mut_root = root.as_mut().unwrap().borrow_mut();
let mut left = mut_root.left.take();
Self::flatten_failed(&mut left);
let mut right = mut_root.right.take();
Self::flatten_failed(&mut right);
// while let Some(node) = left.take() {
... | s_none() {
| identifier_name |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | ten() {
let mut root = build_one_node(TreeNode {
val: 1,
left: build_one_node(TreeNode {
val: 2,
left: build_one_node(TreeNode::new(3)),
right: build_one_node(TreeNode::new(4)),
}),
right: build_one_node(TreeNode {
... | mut_root = root.as_mut().unwrap().borrow_mut();
let mut left = mut_root.left.take();
Self::flatten_failed(&mut left);
let mut right = mut_root.right.take();
Self::flatten_failed(&mut right);
// while let Some(node) = left.take() {
// left = node.borrow_mut().right.ta... | identifier_body |
no_0114_flatten_binary_tree_to_linked_list.rs | // Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
lef... | left: None,
right: build_one_node(TreeNode {
val: 5,
left: None,
right: build_one_node(TreeNode::new(6)),
}),
}),
}),
... | val: 3,
left: None,
right: build_one_node(TreeNode {
val: 4, | random_line_split |
util.rs | /*
* Copyright 2015-2016 Ben Ashford
*
* 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 agree... | $ex
}
}
};
}
macro_rules! from {
($ft:ty, $dt:ident, $ev:ident, $pi:ident) => {
from_exp!($ft, $dt, $pi, $dt::$ev($pi));
};
($ft:ty, $dt:ident, $ev:ident) => {
from!($ft, $dt, $ev, from);
};
} | /// to that module
macro_rules! from_exp {
($ft:ty, $dt:ident, $pi:ident, $ex:expr) => {
impl From<$ft> for $dt {
fn from($pi: $ft) -> $dt { | random_line_split |
util.rs | /*
* Copyright 2015-2016 Ben Ashford
*
* 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 agree... |
}
/// Useful macro for adding a function to supply a value to an optional field
macro_rules! add_field {
($n:ident, $f:ident, $t:ty) => (
pub fn $n<T: Into<$t>>(mut self, val: T) -> Self {
self.$f = Some(val.into());
self
}
);
}
/// Useful macros for implementing `From... | {
let mut s = String::new();
for f in self {
s.push_str(f.as_ref());
s.push_str(join);
}
s.pop();
s
} | identifier_body |
util.rs | /*
* Copyright 2015-2016 Ben Ashford
*
* 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 agree... | (self, join: &str) -> String {
let mut s = String::new();
for f in self {
s.push_str(f.as_ref());
s.push_str(join);
}
s.pop();
s
}
}
/// Useful macro for adding a function to supply a value to an optional field
macro_rules! add_field {
($n:ident, ... | join | identifier_name |
spiral-looper.js | var spiralLooperSketch = function( sl ) {
var canvas, radius, theta0, theta1, x, y;
sl.setup = function() {
canvas = sl.createCanvas(500, 500);
canvas.id("spiral-looper");
canvas.mousePressed(sl.newSpiral);
sl.frameRate(10);
sl.background(0);
sl.noFill();
sl.stroke(255);
sl.smooth... | x = sl.mouseX;
y = sl.mouseY;
//resets radius and thetas to starting values
radius = 10;
theta0 = 0;
theta1 = sl.HALF_PI;
sl.loop();
};
sl.mouseReleased = function() {
sl.noLoop();
};
};
var spiralLooper = new p5(spiralLooperSketch, 'spiral-looper'); | };
sl.newSpiral = function() {
//captures mouse location to start loop | random_line_split |
utils.py | from PyQt4.QtCore import QSize
from PyQt4.QtGui import QVBoxLayout
| QVBoxLayout.__init__(self, parent)
self._last_size = QSize(0, 0)
def setGeometry(self, r):
QVBoxLayout.setGeometry(self, r)
try:
wid = self.parentWidget().parentWidget()
new_size = self.minimumSize()
if new_size == self._last_size: return
... | # This is really really ugly, but the QDockWidget for some reason does not notice when
# its child widget becomes smaller...
# Therefore we manually set its minimum size when our own minimum size changes
class MyVBoxLayout(QVBoxLayout):
def __init__(self, parent=None): | random_line_split |
utils.py | from PyQt4.QtCore import QSize
from PyQt4.QtGui import QVBoxLayout
# This is really really ugly, but the QDockWidget for some reason does not notice when
# its child widget becomes smaller...
# Therefore we manually set its minimum size when our own minimum size changes
class MyVBoxLayout(QVBoxLayout):
def __init... |
def setGeometry(self, r):
QVBoxLayout.setGeometry(self, r)
try:
wid = self.parentWidget().parentWidget()
new_size = self.minimumSize()
if new_size == self._last_size: return
self._last_size = new_size
twid = wid.titleBarWidget()
... | QVBoxLayout.__init__(self, parent)
self._last_size = QSize(0, 0) | identifier_body |
utils.py | from PyQt4.QtCore import QSize
from PyQt4.QtGui import QVBoxLayout
# This is really really ugly, but the QDockWidget for some reason does not notice when
# its child widget becomes smaller...
# Therefore we manually set its minimum size when our own minimum size changes
class MyVBoxLayout(QVBoxLayout):
def __init... |
else:
theight = 0
new_size += QSize(0, theight)
wid.setMinimumSize(new_size)
except Exception:
pass
| theight = twid.sizeHint().height() | conditional_block |
utils.py | from PyQt4.QtCore import QSize
from PyQt4.QtGui import QVBoxLayout
# This is really really ugly, but the QDockWidget for some reason does not notice when
# its child widget becomes smaller...
# Therefore we manually set its minimum size when our own minimum size changes
class | (QVBoxLayout):
def __init__(self, parent=None):
QVBoxLayout.__init__(self, parent)
self._last_size = QSize(0, 0)
def setGeometry(self, r):
QVBoxLayout.setGeometry(self, r)
try:
wid = self.parentWidget().parentWidget()
new_size = self.minimumSize()
... | MyVBoxLayout | identifier_name |
util.ts | -expect-error
import {hiraganize} from 'japanese';
import {random, sample, range} from 'lodash';
import scrapeIt from 'scrape-it';
import State from '../lib/state';
import {Loader} from '../lib/utils';
export interface Quiz {
id: number,
question: string,
answer: string,
note?: string,
author?: string,
}
export ... | id: {
selector: 'td:nth-child(1)',
convert: (n) => parseInt(n),
},
question: 'td:nth-child(2)',
answer: 'td:nth-child(3)',
},
},
});
const quiz = quizes.find((q) => q.id === id);
state.easyCandidates.splice(state.easyCandidates.findIndex((candidate) => candidate === id), 1);
return... | const {quizes} = await scrapeIt.scrapeHTML<Data>($, {
test: 'tbody',
quizes: {
listItem: 'tbody > tr',
data: { | random_line_split |
util.ts | -expect-error
import {hiraganize} from 'japanese';
import {random, sample, range} from 'lodash';
import scrapeIt from 'scrape-it';
import State from '../lib/state';
import {Loader} from '../lib/utils';
export interface Quiz {
id: number,
question: string,
answer: string,
note?: string,
author?: string,
}
export ... | else {
reject(new Error('values not found'));
}
});
});
const loader = new Loader<LoaderData>(async () => {
const state = await State.init<StateObj>('hayaoshi', {
users: Object.create(null),
easyCandidates: [],
itCandidates: [],
abc2019Candidates: [],
});
const auth = await new google.auth.GoogleAut... | {
resolve(response.data.values as string[][]);
} | conditional_block |
issue-18412.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 ... |
struct A(usize);
impl A {
fn bar(&self) -> usize { self.0 }
}
impl Foo for A {
fn foo(&self) -> usize { self.bar() }
}
fn main() {
let f = A::bar;
let g = Foo::foo;
let a = A(42);
assert_eq!(f(&a), g(&a));
} |
trait Foo {
fn foo(&self) -> usize;
} | random_line_split |
issue-18412.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 f = A::bar;
let g = Foo::foo;
let a = A(42);
assert_eq!(f(&a), g(&a));
}
| main | identifier_name |
polyfills.ts | /**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported... |
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************
* APPL... | // (window as any).__Zone_enable_cross_context_check = true; | random_line_split |
urdf_remove_pedestal.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2014-2015, Dataspeed Inc.
# 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 c... |
else:
rospy.logwarn("Parameter '%s' not found", param_src)
except rospy.ROSInterruptException: pass
| rospy.loginfo("Copied parameter '%s' to '%s'", param_src, param_dest) | conditional_block |
urdf_remove_pedestal.py | #!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2014-2015, Dataspeed Inc.
# 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 c... | rospy.logwarn("Failed to find joint 'pedestal_fixed'")
rospy.set_param(param_dest, urdf)
if changed:
rospy.loginfo("Updated parameter '%s'", param_dest)
else:
rospy.loginfo("Copied parameter '%s' to '%s'", param_src, param_... | else: | random_line_split |
OpinionManager.ts | /// <reference path="GameObject.ts" />
module Succession {
type OpinionRule = (opinion: Opinion) => Modifier[];
/*
* Manager of all opinions in the game.
*/
export class OpinionManager extends GameObject {
opinions: Opinion[] = [];
rules: OpinionRule[] = [];
| (callback: (child: GameObject) => void) {
this.opinions.forEach(callback);
}
/**
* Perform a single game step
*/
doStep() {
this.opinions.forEach(op => op.doStep());
}
/**
* Remove all opinions from or about a character.
... | forEachChild | identifier_name |
OpinionManager.ts | /// <reference path="GameObject.ts" />
module Succession {
type OpinionRule = (opinion: Opinion) => Modifier[];
/*
* Manager of all opinions in the game.
*/
export class OpinionManager extends GameObject {
opinions: Opinion[] = [];
rules: OpinionRule[] = [];
forEachChil... |
/**
* Return a stored opinion, or an empty one if it not yet forged.
*/
get(from: Character, about: Character): Opinion {
var result = first(this.opinions, op => op.from == from && op.about == about);
return result || new Opinion(from, about);
}
... | {
this.opinions = this.opinions.filter(ichar => ichar.from != character && ichar.about != character);
} | identifier_body |
OpinionManager.ts | /// <reference path="GameObject.ts" />
module Succession {
type OpinionRule = (opinion: Opinion) => Modifier[];
/*
* Manager of all opinions in the game.
*/
export class OpinionManager extends GameObject {
opinions: Opinion[] = [];
rules: OpinionRule[] = []; |
forEachChild(callback: (child: GameObject) => void) {
this.opinions.forEach(callback);
}
/**
* Perform a single game step
*/
doStep() {
this.opinions.forEach(op => op.doStep());
}
/**
* Remove all opinions from or abou... | random_line_split | |
hessian_identity_list.py | from dolfin import *
from dolfin_adjoint import *
parameters["adjoint"]["cache_factorizations"] = True
mesh = UnitSquareMesh(3, 3)
V = FunctionSpace(mesh, "R", 0)
test = TestFunction(V)
trial = TrialFunction(V)
def main(m):
u = interpolate(Constant(0.1), V, name="Solution")
F = inner(u*u, test)*dx - inner(... | assert minconv > 2.9 | random_line_split | |
hessian_identity_list.py | from dolfin import *
from dolfin_adjoint import *
parameters["adjoint"]["cache_factorizations"] = True
mesh = UnitSquareMesh(3, 3)
V = FunctionSpace(mesh, "R", 0)
test = TestFunction(V)
trial = TrialFunction(V)
def main(m):
u = interpolate(Constant(0.1), V, name="Solution")
F = inner(u*u, test)*dx - inner(... |
direction = [interpolate(Constant(0.1), V)]
minconv = taylor_test(Jhat, controls, Jm, dJdm, HJm=HJm,
perturbation_direction=direction)
assert minconv > 2.9
| m = m[0] # the control is a list of length one, so Jhat will have to
# except a list as well
u = main(m)
return assemble(inner(u, u)**3*dx + inner(m, m)*dx) | identifier_body |
hessian_identity_list.py | from dolfin import *
from dolfin_adjoint import *
parameters["adjoint"]["cache_factorizations"] = True
mesh = UnitSquareMesh(3, 3)
V = FunctionSpace(mesh, "R", 0)
test = TestFunction(V)
trial = TrialFunction(V)
def main(m):
u = interpolate(Constant(0.1), V, name="Solution")
F = inner(u*u, test)*dx - inner(... | minconv = taylor_test(Jhat, controls, Jm, dJdm, HJm=HJm,
perturbation_direction=direction)
assert minconv > 2.9
| m = interpolate(Constant(2.13), V, name="Parameter1")
u = main(m)
parameters["adjoint"]["stop_annotating"] = True
J = Functional((inner(u, u))**3*dx + inner(m, m)*dx, name="NormSquared")
Jm = assemble(inner(u, u)**3*dx + inner(m, m)*dx)
controls = [Control(m)]
dJdm = compute_gradient(J, cont... | conditional_block |
hessian_identity_list.py | from dolfin import *
from dolfin_adjoint import *
parameters["adjoint"]["cache_factorizations"] = True
mesh = UnitSquareMesh(3, 3)
V = FunctionSpace(mesh, "R", 0)
test = TestFunction(V)
trial = TrialFunction(V)
def main(m):
u = interpolate(Constant(0.1), V, name="Solution")
F = inner(u*u, test)*dx - inner(... | (m):
m = m[0] # the control is a list of length one, so Jhat will have to
# except a list as well
u = main(m)
return assemble(inner(u, u)**3*dx + inner(m, m)*dx)
direction = [interpolate(Constant(0.1), V)]
minconv = taylor_test(Jhat, controls, Jm, dJdm, HJm=HJm,
... | Jhat | identifier_name |
LexerParser.py | kita' : 'GT',
#'maslovemosya' : 'LEQ',
#'maslovekita' : 'GEQ',
#'pataskami' : 'EQ',
#'lamangsiya' : 'NEQ',
#'basted' : 'NOT',
#'ot' : 'OR',
#'at' : 'AND',
}
tokens = [
'INT','FLOAT', 'EOL','ID','... |
def p_program_print(self, t):
'''statement : PRINT OPENPAR STRING CLOSEPAR EOL statement
| PRINT OPENPAR statement CLOSEPAR EOL statement'''
#state = i + 1
statementlist.append(t[3])
#print(t[3])
#print(statementlist)
#print(state)
def p_prog... | random_line_split | |
LexerParser.py | [^"\\n\\r\\\\]|(?:"")|(?:\\\\x[0-9a-fA-F]+)|(?:\\\\.))*")|(?:\'(?:[^\'\\n\\r\\\\]|(?:\'\')|(?:\\\\x[0-9a-fA-F]+)| (?:\\\\.))*\')'
t.value = eval(t.value)
t.value[1:-1]
return t
# Tokens
t_COMMA = r'\,'
t_EOL = r';'
#t_QUOTE = r'\"'
t_OPENCURLY = r... | input() | conditional_block | |
LexerParser.py | ?:\\\\x[0-9a-fA-F]+)| (?:\\\\.))*\')'
t.value = eval(t.value)
t.value[1:-1]
return t
# Tokens
t_COMMA = r'\,'
t_EOL = r';'
#t_QUOTE = r'\"'
t_OPENCURLY = r'\{'
t_CLOSECURLY = r'\}'
#t_OPENBRACE = r'\['
#t_CLOSEBRACE = r'\]'
... | 'endprog : END INT EOL'
#print(statementlist)
#print(names)
x = len(statementlist)
for i in range(0, x):
if(statementlist[x-1]=='SCANVALUE'):
input()
else: print(statementlist[x-1])
x = x-1
if t[2] == 0 : t[0] = 0
... | identifier_body | |
LexerParser.py | ita' : 'GT',
#'maslovemosya' : 'LEQ',
#'maslovekita' : 'GEQ',
#'pataskami' : 'EQ',
#'lamangsiya' : 'NEQ',
#'basted' : 'NOT',
#'ot' : 'OR',
#'at' : 'AND',
}
tokens = [
'INT','FLOAT', 'EOL','ID','S... | (self, t):
'nextdecl : COMMA ID ASSIGN value nextdecl '
variableNames.append(t[2])
names[t[2]]=t[4]
def p_program_emptydecl(self, t):
'nextdecl : empty'
def p_program_number(self, t):
'''value : INT
| FLOAT'''
t[0] = t[1]
def p_program_t... | p_program_declassign | identifier_name |
PackageManualDataset.py | )
if os.path.isdir('%s/Packages' % qa2_dir) == False:
os.mkdir('Packages')
os.chdir('Packages')
package_dir = os.getcwd()
#Copying in the scriptForPI.py
os.system('cp -f /users/thunter/AIV/science/qa2/scriptForPI.py %s/%s_%s' % (qa2_dir, datadict['code'], datadict['mous']))
#Getting the cycle number for the s... | PI = raw_input('What is the PI user ID? (from ALMA_Data_Delivery):').strip()
mousid=mous.replace(':','_').replace('/','_')
mous_dir = mousid.split('_')[-1]
datadict = ReadDataFromWeb(mousid)
qa2_dir = '/lustre/naasc/sciops/qa2/%s' % username
# ---------------------------
#running the packager
if os.path.isfile('%s/%... | # ---------------------------
#prerequisites
username = raw_input('What is your lustre username?:').strip()
mous = raw_input('What is the MOUS code? (from SCOPS-ticket):').strip() | random_line_split |
PackageManualDataset.py | )
if os.path.isdir('%s/Packages' % qa2_dir) == False:
os.mkdir('Packages')
os.chdir('Packages')
package_dir = os.getcwd()
#Copying in the scriptForPI.py
os.system('cp -f /users/thunter/AIV/science/qa2/scriptForPI.py %s/%s_%s' % (qa2_dir, datadict['code'], datadict['mous']))
#Getting the cycle number for the s... | (datadict, username, PI, qa2_dir):
# --------------------------------------------------------------------------------------------------
'''
This takes care of putting the SRDP (calibrated_final.ms) in the proprietary area for the PI to pickup
'''
import os
import glob
import sys
#substituting in the PI code
... | ProprietaryAccess | identifier_name |
PackageManualDataset.py | was still Cycle 2 and all C2 projects start with 2013 (there was no call in 2014)
if datadict['code'].startswith('2015'):
style = 'cycle3-nopipe'
if datadict['code'].startswith('2016'):
style = 'cycle4-nopipe'
#writing instructions to run in CASA (these are CASA functions)
packaging_instructions = open('Packa... | cycle = '4'
os.system('mv %s_%s_001_of_001.tar /lustre/naasc/sciops/cycle4_release' % (datadict['code'], datadict['mous']))
os.system('rm %s.ticket.tar' % datadict['code'])
os.system('rm %s.ticket.zip' % datadict['code']) | conditional_block | |
PackageManualDataset.py | style = 'cycle2-nopipe'
#there are no projects that start with 2014, this was still Cycle 2 and all C2 projects start with 2013 (there was no call in 2014)
if datadict['code'].startswith('2015'):
style = 'cycle3-nopipe'
if datadict['code'].startswith('2016'):
style = 'cycle4-nopipe'
#writing instructions to ... | '''
#Running the QA2 Packaging (creates the tarballs and directory to be checked by DRMs)
'''
import os
import glob
import subprocess
#moving to user's qa2 directory and checking if Packages directory is there -- if not, create it
os.chdir(qa2_dir)
if os.path.isdir('%s/Packages' % qa2_dir) == False:
os.mkdi... | identifier_body | |
trait-inheritance-self-in-supertype.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 ... | (&self, other: &f64, epsilon: &f64) -> bool {
(*self - *other).abs() < *epsilon
}
}
impl Float for f64 {
fn two_pi() -> f64 { 6.28318530717958647692528676655900576_f64 }
}
fn compare<F:Float>(f1: F) -> bool {
let f2 = Float::two_pi();
f1.fuzzy_eq(&f2)
}
pub fn main() {
assert!(compare::<f... | fuzzy_eq_eps | identifier_name |
trait-inheritance-self-in-supertype.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 ... | }
pub fn main() {
assert!(compare::<f32>(6.28318530717958647692528676655900576));
assert!(compare::<f32>(6.29));
assert!(compare::<f32>(6.3));
assert!(compare::<f32>(6.19));
assert!(!compare::<f32>(7.28318530717958647692528676655900576));
assert!(!compare::<f32>(6.18));
assert!(compare::<f... | random_line_split | |
trait-inheritance-self-in-supertype.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 fuzzy_eq_eps(&self, other: &f32, epsilon: &f32) -> bool {
(*self - *other).abs() < *epsilon
}
}
impl Float for f32 {
fn two_pi() -> f32 { 6.28318530717958647692528676655900576_f32 }
}
impl FuzzyEq<f64> for f64 {
fn fuzzy_eq(&self, other: &f64) -> bool {
self.fuzzy_eq_eps(other, &(... | {
self.fuzzy_eq_eps(other, &(FUZZY_EPSILON as f32))
} | identifier_body |
helpers.py | import csv
import os
import random
import svm_classifier
def get_classifier_filename(classifier_name):
dir_name = os.path.dirname(os.path.realpath(__file__))
return os.path.join(dir_name, 'classifiers', classifier_name + '.pkl')
def get_image_split(csv_filename, image_folder):
# Get image names and cla... | image_classes[image_name] = int(row[1])
random.shuffle(image_names)
train_ratio = 0.75
train_num = int(train_ratio * len(image_names))
train_filenames = image_names[:train_num]
test_filenames = image_names[train_num:]
return train_filenames, test_filenames, image_classes
def get_... | random_line_split | |
helpers.py | import csv
import os
import random
import svm_classifier
def get_classifier_filename(classifier_name):
|
def get_image_split(csv_filename, image_folder):
# Get image names and classifications
image_names = []
image_classes = {}
with open(csv_filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
# skip the first row
if row[1] == 'level':
... | dir_name = os.path.dirname(os.path.realpath(__file__))
return os.path.join(dir_name, 'classifiers', classifier_name + '.pkl') | identifier_body |
helpers.py | import csv
import os
import random
import svm_classifier
def get_classifier_filename(classifier_name):
dir_name = os.path.dirname(os.path.realpath(__file__))
return os.path.join(dir_name, 'classifiers', classifier_name + '.pkl')
def get_image_split(csv_filename, image_folder):
# Get image names and cla... | (image_folder):
image_names = []
image_classes = {}
for image_class in range(5):
class_image_names = os.listdir(image_folder + '/' + str(image_class))
class_image_names = [image_folder + '/' + str(image_class) + '/' + name
for name in class_image_names]
i... | get_image_split2 | identifier_name |
helpers.py | import csv
import os
import random
import svm_classifier
def get_classifier_filename(classifier_name):
dir_name = os.path.dirname(os.path.realpath(__file__))
return os.path.join(dir_name, 'classifiers', classifier_name + '.pkl')
def get_image_split(csv_filename, image_folder):
# Get image names and cla... | raise ValueError('invalid classifier: ' + str(classifier_name)) | conditional_block | |
retrofit_favicons.js | var favicon = require('./includes/favicon.js');
var feed = require('./includes/feed.js');
| var retrofitIcon = function (f, callback) {
console.log("Checking ", f.htmlUrl);
favicon.find(f.htmlUrl, function (favicon_url) {
f.icon = favicon_url;
feed.update(f, function (err, data) {
callback(err, data);
});
});
};
// retrofit "icon" image urls to each feed
feed.readAll(function (allFeed... | random_line_split | |
retrofit_favicons.js | var favicon = require('./includes/favicon.js');
var feed = require('./includes/feed.js');
var retrofitIcon = function (f, callback) {
console.log("Checking ", f.htmlUrl);
favicon.find(f.htmlUrl, function (favicon_url) {
f.icon = favicon_url;
feed.update(f, function (err, data) {
callback(err, data);
... |
});
| {
f = allFeeds[i];
if (typeof f.icon === "undefined" || f.icon === null) {
retrofitIcon(f, function (err, data) {
console.log(err, data);
});
}
} | conditional_block |
checkDetectPort.js | 'use strict';
const chalk = require('chalk');
const detect = require('detect-port-alt');
const getProcessForPort = require('./getProcessForPort');
function isRoot() {
return process.getuid && process.getuid() === 0;
}
function checkDetectPort(port, host) {
port = parseInt(port, 10) || 0;
return new Promise((resol... | }
}
});
});
}
module.exports = checkDetectPort;
| {
let message = `目前 ${chalk.bold(port)} 端口被占用`;
if (
process.platform !== 'win32' &&
port < 1024 &&
!isRoot()
) {
message =
'`在1024以下的端口上运行服务器需要管理员权限`';
}
const existingProcess = getProcessForPort(port);
if (existingProcess) {
message += `,该端口使用情况:\n ... | conditional_block |
checkDetectPort.js | 'use strict';
const chalk = require('chalk');
const detect = require('detect-port-alt');
const getProcessForPort = require('./getProcessForPort');
function isRoot() {
return process.getuid && process.getuid() === 0;
}
function | (port, host) {
port = parseInt(port, 10) || 0;
return new Promise((resolve, reject) => {
detect(port, host, (err, _port) => {
if (err) {
reject(err);
} else {
if (port === _port) {
resolve(port);
} else {
let message = `目前 ${chalk.bold(port)} 端口被占用`;
if (
process.platform !==... | checkDetectPort | identifier_name |
checkDetectPort.js | 'use strict';
const chalk = require('chalk');
const detect = require('detect-port-alt');
const getProcessForPort = require('./getProcessForPort');
function isRoot() |
function checkDetectPort(port, host) {
port = parseInt(port, 10) || 0;
return new Promise((resolve, reject) => {
detect(port, host, (err, _port) => {
if (err) {
reject(err);
} else {
if (port === _port) {
resolve(port);
} else {
let message = `目前 ${chalk.bold(port)} 端口被占用`;
if (
... | {
return process.getuid && process.getuid() === 0;
} | identifier_body |
checkDetectPort.js | 'use strict';
const chalk = require('chalk');
const detect = require('detect-port-alt');
const getProcessForPort = require('./getProcessForPort');
function isRoot() {
return process.getuid && process.getuid() === 0;
}
function checkDetectPort(port, host) {
port = parseInt(port, 10) || 0;
return new Promise((resol... | if (port === _port) {
resolve(port);
} else {
let message = `目前 ${chalk.bold(port)} 端口被占用`;
if (
process.platform !== 'win32' &&
port < 1024 &&
!isRoot()
) {
message =
'`在1024以下的端口上运行服务器需要管理员权限`';
}
const existingProcess = getProcessForPort(port);
... | if (err) {
reject(err);
} else { | random_line_split |
filter_dates.py | '''
Filter text output by date ranges
'''
import os
import csv
import sys
import dateutil.parser
import argparse
import metadata
settings = None
def get_settings():
''' Return command-line settings '''
parser = argparse.ArgumentParser(description='Filter text corpus by date range. Only updates the metadata file.'... |
if __name__ == '__main__':
if sys.version_info < (3,0):
print("This script requires Python 3")
exit(-1)
main()
| global settings
settings = get_settings()
md = metadata.read_csv(settings.input)
filtered = filter_dates(md, settings.start, settings.end)
metadata.write_csv(settings.output, filtered) | identifier_body |
filter_dates.py | '''
Filter text output by date ranges
'''
import os
import csv
import sys
import dateutil.parser
import argparse
import metadata
settings = None
def get_settings():
''' Return command-line settings '''
parser = argparse.ArgumentParser(description='Filter text corpus by date range. Only updates the metadata file.'... | return parser.parse_args()
def filter_dates(metadata, start, end):
results = list()
if start is not None:
start = dateutil.parser.parse(start)
if end is not None:
end = dateutil.parser.parse(end)
for row in metadata:
try:
date = dateutil.parser.parse(row['date'])
except ValueError as er... | parser.add_argument('-o', dest='output', required=True,
help='Output CSV for filtered results')
parser.add_argument('-s', '--start', dest='start', help='Start date, YYYY-MM-DD format')
parser.add_argument('-e', '--end', dest='end', help='End date, YYYY-MM-DD format') | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.