file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
material-checkbox.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { hasOwn } from './../../shared/utility.functions'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-checkbox-widget', template: ` <md-checkbox *ngIf="isConditionallyShown()" align="left" [color]="options?.color || 'primary'" [disabled]="controlDisabled || options?.readonly" [id]="'control' + layoutNode?._id" [name]="controlName" [checked]="isChecked" (change)="updateValue($event)"> <span *ngIf="options?.title" class="checkbox-name" [style.display]="options?.notitle ? 'none' : ''" [innerHTML]="options?.title"></span> </md-checkbox>`, styles: [` .checkbox-name { white-space: nowrap; } `], }) export class MaterialCheckboxComponent implements OnInit { formControl: AbstractControl; controlName: string; controlValue: any; controlDisabled: boolean = false; boundControl: boolean = false; options: any; trueValue: any = true; falseValue: any = false; @Input() formID: number; @Input() layoutNode: any; @Input() layoutIndex: number[]; @Input() dataIndex: number[]; @Input() data:any; constructor( private jsf: JsonSchemaFormService ) { }
() { this.options = this.layoutNode.options || {}; this.jsf.initializeControl(this); if (this.controlValue === null || this.controlValue === undefined) { this.controlValue = false; } } updateValue(event) { this.jsf.updateValue(this, event.checked ? this.trueValue : this.falseValue); } get isChecked() { return this.jsf.getFormControlValue(this) === this.trueValue; } isConditionallyShown(): boolean { this.data = this.jsf.data; let result: boolean = true; if (this.data && hasOwn(this.options, 'condition')) { const model = this.data; /* tslint:disable */ eval('result = ' + this.options.condition); /* tslint:enable */ } return result; } }
ngOnInit
identifier_name
material-checkbox.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { hasOwn } from './../../shared/utility.functions'; import { JsonSchemaFormService } from '../../json-schema-form.service'; @Component({ selector: 'material-checkbox-widget', template: ` <md-checkbox *ngIf="isConditionallyShown()" align="left" [color]="options?.color || 'primary'" [disabled]="controlDisabled || options?.readonly" [id]="'control' + layoutNode?._id" [name]="controlName" [checked]="isChecked" (change)="updateValue($event)"> <span *ngIf="options?.title" class="checkbox-name" [style.display]="options?.notitle ? 'none' : ''" [innerHTML]="options?.title"></span> </md-checkbox>`, styles: [` .checkbox-name { white-space: nowrap; } `], }) export class MaterialCheckboxComponent implements OnInit { formControl: AbstractControl; controlName: string; controlValue: any; controlDisabled: boolean = false; boundControl: boolean = false; options: any; trueValue: any = true; falseValue: any = false; @Input() formID: number; @Input() layoutNode: any; @Input() layoutIndex: number[]; @Input() dataIndex: number[]; @Input() data:any; constructor( private jsf: JsonSchemaFormService ) { } ngOnInit() { this.options = this.layoutNode.options || {}; this.jsf.initializeControl(this); if (this.controlValue === null || this.controlValue === undefined)
} updateValue(event) { this.jsf.updateValue(this, event.checked ? this.trueValue : this.falseValue); } get isChecked() { return this.jsf.getFormControlValue(this) === this.trueValue; } isConditionallyShown(): boolean { this.data = this.jsf.data; let result: boolean = true; if (this.data && hasOwn(this.options, 'condition')) { const model = this.data; /* tslint:disable */ eval('result = ' + this.options.condition); /* tslint:enable */ } return result; } }
{ this.controlValue = false; }
conditional_block
mod.rs
////////////////////////////////////////////////////////////////////////////// // File: rust-worldgen/noise/perlin/mod.rs ////////////////////////////////////////////////////////////////////////////// // Copyright 2015 Samuel Sleight // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ////////////////////////////////////////////////////////////////////////////// //! A provider of perlin noise. //! //! Perlin noise is generated by combining a number of different values //! of coherent noise (known as octaves). //! //! The perlin noise source has a number of different properties that can //! be customised: the number of octaves, and the frequency, persistence, //! and lacunarity of the noise. use std::default::Default; use super::NoiseProvider; use super::coherent::CoherentNoise; pub use self::property::{Octaves, Frequency, Persistence, Lacunarity}; use self::property::Property; mod property; /// The perlin noise source /// /// # Example ///
/// # use worldgen::noise::perlin::{PerlinNoise, Octaves}; /// # use worldgen::noise::NoiseProvider; /// let noise = PerlinNoise::new() /// .set(Octaves::of(5)); /// /// let value = noise.generate(1.5, 2.5, 15); /// ``` #[derive(Default, Debug, Copy, Clone)] pub struct PerlinNoise { octaves: Octaves, freq: Frequency, pers: Persistence, lacu: Lacunarity } impl PerlinNoise { /// Construct the default perlin source. /// /// The default values are: /// /// ```text /// octaves = 8 /// frequency = 1.0 /// persistence = 0.5 /// lacunarity = 2.0 /// ``` pub fn new() -> PerlinNoise { Default::default() } /// Set a property on the noise source. pub fn set<T: Property>(self, property: T) -> PerlinNoise { property.set_to(self) } fn set_octaves(self, octaves: Octaves) -> PerlinNoise { PerlinNoise { octaves, ..self } } fn set_frequency(self, freq: Frequency) -> PerlinNoise { PerlinNoise { freq, ..self } } fn set_persistence(self, pers: Persistence) -> PerlinNoise { PerlinNoise { pers, ..self } } fn set_lacunarity(self, lacu: Lacunarity) -> PerlinNoise { PerlinNoise { lacu, ..self } } } impl NoiseProvider for PerlinNoise { fn generate(&self, x: f64, y: f64, seed: u64) -> f64 { let mut x = x * self.freq.value; let mut y = y * self.freq.value; let mut pers = 1.0f64; (0 .. self.octaves.value).fold(0.0, |value, octave| { let seed = seed + octave as u64; let value = value + CoherentNoise.generate(x, y, seed) * pers; x *= self.lacu.value; y *= self.lacu.value; pers *= self.pers.value; value }) } }
/// ```
random_line_split
mod.rs
////////////////////////////////////////////////////////////////////////////// // File: rust-worldgen/noise/perlin/mod.rs ////////////////////////////////////////////////////////////////////////////// // Copyright 2015 Samuel Sleight // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ////////////////////////////////////////////////////////////////////////////// //! A provider of perlin noise. //! //! Perlin noise is generated by combining a number of different values //! of coherent noise (known as octaves). //! //! The perlin noise source has a number of different properties that can //! be customised: the number of octaves, and the frequency, persistence, //! and lacunarity of the noise. use std::default::Default; use super::NoiseProvider; use super::coherent::CoherentNoise; pub use self::property::{Octaves, Frequency, Persistence, Lacunarity}; use self::property::Property; mod property; /// The perlin noise source /// /// # Example /// /// ``` /// # use worldgen::noise::perlin::{PerlinNoise, Octaves}; /// # use worldgen::noise::NoiseProvider; /// let noise = PerlinNoise::new() /// .set(Octaves::of(5)); /// /// let value = noise.generate(1.5, 2.5, 15); /// ``` #[derive(Default, Debug, Copy, Clone)] pub struct PerlinNoise { octaves: Octaves, freq: Frequency, pers: Persistence, lacu: Lacunarity } impl PerlinNoise { /// Construct the default perlin source. /// /// The default values are: /// /// ```text /// octaves = 8 /// frequency = 1.0 /// persistence = 0.5 /// lacunarity = 2.0 /// ``` pub fn new() -> PerlinNoise { Default::default() } /// Set a property on the noise source. pub fn set<T: Property>(self, property: T) -> PerlinNoise { property.set_to(self) } fn
(self, octaves: Octaves) -> PerlinNoise { PerlinNoise { octaves, ..self } } fn set_frequency(self, freq: Frequency) -> PerlinNoise { PerlinNoise { freq, ..self } } fn set_persistence(self, pers: Persistence) -> PerlinNoise { PerlinNoise { pers, ..self } } fn set_lacunarity(self, lacu: Lacunarity) -> PerlinNoise { PerlinNoise { lacu, ..self } } } impl NoiseProvider for PerlinNoise { fn generate(&self, x: f64, y: f64, seed: u64) -> f64 { let mut x = x * self.freq.value; let mut y = y * self.freq.value; let mut pers = 1.0f64; (0 .. self.octaves.value).fold(0.0, |value, octave| { let seed = seed + octave as u64; let value = value + CoherentNoise.generate(x, y, seed) * pers; x *= self.lacu.value; y *= self.lacu.value; pers *= self.pers.value; value }) } }
set_octaves
identifier_name
mod.rs
////////////////////////////////////////////////////////////////////////////// // File: rust-worldgen/noise/perlin/mod.rs ////////////////////////////////////////////////////////////////////////////// // Copyright 2015 Samuel Sleight // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ////////////////////////////////////////////////////////////////////////////// //! A provider of perlin noise. //! //! Perlin noise is generated by combining a number of different values //! of coherent noise (known as octaves). //! //! The perlin noise source has a number of different properties that can //! be customised: the number of octaves, and the frequency, persistence, //! and lacunarity of the noise. use std::default::Default; use super::NoiseProvider; use super::coherent::CoherentNoise; pub use self::property::{Octaves, Frequency, Persistence, Lacunarity}; use self::property::Property; mod property; /// The perlin noise source /// /// # Example /// /// ``` /// # use worldgen::noise::perlin::{PerlinNoise, Octaves}; /// # use worldgen::noise::NoiseProvider; /// let noise = PerlinNoise::new() /// .set(Octaves::of(5)); /// /// let value = noise.generate(1.5, 2.5, 15); /// ``` #[derive(Default, Debug, Copy, Clone)] pub struct PerlinNoise { octaves: Octaves, freq: Frequency, pers: Persistence, lacu: Lacunarity } impl PerlinNoise { /// Construct the default perlin source. /// /// The default values are: /// /// ```text /// octaves = 8 /// frequency = 1.0 /// persistence = 0.5 /// lacunarity = 2.0 /// ``` pub fn new() -> PerlinNoise { Default::default() } /// Set a property on the noise source. pub fn set<T: Property>(self, property: T) -> PerlinNoise { property.set_to(self) } fn set_octaves(self, octaves: Octaves) -> PerlinNoise { PerlinNoise { octaves, ..self } } fn set_frequency(self, freq: Frequency) -> PerlinNoise { PerlinNoise { freq, ..self } } fn set_persistence(self, pers: Persistence) -> PerlinNoise { PerlinNoise { pers, ..self } } fn set_lacunarity(self, lacu: Lacunarity) -> PerlinNoise
} impl NoiseProvider for PerlinNoise { fn generate(&self, x: f64, y: f64, seed: u64) -> f64 { let mut x = x * self.freq.value; let mut y = y * self.freq.value; let mut pers = 1.0f64; (0 .. self.octaves.value).fold(0.0, |value, octave| { let seed = seed + octave as u64; let value = value + CoherentNoise.generate(x, y, seed) * pers; x *= self.lacu.value; y *= self.lacu.value; pers *= self.pers.value; value }) } }
{ PerlinNoise { lacu, ..self } }
identifier_body
neutralField1D.py
#!/usr/bin/env python """ Tweak of profile plots as a function of nn. """ import pickle import matplotlib.pylab as plt import matplotlib.lines as mlines import numpy as np from subprocess import Popen import os, sys # If we add to sys.path, then it must be an absolute path commonDir = os.path.abspath("./../../../common") # Sys path is a list of system paths sys.path.append(commonDir) from CELMAPy.plotHelpers import PlotHelper, seqCMap3 scans = (\ "nn_9.9e+20" ,\ "nn_4e+19" ,\ "nn_1.5e+19" ,\ "nn_6.666666666666668e+18",\ "nn_2.5e+18" ,\ ) markers = ("*", "o", "s", "v", "^") ls = (\ (0, ()),\ (0, (5, 5)),\ (0, (3, 1, 1, 1)),\ (0, (3, 1, 1, 1, 1, 1)),\ (0, (1, 1)),\ ) fields = ("n", "phi", "jPar", "om", "ui", "sA", "ue") sD =\ {s:{f:\ {"ax":None,"line":None,"ls":l,"marker":m,"color":None}\ for f in fields}\ for s, m, l in zip(scans, markers, ls)} for direction in ("radial", "parallel"): for scan in scans: folder = "../../CSDXNeutralScanAr/visualizationPhysical/{}/field1D".format(scan) picklePath = os.path.join(folder,\ "mainFields-{}-1D-0.pickle".format(direction)) with open(picklePath, "rb") as f: fig = pickle.load(f) lnAx, phiAx, nAx, omDAx, jParAx, omAx, uiAx, nuiAx, ueAx, sAx =\ fig.get_axes() # Swap axes phiAx.set_position(omDAx.get_position()) sAx .set_position(nuiAx.get_position()) fig.delaxes(lnAx) fig.delaxes(omDAx) fig.delaxes(nuiAx) # Modify title position
pos[1] = 0.75 t.set_position(pos) t.set_va("bottom") # Color adjust axes = (nAx, phiAx, jParAx, omAx, uiAx, sAx, ueAx) colors = seqCMap3(np.linspace(0, 1, len(axes))) # Recolor the lines for ax, color in zip(axes, colors): line = ax.get_lines()[0] line.set_color(color) # NOTE: Using the designated setter gives a comparion error line._markerfacecolor = color line._markeredgecolor = color # Set the colors sD[scan]["n"] ["color"] = colors[0] sD[scan]["phi"] ["color"] = colors[1] sD[scan]["jPar"]["color"] = colors[2] sD[scan]["om"] ["color"] = colors[3] sD[scan]["ui"] ["color"] = colors[4] sD[scan]["sA"] ["color"] = colors[5] sD[scan]["ue"] ["color"] = colors[6] # Set the lines sD[scan]["n"] ["line"] = nAx .get_lines()[0].get_data()[1] sD[scan]["phi"] ["line"] = phiAx .get_lines()[0].get_data()[1] sD[scan]["jPar"]["line"] = jParAx.get_lines()[0].get_data()[1] sD[scan]["om"] ["line"] = omAx .get_lines()[0].get_data()[1] sD[scan]["ui"] ["line"] = uiAx .get_lines()[0].get_data()[1] sD[scan]["sA"] ["line"] = sAx .get_lines()[0].get_data()[1] sD[scan]["ue"] ["line"] = ueAx .get_lines()[0].get_data()[1] xAxis = nAx.get_lines()[0].get_data()[0] # Clear the axes for ax in axes: ax.get_lines()[0].set_data((None,), (None,)) sD[scan]["n"] ["ax"] = nAx sD[scan]["phi"] ["ax"] = phiAx sD[scan]["jPar"]["ax"] = jParAx sD[scan]["om"] ["ax"] = omAx sD[scan]["ui"] ["ax"] = uiAx sD[scan]["sA"] ["ax"] = sAx sD[scan]["ue"] ["ax"] = ueAx # Plot for scan in scans: fig = sD[scans[0]]["n"]["ax"].figure for key in sD[scans[0]].keys(): sD[scans[0]][key]["ax"].plot(xAxis,\ sD[scan][key]["line"],\ color = sD[scan][key]["color"],\ marker = sD[scan][key]["marker"],\ ms = 5,\ markevery = 7,\ alpha = 0.7,\ ls = sD[scan][key]["ls"],\ ) sD[scans[0]][key]["ax"].autoscale(enable=True, axis="y", tight=True) # Put the legends on the y-axis handles, labels = sD[scans[0]][key]["ax"].get_legend_handles_labels() leg = sD[scans[0]][key]["ax"].legend() leg.remove() # Decrease fontsize by 1 to get some spacing sD[scans[0]][key]["ax"].set_ylabel(labels[0], fontsize=11) # Manually ajust the wspace as fig.subplots_adjust messes with the # spacing for key in ("phi", "om", "sA"): pos = sD[scans[0]][key]["ax"].get_position() pos = (pos.x0 + 0.05, pos.y0, pos.width, pos.height) sD[scans[0]][key]["ax"].set_position(pos) # Manually creating the legend handles = [] # Used for conversion n0 = 1e19 for scan in scans: curScan = n0/(n0+float(scan[3:]))*100 label = r"$d = {:d} \;\%$".format(int(curScan)) handle = mlines.Line2D([], [],\ color = "k" ,\ marker = sD[scan]["n"]["marker"],\ ls = sD[scan]["n"]["ls"] ,\ ms = 5 ,\ alpha = 0.7 ,\ label =label) handles.append(handle) # Put legends outside sD[scans[0]]["ue"]["ax"].legend(handles=handles,\ ncol=2,\ bbox_to_anchor=(1.15, 0.25),\ loc="upper left",\ borderaxespad=0.,\ bbox_transform =\ sD[scans[0]]["ue"]["ax"].transAxes,\ ) if direction == "radial": fileName = "nnScanRad.pdf" elif direction == "parallel": fileName = "nnScanPar.pdf" PlotHelper.savePlot(fig, fileName)
t = fig.texts[0] pos = list(t.get_position())
random_line_split
neutralField1D.py
#!/usr/bin/env python """ Tweak of profile plots as a function of nn. """ import pickle import matplotlib.pylab as plt import matplotlib.lines as mlines import numpy as np from subprocess import Popen import os, sys # If we add to sys.path, then it must be an absolute path commonDir = os.path.abspath("./../../../common") # Sys path is a list of system paths sys.path.append(commonDir) from CELMAPy.plotHelpers import PlotHelper, seqCMap3 scans = (\ "nn_9.9e+20" ,\ "nn_4e+19" ,\ "nn_1.5e+19" ,\ "nn_6.666666666666668e+18",\ "nn_2.5e+18" ,\ ) markers = ("*", "o", "s", "v", "^") ls = (\ (0, ()),\ (0, (5, 5)),\ (0, (3, 1, 1, 1)),\ (0, (3, 1, 1, 1, 1, 1)),\ (0, (1, 1)),\ ) fields = ("n", "phi", "jPar", "om", "ui", "sA", "ue") sD =\ {s:{f:\ {"ax":None,"line":None,"ls":l,"marker":m,"color":None}\ for f in fields}\ for s, m, l in zip(scans, markers, ls)} for direction in ("radial", "parallel"): for scan in scans: folder = "../../CSDXNeutralScanAr/visualizationPhysical/{}/field1D".format(scan) picklePath = os.path.join(folder,\ "mainFields-{}-1D-0.pickle".format(direction)) with open(picklePath, "rb") as f: fig = pickle.load(f) lnAx, phiAx, nAx, omDAx, jParAx, omAx, uiAx, nuiAx, ueAx, sAx =\ fig.get_axes() # Swap axes phiAx.set_position(omDAx.get_position()) sAx .set_position(nuiAx.get_position()) fig.delaxes(lnAx) fig.delaxes(omDAx) fig.delaxes(nuiAx) # Modify title position t = fig.texts[0] pos = list(t.get_position()) pos[1] = 0.75 t.set_position(pos) t.set_va("bottom") # Color adjust axes = (nAx, phiAx, jParAx, omAx, uiAx, sAx, ueAx) colors = seqCMap3(np.linspace(0, 1, len(axes))) # Recolor the lines for ax, color in zip(axes, colors): line = ax.get_lines()[0] line.set_color(color) # NOTE: Using the designated setter gives a comparion error line._markerfacecolor = color line._markeredgecolor = color # Set the colors sD[scan]["n"] ["color"] = colors[0] sD[scan]["phi"] ["color"] = colors[1] sD[scan]["jPar"]["color"] = colors[2] sD[scan]["om"] ["color"] = colors[3] sD[scan]["ui"] ["color"] = colors[4] sD[scan]["sA"] ["color"] = colors[5] sD[scan]["ue"] ["color"] = colors[6] # Set the lines sD[scan]["n"] ["line"] = nAx .get_lines()[0].get_data()[1] sD[scan]["phi"] ["line"] = phiAx .get_lines()[0].get_data()[1] sD[scan]["jPar"]["line"] = jParAx.get_lines()[0].get_data()[1] sD[scan]["om"] ["line"] = omAx .get_lines()[0].get_data()[1] sD[scan]["ui"] ["line"] = uiAx .get_lines()[0].get_data()[1] sD[scan]["sA"] ["line"] = sAx .get_lines()[0].get_data()[1] sD[scan]["ue"] ["line"] = ueAx .get_lines()[0].get_data()[1] xAxis = nAx.get_lines()[0].get_data()[0] # Clear the axes for ax in axes: ax.get_lines()[0].set_data((None,), (None,)) sD[scan]["n"] ["ax"] = nAx sD[scan]["phi"] ["ax"] = phiAx sD[scan]["jPar"]["ax"] = jParAx sD[scan]["om"] ["ax"] = omAx sD[scan]["ui"] ["ax"] = uiAx sD[scan]["sA"] ["ax"] = sAx sD[scan]["ue"] ["ax"] = ueAx # Plot for scan in scans: fig = sD[scans[0]]["n"]["ax"].figure for key in sD[scans[0]].keys(): sD[scans[0]][key]["ax"].plot(xAxis,\ sD[scan][key]["line"],\ color = sD[scan][key]["color"],\ marker = sD[scan][key]["marker"],\ ms = 5,\ markevery = 7,\ alpha = 0.7,\ ls = sD[scan][key]["ls"],\ ) sD[scans[0]][key]["ax"].autoscale(enable=True, axis="y", tight=True) # Put the legends on the y-axis handles, labels = sD[scans[0]][key]["ax"].get_legend_handles_labels() leg = sD[scans[0]][key]["ax"].legend() leg.remove() # Decrease fontsize by 1 to get some spacing sD[scans[0]][key]["ax"].set_ylabel(labels[0], fontsize=11) # Manually ajust the wspace as fig.subplots_adjust messes with the # spacing for key in ("phi", "om", "sA"): pos = sD[scans[0]][key]["ax"].get_position() pos = (pos.x0 + 0.05, pos.y0, pos.width, pos.height) sD[scans[0]][key]["ax"].set_position(pos) # Manually creating the legend handles = [] # Used for conversion n0 = 1e19 for scan in scans: curScan = n0/(n0+float(scan[3:]))*100 label = r"$d = {:d} \;\%$".format(int(curScan)) handle = mlines.Line2D([], [],\ color = "k" ,\ marker = sD[scan]["n"]["marker"],\ ls = sD[scan]["n"]["ls"] ,\ ms = 5 ,\ alpha = 0.7 ,\ label =label) handles.append(handle) # Put legends outside sD[scans[0]]["ue"]["ax"].legend(handles=handles,\ ncol=2,\ bbox_to_anchor=(1.15, 0.25),\ loc="upper left",\ borderaxespad=0.,\ bbox_transform =\ sD[scans[0]]["ue"]["ax"].transAxes,\ ) if direction == "radial":
elif direction == "parallel": fileName = "nnScanPar.pdf" PlotHelper.savePlot(fig, fileName)
fileName = "nnScanRad.pdf"
conditional_block
support.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */
var React = require('React'); var Site = require('Site'); var center = require('center'); var H2 = require('H2'); var support = React.createClass({ render: function() { return ( <Site section="support"> <section className="content wrap documentationContent nosidebar"> <div className="inner-content"> <h1>Need help?</h1> <div className="subHeader"></div> <p> <strong>React Unity</strong> is worked on full-time by Unity&#39;s editor interface engineering teams. They&#39;re often around and available for questions. </p> <H2>Stack Overflow</H2> <p>Many members of the community use Stack Overflow to ask questions. Read through the <a href="http://stackoverflow.com/questions/tagged/react-unity">existing questions</a> tagged with <strong>react-native</strong> or <a href="http://stackoverflow.com/questions/ask">ask your own</a>!</p> <H2>IRC</H2> <p>Many developers and users idle on Freenode.net&#39;s IRC network in <strong><a href="irc://chat.freenode.net/reactunity">#reactunity on freenode</a></strong>.</p> <H2>Twitter</H2> <p><a href="https://twitter.com/search?q=%23reactunity"><strong>#reactunity</strong> hash tag on Twitter</a> is used to keep up with the latest React Unity news.</p> <p><center><a className="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactunity" data-widget-id="565960513457098753"></a></center></p> </div> </section> </Site> ); } }); module.exports = support;
random_line_split
list.rs
//! This module has containers for storing the tasks spawned on a scheduler. The //! `OwnedTasks` container is thread-safe but can only store tasks that //! implement Send. The `LocalOwnedTasks` container is not thread safe, but can //! store non-Send tasks. //! //! The collections can be closed to prevent adding new tasks during shutdown of //! the scheduler with the collection. use crate::future::Future; use crate::loom::cell::UnsafeCell; use crate::loom::sync::Mutex; use crate::runtime::task::{JoinHandle, LocalNotified, Notified, Schedule, Task}; use crate::util::linked_list::{Link, LinkedList}; use std::marker::PhantomData; // The id from the module below is used to verify whether a given task is stored // in this OwnedTasks, or some other task. The counter starts at one so we can // use zero for tasks not owned by any list. // // The safety checks in this file can technically be violated if the counter is // overflown, but the checks are not supposed to ever fail unless there is a // bug in Tokio, so we accept that certain bugs would not be caught if the two // mixed up runtimes happen to have the same id. cfg_has_atomic_u64! { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_OWNED_TASKS_ID: AtomicU64 = AtomicU64::new(1); fn get_next_id() -> u64 { loop { let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed); if id != 0 { return id; } } } } cfg_not_has_atomic_u64! { use std::sync::atomic::{AtomicU32, Ordering}; static NEXT_OWNED_TASKS_ID: AtomicU32 = AtomicU32::new(1); fn get_next_id() -> u64 { loop { let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed); if id != 0 { return u64::from(id); } } } } pub(crate) struct OwnedTasks<S: 'static> { inner: Mutex<OwnedTasksInner<S>>, id: u64, } pub(crate) struct LocalOwnedTasks<S: 'static> { inner: UnsafeCell<OwnedTasksInner<S>>, id: u64, _not_send_or_sync: PhantomData<*const ()>, } struct OwnedTasksInner<S: 'static> { list: LinkedList<Task<S>, <Task<S> as Link>::Target>, closed: bool, } impl<S: 'static> OwnedTasks<S> { pub(crate) fn new() -> Self { Self { inner: Mutex::new(OwnedTasksInner { list: LinkedList::new(), closed: false, }), id: get_next_id(), } } /// Binds the provided task to this OwnedTasks instance. This fails if the /// OwnedTasks has been closed. pub(crate) fn bind<T>( &self, task: T, scheduler: S, ) -> (JoinHandle<T::Output>, Option<Notified<S>>) where S: Schedule, T: Future + Send + 'static, T::Output: Send + 'static, { let (task, notified, join) = super::new_task(task, scheduler); unsafe { // safety: We just created the task, so we have exclusive access // to the field. task.header().set_owner_id(self.id); } let mut lock = self.inner.lock(); if lock.closed { drop(lock); drop(notified); task.shutdown(); (join, None) } else { lock.list.push_front(task); (join, Some(notified)) } } /// Asserts that the given task is owned by this OwnedTasks and convert it to /// a LocalNotified, giving the thread permission to poll this task. #[inline] pub(crate) fn
(&self, task: Notified<S>) -> LocalNotified<S> { assert_eq!(task.header().get_owner_id(), self.id); // safety: All tasks bound to this OwnedTasks are Send, so it is safe // to poll it on this thread no matter what thread we are on. LocalNotified { task: task.0, _not_send: PhantomData, } } /// Shuts down all tasks in the collection. This call also closes the /// collection, preventing new items from being added. pub(crate) fn close_and_shutdown_all(&self) where S: Schedule, { // The first iteration of the loop was unrolled so it can set the // closed bool. let first_task = { let mut lock = self.inner.lock(); lock.closed = true; lock.list.pop_back() }; match first_task { Some(task) => task.shutdown(), None => return, } loop { let task = match self.inner.lock().list.pop_back() { Some(task) => task, None => return, }; task.shutdown(); } } pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> { let task_id = task.header().get_owner_id(); if task_id == 0 { // The task is unowned. return None; } assert_eq!(task_id, self.id); // safety: We just checked that the provided task is not in some other // linked list. unsafe { self.inner.lock().list.remove(task.header().into()) } } pub(crate) fn is_empty(&self) -> bool { self.inner.lock().list.is_empty() } } impl<S: 'static> LocalOwnedTasks<S> { pub(crate) fn new() -> Self { Self { inner: UnsafeCell::new(OwnedTasksInner { list: LinkedList::new(), closed: false, }), id: get_next_id(), _not_send_or_sync: PhantomData, } } pub(crate) fn bind<T>( &self, task: T, scheduler: S, ) -> (JoinHandle<T::Output>, Option<Notified<S>>) where S: Schedule, T: Future + 'static, T::Output: 'static, { let (task, notified, join) = super::new_task(task, scheduler); unsafe { // safety: We just created the task, so we have exclusive access // to the field. task.header().set_owner_id(self.id); } if self.is_closed() { drop(notified); task.shutdown(); (join, None) } else { self.with_inner(|inner| { inner.list.push_front(task); }); (join, Some(notified)) } } /// Shuts down all tasks in the collection. This call also closes the /// collection, preventing new items from being added. pub(crate) fn close_and_shutdown_all(&self) where S: Schedule, { self.with_inner(|inner| inner.closed = true); while let Some(task) = self.with_inner(|inner| inner.list.pop_back()) { task.shutdown(); } } pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> { let task_id = task.header().get_owner_id(); if task_id == 0 { // The task is unowned. return None; } assert_eq!(task_id, self.id); self.with_inner(|inner| // safety: We just checked that the provided task is not in some // other linked list. unsafe { inner.list.remove(task.header().into()) }) } /// Asserts that the given task is owned by this LocalOwnedTasks and convert /// it to a LocalNotified, giving the thread permission to poll this task. #[inline] pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> { assert_eq!(task.header().get_owner_id(), self.id); // safety: The task was bound to this LocalOwnedTasks, and the // LocalOwnedTasks is not Send or Sync, so we are on the right thread // for polling this task. LocalNotified { task: task.0, _not_send: PhantomData, } } #[inline] fn with_inner<F, T>(&self, f: F) -> T where F: FnOnce(&mut OwnedTasksInner<S>) -> T, { // safety: This type is not Sync, so concurrent calls of this method // can't happen. Furthermore, all uses of this method in this file make // sure that they don't call `with_inner` recursively. self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) }) } pub(crate) fn is_closed(&self) -> bool { self.with_inner(|inner| inner.closed) } pub(crate) fn is_empty(&self) -> bool { self.with_inner(|inner| inner.list.is_empty()) } } #[cfg(all(test))] mod tests { use super::*; // This test may run in parallel with other tests, so we only test that ids // come in increasing order. #[test] fn test_id_not_broken() { let mut last_id = get_next_id(); assert_ne!(last_id, 0); for _ in 0..1000 { let next_id = get_next_id(); assert_ne!(next_id, 0); assert!(last_id < next_id); last_id = next_id; } } }
assert_owner
identifier_name
list.rs
//! This module has containers for storing the tasks spawned on a scheduler. The //! `OwnedTasks` container is thread-safe but can only store tasks that //! implement Send. The `LocalOwnedTasks` container is not thread safe, but can //! store non-Send tasks. //! //! The collections can be closed to prevent adding new tasks during shutdown of //! the scheduler with the collection. use crate::future::Future; use crate::loom::cell::UnsafeCell; use crate::loom::sync::Mutex; use crate::runtime::task::{JoinHandle, LocalNotified, Notified, Schedule, Task}; use crate::util::linked_list::{Link, LinkedList}; use std::marker::PhantomData; // The id from the module below is used to verify whether a given task is stored // in this OwnedTasks, or some other task. The counter starts at one so we can // use zero for tasks not owned by any list. // // The safety checks in this file can technically be violated if the counter is // overflown, but the checks are not supposed to ever fail unless there is a // bug in Tokio, so we accept that certain bugs would not be caught if the two // mixed up runtimes happen to have the same id. cfg_has_atomic_u64! { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_OWNED_TASKS_ID: AtomicU64 = AtomicU64::new(1); fn get_next_id() -> u64 { loop { let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed); if id != 0 { return id; } } } } cfg_not_has_atomic_u64! { use std::sync::atomic::{AtomicU32, Ordering}; static NEXT_OWNED_TASKS_ID: AtomicU32 = AtomicU32::new(1); fn get_next_id() -> u64 { loop { let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed); if id != 0 { return u64::from(id); } } } } pub(crate) struct OwnedTasks<S: 'static> { inner: Mutex<OwnedTasksInner<S>>, id: u64, } pub(crate) struct LocalOwnedTasks<S: 'static> { inner: UnsafeCell<OwnedTasksInner<S>>, id: u64, _not_send_or_sync: PhantomData<*const ()>, } struct OwnedTasksInner<S: 'static> { list: LinkedList<Task<S>, <Task<S> as Link>::Target>, closed: bool, } impl<S: 'static> OwnedTasks<S> { pub(crate) fn new() -> Self { Self { inner: Mutex::new(OwnedTasksInner { list: LinkedList::new(), closed: false, }), id: get_next_id(), } } /// Binds the provided task to this OwnedTasks instance. This fails if the /// OwnedTasks has been closed. pub(crate) fn bind<T>( &self, task: T, scheduler: S, ) -> (JoinHandle<T::Output>, Option<Notified<S>>) where S: Schedule, T: Future + Send + 'static, T::Output: Send + 'static, { let (task, notified, join) = super::new_task(task, scheduler); unsafe { // safety: We just created the task, so we have exclusive access // to the field. task.header().set_owner_id(self.id); } let mut lock = self.inner.lock(); if lock.closed { drop(lock); drop(notified); task.shutdown(); (join, None) } else { lock.list.push_front(task); (join, Some(notified)) } } /// Asserts that the given task is owned by this OwnedTasks and convert it to /// a LocalNotified, giving the thread permission to poll this task. #[inline] pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> { assert_eq!(task.header().get_owner_id(), self.id); // safety: All tasks bound to this OwnedTasks are Send, so it is safe // to poll it on this thread no matter what thread we are on. LocalNotified { task: task.0, _not_send: PhantomData, } } /// Shuts down all tasks in the collection. This call also closes the /// collection, preventing new items from being added. pub(crate) fn close_and_shutdown_all(&self) where S: Schedule,
pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> { let task_id = task.header().get_owner_id(); if task_id == 0 { // The task is unowned. return None; } assert_eq!(task_id, self.id); // safety: We just checked that the provided task is not in some other // linked list. unsafe { self.inner.lock().list.remove(task.header().into()) } } pub(crate) fn is_empty(&self) -> bool { self.inner.lock().list.is_empty() } } impl<S: 'static> LocalOwnedTasks<S> { pub(crate) fn new() -> Self { Self { inner: UnsafeCell::new(OwnedTasksInner { list: LinkedList::new(), closed: false, }), id: get_next_id(), _not_send_or_sync: PhantomData, } } pub(crate) fn bind<T>( &self, task: T, scheduler: S, ) -> (JoinHandle<T::Output>, Option<Notified<S>>) where S: Schedule, T: Future + 'static, T::Output: 'static, { let (task, notified, join) = super::new_task(task, scheduler); unsafe { // safety: We just created the task, so we have exclusive access // to the field. task.header().set_owner_id(self.id); } if self.is_closed() { drop(notified); task.shutdown(); (join, None) } else { self.with_inner(|inner| { inner.list.push_front(task); }); (join, Some(notified)) } } /// Shuts down all tasks in the collection. This call also closes the /// collection, preventing new items from being added. pub(crate) fn close_and_shutdown_all(&self) where S: Schedule, { self.with_inner(|inner| inner.closed = true); while let Some(task) = self.with_inner(|inner| inner.list.pop_back()) { task.shutdown(); } } pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> { let task_id = task.header().get_owner_id(); if task_id == 0 { // The task is unowned. return None; } assert_eq!(task_id, self.id); self.with_inner(|inner| // safety: We just checked that the provided task is not in some // other linked list. unsafe { inner.list.remove(task.header().into()) }) } /// Asserts that the given task is owned by this LocalOwnedTasks and convert /// it to a LocalNotified, giving the thread permission to poll this task. #[inline] pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> { assert_eq!(task.header().get_owner_id(), self.id); // safety: The task was bound to this LocalOwnedTasks, and the // LocalOwnedTasks is not Send or Sync, so we are on the right thread // for polling this task. LocalNotified { task: task.0, _not_send: PhantomData, } } #[inline] fn with_inner<F, T>(&self, f: F) -> T where F: FnOnce(&mut OwnedTasksInner<S>) -> T, { // safety: This type is not Sync, so concurrent calls of this method // can't happen. Furthermore, all uses of this method in this file make // sure that they don't call `with_inner` recursively. self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) }) } pub(crate) fn is_closed(&self) -> bool { self.with_inner(|inner| inner.closed) } pub(crate) fn is_empty(&self) -> bool { self.with_inner(|inner| inner.list.is_empty()) } } #[cfg(all(test))] mod tests { use super::*; // This test may run in parallel with other tests, so we only test that ids // come in increasing order. #[test] fn test_id_not_broken() { let mut last_id = get_next_id(); assert_ne!(last_id, 0); for _ in 0..1000 { let next_id = get_next_id(); assert_ne!(next_id, 0); assert!(last_id < next_id); last_id = next_id; } } }
{ // The first iteration of the loop was unrolled so it can set the // closed bool. let first_task = { let mut lock = self.inner.lock(); lock.closed = true; lock.list.pop_back() }; match first_task { Some(task) => task.shutdown(), None => return, } loop { let task = match self.inner.lock().list.pop_back() { Some(task) => task, None => return, }; task.shutdown(); } }
identifier_body
list.rs
//! This module has containers for storing the tasks spawned on a scheduler. The //! `OwnedTasks` container is thread-safe but can only store tasks that //! implement Send. The `LocalOwnedTasks` container is not thread safe, but can //! store non-Send tasks. //! //! The collections can be closed to prevent adding new tasks during shutdown of //! the scheduler with the collection. use crate::future::Future; use crate::loom::cell::UnsafeCell; use crate::loom::sync::Mutex; use crate::runtime::task::{JoinHandle, LocalNotified, Notified, Schedule, Task}; use crate::util::linked_list::{Link, LinkedList}; use std::marker::PhantomData; // The id from the module below is used to verify whether a given task is stored // in this OwnedTasks, or some other task. The counter starts at one so we can // use zero for tasks not owned by any list. // // The safety checks in this file can technically be violated if the counter is // overflown, but the checks are not supposed to ever fail unless there is a // bug in Tokio, so we accept that certain bugs would not be caught if the two // mixed up runtimes happen to have the same id. cfg_has_atomic_u64! { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_OWNED_TASKS_ID: AtomicU64 = AtomicU64::new(1); fn get_next_id() -> u64 { loop { let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed); if id != 0 { return id; } } } } cfg_not_has_atomic_u64! { use std::sync::atomic::{AtomicU32, Ordering}; static NEXT_OWNED_TASKS_ID: AtomicU32 = AtomicU32::new(1); fn get_next_id() -> u64 { loop { let id = NEXT_OWNED_TASKS_ID.fetch_add(1, Ordering::Relaxed); if id != 0 { return u64::from(id); } } } } pub(crate) struct OwnedTasks<S: 'static> { inner: Mutex<OwnedTasksInner<S>>, id: u64, } pub(crate) struct LocalOwnedTasks<S: 'static> { inner: UnsafeCell<OwnedTasksInner<S>>, id: u64, _not_send_or_sync: PhantomData<*const ()>, } struct OwnedTasksInner<S: 'static> { list: LinkedList<Task<S>, <Task<S> as Link>::Target>, closed: bool, } impl<S: 'static> OwnedTasks<S> { pub(crate) fn new() -> Self { Self { inner: Mutex::new(OwnedTasksInner { list: LinkedList::new(), closed: false, }), id: get_next_id(), } } /// Binds the provided task to this OwnedTasks instance. This fails if the /// OwnedTasks has been closed. pub(crate) fn bind<T>( &self, task: T, scheduler: S, ) -> (JoinHandle<T::Output>, Option<Notified<S>>) where S: Schedule, T: Future + Send + 'static, T::Output: Send + 'static, { let (task, notified, join) = super::new_task(task, scheduler); unsafe { // safety: We just created the task, so we have exclusive access // to the field. task.header().set_owner_id(self.id); } let mut lock = self.inner.lock(); if lock.closed { drop(lock); drop(notified); task.shutdown(); (join, None) } else { lock.list.push_front(task); (join, Some(notified)) } } /// Asserts that the given task is owned by this OwnedTasks and convert it to /// a LocalNotified, giving the thread permission to poll this task. #[inline] pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> { assert_eq!(task.header().get_owner_id(), self.id); // safety: All tasks bound to this OwnedTasks are Send, so it is safe // to poll it on this thread no matter what thread we are on. LocalNotified { task: task.0, _not_send: PhantomData, } } /// Shuts down all tasks in the collection. This call also closes the /// collection, preventing new items from being added. pub(crate) fn close_and_shutdown_all(&self) where S: Schedule, { // The first iteration of the loop was unrolled so it can set the // closed bool. let first_task = { let mut lock = self.inner.lock(); lock.closed = true; lock.list.pop_back() }; match first_task { Some(task) => task.shutdown(), None => return, } loop { let task = match self.inner.lock().list.pop_back() { Some(task) => task, None => return, }; task.shutdown(); } } pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> { let task_id = task.header().get_owner_id(); if task_id == 0 { // The task is unowned. return None; } assert_eq!(task_id, self.id); // safety: We just checked that the provided task is not in some other // linked list. unsafe { self.inner.lock().list.remove(task.header().into()) } } pub(crate) fn is_empty(&self) -> bool { self.inner.lock().list.is_empty() } } impl<S: 'static> LocalOwnedTasks<S> { pub(crate) fn new() -> Self { Self { inner: UnsafeCell::new(OwnedTasksInner { list: LinkedList::new(), closed: false, }), id: get_next_id(), _not_send_or_sync: PhantomData, } } pub(crate) fn bind<T>( &self, task: T, scheduler: S, ) -> (JoinHandle<T::Output>, Option<Notified<S>>) where S: Schedule, T: Future + 'static, T::Output: 'static, { let (task, notified, join) = super::new_task(task, scheduler); unsafe { // safety: We just created the task, so we have exclusive access // to the field. task.header().set_owner_id(self.id); } if self.is_closed() { drop(notified); task.shutdown(); (join, None) } else { self.with_inner(|inner| { inner.list.push_front(task); }); (join, Some(notified)) } } /// Shuts down all tasks in the collection. This call also closes the /// collection, preventing new items from being added. pub(crate) fn close_and_shutdown_all(&self) where S: Schedule, { self.with_inner(|inner| inner.closed = true); while let Some(task) = self.with_inner(|inner| inner.list.pop_back()) { task.shutdown(); } } pub(crate) fn remove(&self, task: &Task<S>) -> Option<Task<S>> { let task_id = task.header().get_owner_id(); if task_id == 0 { // The task is unowned. return None; } assert_eq!(task_id, self.id); self.with_inner(|inner| // safety: We just checked that the provided task is not in some // other linked list. unsafe { inner.list.remove(task.header().into()) })
/// it to a LocalNotified, giving the thread permission to poll this task. #[inline] pub(crate) fn assert_owner(&self, task: Notified<S>) -> LocalNotified<S> { assert_eq!(task.header().get_owner_id(), self.id); // safety: The task was bound to this LocalOwnedTasks, and the // LocalOwnedTasks is not Send or Sync, so we are on the right thread // for polling this task. LocalNotified { task: task.0, _not_send: PhantomData, } } #[inline] fn with_inner<F, T>(&self, f: F) -> T where F: FnOnce(&mut OwnedTasksInner<S>) -> T, { // safety: This type is not Sync, so concurrent calls of this method // can't happen. Furthermore, all uses of this method in this file make // sure that they don't call `with_inner` recursively. self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) }) } pub(crate) fn is_closed(&self) -> bool { self.with_inner(|inner| inner.closed) } pub(crate) fn is_empty(&self) -> bool { self.with_inner(|inner| inner.list.is_empty()) } } #[cfg(all(test))] mod tests { use super::*; // This test may run in parallel with other tests, so we only test that ids // come in increasing order. #[test] fn test_id_not_broken() { let mut last_id = get_next_id(); assert_ne!(last_id, 0); for _ in 0..1000 { let next_id = get_next_id(); assert_ne!(next_id, 0); assert!(last_id < next_id); last_id = next_id; } } }
} /// Asserts that the given task is owned by this LocalOwnedTasks and convert
random_line_split
test_user_api_token.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import wavefront_api_client from wavefront_api_client.models.user_api_token import UserApiToken # noqa: E501 from wavefront_api_client.rest import ApiException class TestUserApiToken(unittest.TestCase): """UserApiToken unit test stubs""" def setUp(self): pass def tearDown(self): pass def testUserApiToken(self):
if __name__ == '__main__': unittest.main()
"""Test UserApiToken""" # FIXME: construct object with mandatory attributes with example values # model = wavefront_api_client.models.user_api_token.UserApiToken() # noqa: E501 pass
identifier_body
test_user_api_token.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import wavefront_api_client from wavefront_api_client.models.user_api_token import UserApiToken # noqa: E501 from wavefront_api_client.rest import ApiException class TestUserApiToken(unittest.TestCase): """UserApiToken unit test stubs""" def setUp(self): pass def tearDown(self): pass def testUserApiToken(self): """Test UserApiToken""" # FIXME: construct object with mandatory attributes with example values # model = wavefront_api_client.models.user_api_token.UserApiToken() # noqa: E501 pass if __name__ == '__main__':
unittest.main()
conditional_block
test_user_api_token.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import wavefront_api_client from wavefront_api_client.models.user_api_token import UserApiToken # noqa: E501 from wavefront_api_client.rest import ApiException class TestUserApiToken(unittest.TestCase): """UserApiToken unit test stubs""" def
(self): pass def tearDown(self): pass def testUserApiToken(self): """Test UserApiToken""" # FIXME: construct object with mandatory attributes with example values # model = wavefront_api_client.models.user_api_token.UserApiToken() # noqa: E501 pass if __name__ == '__main__': unittest.main()
setUp
identifier_name
test_user_api_token.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import
from wavefront_api_client.rest import ApiException class TestUserApiToken(unittest.TestCase): """UserApiToken unit test stubs""" def setUp(self): pass def tearDown(self): pass def testUserApiToken(self): """Test UserApiToken""" # FIXME: construct object with mandatory attributes with example values # model = wavefront_api_client.models.user_api_token.UserApiToken() # noqa: E501 pass if __name__ == '__main__': unittest.main()
import unittest import wavefront_api_client from wavefront_api_client.models.user_api_token import UserApiToken # noqa: E501
random_line_split
RP14part1.js
/* global console, LAMBDA */ (function() { "use strict"; var L = LAMBDA; var question = {}; var RP14part1 = { init: function() { var vs = "uvxyz"; var maxDepth = 6; var minDepth = 4; // David: all of these helper functions are duplicated in // RP14part2.js. Because... // When I moved them to a separate JS file that I loaded (with // use-require) in both RP14part1.html and RP14part2.html, // OpenDSA did not like it (error on loading the shared JS file) function pickRndCharacter(c,s) { var list = s.split("") .map(function (e,i) { return (e===c ? i : -1) ; }); list = list.filter(function (x) { return x >= 0; }); return list[L.getRnd(0,list.length-1)]; } function findMatchingParen(s,index) { s = s.split(""); var count = 0; for(var i=index+1; i<s.length; i++) { if (s[i] === ')') { if (count === 0) { return i; } else { count--; } } else { if (s[i] === '(') { count++; } } } throw new Error("Could not find closing paren for the one " + "at position " + index + " in " + s); } function removeParenPair(s) { var openParen = pickRndCharacter('(',s); var closeParen = findMatchingParen(s,openParen); return s.substring(0,openParen) + s.substring(openParen+1,closeParen) + s.substring(closeParen+1); } function removeDot(s) { var dot = pickRndCharacter('.',s); return s.substring(0,dot) + " " + s.substring(dot+1); } function addParens(s) { var n = s.length; var closing = n-1; while (s[closing] === ')') { closing--; } var p1 = L.getRnd(0,closing-1); var p2 = L.getRnd(closing+1,n-1); // do not insert in front of a space or a dot if (s[p1] === " " || s[p1] === ".") { p1++; } // do not insert after a lambda if (p1>0 && s[p1-1] === "\u03BB" ) { p1 += 2; } return s.substring(0,p1) + "(" + s.substring(p1,p2) + ")" + s.substring(p2); } function getSyntaxError(minDepth,maxDepth,vs) { var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); var rnd = L.getRnd(1,3); question.answer = "True"; switch (rnd) { case 1: if (s.indexOf('(') !== -1) { s = removeParenPair(s); question.answer = "False"; } // leave s unchanged if it does not contain any parens break; case 2: if (s.indexOf('.') !== -1) { s = removeDot(s); question.answer = "False"; } // leave s unchanged if it does not contain any dot break; case 3: s = addParens(s); question.answer = "False"; break; } return s; }// getSyntaxError function if (L.getRnd(0,1) === 0) { // syntactically correct lambda exp this.expression = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); this.answer = "True"; } else { this.expression = getSyntaxError(minDepth,maxDepth,vs); this.answer = question.answer; } } //init };// RP14part1 window.RP14part1 = window.RP14part1 || RP14part1;
}());
random_line_split
RP14part1.js
/* global console, LAMBDA */ (function() { "use strict"; var L = LAMBDA; var question = {}; var RP14part1 = { init: function() { var vs = "uvxyz"; var maxDepth = 6; var minDepth = 4; // David: all of these helper functions are duplicated in // RP14part2.js. Because... // When I moved them to a separate JS file that I loaded (with // use-require) in both RP14part1.html and RP14part2.html, // OpenDSA did not like it (error on loading the shared JS file) function pickRndCharacter(c,s) { var list = s.split("") .map(function (e,i) { return (e===c ? i : -1) ; }); list = list.filter(function (x) { return x >= 0; }); return list[L.getRnd(0,list.length-1)]; } function findMatchingParen(s,index) { s = s.split(""); var count = 0; for(var i=index+1; i<s.length; i++) { if (s[i] === ')') { if (count === 0) { return i; } else { count--; } } else { if (s[i] === '(') { count++; } } } throw new Error("Could not find closing paren for the one " + "at position " + index + " in " + s); } function removeParenPair(s) { var openParen = pickRndCharacter('(',s); var closeParen = findMatchingParen(s,openParen); return s.substring(0,openParen) + s.substring(openParen+1,closeParen) + s.substring(closeParen+1); } function removeDot(s) { var dot = pickRndCharacter('.',s); return s.substring(0,dot) + " " + s.substring(dot+1); } function addParens(s)
function getSyntaxError(minDepth,maxDepth,vs) { var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); var rnd = L.getRnd(1,3); question.answer = "True"; switch (rnd) { case 1: if (s.indexOf('(') !== -1) { s = removeParenPair(s); question.answer = "False"; } // leave s unchanged if it does not contain any parens break; case 2: if (s.indexOf('.') !== -1) { s = removeDot(s); question.answer = "False"; } // leave s unchanged if it does not contain any dot break; case 3: s = addParens(s); question.answer = "False"; break; } return s; }// getSyntaxError function if (L.getRnd(0,1) === 0) { // syntactically correct lambda exp this.expression = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); this.answer = "True"; } else { this.expression = getSyntaxError(minDepth,maxDepth,vs); this.answer = question.answer; } } //init };// RP14part1 window.RP14part1 = window.RP14part1 || RP14part1; }());
{ var n = s.length; var closing = n-1; while (s[closing] === ')') { closing--; } var p1 = L.getRnd(0,closing-1); var p2 = L.getRnd(closing+1,n-1); // do not insert in front of a space or a dot if (s[p1] === " " || s[p1] === ".") { p1++; } // do not insert after a lambda if (p1>0 && s[p1-1] === "\u03BB" ) { p1 += 2; } return s.substring(0,p1) + "(" + s.substring(p1,p2) + ")" + s.substring(p2); }
identifier_body
RP14part1.js
/* global console, LAMBDA */ (function() { "use strict"; var L = LAMBDA; var question = {}; var RP14part1 = { init: function() { var vs = "uvxyz"; var maxDepth = 6; var minDepth = 4; // David: all of these helper functions are duplicated in // RP14part2.js. Because... // When I moved them to a separate JS file that I loaded (with // use-require) in both RP14part1.html and RP14part2.html, // OpenDSA did not like it (error on loading the shared JS file) function pickRndCharacter(c,s) { var list = s.split("") .map(function (e,i) { return (e===c ? i : -1) ; }); list = list.filter(function (x) { return x >= 0; }); return list[L.getRnd(0,list.length-1)]; } function findMatchingParen(s,index) { s = s.split(""); var count = 0; for(var i=index+1; i<s.length; i++) { if (s[i] === ')') { if (count === 0) { return i; } else { count--; } } else { if (s[i] === '(') { count++; } } } throw new Error("Could not find closing paren for the one " + "at position " + index + " in " + s); } function removeParenPair(s) { var openParen = pickRndCharacter('(',s); var closeParen = findMatchingParen(s,openParen); return s.substring(0,openParen) + s.substring(openParen+1,closeParen) + s.substring(closeParen+1); } function removeDot(s) { var dot = pickRndCharacter('.',s); return s.substring(0,dot) + " " + s.substring(dot+1); } function addParens(s) { var n = s.length; var closing = n-1; while (s[closing] === ')') { closing--; } var p1 = L.getRnd(0,closing-1); var p2 = L.getRnd(closing+1,n-1); // do not insert in front of a space or a dot if (s[p1] === " " || s[p1] === ".")
// do not insert after a lambda if (p1>0 && s[p1-1] === "\u03BB" ) { p1 += 2; } return s.substring(0,p1) + "(" + s.substring(p1,p2) + ")" + s.substring(p2); } function getSyntaxError(minDepth,maxDepth,vs) { var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); var rnd = L.getRnd(1,3); question.answer = "True"; switch (rnd) { case 1: if (s.indexOf('(') !== -1) { s = removeParenPair(s); question.answer = "False"; } // leave s unchanged if it does not contain any parens break; case 2: if (s.indexOf('.') !== -1) { s = removeDot(s); question.answer = "False"; } // leave s unchanged if it does not contain any dot break; case 3: s = addParens(s); question.answer = "False"; break; } return s; }// getSyntaxError function if (L.getRnd(0,1) === 0) { // syntactically correct lambda exp this.expression = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); this.answer = "True"; } else { this.expression = getSyntaxError(minDepth,maxDepth,vs); this.answer = question.answer; } } //init };// RP14part1 window.RP14part1 = window.RP14part1 || RP14part1; }());
{ p1++; }
conditional_block
RP14part1.js
/* global console, LAMBDA */ (function() { "use strict"; var L = LAMBDA; var question = {}; var RP14part1 = { init: function() { var vs = "uvxyz"; var maxDepth = 6; var minDepth = 4; // David: all of these helper functions are duplicated in // RP14part2.js. Because... // When I moved them to a separate JS file that I loaded (with // use-require) in both RP14part1.html and RP14part2.html, // OpenDSA did not like it (error on loading the shared JS file) function pickRndCharacter(c,s) { var list = s.split("") .map(function (e,i) { return (e===c ? i : -1) ; }); list = list.filter(function (x) { return x >= 0; }); return list[L.getRnd(0,list.length-1)]; } function
(s,index) { s = s.split(""); var count = 0; for(var i=index+1; i<s.length; i++) { if (s[i] === ')') { if (count === 0) { return i; } else { count--; } } else { if (s[i] === '(') { count++; } } } throw new Error("Could not find closing paren for the one " + "at position " + index + " in " + s); } function removeParenPair(s) { var openParen = pickRndCharacter('(',s); var closeParen = findMatchingParen(s,openParen); return s.substring(0,openParen) + s.substring(openParen+1,closeParen) + s.substring(closeParen+1); } function removeDot(s) { var dot = pickRndCharacter('.',s); return s.substring(0,dot) + " " + s.substring(dot+1); } function addParens(s) { var n = s.length; var closing = n-1; while (s[closing] === ')') { closing--; } var p1 = L.getRnd(0,closing-1); var p2 = L.getRnd(closing+1,n-1); // do not insert in front of a space or a dot if (s[p1] === " " || s[p1] === ".") { p1++; } // do not insert after a lambda if (p1>0 && s[p1-1] === "\u03BB" ) { p1 += 2; } return s.substring(0,p1) + "(" + s.substring(p1,p2) + ")" + s.substring(p2); } function getSyntaxError(minDepth,maxDepth,vs) { var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); var rnd = L.getRnd(1,3); question.answer = "True"; switch (rnd) { case 1: if (s.indexOf('(') !== -1) { s = removeParenPair(s); question.answer = "False"; } // leave s unchanged if it does not contain any parens break; case 2: if (s.indexOf('.') !== -1) { s = removeDot(s); question.answer = "False"; } // leave s unchanged if it does not contain any dot break; case 3: s = addParens(s); question.answer = "False"; break; } return s; }// getSyntaxError function if (L.getRnd(0,1) === 0) { // syntactically correct lambda exp this.expression = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); this.answer = "True"; } else { this.expression = getSyntaxError(minDepth,maxDepth,vs); this.answer = question.answer; } } //init };// RP14part1 window.RP14part1 = window.RP14part1 || RP14part1; }());
findMatchingParen
identifier_name
TestIt.py
# TestIt.py # Copyright (C) 2009 Matthias Treder # # 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 2 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Use TestIt to test your new visual elements. Test it opens a test screen, displays the element and goes through its states. """ import sys import pygame import Textrow bgcolor = 0, 0, 0 screenSize = 500, 500 """ Import & define your element here""" #import Hexagon,math #e = Hexagon.Hexagon(color=(255,255,255),radius=60,text="ABCD",edgecolor=(255,255,255),textcolor=(10,10,100),textsize=10,colorkey=(0,0,0),antialias=True) text = "LUXUS" """ Init pygame, open screen etc """ pygame.init() screen = pygame.display.set_mode(screenSize) background = pygame.Surface(screenSize) background.fill(bgcolor) screen.blit(background, [0, 0]) pygame.display.update() """ Loop between the states and pause in between """ width, height = screenSize e.pos = (width / 2, height / 2) e.refresh() e.update(0) pos = 0 while 1:
screen.blit(background, [0, 0]) screen.blit(e.image, e.rect) pygame.display.flip() e.update() pygame.time.delay(400) e.highlight = [pos] e.refresh() pos = (pos + 1) % len(text) for event in pygame.event.get(): if event.type in (pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN): sys.exit(0) break
conditional_block
TestIt.py
# TestIt.py # Copyright (C) 2009 Matthias Treder # # 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 2 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Use TestIt to test your new visual elements. Test it opens a test screen, displays the element and goes through its states. """ import sys import pygame import Textrow bgcolor = 0, 0, 0 screenSize = 500, 500 """ Import & define your element here""" #import Hexagon,math #e = Hexagon.Hexagon(color=(255,255,255),radius=60,text="ABCD",edgecolor=(255,255,255),textcolor=(10,10,100),textsize=10,colorkey=(0,0,0),antialias=True) text = "LUXUS" """ Init pygame, open screen etc """ pygame.init() screen = pygame.display.set_mode(screenSize) background = pygame.Surface(screenSize) background.fill(bgcolor) screen.blit(background, [0, 0]) pygame.display.update() """ Loop between the states and pause in between """ width, height = screenSize
screen.blit(background, [0, 0]) screen.blit(e.image, e.rect) pygame.display.flip() e.update() pygame.time.delay(400) e.highlight = [pos] e.refresh() pos = (pos + 1) % len(text) for event in pygame.event.get(): if event.type in (pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN): sys.exit(0) break
e.pos = (width / 2, height / 2) e.refresh() e.update(0) pos = 0 while 1:
random_line_split
dst-dtor-1.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. static mut DROP_RAN: bool = false; struct Foo; impl Drop for Foo { fn drop(&mut self) { unsafe { DROP_RAN = true; } } } trait Trait { fn dummy(&self) { } } impl Trait for Foo {} struct Fat<T: ?Sized> { f: T } pub fn main() { { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo }); } unsafe { assert!(DROP_RAN); } }
// http://rust-lang.org/COPYRIGHT. //
random_line_split
dst-dtor-1.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. static mut DROP_RAN: bool = false; struct Foo; impl Drop for Foo { fn drop(&mut self) { unsafe { DROP_RAN = true; } } } trait Trait { fn dummy(&self) { } } impl Trait for Foo {} struct Fat<T: ?Sized> { f: T } pub fn
() { { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo }); } unsafe { assert!(DROP_RAN); } }
main
identifier_name
dst-dtor-1.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. static mut DROP_RAN: bool = false; struct Foo; impl Drop for Foo { fn drop(&mut self)
} trait Trait { fn dummy(&self) { } } impl Trait for Foo {} struct Fat<T: ?Sized> { f: T } pub fn main() { { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. let _x: Box<Fat<Trait>> = Box::<Fat<Foo>>::new(Fat { f: Foo }); } unsafe { assert!(DROP_RAN); } }
{ unsafe { DROP_RAN = true; } }
identifier_body
lib.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364) #![cfg_attr(stage0, feature(custom_attribute))]
#![unstable(feature = "rustc_private")] #![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![allow(non_camel_case_types)] #![feature(quote)] #![feature(rustc_diagnostic_macros)] #![feature(rustc_private)] #![feature(staged_api)] #![feature(into_cow)] #[macro_use] extern crate log; #[macro_use] extern crate syntax; // for "clarity", rename the graphviz crate to dot; graphviz within `borrowck` // refers to the borrowck-specific graphviz adapter traits. extern crate graphviz as dot; extern crate rustc; pub use borrowck::check_crate; pub use borrowck::build_borrowck_dataflow_data_for_fn; pub use borrowck::FnPartsWithCFG; // NB: This module needs to be declared first so diagnostics are // registered before they are used. pub mod diagnostics; mod borrowck; pub mod graphviz; #[cfg(stage0)] __build_diagnostic_array! { DIAGNOSTICS } #[cfg(not(stage0))] __build_diagnostic_array! { librustc_borrowck, DIAGNOSTICS }
#![crate_name = "rustc_borrowck"]
random_line_split
index.windows.js
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Text, TouchableOpacity, Button } from 'react-native'; import MenuSide from './App/MenuSide' import LogArea from './App/LogArea' import { Pages, ControlsPage, FixesPage, MainPage, AccessibilityPage, WebViewPage } from './App/ContentSide' var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter') import * as Animatable from 'react-native-animatable' import GenericModal from "./App/Modals/GenericModal"; const LOG_INIT_MESSAGE = 'Playground v 0.3' class Playground extends Component { constructor(props) { super(props) this.state = { displayPage: Pages.MAIN, log: LOG_INIT_MESSAGE, isModalOpen: false } } switchContent = (page) => { if (page === 'CLEAR_LOG')
this.setState(previousState => ({ displayPage: page, log: `${previousState.log}\n${new Date().toISOString()}: Page changed to ${page}` })) } renderContent = () => { const { displayPage } = this.state return ( <View style={styles.clientArea}> {displayPage === Pages.MAIN && <MainPage/>} {displayPage === Pages.CONTROLS && <ControlsPage logger={this.log} />} {displayPage === Pages.FIXES && <FixesPage logger={this.log} />} {displayPage === Pages.ACCESSIBILITY && <AccessibilityPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} {displayPage === Pages.WEBVIEW && <WebViewPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} </View> ) } log = (message) => { this.setState(previousState => ( { log: `${previousState.log}\n${new Date().toISOString()}: ${message}` } )) } modalButtonClickHandler = (isOpen) => { this.setState({isModalOpen: isOpen}) } componentWillMount() { RCTDeviceEventEmitter.addListener('logMessageCreated', (evt) => { this.log(`${evt.messageSender}: ${evt.message}`) }) } render() { return ( <View isFocusable={this.state.isModalOpen === false} style={styles.container}> <Animatable.View isFocusable={this.state.isModalOpen === false} style={styles.content} ref='content' animation='fadeInUp' duration={800} easing='ease-in'> <View isFocusable={this.state.isModalOpen === false} style={styles.content}> <MenuSide isFocusable={this.state.isModalOpen === false} logger={this.log} menuClick={this.switchContent} /> {this.renderContent()} </View> </Animatable.View> <LogArea content={this.state.log} /> <View style={{backgroundColor: 'gray', alignItems: 'center', justifyContent: 'center'}} isFocusable={this.state.isModalOpen === false}> <TouchableOpacity onPress={() => this.modalButtonClickHandler(true)}> <Text>Show Modal</Text> </TouchableOpacity> </View> <GenericModal isOpen={this.state.isModalOpen} close={() => this.modalButtonClickHandler(false)} /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, content: { flex: 1, flexGrow: 2, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch', minHeight: 200 }, clientArea: { flexGrow: 2, } }); AppRegistry.registerComponent('Playground.Net46', () => Playground);
{ this.setState(previousState => ({ log: LOG_INIT_MESSAGE }) ) return }
conditional_block
index.windows.js
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Text, TouchableOpacity, Button } from 'react-native'; import MenuSide from './App/MenuSide' import LogArea from './App/LogArea' import { Pages, ControlsPage, FixesPage, MainPage, AccessibilityPage, WebViewPage } from './App/ContentSide' var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter') import * as Animatable from 'react-native-animatable' import GenericModal from "./App/Modals/GenericModal"; const LOG_INIT_MESSAGE = 'Playground v 0.3' class Playground extends Component { constructor(props) { super(props) this.state = { displayPage: Pages.MAIN, log: LOG_INIT_MESSAGE, isModalOpen: false } } switchContent = (page) => { if (page === 'CLEAR_LOG') { this.setState(previousState => ({ log: LOG_INIT_MESSAGE }) ) return } this.setState(previousState => ({ displayPage: page, log: `${previousState.log}\n${new Date().toISOString()}: Page changed to ${page}` })) } renderContent = () => { const { displayPage } = this.state return ( <View style={styles.clientArea}> {displayPage === Pages.MAIN && <MainPage/>} {displayPage === Pages.CONTROLS && <ControlsPage logger={this.log} />} {displayPage === Pages.FIXES && <FixesPage logger={this.log} />} {displayPage === Pages.ACCESSIBILITY && <AccessibilityPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} {displayPage === Pages.WEBVIEW && <WebViewPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} </View> ) } log = (message) => { this.setState(previousState => ( { log: `${previousState.log}\n${new Date().toISOString()}: ${message}` } )) } modalButtonClickHandler = (isOpen) => { this.setState({isModalOpen: isOpen}) }
() { RCTDeviceEventEmitter.addListener('logMessageCreated', (evt) => { this.log(`${evt.messageSender}: ${evt.message}`) }) } render() { return ( <View isFocusable={this.state.isModalOpen === false} style={styles.container}> <Animatable.View isFocusable={this.state.isModalOpen === false} style={styles.content} ref='content' animation='fadeInUp' duration={800} easing='ease-in'> <View isFocusable={this.state.isModalOpen === false} style={styles.content}> <MenuSide isFocusable={this.state.isModalOpen === false} logger={this.log} menuClick={this.switchContent} /> {this.renderContent()} </View> </Animatable.View> <LogArea content={this.state.log} /> <View style={{backgroundColor: 'gray', alignItems: 'center', justifyContent: 'center'}} isFocusable={this.state.isModalOpen === false}> <TouchableOpacity onPress={() => this.modalButtonClickHandler(true)}> <Text>Show Modal</Text> </TouchableOpacity> </View> <GenericModal isOpen={this.state.isModalOpen} close={() => this.modalButtonClickHandler(false)} /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, content: { flex: 1, flexGrow: 2, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch', minHeight: 200 }, clientArea: { flexGrow: 2, } }); AppRegistry.registerComponent('Playground.Net46', () => Playground);
componentWillMount
identifier_name
index.windows.js
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Text, TouchableOpacity, Button } from 'react-native'; import MenuSide from './App/MenuSide' import LogArea from './App/LogArea' import { Pages, ControlsPage, FixesPage, MainPage, AccessibilityPage, WebViewPage } from './App/ContentSide' var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter') import * as Animatable from 'react-native-animatable' import GenericModal from "./App/Modals/GenericModal"; const LOG_INIT_MESSAGE = 'Playground v 0.3' class Playground extends Component { constructor(props) { super(props) this.state = { displayPage: Pages.MAIN, log: LOG_INIT_MESSAGE, isModalOpen: false } } switchContent = (page) => { if (page === 'CLEAR_LOG') { this.setState(previousState => ({ log: LOG_INIT_MESSAGE }) ) return } this.setState(previousState => ({ displayPage: page, log: `${previousState.log}\n${new Date().toISOString()}: Page changed to ${page}` })) } renderContent = () => { const { displayPage } = this.state return ( <View style={styles.clientArea}> {displayPage === Pages.MAIN && <MainPage/>} {displayPage === Pages.CONTROLS && <ControlsPage logger={this.log} />} {displayPage === Pages.FIXES && <FixesPage logger={this.log} />} {displayPage === Pages.ACCESSIBILITY && <AccessibilityPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} {displayPage === Pages.WEBVIEW && <WebViewPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} </View> ) }
log = (message) => { this.setState(previousState => ( { log: `${previousState.log}\n${new Date().toISOString()}: ${message}` } )) } modalButtonClickHandler = (isOpen) => { this.setState({isModalOpen: isOpen}) } componentWillMount() { RCTDeviceEventEmitter.addListener('logMessageCreated', (evt) => { this.log(`${evt.messageSender}: ${evt.message}`) }) } render() { return ( <View isFocusable={this.state.isModalOpen === false} style={styles.container}> <Animatable.View isFocusable={this.state.isModalOpen === false} style={styles.content} ref='content' animation='fadeInUp' duration={800} easing='ease-in'> <View isFocusable={this.state.isModalOpen === false} style={styles.content}> <MenuSide isFocusable={this.state.isModalOpen === false} logger={this.log} menuClick={this.switchContent} /> {this.renderContent()} </View> </Animatable.View> <LogArea content={this.state.log} /> <View style={{backgroundColor: 'gray', alignItems: 'center', justifyContent: 'center'}} isFocusable={this.state.isModalOpen === false}> <TouchableOpacity onPress={() => this.modalButtonClickHandler(true)}> <Text>Show Modal</Text> </TouchableOpacity> </View> <GenericModal isOpen={this.state.isModalOpen} close={() => this.modalButtonClickHandler(false)} /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, content: { flex: 1, flexGrow: 2, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch', minHeight: 200 }, clientArea: { flexGrow: 2, } }); AppRegistry.registerComponent('Playground.Net46', () => Playground);
random_line_split
index.windows.js
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Text, TouchableOpacity, Button } from 'react-native'; import MenuSide from './App/MenuSide' import LogArea from './App/LogArea' import { Pages, ControlsPage, FixesPage, MainPage, AccessibilityPage, WebViewPage } from './App/ContentSide' var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter') import * as Animatable from 'react-native-animatable' import GenericModal from "./App/Modals/GenericModal"; const LOG_INIT_MESSAGE = 'Playground v 0.3' class Playground extends Component { constructor(props)
switchContent = (page) => { if (page === 'CLEAR_LOG') { this.setState(previousState => ({ log: LOG_INIT_MESSAGE }) ) return } this.setState(previousState => ({ displayPage: page, log: `${previousState.log}\n${new Date().toISOString()}: Page changed to ${page}` })) } renderContent = () => { const { displayPage } = this.state return ( <View style={styles.clientArea}> {displayPage === Pages.MAIN && <MainPage/>} {displayPage === Pages.CONTROLS && <ControlsPage logger={this.log} />} {displayPage === Pages.FIXES && <FixesPage logger={this.log} />} {displayPage === Pages.ACCESSIBILITY && <AccessibilityPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} {displayPage === Pages.WEBVIEW && <WebViewPage isFocusable={this.state.isModalOpen === false} logger={this.log} />} </View> ) } log = (message) => { this.setState(previousState => ( { log: `${previousState.log}\n${new Date().toISOString()}: ${message}` } )) } modalButtonClickHandler = (isOpen) => { this.setState({isModalOpen: isOpen}) } componentWillMount() { RCTDeviceEventEmitter.addListener('logMessageCreated', (evt) => { this.log(`${evt.messageSender}: ${evt.message}`) }) } render() { return ( <View isFocusable={this.state.isModalOpen === false} style={styles.container}> <Animatable.View isFocusable={this.state.isModalOpen === false} style={styles.content} ref='content' animation='fadeInUp' duration={800} easing='ease-in'> <View isFocusable={this.state.isModalOpen === false} style={styles.content}> <MenuSide isFocusable={this.state.isModalOpen === false} logger={this.log} menuClick={this.switchContent} /> {this.renderContent()} </View> </Animatable.View> <LogArea content={this.state.log} /> <View style={{backgroundColor: 'gray', alignItems: 'center', justifyContent: 'center'}} isFocusable={this.state.isModalOpen === false}> <TouchableOpacity onPress={() => this.modalButtonClickHandler(true)}> <Text>Show Modal</Text> </TouchableOpacity> </View> <GenericModal isOpen={this.state.isModalOpen} close={() => this.modalButtonClickHandler(false)} /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', }, content: { flex: 1, flexGrow: 2, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch', minHeight: 200 }, clientArea: { flexGrow: 2, } }); AppRegistry.registerComponent('Playground.Net46', () => Playground);
{ super(props) this.state = { displayPage: Pages.MAIN, log: LOG_INIT_MESSAGE, isModalOpen: false } }
identifier_body
qquote.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-pretty // ignore-test #![feature(quote)] extern crate syntax; use std::io::*; use syntax::diagnostic; use syntax::ast; use syntax::codemap; use syntax::codemap::span; use syntax::parse; use syntax::print::*; trait fake_ext_ctxt { fn cfg() -> ast::CrateConfig; fn parse_sess() -> parse::parse_sess; fn call_site() -> span; fn ident_of(st: &str) -> ast::ident; } type fake_session = parse::parse_sess; impl fake_ext_ctxt for fake_session { fn cfg() -> ast::CrateConfig { Vec::new() } fn parse_sess() -> parse::parse_sess { self } fn call_site() -> span { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), expn_info: None } } fn ident_of(st: &str) -> ast::ident { self.interner.intern(st) } } fn mk_ctxt() -> fake_ext_ctxt { parse::new_parse_sess(None) as fake_ext_ctxt } fn main() { let cx = mk_ctxt(); let abc = quote_expr!(cx, 23); check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned()); let ty = quote_ty!(cx, int); check_pp(ext_cx, ty, pprust::print_type, "int".to_owned()); let item = quote_item!(cx, static x : int = 10;).get(); check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned()); let stmt = quote_stmt!(cx, let x = 20;); check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned()); let pat = quote_pat!(cx, Some(_)); check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned());
expr: T, f: |pprust::ps, T|, expect: StrBuf) { let s = io::with_str_writer(|wr| { let pp = pprust::rust_printer(wr, cx.parse_sess().interner); f(pp, expr); pp::eof(pp.s); }); stdout().write_line(s); if expect != "".to_owned() { println!("expect: '%s', got: '%s'", expect, s); assert_eq!(s, expect); } }
} fn check_pp<T>(cx: fake_ext_ctxt,
random_line_split
qquote.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-pretty // ignore-test #![feature(quote)] extern crate syntax; use std::io::*; use syntax::diagnostic; use syntax::ast; use syntax::codemap; use syntax::codemap::span; use syntax::parse; use syntax::print::*; trait fake_ext_ctxt { fn cfg() -> ast::CrateConfig; fn parse_sess() -> parse::parse_sess; fn call_site() -> span; fn ident_of(st: &str) -> ast::ident; } type fake_session = parse::parse_sess; impl fake_ext_ctxt for fake_session { fn cfg() -> ast::CrateConfig { Vec::new() } fn parse_sess() -> parse::parse_sess
fn call_site() -> span { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), expn_info: None } } fn ident_of(st: &str) -> ast::ident { self.interner.intern(st) } } fn mk_ctxt() -> fake_ext_ctxt { parse::new_parse_sess(None) as fake_ext_ctxt } fn main() { let cx = mk_ctxt(); let abc = quote_expr!(cx, 23); check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned()); let ty = quote_ty!(cx, int); check_pp(ext_cx, ty, pprust::print_type, "int".to_owned()); let item = quote_item!(cx, static x : int = 10;).get(); check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned()); let stmt = quote_stmt!(cx, let x = 20;); check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned()); let pat = quote_pat!(cx, Some(_)); check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned()); } fn check_pp<T>(cx: fake_ext_ctxt, expr: T, f: |pprust::ps, T|, expect: StrBuf) { let s = io::with_str_writer(|wr| { let pp = pprust::rust_printer(wr, cx.parse_sess().interner); f(pp, expr); pp::eof(pp.s); }); stdout().write_line(s); if expect != "".to_owned() { println!("expect: '%s', got: '%s'", expect, s); assert_eq!(s, expect); } }
{ self }
identifier_body
qquote.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-pretty // ignore-test #![feature(quote)] extern crate syntax; use std::io::*; use syntax::diagnostic; use syntax::ast; use syntax::codemap; use syntax::codemap::span; use syntax::parse; use syntax::print::*; trait fake_ext_ctxt { fn cfg() -> ast::CrateConfig; fn parse_sess() -> parse::parse_sess; fn call_site() -> span; fn ident_of(st: &str) -> ast::ident; } type fake_session = parse::parse_sess; impl fake_ext_ctxt for fake_session { fn cfg() -> ast::CrateConfig { Vec::new() } fn parse_sess() -> parse::parse_sess { self } fn call_site() -> span { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), expn_info: None } } fn ident_of(st: &str) -> ast::ident { self.interner.intern(st) } } fn mk_ctxt() -> fake_ext_ctxt { parse::new_parse_sess(None) as fake_ext_ctxt } fn
() { let cx = mk_ctxt(); let abc = quote_expr!(cx, 23); check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned()); let ty = quote_ty!(cx, int); check_pp(ext_cx, ty, pprust::print_type, "int".to_owned()); let item = quote_item!(cx, static x : int = 10;).get(); check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned()); let stmt = quote_stmt!(cx, let x = 20;); check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned()); let pat = quote_pat!(cx, Some(_)); check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned()); } fn check_pp<T>(cx: fake_ext_ctxt, expr: T, f: |pprust::ps, T|, expect: StrBuf) { let s = io::with_str_writer(|wr| { let pp = pprust::rust_printer(wr, cx.parse_sess().interner); f(pp, expr); pp::eof(pp.s); }); stdout().write_line(s); if expect != "".to_owned() { println!("expect: '%s', got: '%s'", expect, s); assert_eq!(s, expect); } }
main
identifier_name
qquote.rs
// Copyright 2012-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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-pretty // ignore-test #![feature(quote)] extern crate syntax; use std::io::*; use syntax::diagnostic; use syntax::ast; use syntax::codemap; use syntax::codemap::span; use syntax::parse; use syntax::print::*; trait fake_ext_ctxt { fn cfg() -> ast::CrateConfig; fn parse_sess() -> parse::parse_sess; fn call_site() -> span; fn ident_of(st: &str) -> ast::ident; } type fake_session = parse::parse_sess; impl fake_ext_ctxt for fake_session { fn cfg() -> ast::CrateConfig { Vec::new() } fn parse_sess() -> parse::parse_sess { self } fn call_site() -> span { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), expn_info: None } } fn ident_of(st: &str) -> ast::ident { self.interner.intern(st) } } fn mk_ctxt() -> fake_ext_ctxt { parse::new_parse_sess(None) as fake_ext_ctxt } fn main() { let cx = mk_ctxt(); let abc = quote_expr!(cx, 23); check_pp(ext_cx, abc, pprust::print_expr, "23".to_owned()); let ty = quote_ty!(cx, int); check_pp(ext_cx, ty, pprust::print_type, "int".to_owned()); let item = quote_item!(cx, static x : int = 10;).get(); check_pp(ext_cx, item, pprust::print_item, "static x: int = 10;".to_owned()); let stmt = quote_stmt!(cx, let x = 20;); check_pp(ext_cx, *stmt, pprust::print_stmt, "let x = 20;".to_owned()); let pat = quote_pat!(cx, Some(_)); check_pp(ext_cx, pat, pprust::print_pat, "Some(_)".to_owned()); } fn check_pp<T>(cx: fake_ext_ctxt, expr: T, f: |pprust::ps, T|, expect: StrBuf) { let s = io::with_str_writer(|wr| { let pp = pprust::rust_printer(wr, cx.parse_sess().interner); f(pp, expr); pp::eof(pp.s); }); stdout().write_line(s); if expect != "".to_owned()
}
{ println!("expect: '%s', got: '%s'", expect, s); assert_eq!(s, expect); }
conditional_block
lib_RC2014_BusSupervisor.py
#!/usr/bin/python ################################################################################ # Bus Supervisor Interface # # - interfaces to the MCP23017 and PCF8574 IO expander chips # # The logic for this was ported from Dr Scott M. Baker's project: # http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor # ################################################################################ from libArdySer import ArdySer from lib_GenericChip import GenericChip from GS_Timing import delay from lib_MCP23017_IOExpander16 import MCP23017_IOExpander16 from lib_PCF8574_IOExpander8 import PCF8574_IOExpander8 class RC2014_BusSupervisor: ################################## # class variables ardy = None cpuIoData = None # A0-A7 - Data byte # B0-B7 - Bus control M1 = 0x01 # B0 CLK = 0x02 # B1 INT = 0x04 # B2 MREQ = 0x08 # B3 WR = 0x10 # B4 RD = 0x20 # B5 IORQ = 0x40 # B6 BUSACK = 0x80 # B7 cpuControl = None # 0x0F - control, clock, etc BUSREQ = 0x01 RESET = 0x02 CLKEN = 0x04 CLKOUT = 0x08 # 0xF0 - unused cpuAddress = None # A0-A7, B0-B7 - Address lines (reversed) # our mirror values here data = 0 dataControl = 0 dataAddress = 0 ############################## def bitReverse( data ): retval = 0 if( (data & 0x80) == 0x80 ): retval = retval | 0x01 if( (data & 0x40) == 0x40 ): retval = retval | 0x02 if( (data & 0x20) == 0x20 ): retval = retval | 0x04 if( (data & 0x10) == 0x10 ): retval = retval | 0x08 if( (data & 0x08) == 0x08 ): retval = retval | 0x10 if( (data & 0x04) == 0x04 ): retval = retval | 0x20 if( (data & 0x02) == 0x02 ): retval = retval | 0x40 if( (data & 0x01) == 0x01 ): retval = retval | 0x80 return retval ################################## # Initialization def __init__( self, _ardy, _i2cAddr8 = None ): # set the arduino object baseAddr = _i2cAddr8 if _i2cAddr8 is None: baseAddr = 0x21 self.data = 0 self.dataControl = 0 self.dataAddress = 0 self.ardy = _ardy self.cpuIoData = MCP23017_IOExpander16( _ardy, baseAddr + 0 ) self.cpuControl = PCF8574_IOExpander8( _ardy, baseAddr + 1 ) self.cpuAddress = MCP23017_IOExpander16( _ardy, baseAddr + 2 ) self.ClearAllExpanders() def ClearAllExpaners( self ): # clear data register self.cpuIoData.DirectionA( IODIRA, IOALLINPUT ) self.cpuIoData.SetA( 0x00 ) self.cpuIoData.DirectionB( IODIRA, IOALLINPUT ) self.cpuIoData.SetB( 0x00 ) # clear control register self.cpuControl.Set( 0x00 ) # clear address register self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.SetA( 0x00 ) self.cpuAddress.DirectionB( IOALLINPUT ) self.cpuAddress.SetB( 0x00 ) ################################## # Low-level commands ################################## # Package commands def SupervisorDelay( self ): delay( 1 ) def
( self ): # RESET = 0 value = 0x00 self.cpuControl.Set( value ) self.SupervisorDelay() # RESET = 1 value = self.RESET self.cpuControl.Set( value ) return def TakeBus( self ): value = self.BUSREQ self.cpuControl.Set( value ) while True: value = self.cpuIoData.GetB( ) if (value & BUSAQ) == 0 break self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.DirectionB( IOALLINPUT ) value = M1 | C data.iodir |= M1, CLK, INT, BUSACK data, setgpio MREQ WR RD IORQ return def ReleaseBus( self ): address[0].iodir = 0xff # input (high-z) address[1].iodir = 0xff # input (high-z) data.iodir = 0xff if( reset ) supervisorDelay busreq = 1 while trie get gpio[1] if busaq != 0 break return def SlowClock( self ): period = 1.0/Float( rate )/2.0 clken = 0 while true: clkout = 0 sleep( period ) clkout = 1 sleep( period ) return def NormalClock( self ): CLKEN =1 return def SetAddress( self, addr ): gpio0 = bitswap( addr >> 8 ) gpio1 = bitswap( addr & 0xff ) return ############################## def MemRead( self, addr ): set address( addr) rd = 0 mreq = 0 result = daa.getgpio(0) rd = 1 MREQ = 1 return 0xff def MemWrite( self, addr, data ): set address( addr ) data.setgpio( val ) wr = 0 mreq = 0 wr = 1 mreq = 1 iodir0 = 0xff return def IORead( self, addr ): set address (addr ) rd = 0 iorq = 0 val = data.getgpio rd = 1 iorq = 1 return 0xff def IOWrite( self, addr, data ): set address( addr ) iodir 0 = 0x00 data.setgpio( data ) wr = 0 iorq = 0 wr = 1 iorq = 1 iodir 0 = 0xff return
Reset
identifier_name
lib_RC2014_BusSupervisor.py
#!/usr/bin/python ################################################################################ # Bus Supervisor Interface # # - interfaces to the MCP23017 and PCF8574 IO expander chips # # The logic for this was ported from Dr Scott M. Baker's project: # http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor # ################################################################################ from libArdySer import ArdySer from lib_GenericChip import GenericChip from GS_Timing import delay from lib_MCP23017_IOExpander16 import MCP23017_IOExpander16 from lib_PCF8574_IOExpander8 import PCF8574_IOExpander8 class RC2014_BusSupervisor: ################################## # class variables ardy = None cpuIoData = None # A0-A7 - Data byte # B0-B7 - Bus control M1 = 0x01 # B0 CLK = 0x02 # B1 INT = 0x04 # B2 MREQ = 0x08 # B3 WR = 0x10 # B4 RD = 0x20 # B5 IORQ = 0x40 # B6 BUSACK = 0x80 # B7 cpuControl = None # 0x0F - control, clock, etc BUSREQ = 0x01 RESET = 0x02 CLKEN = 0x04 CLKOUT = 0x08 # 0xF0 - unused cpuAddress = None # A0-A7, B0-B7 - Address lines (reversed) # our mirror values here data = 0 dataControl = 0 dataAddress = 0 ############################## def bitReverse( data ): retval = 0 if( (data & 0x80) == 0x80 ): retval = retval | 0x01 if( (data & 0x40) == 0x40 ): retval = retval | 0x02 if( (data & 0x20) == 0x20 ): retval = retval | 0x04 if( (data & 0x10) == 0x10 ): retval = retval | 0x08 if( (data & 0x08) == 0x08 ): retval = retval | 0x10 if( (data & 0x04) == 0x04 ): retval = retval | 0x20 if( (data & 0x02) == 0x02 ): retval = retval | 0x40 if( (data & 0x01) == 0x01 ): retval = retval | 0x80 return retval ################################## # Initialization def __init__( self, _ardy, _i2cAddr8 = None ): # set the arduino object baseAddr = _i2cAddr8 if _i2cAddr8 is None: baseAddr = 0x21 self.data = 0 self.dataControl = 0 self.dataAddress = 0 self.ardy = _ardy self.cpuIoData = MCP23017_IOExpander16( _ardy, baseAddr + 0 ) self.cpuControl = PCF8574_IOExpander8( _ardy, baseAddr + 1 ) self.cpuAddress = MCP23017_IOExpander16( _ardy, baseAddr + 2 ) self.ClearAllExpanders() def ClearAllExpaners( self ): # clear data register self.cpuIoData.DirectionA( IODIRA, IOALLINPUT ) self.cpuIoData.SetA( 0x00 ) self.cpuIoData.DirectionB( IODIRA, IOALLINPUT ) self.cpuIoData.SetB( 0x00 ) # clear control register self.cpuControl.Set( 0x00 ) # clear address register self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.SetA( 0x00 ) self.cpuAddress.DirectionB( IOALLINPUT ) self.cpuAddress.SetB( 0x00 ) ################################## # Low-level commands ################################## # Package commands def SupervisorDelay( self ): delay( 1 ) def Reset( self ): # RESET = 0
def TakeBus( self ): value = self.BUSREQ self.cpuControl.Set( value ) while True: value = self.cpuIoData.GetB( ) if (value & BUSAQ) == 0 break self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.DirectionB( IOALLINPUT ) value = M1 | C data.iodir |= M1, CLK, INT, BUSACK data, setgpio MREQ WR RD IORQ return def ReleaseBus( self ): address[0].iodir = 0xff # input (high-z) address[1].iodir = 0xff # input (high-z) data.iodir = 0xff if( reset ) supervisorDelay busreq = 1 while trie get gpio[1] if busaq != 0 break return def SlowClock( self ): period = 1.0/Float( rate )/2.0 clken = 0 while true: clkout = 0 sleep( period ) clkout = 1 sleep( period ) return def NormalClock( self ): CLKEN =1 return def SetAddress( self, addr ): gpio0 = bitswap( addr >> 8 ) gpio1 = bitswap( addr & 0xff ) return ############################## def MemRead( self, addr ): set address( addr) rd = 0 mreq = 0 result = daa.getgpio(0) rd = 1 MREQ = 1 return 0xff def MemWrite( self, addr, data ): set address( addr ) data.setgpio( val ) wr = 0 mreq = 0 wr = 1 mreq = 1 iodir0 = 0xff return def IORead( self, addr ): set address (addr ) rd = 0 iorq = 0 val = data.getgpio rd = 1 iorq = 1 return 0xff def IOWrite( self, addr, data ): set address( addr ) iodir 0 = 0x00 data.setgpio( data ) wr = 0 iorq = 0 wr = 1 iorq = 1 iodir 0 = 0xff return
value = 0x00 self.cpuControl.Set( value ) self.SupervisorDelay() # RESET = 1 value = self.RESET self.cpuControl.Set( value ) return
identifier_body
lib_RC2014_BusSupervisor.py
#!/usr/bin/python ################################################################################ # Bus Supervisor Interface # # - interfaces to the MCP23017 and PCF8574 IO expander chips # # The logic for this was ported from Dr Scott M. Baker's project: # http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor # ################################################################################ from libArdySer import ArdySer from lib_GenericChip import GenericChip from GS_Timing import delay from lib_MCP23017_IOExpander16 import MCP23017_IOExpander16 from lib_PCF8574_IOExpander8 import PCF8574_IOExpander8 class RC2014_BusSupervisor: ################################## # class variables ardy = None cpuIoData = None # A0-A7 - Data byte # B0-B7 - Bus control M1 = 0x01 # B0 CLK = 0x02 # B1 INT = 0x04 # B2 MREQ = 0x08 # B3 WR = 0x10 # B4 RD = 0x20 # B5 IORQ = 0x40 # B6 BUSACK = 0x80 # B7 cpuControl = None # 0x0F - control, clock, etc BUSREQ = 0x01 RESET = 0x02 CLKEN = 0x04 CLKOUT = 0x08 # 0xF0 - unused cpuAddress = None # A0-A7, B0-B7 - Address lines (reversed) # our mirror values here data = 0 dataControl = 0 dataAddress = 0 ############################## def bitReverse( data ): retval = 0 if( (data & 0x80) == 0x80 ): retval = retval | 0x01 if( (data & 0x40) == 0x40 ): retval = retval | 0x02 if( (data & 0x20) == 0x20 ): retval = retval | 0x04 if( (data & 0x10) == 0x10 ): retval = retval | 0x08 if( (data & 0x08) == 0x08 ): retval = retval | 0x10 if( (data & 0x04) == 0x04 ): retval = retval | 0x20 if( (data & 0x02) == 0x02 ): retval = retval | 0x40 if( (data & 0x01) == 0x01 ): retval = retval | 0x80 return retval ################################## # Initialization def __init__( self, _ardy, _i2cAddr8 = None ): # set the arduino object baseAddr = _i2cAddr8 if _i2cAddr8 is None: baseAddr = 0x21 self.data = 0 self.dataControl = 0 self.dataAddress = 0 self.ardy = _ardy self.cpuIoData = MCP23017_IOExpander16( _ardy, baseAddr + 0 ) self.cpuControl = PCF8574_IOExpander8( _ardy, baseAddr + 1 ) self.cpuAddress = MCP23017_IOExpander16( _ardy, baseAddr + 2 ) self.ClearAllExpanders() def ClearAllExpaners( self ): # clear data register self.cpuIoData.DirectionA( IODIRA, IOALLINPUT ) self.cpuIoData.SetA( 0x00 ) self.cpuIoData.DirectionB( IODIRA, IOALLINPUT ) self.cpuIoData.SetB( 0x00 ) # clear control register self.cpuControl.Set( 0x00 ) # clear address register self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.SetA( 0x00 ) self.cpuAddress.DirectionB( IOALLINPUT ) self.cpuAddress.SetB( 0x00 ) ################################## # Low-level commands ################################## # Package commands def SupervisorDelay( self ): delay( 1 ) def Reset( self ): # RESET = 0 value = 0x00 self.cpuControl.Set( value ) self.SupervisorDelay() # RESET = 1 value = self.RESET self.cpuControl.Set( value ) return def TakeBus( self ): value = self.BUSREQ self.cpuControl.Set( value ) while True: value = self.cpuIoData.GetB( ) if (value & BUSAQ) == 0 break self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.DirectionB( IOALLINPUT ) value = M1 | C data.iodir |= M1, CLK, INT, BUSACK data, setgpio MREQ WR RD IORQ return def ReleaseBus( self ): address[0].iodir = 0xff # input (high-z) address[1].iodir = 0xff # input (high-z) data.iodir = 0xff if( reset ) supervisorDelay busreq = 1 while trie get gpio[1] if busaq != 0 break return def SlowClock( self ):
def NormalClock( self ): CLKEN =1 return def SetAddress( self, addr ): gpio0 = bitswap( addr >> 8 ) gpio1 = bitswap( addr & 0xff ) return ############################## def MemRead( self, addr ): set address( addr) rd = 0 mreq = 0 result = daa.getgpio(0) rd = 1 MREQ = 1 return 0xff def MemWrite( self, addr, data ): set address( addr ) data.setgpio( val ) wr = 0 mreq = 0 wr = 1 mreq = 1 iodir0 = 0xff return def IORead( self, addr ): set address (addr ) rd = 0 iorq = 0 val = data.getgpio rd = 1 iorq = 1 return 0xff def IOWrite( self, addr, data ): set address( addr ) iodir 0 = 0x00 data.setgpio( data ) wr = 0 iorq = 0 wr = 1 iorq = 1 iodir 0 = 0xff return
period = 1.0/Float( rate )/2.0 clken = 0 while true: clkout = 0 sleep( period ) clkout = 1 sleep( period ) return
conditional_block
lib_RC2014_BusSupervisor.py
#!/usr/bin/python ################################################################################ # Bus Supervisor Interface # # - interfaces to the MCP23017 and PCF8574 IO expander chips # # The logic for this was ported from Dr Scott M. Baker's project: # http://www.smbaker.com/z80-retrocomputing-4-bus-supervisor # ################################################################################ from libArdySer import ArdySer from lib_GenericChip import GenericChip from GS_Timing import delay from lib_MCP23017_IOExpander16 import MCP23017_IOExpander16 from lib_PCF8574_IOExpander8 import PCF8574_IOExpander8 class RC2014_BusSupervisor:
ardy = None cpuIoData = None # A0-A7 - Data byte # B0-B7 - Bus control M1 = 0x01 # B0 CLK = 0x02 # B1 INT = 0x04 # B2 MREQ = 0x08 # B3 WR = 0x10 # B4 RD = 0x20 # B5 IORQ = 0x40 # B6 BUSACK = 0x80 # B7 cpuControl = None # 0x0F - control, clock, etc BUSREQ = 0x01 RESET = 0x02 CLKEN = 0x04 CLKOUT = 0x08 # 0xF0 - unused cpuAddress = None # A0-A7, B0-B7 - Address lines (reversed) # our mirror values here data = 0 dataControl = 0 dataAddress = 0 ############################## def bitReverse( data ): retval = 0 if( (data & 0x80) == 0x80 ): retval = retval | 0x01 if( (data & 0x40) == 0x40 ): retval = retval | 0x02 if( (data & 0x20) == 0x20 ): retval = retval | 0x04 if( (data & 0x10) == 0x10 ): retval = retval | 0x08 if( (data & 0x08) == 0x08 ): retval = retval | 0x10 if( (data & 0x04) == 0x04 ): retval = retval | 0x20 if( (data & 0x02) == 0x02 ): retval = retval | 0x40 if( (data & 0x01) == 0x01 ): retval = retval | 0x80 return retval ################################## # Initialization def __init__( self, _ardy, _i2cAddr8 = None ): # set the arduino object baseAddr = _i2cAddr8 if _i2cAddr8 is None: baseAddr = 0x21 self.data = 0 self.dataControl = 0 self.dataAddress = 0 self.ardy = _ardy self.cpuIoData = MCP23017_IOExpander16( _ardy, baseAddr + 0 ) self.cpuControl = PCF8574_IOExpander8( _ardy, baseAddr + 1 ) self.cpuAddress = MCP23017_IOExpander16( _ardy, baseAddr + 2 ) self.ClearAllExpanders() def ClearAllExpaners( self ): # clear data register self.cpuIoData.DirectionA( IODIRA, IOALLINPUT ) self.cpuIoData.SetA( 0x00 ) self.cpuIoData.DirectionB( IODIRA, IOALLINPUT ) self.cpuIoData.SetB( 0x00 ) # clear control register self.cpuControl.Set( 0x00 ) # clear address register self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.SetA( 0x00 ) self.cpuAddress.DirectionB( IOALLINPUT ) self.cpuAddress.SetB( 0x00 ) ################################## # Low-level commands ################################## # Package commands def SupervisorDelay( self ): delay( 1 ) def Reset( self ): # RESET = 0 value = 0x00 self.cpuControl.Set( value ) self.SupervisorDelay() # RESET = 1 value = self.RESET self.cpuControl.Set( value ) return def TakeBus( self ): value = self.BUSREQ self.cpuControl.Set( value ) while True: value = self.cpuIoData.GetB( ) if (value & BUSAQ) == 0 break self.cpuAddress.DirectionA( IOALLINPUT ) self.cpuAddress.DirectionB( IOALLINPUT ) value = M1 | C data.iodir |= M1, CLK, INT, BUSACK data, setgpio MREQ WR RD IORQ return def ReleaseBus( self ): address[0].iodir = 0xff # input (high-z) address[1].iodir = 0xff # input (high-z) data.iodir = 0xff if( reset ) supervisorDelay busreq = 1 while trie get gpio[1] if busaq != 0 break return def SlowClock( self ): period = 1.0/Float( rate )/2.0 clken = 0 while true: clkout = 0 sleep( period ) clkout = 1 sleep( period ) return def NormalClock( self ): CLKEN =1 return def SetAddress( self, addr ): gpio0 = bitswap( addr >> 8 ) gpio1 = bitswap( addr & 0xff ) return ############################## def MemRead( self, addr ): set address( addr) rd = 0 mreq = 0 result = daa.getgpio(0) rd = 1 MREQ = 1 return 0xff def MemWrite( self, addr, data ): set address( addr ) data.setgpio( val ) wr = 0 mreq = 0 wr = 1 mreq = 1 iodir0 = 0xff return def IORead( self, addr ): set address (addr ) rd = 0 iorq = 0 val = data.getgpio rd = 1 iorq = 1 return 0xff def IOWrite( self, addr, data ): set address( addr ) iodir 0 = 0x00 data.setgpio( data ) wr = 0 iorq = 0 wr = 1 iorq = 1 iodir 0 = 0xff return
################################## # class variables
random_line_split
gaia_unit.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import sys import glob import subprocess import json # load modules from parent dir sys.path.insert(1, os.path.dirname(sys.path[0])) from mozharness.mozilla.testing.gaia_test import GaiaTest from mozharness.mozilla.testing.unittest import TestSummaryOutputParserHelper class GaiaUnitTest(GaiaTest): def __init__(self, require_config_file=False): GaiaTest.__init__(self, require_config_file) def pull(self, **kwargs): GaiaTest.pull(self, **kwargs) def run_tests(self): """ Run the unit test suite. """ dirs = self.query_abs_dirs() self.make_node_modules() # make the gaia profile self.make_gaia(dirs['abs_gaia_dir'], self.config.get('xre_path'), xre_url=self.config.get('xre_url'), debug=True) # build the testrunner command arguments python = self.query_python_path('python') cmd = [python, '-u', os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'main.py')] executable = 'firefox' if 'b2g' in self.binary_path: executable = 'b2g-bin' profile = os.path.join(dirs['abs_gaia_dir'], 'profile-debug') binary = os.path.join(os.path.dirname(self.binary_path), executable) cmd.extend(self._build_arg('--binary', binary)) cmd.extend(self._build_arg('--profile', profile)) cmd.extend(self._build_arg('--symbols-path', self.symbols_path)) cmd.extend(self._build_arg('--browser-arg', self.config.get('browser_arg'))) # Add support for chunking if self.config.get('total_chunks') and self.config.get('this_chunk'): chunker = [ os.path.join(dirs['abs_gaia_dir'], 'bin', 'chunk'), self.config.get('total_chunks'), self.config.get('this_chunk') ] disabled_tests = [] disabled_manifest = os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'disabled.json') with open(disabled_manifest, 'r') as m: try: disabled_tests = json.loads(m.read()) except: print "Error while decoding disabled.json; please make sure this file has valid JSON syntax." sys.exit(1) # Construct a list of all tests unit_tests = [] for path in ('apps', 'tv_apps'): test_root = os.path.join(dirs['abs_gaia_dir'], path) full_paths = glob.glob(os.path.join(test_root, '*/test/unit/*_test.js')) unit_tests += map(lambda x: os.path.relpath(x, test_root), full_paths) # Remove the tests that are disabled active_unit_tests = filter(lambda x: x not in disabled_tests, unit_tests) # Chunk the list as requested tests_to_run = subprocess.check_output(chunker + active_unit_tests).strip().split(' ') cmd.extend(tests_to_run) output_parser = TestSummaryOutputParserHelper(config=self.config, log_obj=self.log_obj, error_list=self.error_list) upload_dir = self.query_abs_dirs()['abs_blob_upload_dir'] if not os.path.isdir(upload_dir): self.mkdir_p(upload_dir) env = self.query_env() env['MOZ_UPLOAD_DIR'] = upload_dir # I don't like this output_timeout hardcode, but bug 920153 code = self.run_command(cmd, env=env, output_parser=output_parser, output_timeout=1760) output_parser.print_summary('gaia-unit-tests') self.publish(code) if __name__ == '__main__':
gaia_unit_test = GaiaUnitTest() gaia_unit_test.run_and_exit()
conditional_block
gaia_unit.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import sys import glob import subprocess import json # load modules from parent dir sys.path.insert(1, os.path.dirname(sys.path[0])) from mozharness.mozilla.testing.gaia_test import GaiaTest from mozharness.mozilla.testing.unittest import TestSummaryOutputParserHelper class GaiaUnitTest(GaiaTest): def __init__(self, require_config_file=False): GaiaTest.__init__(self, require_config_file) def pull(self, **kwargs): GaiaTest.pull(self, **kwargs) def run_tests(self): """ Run the unit test suite. """ dirs = self.query_abs_dirs() self.make_node_modules() # make the gaia profile self.make_gaia(dirs['abs_gaia_dir'], self.config.get('xre_path'), xre_url=self.config.get('xre_url'), debug=True) # build the testrunner command arguments python = self.query_python_path('python') cmd = [python, '-u', os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'main.py')] executable = 'firefox' if 'b2g' in self.binary_path: executable = 'b2g-bin' profile = os.path.join(dirs['abs_gaia_dir'], 'profile-debug') binary = os.path.join(os.path.dirname(self.binary_path), executable) cmd.extend(self._build_arg('--binary', binary)) cmd.extend(self._build_arg('--profile', profile)) cmd.extend(self._build_arg('--symbols-path', self.symbols_path)) cmd.extend(self._build_arg('--browser-arg', self.config.get('browser_arg'))) # Add support for chunking if self.config.get('total_chunks') and self.config.get('this_chunk'): chunker = [ os.path.join(dirs['abs_gaia_dir'], 'bin', 'chunk'), self.config.get('total_chunks'), self.config.get('this_chunk') ] disabled_tests = [] disabled_manifest = os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'disabled.json') with open(disabled_manifest, 'r') as m: try: disabled_tests = json.loads(m.read())
# Construct a list of all tests unit_tests = [] for path in ('apps', 'tv_apps'): test_root = os.path.join(dirs['abs_gaia_dir'], path) full_paths = glob.glob(os.path.join(test_root, '*/test/unit/*_test.js')) unit_tests += map(lambda x: os.path.relpath(x, test_root), full_paths) # Remove the tests that are disabled active_unit_tests = filter(lambda x: x not in disabled_tests, unit_tests) # Chunk the list as requested tests_to_run = subprocess.check_output(chunker + active_unit_tests).strip().split(' ') cmd.extend(tests_to_run) output_parser = TestSummaryOutputParserHelper(config=self.config, log_obj=self.log_obj, error_list=self.error_list) upload_dir = self.query_abs_dirs()['abs_blob_upload_dir'] if not os.path.isdir(upload_dir): self.mkdir_p(upload_dir) env = self.query_env() env['MOZ_UPLOAD_DIR'] = upload_dir # I don't like this output_timeout hardcode, but bug 920153 code = self.run_command(cmd, env=env, output_parser=output_parser, output_timeout=1760) output_parser.print_summary('gaia-unit-tests') self.publish(code) if __name__ == '__main__': gaia_unit_test = GaiaUnitTest() gaia_unit_test.run_and_exit()
except: print "Error while decoding disabled.json; please make sure this file has valid JSON syntax." sys.exit(1)
random_line_split
gaia_unit.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import sys import glob import subprocess import json # load modules from parent dir sys.path.insert(1, os.path.dirname(sys.path[0])) from mozharness.mozilla.testing.gaia_test import GaiaTest from mozharness.mozilla.testing.unittest import TestSummaryOutputParserHelper class GaiaUnitTest(GaiaTest): def __init__(self, require_config_file=False): GaiaTest.__init__(self, require_config_file) def pull(self, **kwargs): GaiaTest.pull(self, **kwargs) def
(self): """ Run the unit test suite. """ dirs = self.query_abs_dirs() self.make_node_modules() # make the gaia profile self.make_gaia(dirs['abs_gaia_dir'], self.config.get('xre_path'), xre_url=self.config.get('xre_url'), debug=True) # build the testrunner command arguments python = self.query_python_path('python') cmd = [python, '-u', os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'main.py')] executable = 'firefox' if 'b2g' in self.binary_path: executable = 'b2g-bin' profile = os.path.join(dirs['abs_gaia_dir'], 'profile-debug') binary = os.path.join(os.path.dirname(self.binary_path), executable) cmd.extend(self._build_arg('--binary', binary)) cmd.extend(self._build_arg('--profile', profile)) cmd.extend(self._build_arg('--symbols-path', self.symbols_path)) cmd.extend(self._build_arg('--browser-arg', self.config.get('browser_arg'))) # Add support for chunking if self.config.get('total_chunks') and self.config.get('this_chunk'): chunker = [ os.path.join(dirs['abs_gaia_dir'], 'bin', 'chunk'), self.config.get('total_chunks'), self.config.get('this_chunk') ] disabled_tests = [] disabled_manifest = os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'disabled.json') with open(disabled_manifest, 'r') as m: try: disabled_tests = json.loads(m.read()) except: print "Error while decoding disabled.json; please make sure this file has valid JSON syntax." sys.exit(1) # Construct a list of all tests unit_tests = [] for path in ('apps', 'tv_apps'): test_root = os.path.join(dirs['abs_gaia_dir'], path) full_paths = glob.glob(os.path.join(test_root, '*/test/unit/*_test.js')) unit_tests += map(lambda x: os.path.relpath(x, test_root), full_paths) # Remove the tests that are disabled active_unit_tests = filter(lambda x: x not in disabled_tests, unit_tests) # Chunk the list as requested tests_to_run = subprocess.check_output(chunker + active_unit_tests).strip().split(' ') cmd.extend(tests_to_run) output_parser = TestSummaryOutputParserHelper(config=self.config, log_obj=self.log_obj, error_list=self.error_list) upload_dir = self.query_abs_dirs()['abs_blob_upload_dir'] if not os.path.isdir(upload_dir): self.mkdir_p(upload_dir) env = self.query_env() env['MOZ_UPLOAD_DIR'] = upload_dir # I don't like this output_timeout hardcode, but bug 920153 code = self.run_command(cmd, env=env, output_parser=output_parser, output_timeout=1760) output_parser.print_summary('gaia-unit-tests') self.publish(code) if __name__ == '__main__': gaia_unit_test = GaiaUnitTest() gaia_unit_test.run_and_exit()
run_tests
identifier_name
gaia_unit.py
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # 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/. # ***** END LICENSE BLOCK ***** import os import sys import glob import subprocess import json # load modules from parent dir sys.path.insert(1, os.path.dirname(sys.path[0])) from mozharness.mozilla.testing.gaia_test import GaiaTest from mozharness.mozilla.testing.unittest import TestSummaryOutputParserHelper class GaiaUnitTest(GaiaTest): def __init__(self, require_config_file=False): GaiaTest.__init__(self, require_config_file) def pull(self, **kwargs):
def run_tests(self): """ Run the unit test suite. """ dirs = self.query_abs_dirs() self.make_node_modules() # make the gaia profile self.make_gaia(dirs['abs_gaia_dir'], self.config.get('xre_path'), xre_url=self.config.get('xre_url'), debug=True) # build the testrunner command arguments python = self.query_python_path('python') cmd = [python, '-u', os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'main.py')] executable = 'firefox' if 'b2g' in self.binary_path: executable = 'b2g-bin' profile = os.path.join(dirs['abs_gaia_dir'], 'profile-debug') binary = os.path.join(os.path.dirname(self.binary_path), executable) cmd.extend(self._build_arg('--binary', binary)) cmd.extend(self._build_arg('--profile', profile)) cmd.extend(self._build_arg('--symbols-path', self.symbols_path)) cmd.extend(self._build_arg('--browser-arg', self.config.get('browser_arg'))) # Add support for chunking if self.config.get('total_chunks') and self.config.get('this_chunk'): chunker = [ os.path.join(dirs['abs_gaia_dir'], 'bin', 'chunk'), self.config.get('total_chunks'), self.config.get('this_chunk') ] disabled_tests = [] disabled_manifest = os.path.join(dirs['abs_runner_dir'], 'gaia_unit_test', 'disabled.json') with open(disabled_manifest, 'r') as m: try: disabled_tests = json.loads(m.read()) except: print "Error while decoding disabled.json; please make sure this file has valid JSON syntax." sys.exit(1) # Construct a list of all tests unit_tests = [] for path in ('apps', 'tv_apps'): test_root = os.path.join(dirs['abs_gaia_dir'], path) full_paths = glob.glob(os.path.join(test_root, '*/test/unit/*_test.js')) unit_tests += map(lambda x: os.path.relpath(x, test_root), full_paths) # Remove the tests that are disabled active_unit_tests = filter(lambda x: x not in disabled_tests, unit_tests) # Chunk the list as requested tests_to_run = subprocess.check_output(chunker + active_unit_tests).strip().split(' ') cmd.extend(tests_to_run) output_parser = TestSummaryOutputParserHelper(config=self.config, log_obj=self.log_obj, error_list=self.error_list) upload_dir = self.query_abs_dirs()['abs_blob_upload_dir'] if not os.path.isdir(upload_dir): self.mkdir_p(upload_dir) env = self.query_env() env['MOZ_UPLOAD_DIR'] = upload_dir # I don't like this output_timeout hardcode, but bug 920153 code = self.run_command(cmd, env=env, output_parser=output_parser, output_timeout=1760) output_parser.print_summary('gaia-unit-tests') self.publish(code) if __name__ == '__main__': gaia_unit_test = GaiaUnitTest() gaia_unit_test.run_and_exit()
GaiaTest.pull(self, **kwargs)
identifier_body
setPassword.component.ts
import { Component, ViewEncapsulation, OnInit } from '@angular/core'; import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms'; import { Http, Headers } from '@angular/http'; import { JwtHelper } from 'angular2-jwt'; import { Router, ActivatedRoute, Params } from '@angular/router'; import 'rxjs/add/operator/map'; import { SetPasswordService } from './../_authService/setPassword.service'; import { DataService } from './../../data/data.service'; @Component({ selector: 'setPassword', template: require('./setPassword.html'), }) export class setPassword implements OnInit { public setPasswordForm:FormGroup; public password:AbstractControl; public repassword:AbstractControl; public token; constructor( private _fb: FormBuilder, private route: ActivatedRoute, private router: Router, private SetPasswordService: SetPasswordService, private DataService: DataService, ) { } ngOnInit() { this.route.params.subscribe((params: Params) => { this.token = params['token']; }); if(this.SetPasswordService.CheckingToken(this.token)) { this.DataService.showMessageError('Token invalid'); this.router.navigate(['/admin']); } else { this.setPasswordForm = this._fb.group({ 'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
}, { validator: this.MatchPassword // your validation method }); this.password = this.setPasswordForm.controls['password']; this.repassword = this.setPasswordForm.controls['repassword']; } } // check match password MatchPassword(AC: AbstractControl) { let password = AC.get('password').value; // to get value in input tag let repassword = AC.get('repassword').value; // to get value in input tag if(password != repassword) { AC.get('repassword').setErrors( {MatchPassword: true}); } else { return null; } } onSubmit() { this.SetPasswordService.UpdatePassword(this.token, this.setPasswordForm.value.password) .subscribe(data => { if(data.status != 200) { this.DataService.showMessageError(data.message); } else { this.DataService.showMessageSuccess(data.message); this.router.navigate(['/']); } }); } } //irmusyafa.dev © 2017
'repassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
random_line_split
setPassword.component.ts
import { Component, ViewEncapsulation, OnInit } from '@angular/core'; import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms'; import { Http, Headers } from '@angular/http'; import { JwtHelper } from 'angular2-jwt'; import { Router, ActivatedRoute, Params } from '@angular/router'; import 'rxjs/add/operator/map'; import { SetPasswordService } from './../_authService/setPassword.service'; import { DataService } from './../../data/data.service'; @Component({ selector: 'setPassword', template: require('./setPassword.html'), }) export class setPassword implements OnInit { public setPasswordForm:FormGroup; public password:AbstractControl; public repassword:AbstractControl; public token; constructor( private _fb: FormBuilder, private route: ActivatedRoute, private router: Router, private SetPasswordService: SetPasswordService, private DataService: DataService, ) { } ngOnInit() { this.route.params.subscribe((params: Params) => { this.token = params['token']; }); if(this.SetPasswordService.CheckingToken(this.token))
else { this.setPasswordForm = this._fb.group({ 'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])], 'repassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])] }, { validator: this.MatchPassword // your validation method }); this.password = this.setPasswordForm.controls['password']; this.repassword = this.setPasswordForm.controls['repassword']; } } // check match password MatchPassword(AC: AbstractControl) { let password = AC.get('password').value; // to get value in input tag let repassword = AC.get('repassword').value; // to get value in input tag if(password != repassword) { AC.get('repassword').setErrors( {MatchPassword: true}); } else { return null; } } onSubmit() { this.SetPasswordService.UpdatePassword(this.token, this.setPasswordForm.value.password) .subscribe(data => { if(data.status != 200) { this.DataService.showMessageError(data.message); } else { this.DataService.showMessageSuccess(data.message); this.router.navigate(['/']); } }); } } //irmusyafa.dev © 2017
{ this.DataService.showMessageError('Token invalid'); this.router.navigate(['/admin']); }
conditional_block
setPassword.component.ts
import { Component, ViewEncapsulation, OnInit } from '@angular/core'; import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms'; import { Http, Headers } from '@angular/http'; import { JwtHelper } from 'angular2-jwt'; import { Router, ActivatedRoute, Params } from '@angular/router'; import 'rxjs/add/operator/map'; import { SetPasswordService } from './../_authService/setPassword.service'; import { DataService } from './../../data/data.service'; @Component({ selector: 'setPassword', template: require('./setPassword.html'), }) export class setPassword implements OnInit { public setPasswordForm:FormGroup; public password:AbstractControl; public repassword:AbstractControl; public token; constructor( private _fb: FormBuilder, private route: ActivatedRoute, private router: Router, private SetPasswordService: SetPasswordService, private DataService: DataService, ) { } ngOnInit() { this.route.params.subscribe((params: Params) => { this.token = params['token']; }); if(this.SetPasswordService.CheckingToken(this.token)) { this.DataService.showMessageError('Token invalid'); this.router.navigate(['/admin']); } else { this.setPasswordForm = this._fb.group({ 'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])], 'repassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])] }, { validator: this.MatchPassword // your validation method }); this.password = this.setPasswordForm.controls['password']; this.repassword = this.setPasswordForm.controls['repassword']; } } // check match password
(AC: AbstractControl) { let password = AC.get('password').value; // to get value in input tag let repassword = AC.get('repassword').value; // to get value in input tag if(password != repassword) { AC.get('repassword').setErrors( {MatchPassword: true}); } else { return null; } } onSubmit() { this.SetPasswordService.UpdatePassword(this.token, this.setPasswordForm.value.password) .subscribe(data => { if(data.status != 200) { this.DataService.showMessageError(data.message); } else { this.DataService.showMessageSuccess(data.message); this.router.navigate(['/']); } }); } } //irmusyafa.dev © 2017
MatchPassword
identifier_name
borrowck-borrow-overloaded-auto-deref-mut.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test how overloaded deref interacts with borrows when DerefMut // is implemented. use std::ops::{Deref, DerefMut}; struct Own<T> { value: *mut T } impl<T> Deref for Own<T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.value } } } impl<T> DerefMut for Own<T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.value } } } struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) } fn set(&mut self, x: int, y: int) { self.x = x; self.y = y; } fn x_ref(&self) -> &int { &self.x } fn y_mut(&mut self) -> &mut int { &mut self.y } } fn deref_imm_field(x: Own<Point>) { let _i = &x.y; } fn deref_mut_field1(x: Own<Point>) { let _i = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Own<Point>) { let _i = &mut x.y; } fn deref_extend_field(x: &Own<Point>) -> &int { &x.y } fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int { &mut x.y //~ ERROR cannot borrow } fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int { &mut x.y } fn deref_extend_mut_field3(x: &mut Own<Point>) { // Hmm, this is unfortunate, because with box it would work, // but it's presently the expected outcome. See `deref_extend_mut_field4` // for the workaround. let _x = &mut x.x; let _y = &mut x.y; //~ ERROR cannot borrow } fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) { let p = &mut **x; let _x = &mut p.x; let _y = &mut p.y; } fn assign_field1<'a>(x: Own<Point>) { x.y = 3; //~ ERROR cannot borrow } fn assign_field2<'a>(x: &'a Own<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field3<'a>(x: &'a mut Own<Point>) { x.y = 3; } fn assign_field4<'a>(x: &'a mut Own<Point>) { let _p: &mut Point = &mut **x; x.y = 3; //~ ERROR cannot borrow } // FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut. /* fn deref_imm_method(x: Own<Point>) { let _i = x.get(); } */ fn deref_mut_method1(x: Own<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Own<Point>) { x.set(0, 0); } fn deref_extend_method(x: &Own<Point>) -> &int { x.x_ref() } fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int { x.y_mut() } fn assign_method1<'a>(x: Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Own<Point>)
pub fn main() {}
{ *x.y_mut() = 3; }
identifier_body
borrowck-borrow-overloaded-auto-deref-mut.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test how overloaded deref interacts with borrows when DerefMut // is implemented. use std::ops::{Deref, DerefMut}; struct Own<T> { value: *mut T } impl<T> Deref for Own<T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.value } } } impl<T> DerefMut for Own<T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.value } } } struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) }
self.y = y; } fn x_ref(&self) -> &int { &self.x } fn y_mut(&mut self) -> &mut int { &mut self.y } } fn deref_imm_field(x: Own<Point>) { let _i = &x.y; } fn deref_mut_field1(x: Own<Point>) { let _i = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Own<Point>) { let _i = &mut x.y; } fn deref_extend_field(x: &Own<Point>) -> &int { &x.y } fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int { &mut x.y //~ ERROR cannot borrow } fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int { &mut x.y } fn deref_extend_mut_field3(x: &mut Own<Point>) { // Hmm, this is unfortunate, because with box it would work, // but it's presently the expected outcome. See `deref_extend_mut_field4` // for the workaround. let _x = &mut x.x; let _y = &mut x.y; //~ ERROR cannot borrow } fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) { let p = &mut **x; let _x = &mut p.x; let _y = &mut p.y; } fn assign_field1<'a>(x: Own<Point>) { x.y = 3; //~ ERROR cannot borrow } fn assign_field2<'a>(x: &'a Own<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field3<'a>(x: &'a mut Own<Point>) { x.y = 3; } fn assign_field4<'a>(x: &'a mut Own<Point>) { let _p: &mut Point = &mut **x; x.y = 3; //~ ERROR cannot borrow } // FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut. /* fn deref_imm_method(x: Own<Point>) { let _i = x.get(); } */ fn deref_mut_method1(x: Own<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Own<Point>) { x.set(0, 0); } fn deref_extend_method(x: &Own<Point>) -> &int { x.x_ref() } fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int { x.y_mut() } fn assign_method1<'a>(x: Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Own<Point>) { *x.y_mut() = 3; } pub fn main() {}
fn set(&mut self, x: int, y: int) { self.x = x;
random_line_split
borrowck-borrow-overloaded-auto-deref-mut.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test how overloaded deref interacts with borrows when DerefMut // is implemented. use std::ops::{Deref, DerefMut}; struct Own<T> { value: *mut T } impl<T> Deref for Own<T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.value } } } impl<T> DerefMut for Own<T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.value } } } struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) } fn set(&mut self, x: int, y: int) { self.x = x; self.y = y; } fn x_ref(&self) -> &int { &self.x } fn y_mut(&mut self) -> &mut int { &mut self.y } } fn deref_imm_field(x: Own<Point>) { let _i = &x.y; } fn deref_mut_field1(x: Own<Point>) { let _i = &mut x.y; //~ ERROR cannot borrow } fn deref_mut_field2(mut x: Own<Point>) { let _i = &mut x.y; } fn deref_extend_field(x: &Own<Point>) -> &int { &x.y } fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int { &mut x.y //~ ERROR cannot borrow } fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int { &mut x.y } fn deref_extend_mut_field3(x: &mut Own<Point>) { // Hmm, this is unfortunate, because with box it would work, // but it's presently the expected outcome. See `deref_extend_mut_field4` // for the workaround. let _x = &mut x.x; let _y = &mut x.y; //~ ERROR cannot borrow } fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) { let p = &mut **x; let _x = &mut p.x; let _y = &mut p.y; } fn assign_field1<'a>(x: Own<Point>) { x.y = 3; //~ ERROR cannot borrow } fn assign_field2<'a>(x: &'a Own<Point>) { x.y = 3; //~ ERROR cannot assign } fn assign_field3<'a>(x: &'a mut Own<Point>) { x.y = 3; } fn assign_field4<'a>(x: &'a mut Own<Point>) { let _p: &mut Point = &mut **x; x.y = 3; //~ ERROR cannot borrow } // FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut. /* fn deref_imm_method(x: Own<Point>) { let _i = x.get(); } */ fn deref_mut_method1(x: Own<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Own<Point>) { x.set(0, 0); } fn deref_extend_method(x: &Own<Point>) -> &int { x.x_ref() } fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int { x.y_mut() } fn assign_method1<'a>(x: Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn
<'a>(x: &'a Own<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method3<'a>(x: &'a mut Own<Point>) { *x.y_mut() = 3; } pub fn main() {}
assign_method2
identifier_name
gofish.py
#!/usr/bin/env python from __future__ import print_function from builtins import input import sys import pmagpy.pmag as pmag def main(): """ NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gofish.py [options] [< filename] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify input file -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, N, R, k, a95, csd """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename
elif '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data = sys.stdin.readlines() # read from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if ofile == "": print(outstring) else: out.write(outstring+'\n') # if __name__ == "__main__": main()
file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines()
conditional_block
gofish.py
#!/usr/bin/env python
from builtins import input import sys import pmagpy.pmag as pmag def main(): """ NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gofish.py [options] [< filename] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify input file -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, N, R, k, a95, csd """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines() elif '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data = sys.stdin.readlines() # read from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if ofile == "": print(outstring) else: out.write(outstring+'\n') # if __name__ == "__main__": main()
from __future__ import print_function
random_line_split
gofish.py
#!/usr/bin/env python from __future__ import print_function from builtins import input import sys import pmagpy.pmag as pmag def
(): """ NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gofish.py [options] [< filename] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify input file -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, N, R, k, a95, csd """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines() elif '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data = sys.stdin.readlines() # read from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if ofile == "": print(outstring) else: out.write(outstring+'\n') # if __name__ == "__main__": main()
main
identifier_name
gofish.py
#!/usr/bin/env python from __future__ import print_function from builtins import input import sys import pmagpy.pmag as pmag def main():
if __name__ == "__main__": main()
""" NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gofish.py [options] [< filename] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify input file -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, N, R, k, a95, csd """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines() elif '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data = sys.stdin.readlines() # read from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if ofile == "": print(outstring) else: out.write(outstring+'\n') #
identifier_body
chrome-runner.ts
/// <reference path='../../third_party/typings/node/node.d.ts' /> // Platform independnet way to run the Chrome binary using node. import path = require('path'); import childProcess = require('child_process'); import fs = require('fs'); export interface PlatformPaths { windowsXp ?: string[]; windowsVista ?: string[]; macSystem ?: string[]; macUser ?: string[]; linuxSystem ?: string[]; [other:string] : string[]; } var chromeStablePaths :PlatformPaths = { windowsXp: [path.join(process.env['HOMEPATH'] || '', 'Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe')], windowsVista: [path.join(process.env['USERPROFILE'] || '', '\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')], macSystem: ['/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'], macUser: [path.join(process.env['HOME'] || '', '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome')], linuxSystem: ['/usr/bin/google-chrome', '/usr/local/bin/google-chrome', '/opt/bin/google-chrome'], } var chromeCanaryPaths :PlatformPaths = { windowsXp: [path.join(process.env['HOMEPATH'] || '', 'Local Settings\\Application Data\\Google\\Chrome\ SxS\\Application\\chrome.exe')], windowsVista: [path.join(process.env['USERPROFILE'] || '', '\\AppData\\Local\\Google\\Chrome\ SxS\\Application\\chrome.exe')], macSystem: ['/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary'], macUser: [path.join(process.env['HOME'] || '', '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary')], linuxSystem: ['/usr/bin/google-chrome-unstable', '/usr/local/bin/google-chrome-unstable', '/opt/bin/google-chrome-unstable'] } export var chromePaths = { stable: chromeStablePaths, canary: chromeCanaryPaths }; // Utility function to pick the first path for chrome that exists in the // filesystem (searches in order, lexographically first of version specified, // and then for that version for each platform path). Returns null if no path // if found. export function pickFirstPath(chromePathsForVersions:PlatformPaths[]) : string
export interface NodeChildProcessOptions { cwd?: string; stdio?: any; custom?: any; env?: any; detached?: boolean; }; // Run the chrome binary. export function runChrome( config:{ path ?:string; versions ?:PlatformPaths[]; args ?:string[]; processOptions?:NodeChildProcessOptions; } = {}) : { path :string; childProcess :childProcess.ChildProcess } { var chromePathsForVersions :PlatformPaths[] = config.path ? [{ other: [config.path] }] : config.versions || [chromePaths.stable, chromePaths.canary]; var chosenChromePath = pickFirstPath(chromePathsForVersions); if (!chosenChromePath) { throw new Error('Cannot find Chrome binary in: ' + JSON.stringify(chromePathsForVersions)); } return { path: chosenChromePath, childProcess :childProcess.spawn(chosenChromePath, config.args, config.processOptions), }; }
{ for(var i = 0; i < chromePathsForVersions.length; ++i) { var chromePaths = chromePathsForVersions[i]; for (var pathName in chromePaths) { var paths = chromePaths[pathName]; for (var j = 0; j < paths.length; j++) { var path = paths[j]; if (fs.existsSync(path)) return path; } } } return null; }
identifier_body
chrome-runner.ts
/// <reference path='../../third_party/typings/node/node.d.ts' /> // Platform independnet way to run the Chrome binary using node. import path = require('path'); import childProcess = require('child_process'); import fs = require('fs'); export interface PlatformPaths { windowsXp ?: string[]; windowsVista ?: string[]; macSystem ?: string[]; macUser ?: string[]; linuxSystem ?: string[]; [other:string] : string[]; } var chromeStablePaths :PlatformPaths = { windowsXp: [path.join(process.env['HOMEPATH'] || '', 'Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe')], windowsVista: [path.join(process.env['USERPROFILE'] || '', '\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')], macSystem: ['/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'], macUser: [path.join(process.env['HOME'] || '', '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome')], linuxSystem: ['/usr/bin/google-chrome', '/usr/local/bin/google-chrome', '/opt/bin/google-chrome'], } var chromeCanaryPaths :PlatformPaths = { windowsXp: [path.join(process.env['HOMEPATH'] || '', 'Local Settings\\Application Data\\Google\\Chrome\ SxS\\Application\\chrome.exe')], windowsVista: [path.join(process.env['USERPROFILE'] || '', '\\AppData\\Local\\Google\\Chrome\ SxS\\Application\\chrome.exe')], macSystem: ['/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary'], macUser: [path.join(process.env['HOME'] || '', '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary')], linuxSystem: ['/usr/bin/google-chrome-unstable', '/usr/local/bin/google-chrome-unstable', '/opt/bin/google-chrome-unstable'] } export var chromePaths = { stable: chromeStablePaths, canary: chromeCanaryPaths }; // Utility function to pick the first path for chrome that exists in the // filesystem (searches in order, lexographically first of version specified, // and then for that version for each platform path). Returns null if no path // if found. export function pickFirstPath(chromePathsForVersions:PlatformPaths[]) : string { for(var i = 0; i < chromePathsForVersions.length; ++i) { var chromePaths = chromePathsForVersions[i]; for (var pathName in chromePaths) { var paths = chromePaths[pathName]; for (var j = 0; j < paths.length; j++) { var path = paths[j]; if (fs.existsSync(path)) return path; } } } return null; } export interface NodeChildProcessOptions { cwd?: string; stdio?: any; custom?: any; env?: any; detached?: boolean; }; // Run the chrome binary. export function
( config:{ path ?:string; versions ?:PlatformPaths[]; args ?:string[]; processOptions?:NodeChildProcessOptions; } = {}) : { path :string; childProcess :childProcess.ChildProcess } { var chromePathsForVersions :PlatformPaths[] = config.path ? [{ other: [config.path] }] : config.versions || [chromePaths.stable, chromePaths.canary]; var chosenChromePath = pickFirstPath(chromePathsForVersions); if (!chosenChromePath) { throw new Error('Cannot find Chrome binary in: ' + JSON.stringify(chromePathsForVersions)); } return { path: chosenChromePath, childProcess :childProcess.spawn(chosenChromePath, config.args, config.processOptions), }; }
runChrome
identifier_name
chrome-runner.ts
/// <reference path='../../third_party/typings/node/node.d.ts' /> // Platform independnet way to run the Chrome binary using node. import path = require('path'); import childProcess = require('child_process'); import fs = require('fs'); export interface PlatformPaths { windowsXp ?: string[]; windowsVista ?: string[]; macSystem ?: string[]; macUser ?: string[]; linuxSystem ?: string[]; [other:string] : string[]; } var chromeStablePaths :PlatformPaths = { windowsXp: [path.join(process.env['HOMEPATH'] || '', 'Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe')], windowsVista: [path.join(process.env['USERPROFILE'] || '', '\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')], macSystem: ['/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'], macUser: [path.join(process.env['HOME'] || '', '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome')], linuxSystem: ['/usr/bin/google-chrome', '/usr/local/bin/google-chrome', '/opt/bin/google-chrome'], } var chromeCanaryPaths :PlatformPaths = { windowsXp: [path.join(process.env['HOMEPATH'] || '', 'Local Settings\\Application Data\\Google\\Chrome\ SxS\\Application\\chrome.exe')], windowsVista: [path.join(process.env['USERPROFILE'] || '', '\\AppData\\Local\\Google\\Chrome\ SxS\\Application\\chrome.exe')], macSystem: ['/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary'], macUser: [path.join(process.env['HOME'] || '', '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary')], linuxSystem: ['/usr/bin/google-chrome-unstable', '/usr/local/bin/google-chrome-unstable', '/opt/bin/google-chrome-unstable'] } export var chromePaths = { stable: chromeStablePaths, canary: chromeCanaryPaths }; // Utility function to pick the first path for chrome that exists in the // filesystem (searches in order, lexographically first of version specified, // and then for that version for each platform path). Returns null if no path // if found.
var chromePaths = chromePathsForVersions[i]; for (var pathName in chromePaths) { var paths = chromePaths[pathName]; for (var j = 0; j < paths.length; j++) { var path = paths[j]; if (fs.existsSync(path)) return path; } } } return null; } export interface NodeChildProcessOptions { cwd?: string; stdio?: any; custom?: any; env?: any; detached?: boolean; }; // Run the chrome binary. export function runChrome( config:{ path ?:string; versions ?:PlatformPaths[]; args ?:string[]; processOptions?:NodeChildProcessOptions; } = {}) : { path :string; childProcess :childProcess.ChildProcess } { var chromePathsForVersions :PlatformPaths[] = config.path ? [{ other: [config.path] }] : config.versions || [chromePaths.stable, chromePaths.canary]; var chosenChromePath = pickFirstPath(chromePathsForVersions); if (!chosenChromePath) { throw new Error('Cannot find Chrome binary in: ' + JSON.stringify(chromePathsForVersions)); } return { path: chosenChromePath, childProcess :childProcess.spawn(chosenChromePath, config.args, config.processOptions), }; }
export function pickFirstPath(chromePathsForVersions:PlatformPaths[]) : string { for(var i = 0; i < chromePathsForVersions.length; ++i) {
random_line_split
karma.conf.js
Encore.configureRuntimeEnvironment('dev'); const encoreConfig = require('./webpack-encore-config'); const webpackConfig = encoreConfig('tests/Functional/App/var/karma/build').getWebpackConfig(); delete webpackConfig.entry; delete webpackConfig.optimization.runtimeChunk; delete webpackConfig.optimization.splitChunks; // Replace the mini-css-extract-plugin's loader by the style-loader const styleExtensions = ['/\\.css$/', '/\\.s[ac]ss$/', '/\\.less$/', '/\\.styl$/']; for (const rule of webpackConfig.module.rules) { if (rule.test && rule.oneOf && styleExtensions.includes(rule.test.toString())) { rule.oneOf.forEach((oneOf) => { oneOf.use[0] = 'style-loader'; }) } } // Karma options module.exports = function(config) { config.set({ frameworks: ['jasmine-ajax', 'jasmine'], browserConsoleLogOptions: { level: 'log', terminal: false //Remove console.* logs }, files: [ 'tests/Resources/assets/js/main.js' ], preprocessors: { 'tests/Resources/assets/js/main.js': ['webpack'] }, webpackMiddleware: { stats: 'errors-only', noInfo: true, }, browsers: ['Firefox'], reporters: ['spec'], specReporter: { suppressPassed: true, }, webpack: webpackConfig }); };
const Encore = require('@symfony/webpack-encore');
random_line_split
karma.conf.js
const Encore = require('@symfony/webpack-encore'); Encore.configureRuntimeEnvironment('dev'); const encoreConfig = require('./webpack-encore-config'); const webpackConfig = encoreConfig('tests/Functional/App/var/karma/build').getWebpackConfig(); delete webpackConfig.entry; delete webpackConfig.optimization.runtimeChunk; delete webpackConfig.optimization.splitChunks; // Replace the mini-css-extract-plugin's loader by the style-loader const styleExtensions = ['/\\.css$/', '/\\.s[ac]ss$/', '/\\.less$/', '/\\.styl$/']; for (const rule of webpackConfig.module.rules) { if (rule.test && rule.oneOf && styleExtensions.includes(rule.test.toString()))
} // Karma options module.exports = function(config) { config.set({ frameworks: ['jasmine-ajax', 'jasmine'], browserConsoleLogOptions: { level: 'log', terminal: false //Remove console.* logs }, files: [ 'tests/Resources/assets/js/main.js' ], preprocessors: { 'tests/Resources/assets/js/main.js': ['webpack'] }, webpackMiddleware: { stats: 'errors-only', noInfo: true, }, browsers: ['Firefox'], reporters: ['spec'], specReporter: { suppressPassed: true, }, webpack: webpackConfig }); };
{ rule.oneOf.forEach((oneOf) => { oneOf.use[0] = 'style-loader'; }) }
conditional_block
parsemode.py
#!/usr/bin/env python # pylint: disable=R0903 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2021 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains an object that represents a Telegram Message Parse Modes.""" from typing import ClassVar from telegram import constants from telegram.utils.deprecate import set_new_attribute_deprecated class
: """This object represents a Telegram Message Parse Modes.""" __slots__ = ('__dict__',) MARKDOWN: ClassVar[str] = constants.PARSEMODE_MARKDOWN """:const:`telegram.constants.PARSEMODE_MARKDOWN`\n Note: :attr:`MARKDOWN` is a legacy mode, retained by Telegram for backward compatibility. You should use :attr:`MARKDOWN_V2` instead. """ MARKDOWN_V2: ClassVar[str] = constants.PARSEMODE_MARKDOWN_V2 """:const:`telegram.constants.PARSEMODE_MARKDOWN_V2`""" HTML: ClassVar[str] = constants.PARSEMODE_HTML """:const:`telegram.constants.PARSEMODE_HTML`""" def __setattr__(self, key: str, value: object) -> None: set_new_attribute_deprecated(self, key, value)
ParseMode
identifier_name
parsemode.py
#!/usr/bin/env python # pylint: disable=R0903 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2021 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains an object that represents a Telegram Message Parse Modes.""" from typing import ClassVar from telegram import constants from telegram.utils.deprecate import set_new_attribute_deprecated class ParseMode: """This object represents a Telegram Message Parse Modes."""
__slots__ = ('__dict__',) MARKDOWN: ClassVar[str] = constants.PARSEMODE_MARKDOWN """:const:`telegram.constants.PARSEMODE_MARKDOWN`\n Note: :attr:`MARKDOWN` is a legacy mode, retained by Telegram for backward compatibility. You should use :attr:`MARKDOWN_V2` instead. """ MARKDOWN_V2: ClassVar[str] = constants.PARSEMODE_MARKDOWN_V2 """:const:`telegram.constants.PARSEMODE_MARKDOWN_V2`""" HTML: ClassVar[str] = constants.PARSEMODE_HTML """:const:`telegram.constants.PARSEMODE_HTML`""" def __setattr__(self, key: str, value: object) -> None: set_new_attribute_deprecated(self, key, value)
random_line_split
parsemode.py
#!/usr/bin/env python # pylint: disable=R0903 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2021 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains an object that represents a Telegram Message Parse Modes.""" from typing import ClassVar from telegram import constants from telegram.utils.deprecate import set_new_attribute_deprecated class ParseMode: """This object represents a Telegram Message Parse Modes.""" __slots__ = ('__dict__',) MARKDOWN: ClassVar[str] = constants.PARSEMODE_MARKDOWN """:const:`telegram.constants.PARSEMODE_MARKDOWN`\n Note: :attr:`MARKDOWN` is a legacy mode, retained by Telegram for backward compatibility. You should use :attr:`MARKDOWN_V2` instead. """ MARKDOWN_V2: ClassVar[str] = constants.PARSEMODE_MARKDOWN_V2 """:const:`telegram.constants.PARSEMODE_MARKDOWN_V2`""" HTML: ClassVar[str] = constants.PARSEMODE_HTML """:const:`telegram.constants.PARSEMODE_HTML`""" def __setattr__(self, key: str, value: object) -> None:
set_new_attribute_deprecated(self, key, value)
identifier_body
dataverseRubeusCfg.js
/** * Dataverse FileBrowser configuration module. */ var $ = require('jquery'); var HGrid = require('hgrid'); var Rubeus = require('rubeus'); var bootbox = require('bootbox'); var osfHelpers = require('osfHelpers'); // Private members function refreshDataverseTree(grid, item, state) { var data = item.data || {}; data.state = state; var url = item.urls.state + '?' + $.param({state: state}); $.ajax({ type: 'get', url: url, success: function(data) { // Update the item with the new state data $.extend(item, data[0]); grid.reloadFolder(item); } }); } // Define HGrid Button Actions HGrid.Actions['releaseStudy'] = { on: 'click', callback: function (evt, row) { var self = this; var url = row.urls.release; bootbox.confirm({ title: 'Release this study?', message: 'By releasing this study, all content will be ' + 'made available through the Harvard Dataverse using their ' + 'internal privacy settings, regardless of your OSF project ' + 'settings. Are you sure you want to release this study?', callback: function(result) { if(result) { self.changeStatus(row, Rubeus.Status.RELEASING_STUDY); osfHelpers.putJSON( url, {} ).done(function() { osfHelpers.growl('Your study has been released.', 'Please allow up to 24 hours for the released version to ' + 'appear on your OSF project\'s file page.', 'success'); self.updateItem(row); }).fail( function(args) { var message = args.responseJSON.code === 400 ? 'Something went wrong when attempting to ' + 'release your study.' : 'This version has already been released.'; osfHelpers.growl('Error', message); self.updateItem(row); }); } } }); } }; // Register configuration Rubeus.cfg.dataverse = { // Handle events listeners: [ { on: 'change', selector: '.dataverse-state-select', callback: function(evt, row, grid) { var $this = $(evt.target); var state = $this.val(); refreshDataverseTree(grid, row, state); } } ], // Update file information for updated files uploadSuccess: function(file, row, data) { if (data.actionTaken === 'file_updated')
}, UPLOAD_ERROR: '<span class="text-danger">The Dataverse could ' + 'not accept your file at this time. </span>' };
{ var gridData = this.getData(); for (var i=0; i < gridData.length; i++) { var item = gridData[i]; if (item.file_id && data.old_id && item.file_id === data.old_id) { $.extend(item, data); this.updateItem(item); } } }
conditional_block
dataverseRubeusCfg.js
/** * Dataverse FileBrowser configuration module. */ var $ = require('jquery'); var HGrid = require('hgrid'); var Rubeus = require('rubeus'); var bootbox = require('bootbox'); var osfHelpers = require('osfHelpers'); // Private members function refreshDataverseTree(grid, item, state)
// Define HGrid Button Actions HGrid.Actions['releaseStudy'] = { on: 'click', callback: function (evt, row) { var self = this; var url = row.urls.release; bootbox.confirm({ title: 'Release this study?', message: 'By releasing this study, all content will be ' + 'made available through the Harvard Dataverse using their ' + 'internal privacy settings, regardless of your OSF project ' + 'settings. Are you sure you want to release this study?', callback: function(result) { if(result) { self.changeStatus(row, Rubeus.Status.RELEASING_STUDY); osfHelpers.putJSON( url, {} ).done(function() { osfHelpers.growl('Your study has been released.', 'Please allow up to 24 hours for the released version to ' + 'appear on your OSF project\'s file page.', 'success'); self.updateItem(row); }).fail( function(args) { var message = args.responseJSON.code === 400 ? 'Something went wrong when attempting to ' + 'release your study.' : 'This version has already been released.'; osfHelpers.growl('Error', message); self.updateItem(row); }); } } }); } }; // Register configuration Rubeus.cfg.dataverse = { // Handle events listeners: [ { on: 'change', selector: '.dataverse-state-select', callback: function(evt, row, grid) { var $this = $(evt.target); var state = $this.val(); refreshDataverseTree(grid, row, state); } } ], // Update file information for updated files uploadSuccess: function(file, row, data) { if (data.actionTaken === 'file_updated') { var gridData = this.getData(); for (var i=0; i < gridData.length; i++) { var item = gridData[i]; if (item.file_id && data.old_id && item.file_id === data.old_id) { $.extend(item, data); this.updateItem(item); } } } }, UPLOAD_ERROR: '<span class="text-danger">The Dataverse could ' + 'not accept your file at this time. </span>' };
{ var data = item.data || {}; data.state = state; var url = item.urls.state + '?' + $.param({state: state}); $.ajax({ type: 'get', url: url, success: function(data) { // Update the item with the new state data $.extend(item, data[0]); grid.reloadFolder(item); } }); }
identifier_body
dataverseRubeusCfg.js
/** * Dataverse FileBrowser configuration module. */ var $ = require('jquery'); var HGrid = require('hgrid'); var Rubeus = require('rubeus'); var bootbox = require('bootbox'); var osfHelpers = require('osfHelpers'); // Private members function refreshDataverseTree(grid, item, state) { var data = item.data || {}; data.state = state; var url = item.urls.state + '?' + $.param({state: state}); $.ajax({ type: 'get', url: url, success: function(data) { // Update the item with the new state data $.extend(item, data[0]); grid.reloadFolder(item); } }); } // Define HGrid Button Actions HGrid.Actions['releaseStudy'] = { on: 'click', callback: function (evt, row) { var self = this; var url = row.urls.release; bootbox.confirm({ title: 'Release this study?', message: 'By releasing this study, all content will be ' + 'made available through the Harvard Dataverse using their ' + 'internal privacy settings, regardless of your OSF project ' + 'settings. Are you sure you want to release this study?', callback: function(result) { if(result) { self.changeStatus(row, Rubeus.Status.RELEASING_STUDY); osfHelpers.putJSON( url, {} ).done(function() { osfHelpers.growl('Your study has been released.', 'Please allow up to 24 hours for the released version to ' + 'appear on your OSF project\'s file page.', 'success'); self.updateItem(row); }).fail( function(args) { var message = args.responseJSON.code === 400 ? 'Something went wrong when attempting to ' + 'release your study.' : 'This version has already been released.'; osfHelpers.growl('Error', message); self.updateItem(row); }); } } }); } }; // Register configuration Rubeus.cfg.dataverse = { // Handle events listeners: [ {
var state = $this.val(); refreshDataverseTree(grid, row, state); } } ], // Update file information for updated files uploadSuccess: function(file, row, data) { if (data.actionTaken === 'file_updated') { var gridData = this.getData(); for (var i=0; i < gridData.length; i++) { var item = gridData[i]; if (item.file_id && data.old_id && item.file_id === data.old_id) { $.extend(item, data); this.updateItem(item); } } } }, UPLOAD_ERROR: '<span class="text-danger">The Dataverse could ' + 'not accept your file at this time. </span>' };
on: 'change', selector: '.dataverse-state-select', callback: function(evt, row, grid) { var $this = $(evt.target);
random_line_split
dataverseRubeusCfg.js
/** * Dataverse FileBrowser configuration module. */ var $ = require('jquery'); var HGrid = require('hgrid'); var Rubeus = require('rubeus'); var bootbox = require('bootbox'); var osfHelpers = require('osfHelpers'); // Private members function
(grid, item, state) { var data = item.data || {}; data.state = state; var url = item.urls.state + '?' + $.param({state: state}); $.ajax({ type: 'get', url: url, success: function(data) { // Update the item with the new state data $.extend(item, data[0]); grid.reloadFolder(item); } }); } // Define HGrid Button Actions HGrid.Actions['releaseStudy'] = { on: 'click', callback: function (evt, row) { var self = this; var url = row.urls.release; bootbox.confirm({ title: 'Release this study?', message: 'By releasing this study, all content will be ' + 'made available through the Harvard Dataverse using their ' + 'internal privacy settings, regardless of your OSF project ' + 'settings. Are you sure you want to release this study?', callback: function(result) { if(result) { self.changeStatus(row, Rubeus.Status.RELEASING_STUDY); osfHelpers.putJSON( url, {} ).done(function() { osfHelpers.growl('Your study has been released.', 'Please allow up to 24 hours for the released version to ' + 'appear on your OSF project\'s file page.', 'success'); self.updateItem(row); }).fail( function(args) { var message = args.responseJSON.code === 400 ? 'Something went wrong when attempting to ' + 'release your study.' : 'This version has already been released.'; osfHelpers.growl('Error', message); self.updateItem(row); }); } } }); } }; // Register configuration Rubeus.cfg.dataverse = { // Handle events listeners: [ { on: 'change', selector: '.dataverse-state-select', callback: function(evt, row, grid) { var $this = $(evt.target); var state = $this.val(); refreshDataverseTree(grid, row, state); } } ], // Update file information for updated files uploadSuccess: function(file, row, data) { if (data.actionTaken === 'file_updated') { var gridData = this.getData(); for (var i=0; i < gridData.length; i++) { var item = gridData[i]; if (item.file_id && data.old_id && item.file_id === data.old_id) { $.extend(item, data); this.updateItem(item); } } } }, UPLOAD_ERROR: '<span class="text-danger">The Dataverse could ' + 'not accept your file at this time. </span>' };
refreshDataverseTree
identifier_name
size_of_tests.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use gecko_like_types; use gecko_like_types::*; use parser; use parser::*; use precomputed_hash::PrecomputedHash; use std::fmt; use visitor::SelectorVisitor; size_of_test!(size_of_selector, Selector<Impl>, 48); size_of_test!(size_of_pseudo_element, gecko_like_types::PseudoElement, 1); size_of_test!(size_of_selector_inner, SelectorInner<Impl>, 40); size_of_test!(size_of_complex_selector, ComplexSelector<Impl>, 24); size_of_test!(size_of_component, Component<Impl>, 32); size_of_test!(size_of_pseudo_class, PseudoClass, 24); impl parser::PseudoElement for gecko_like_types::PseudoElement { type Impl = Impl; } // Boilerplate impl SelectorImpl for Impl { type AttrValue = Atom; type Identifier = Atom; type ClassName = Atom; type LocalName = Atom; type NamespaceUrl = Atom; type NamespacePrefix = Atom; type BorrowedLocalName = Atom; type BorrowedNamespaceUrl = Atom; type NonTSPseudoClass = PseudoClass; type PseudoElement = gecko_like_types::PseudoElement; } impl SelectorMethods for PseudoClass { type Impl = Impl; fn visit<V>(&self, _visitor: &mut V) -> bool where V: SelectorVisitor<Impl = Self::Impl> { unimplemented!() } } impl ToCss for PseudoClass { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() } } impl ToCss for gecko_like_types::PseudoElement { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() } } impl fmt::Display for Atom { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() } } impl From<String> for Atom { fn
(_: String) -> Self { unimplemented!() } } impl<'a> From<&'a str> for Atom { fn from(_: &'a str) -> Self { unimplemented!() } } impl PrecomputedHash for Atom { fn precomputed_hash(&self) -> u32 { unimplemented!() } }
from
identifier_name
size_of_tests.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use gecko_like_types; use gecko_like_types::*; use parser; use parser::*; use precomputed_hash::PrecomputedHash; use std::fmt; use visitor::SelectorVisitor; size_of_test!(size_of_selector, Selector<Impl>, 48); size_of_test!(size_of_pseudo_element, gecko_like_types::PseudoElement, 1); size_of_test!(size_of_selector_inner, SelectorInner<Impl>, 40); size_of_test!(size_of_complex_selector, ComplexSelector<Impl>, 24); size_of_test!(size_of_component, Component<Impl>, 32); size_of_test!(size_of_pseudo_class, PseudoClass, 24); impl parser::PseudoElement for gecko_like_types::PseudoElement { type Impl = Impl; } // Boilerplate impl SelectorImpl for Impl { type AttrValue = Atom; type Identifier = Atom; type ClassName = Atom; type LocalName = Atom; type NamespaceUrl = Atom; type NamespacePrefix = Atom; type BorrowedLocalName = Atom; type BorrowedNamespaceUrl = Atom; type NonTSPseudoClass = PseudoClass; type PseudoElement = gecko_like_types::PseudoElement; } impl SelectorMethods for PseudoClass { type Impl = Impl; fn visit<V>(&self, _visitor: &mut V) -> bool where V: SelectorVisitor<Impl = Self::Impl> { unimplemented!() } } impl ToCss for PseudoClass { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() } } impl ToCss for gecko_like_types::PseudoElement { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() } } impl fmt::Display for Atom { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() } } impl From<String> for Atom { fn from(_: String) -> Self
} impl<'a> From<&'a str> for Atom { fn from(_: &'a str) -> Self { unimplemented!() } } impl PrecomputedHash for Atom { fn precomputed_hash(&self) -> u32 { unimplemented!() } }
{ unimplemented!() }
identifier_body
size_of_tests.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::ToCss; use gecko_like_types; use gecko_like_types::*; use parser; use parser::*; use precomputed_hash::PrecomputedHash; use std::fmt;
size_of_test!(size_of_selector_inner, SelectorInner<Impl>, 40); size_of_test!(size_of_complex_selector, ComplexSelector<Impl>, 24); size_of_test!(size_of_component, Component<Impl>, 32); size_of_test!(size_of_pseudo_class, PseudoClass, 24); impl parser::PseudoElement for gecko_like_types::PseudoElement { type Impl = Impl; } // Boilerplate impl SelectorImpl for Impl { type AttrValue = Atom; type Identifier = Atom; type ClassName = Atom; type LocalName = Atom; type NamespaceUrl = Atom; type NamespacePrefix = Atom; type BorrowedLocalName = Atom; type BorrowedNamespaceUrl = Atom; type NonTSPseudoClass = PseudoClass; type PseudoElement = gecko_like_types::PseudoElement; } impl SelectorMethods for PseudoClass { type Impl = Impl; fn visit<V>(&self, _visitor: &mut V) -> bool where V: SelectorVisitor<Impl = Self::Impl> { unimplemented!() } } impl ToCss for PseudoClass { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() } } impl ToCss for gecko_like_types::PseudoElement { fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write { unimplemented!() } } impl fmt::Display for Atom { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { unimplemented!() } } impl From<String> for Atom { fn from(_: String) -> Self { unimplemented!() } } impl<'a> From<&'a str> for Atom { fn from(_: &'a str) -> Self { unimplemented!() } } impl PrecomputedHash for Atom { fn precomputed_hash(&self) -> u32 { unimplemented!() } }
use visitor::SelectorVisitor; size_of_test!(size_of_selector, Selector<Impl>, 48); size_of_test!(size_of_pseudo_element, gecko_like_types::PseudoElement, 1);
random_line_split
compl.rs
use std::env; use std::fs; use sym::Symtable; extern crate glob; fn common_prefix(mut strs: Vec<String>) -> String { let mut c_prefix = String::new(); if strs.len() == 0 { return c_prefix; } let delegate = strs.pop().unwrap().clone(); for (di, dc) in delegate.chars().enumerate() { for ostr in &strs { match ostr.chars().nth(di) { Some(oc) => { if dc != oc { return c_prefix; } } None => { return c_prefix; } } } c_prefix.push(dc); } c_prefix } fn print_completions(res_vec: &Vec<String>) { // TODO: prettier println!(""); for p in res_vec { println!("{}", p); } } pub fn
(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String { if first_word && !in_str.contains('/') { bin_complete(in_str, st, print_multi) } else { fs_complete(in_str, print_multi) } } pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String { let res_vec = st.prefix_resolve_exec(in_str); if res_vec.len() == 1 { let mut res = res_vec[0].clone(); res.push(' '); res } else if res_vec.len() == 0 { in_str.to_string() } else { if print_multi { print_completions(&res_vec); } common_prefix(res_vec) } } // TODO: more completely handle globs in the to-complete string pub fn fs_complete(in_str: &str, print_multi: bool) -> String { let mut input; let mut tilde = false; let mut cpref = false; if in_str.starts_with("~/") { tilde = true; let in_str = in_str.trim_left_matches("~"); input = env::var("HOME").unwrap_or("~/".to_string()); input.push_str(in_str); } else { if in_str.starts_with("./") { cpref = true; } input = in_str.to_string(); } if !input.ends_with('*') { input.push('*'); } let mut postfix = ""; let res_vec = match glob::glob(&input) { Ok(x) => x, Err(_) => { return in_str.to_string(); } } .filter_map(Result::ok) .map(|x| format!("{}", x.display())) .collect::<Vec<String>>(); let mut ret = if res_vec.len() == 1 { let ref res = res_vec[0]; postfix = match fs::metadata(res) { Ok(x) => { if x.is_dir() { "/" } else { " " } } Err(_) => "", }; res.clone() } else if res_vec.len() > 0 { if print_multi { print_completions(&res_vec); } // find common prefix common_prefix(res_vec) } else { in_str.to_string() }; // post-facto formatting ret = ret.replace(" ", "\\ "); ret.push_str(postfix); if tilde { ret.replace(&env::var("HOME").unwrap(), "~") } else { if cpref && !ret.starts_with("./") { ret.insert(0, '.'); ret.insert(1, '/'); } ret } }
complete
identifier_name
compl.rs
use std::env; use std::fs; use sym::Symtable; extern crate glob; fn common_prefix(mut strs: Vec<String>) -> String { let mut c_prefix = String::new(); if strs.len() == 0 { return c_prefix; } let delegate = strs.pop().unwrap().clone(); for (di, dc) in delegate.chars().enumerate() { for ostr in &strs { match ostr.chars().nth(di) { Some(oc) =>
None => { return c_prefix; } } } c_prefix.push(dc); } c_prefix } fn print_completions(res_vec: &Vec<String>) { // TODO: prettier println!(""); for p in res_vec { println!("{}", p); } } pub fn complete(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String { if first_word && !in_str.contains('/') { bin_complete(in_str, st, print_multi) } else { fs_complete(in_str, print_multi) } } pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String { let res_vec = st.prefix_resolve_exec(in_str); if res_vec.len() == 1 { let mut res = res_vec[0].clone(); res.push(' '); res } else if res_vec.len() == 0 { in_str.to_string() } else { if print_multi { print_completions(&res_vec); } common_prefix(res_vec) } } // TODO: more completely handle globs in the to-complete string pub fn fs_complete(in_str: &str, print_multi: bool) -> String { let mut input; let mut tilde = false; let mut cpref = false; if in_str.starts_with("~/") { tilde = true; let in_str = in_str.trim_left_matches("~"); input = env::var("HOME").unwrap_or("~/".to_string()); input.push_str(in_str); } else { if in_str.starts_with("./") { cpref = true; } input = in_str.to_string(); } if !input.ends_with('*') { input.push('*'); } let mut postfix = ""; let res_vec = match glob::glob(&input) { Ok(x) => x, Err(_) => { return in_str.to_string(); } } .filter_map(Result::ok) .map(|x| format!("{}", x.display())) .collect::<Vec<String>>(); let mut ret = if res_vec.len() == 1 { let ref res = res_vec[0]; postfix = match fs::metadata(res) { Ok(x) => { if x.is_dir() { "/" } else { " " } } Err(_) => "", }; res.clone() } else if res_vec.len() > 0 { if print_multi { print_completions(&res_vec); } // find common prefix common_prefix(res_vec) } else { in_str.to_string() }; // post-facto formatting ret = ret.replace(" ", "\\ "); ret.push_str(postfix); if tilde { ret.replace(&env::var("HOME").unwrap(), "~") } else { if cpref && !ret.starts_with("./") { ret.insert(0, '.'); ret.insert(1, '/'); } ret } }
{ if dc != oc { return c_prefix; } }
conditional_block
compl.rs
use std::env; use std::fs; use sym::Symtable; extern crate glob; fn common_prefix(mut strs: Vec<String>) -> String { let mut c_prefix = String::new(); if strs.len() == 0 { return c_prefix; } let delegate = strs.pop().unwrap().clone(); for (di, dc) in delegate.chars().enumerate() { for ostr in &strs { match ostr.chars().nth(di) { Some(oc) => { if dc != oc { return c_prefix; } } None => { return c_prefix; } } } c_prefix.push(dc); } c_prefix } fn print_completions(res_vec: &Vec<String>)
pub fn complete(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String { if first_word && !in_str.contains('/') { bin_complete(in_str, st, print_multi) } else { fs_complete(in_str, print_multi) } } pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String { let res_vec = st.prefix_resolve_exec(in_str); if res_vec.len() == 1 { let mut res = res_vec[0].clone(); res.push(' '); res } else if res_vec.len() == 0 { in_str.to_string() } else { if print_multi { print_completions(&res_vec); } common_prefix(res_vec) } } // TODO: more completely handle globs in the to-complete string pub fn fs_complete(in_str: &str, print_multi: bool) -> String { let mut input; let mut tilde = false; let mut cpref = false; if in_str.starts_with("~/") { tilde = true; let in_str = in_str.trim_left_matches("~"); input = env::var("HOME").unwrap_or("~/".to_string()); input.push_str(in_str); } else { if in_str.starts_with("./") { cpref = true; } input = in_str.to_string(); } if !input.ends_with('*') { input.push('*'); } let mut postfix = ""; let res_vec = match glob::glob(&input) { Ok(x) => x, Err(_) => { return in_str.to_string(); } } .filter_map(Result::ok) .map(|x| format!("{}", x.display())) .collect::<Vec<String>>(); let mut ret = if res_vec.len() == 1 { let ref res = res_vec[0]; postfix = match fs::metadata(res) { Ok(x) => { if x.is_dir() { "/" } else { " " } } Err(_) => "", }; res.clone() } else if res_vec.len() > 0 { if print_multi { print_completions(&res_vec); } // find common prefix common_prefix(res_vec) } else { in_str.to_string() }; // post-facto formatting ret = ret.replace(" ", "\\ "); ret.push_str(postfix); if tilde { ret.replace(&env::var("HOME").unwrap(), "~") } else { if cpref && !ret.starts_with("./") { ret.insert(0, '.'); ret.insert(1, '/'); } ret } }
{ // TODO: prettier println!(""); for p in res_vec { println!("{}", p); } }
identifier_body
compl.rs
use std::env; use std::fs; use sym::Symtable; extern crate glob; fn common_prefix(mut strs: Vec<String>) -> String { let mut c_prefix = String::new(); if strs.len() == 0 { return c_prefix; } let delegate = strs.pop().unwrap().clone(); for (di, dc) in delegate.chars().enumerate() { for ostr in &strs { match ostr.chars().nth(di) { Some(oc) => { if dc != oc { return c_prefix; } } None => { return c_prefix; } } } c_prefix.push(dc); } c_prefix } fn print_completions(res_vec: &Vec<String>) { // TODO: prettier println!(""); for p in res_vec { println!("{}", p); }
pub fn complete(in_str: &str, st: &Symtable, first_word: bool, print_multi: bool) -> String { if first_word && !in_str.contains('/') { bin_complete(in_str, st, print_multi) } else { fs_complete(in_str, print_multi) } } pub fn bin_complete(in_str: &str, st: &Symtable, print_multi: bool) -> String { let res_vec = st.prefix_resolve_exec(in_str); if res_vec.len() == 1 { let mut res = res_vec[0].clone(); res.push(' '); res } else if res_vec.len() == 0 { in_str.to_string() } else { if print_multi { print_completions(&res_vec); } common_prefix(res_vec) } } // TODO: more completely handle globs in the to-complete string pub fn fs_complete(in_str: &str, print_multi: bool) -> String { let mut input; let mut tilde = false; let mut cpref = false; if in_str.starts_with("~/") { tilde = true; let in_str = in_str.trim_left_matches("~"); input = env::var("HOME").unwrap_or("~/".to_string()); input.push_str(in_str); } else { if in_str.starts_with("./") { cpref = true; } input = in_str.to_string(); } if !input.ends_with('*') { input.push('*'); } let mut postfix = ""; let res_vec = match glob::glob(&input) { Ok(x) => x, Err(_) => { return in_str.to_string(); } } .filter_map(Result::ok) .map(|x| format!("{}", x.display())) .collect::<Vec<String>>(); let mut ret = if res_vec.len() == 1 { let ref res = res_vec[0]; postfix = match fs::metadata(res) { Ok(x) => { if x.is_dir() { "/" } else { " " } } Err(_) => "", }; res.clone() } else if res_vec.len() > 0 { if print_multi { print_completions(&res_vec); } // find common prefix common_prefix(res_vec) } else { in_str.to_string() }; // post-facto formatting ret = ret.replace(" ", "\\ "); ret.push_str(postfix); if tilde { ret.replace(&env::var("HOME").unwrap(), "~") } else { if cpref && !ret.starts_with("./") { ret.insert(0, '.'); ret.insert(1, '/'); } ret } }
}
random_line_split
io.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library 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; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // //! Proxy objects for std::io::Stdin, std::io::Stdout, std::io::Stderr use std::fmt::Debug; use std::io::Write; /// Proxy object for output /// /// This is returned by `Runtime::stdout()` does implement `Write`. So you can /// `write!(rt.stdout(), "some things")` and it just works. /// /// The `Runtime` has to decide whether the OutputProxy should write to stdout, stderr or simply be /// a "sink" which does not write to either. /// pub enum OutputProxy { Out(::std::io::Stdout), Err(::std::io::Stderr), Sink, } impl Write for OutputProxy { fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> { match *self { OutputProxy::Out(ref mut r) => r.write(buf), OutputProxy::Err(ref mut r) => r.write(buf), OutputProxy::Sink => Ok(0), } } fn flush(&mut self) -> ::std::io::Result<()> { match *self { OutputProxy::Out(ref mut r) => r.flush(), OutputProxy::Err(ref mut r) => r.flush(), OutputProxy::Sink => Ok(()), } } } impl Debug for OutputProxy { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { match *self { OutputProxy::Out(..) => write!(f, "OutputProxy(Stdout)"), OutputProxy::Err(..) => write!(f, "OutputProxy(Stderr)"), OutputProxy::Sink => write!(f, "OutputProxy(Sink)"), } } } impl OutputProxy { pub fn lock(&self) -> LockedOutputProxy { match *self { OutputProxy::Out(ref r) => LockedOutputProxy::Out(r.lock()), OutputProxy::Err(ref r) => LockedOutputProxy::Err(r.lock()), OutputProxy::Sink => LockedOutputProxy::Sink, } } } pub enum LockedOutputProxy<'a> { Out(::std::io::StdoutLock<'a>), Err(::std::io::StderrLock<'a>), Sink, } impl<'a> Write for LockedOutputProxy<'a> { fn
(&mut self, buf: &[u8]) -> ::std::io::Result<usize> { match *self { LockedOutputProxy::Out(ref mut r) => r.write(buf), LockedOutputProxy::Err(ref mut r) => r.write(buf), LockedOutputProxy::Sink => Ok(buf.len()), } } fn flush(&mut self) -> ::std::io::Result<()> { match *self { LockedOutputProxy::Out(ref mut r) => r.flush(), LockedOutputProxy::Err(ref mut r) => r.flush(), LockedOutputProxy::Sink => Ok(()), } } } impl<'a> Debug for LockedOutputProxy<'a> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { match *self { LockedOutputProxy::Out(..) => write!(f, "LockedOutputProxy(Stdout)"), LockedOutputProxy::Err(..) => write!(f, "LockedOutputProxy(Stderr)"), LockedOutputProxy::Sink => write!(f, "LockedOutputProxy(Sink)"), } } }
write
identifier_name
io.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library 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; version // 2.1 of the License. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // //! Proxy objects for std::io::Stdin, std::io::Stdout, std::io::Stderr use std::fmt::Debug; use std::io::Write; /// Proxy object for output /// /// This is returned by `Runtime::stdout()` does implement `Write`. So you can /// `write!(rt.stdout(), "some things")` and it just works. /// /// The `Runtime` has to decide whether the OutputProxy should write to stdout, stderr or simply be /// a "sink" which does not write to either. /// pub enum OutputProxy { Out(::std::io::Stdout), Err(::std::io::Stderr), Sink, } impl Write for OutputProxy { fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> { match *self { OutputProxy::Out(ref mut r) => r.write(buf), OutputProxy::Err(ref mut r) => r.write(buf), OutputProxy::Sink => Ok(0), } } fn flush(&mut self) -> ::std::io::Result<()> { match *self { OutputProxy::Out(ref mut r) => r.flush(), OutputProxy::Err(ref mut r) => r.flush(),
} impl Debug for OutputProxy { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { match *self { OutputProxy::Out(..) => write!(f, "OutputProxy(Stdout)"), OutputProxy::Err(..) => write!(f, "OutputProxy(Stderr)"), OutputProxy::Sink => write!(f, "OutputProxy(Sink)"), } } } impl OutputProxy { pub fn lock(&self) -> LockedOutputProxy { match *self { OutputProxy::Out(ref r) => LockedOutputProxy::Out(r.lock()), OutputProxy::Err(ref r) => LockedOutputProxy::Err(r.lock()), OutputProxy::Sink => LockedOutputProxy::Sink, } } } pub enum LockedOutputProxy<'a> { Out(::std::io::StdoutLock<'a>), Err(::std::io::StderrLock<'a>), Sink, } impl<'a> Write for LockedOutputProxy<'a> { fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> { match *self { LockedOutputProxy::Out(ref mut r) => r.write(buf), LockedOutputProxy::Err(ref mut r) => r.write(buf), LockedOutputProxy::Sink => Ok(buf.len()), } } fn flush(&mut self) -> ::std::io::Result<()> { match *self { LockedOutputProxy::Out(ref mut r) => r.flush(), LockedOutputProxy::Err(ref mut r) => r.flush(), LockedOutputProxy::Sink => Ok(()), } } } impl<'a> Debug for LockedOutputProxy<'a> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { match *self { LockedOutputProxy::Out(..) => write!(f, "LockedOutputProxy(Stdout)"), LockedOutputProxy::Err(..) => write!(f, "LockedOutputProxy(Stderr)"), LockedOutputProxy::Sink => write!(f, "LockedOutputProxy(Sink)"), } } }
OutputProxy::Sink => Ok(()), } }
random_line_split
office_strings.debug.js
 Type.registerNamespace("Strings"); Strings.OfficeOM = function() { }; Strings.OfficeOM.registerClass("Strings.OfficeOM"); Strings.OfficeOM.L_InvalidNamedItemForBindingType = "Navedeni tip povezivanja nije kompatibilan sa navedenom imenovanom stavkom."; Strings.OfficeOM.L_EventHandlerNotExist = "Navedeni tip događaja nije podržan na ovom objektu."; Strings.OfficeOM.L_UnknownBindingType = "Tip povezivanja nije podržan."; Strings.OfficeOM.L_InvalidNode = "Nevažeći čvor"; Strings.OfficeOM.L_NotImplemented = "Funkcija {0} nije primenjena."; Strings.OfficeOM.L_NoCapability = "Nemate dovoljno dozvola za ovu radnju."; Strings.OfficeOM.L_SettingsCannotSave = "Nije bilo moguće sačuvati postavke."; Strings.OfficeOM.L_DataWriteReminder = "Data Write Reminder"; Strings.OfficeOM.L_InvalidBinding = "Nevažeće povezivanje"; Strings.OfficeOM.L_InvalidSetColumns = "Navedene kolone su nevažeće."; Strings.OfficeOM.L_BindingCreationError = "Greška u stvaranju povezivanja"; Strings.OfficeOM.L_FormatValueOutOfRange = "Vrednost je izvan dozvoljenog opsega."; Strings.OfficeOM.L_SelectionNotSupportCoercionType = "Trenutna selekcija nije kompatibilna sa navedenim tipom promene."; Strings.OfficeOM.L_InvalidBindingError = "Greška nevažećeg povezivanja";
Strings.OfficeOM.L_SettingsStaleError = "Greška usled zastarelih postavki"; Strings.OfficeOM.L_CannotNavigateTo = "Objekat se nalazi na lokaciji na kojoj navigacija nije podržana."; Strings.OfficeOM.L_ReadSettingsError = "Greška u postavkama čitanja"; Strings.OfficeOM.L_InvalidGetColumns = "Navedene kolone su nevažeće."; Strings.OfficeOM.L_CoercionTypeNotSupported = "Navedeni tip promene nije podržan."; Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "Aplikacija {0} ne postoji. Microsoft.Office.WebExtension.initialize(razlog) nije pozvan."; Strings.OfficeOM.L_OverwriteWorksheetData = "Operacija postavljanja nije uspela zato što će navedeni objekat podataka zameniti ili premestiti podatke."; Strings.OfficeOM.L_RowIndexOutOfRange = "Vrednost indeksa reda je izvan dozvoljenog opsega. Koristite vrednost (0 ili veću) koja je manja od broja redova."; Strings.OfficeOM.L_ColIndexOutOfRange = "Vrednost indeksa kolone je izvan dozvoljenog opsega. Koristite vrednost (0 ili veću) koja je manja od broja kolona."; Strings.OfficeOM.L_UnsupportedEnumeration = "Nepodržano nabrajanje"; Strings.OfficeOM.L_InvalidParameters = "Funkcija {0} ima nevažeće parametre."; Strings.OfficeOM.L_SetDataParametersConflict = "Navedeni parametri su neusaglašeni."; Strings.OfficeOM.L_DataNotMatchCoercionType = "Tip navedenog objekta podataka nije kompatibilan sa trenutnom selekcijom."; Strings.OfficeOM.L_UnsupportedEnumerationMessage = "Nabrajanje nije podržano u trenutnoj aplikaciji hosta."; Strings.OfficeOM.L_InvalidCoercion = "Nevažeći tip promene"; Strings.OfficeOM.L_NotSupportedEventType = "Navedeni tip događaja {0} nije podržan."; Strings.OfficeOM.L_UnsupportedDataObject = "Navedeni tip objekta podataka nije podržan."; Strings.OfficeOM.L_GetDataIsTooLarge = "Zahtevani skup podataka je prevelik."; Strings.OfficeOM.L_AppNameNotExist = "AppName za {0} ne postoji."; Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Napravite selekciju."; Strings.OfficeOM.L_MultipleNamedItemFound = "Pronađeno je više objekata sa istim imenom."; Strings.OfficeOM.L_InvalidCellsValue = "Neki parametri ćelije imaju vrednosti koje nisu dozvoljene. Proverite vrednosti još jednom i probajte ponovo."; Strings.OfficeOM.L_DataNotMatchBindingType = "Navedeni objekat podataka nije kompatibilan sa tipom povezivanja."; Strings.OfficeOM.L_InvalidFormatValue = "Neki parametri formata imaju vrednosti koje nisu dozvoljene. Proverite vrednosti još jednom i probajte ponovo."; Strings.OfficeOM.L_NotSupportedBindingType = "Navedeni tip povezivanja {0} nije podržan."; Strings.OfficeOM.L_InitializeNotReady = "Office.js još uvek nije potpuno učitan. Pokušajte ponovo kasnije ili postarajte se da dodate vaš kôd za pokretanje na vaš Office.initialize function."; Strings.OfficeOM.L_FormattingReminder = "Formatting Reminder"; Strings.OfficeOM.L_ShuttingDown = "Operacija nije uspela zato što podaci na serveru nisu u toku."; Strings.OfficeOM.L_OperationNotSupported = "Operacija nije podržana."; Strings.OfficeOM.L_DocumentReadOnly = "Zahtevana operacija nije dozvoljena u trenutnom režimu dokumenta."; Strings.OfficeOM.L_NamedItemNotFound = "Imenovana stavka ne postoji."; Strings.OfficeOM.L_InvalidApiCallInContext = "Nevažeći API poziv u trenutnom kontekstu."; Strings.OfficeOM.L_InvalidGetRows = "Navedeni redovi su nevažeći."; Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Note: The formatting sets set by a Formatting API call is suggested to be below 100."; Strings.OfficeOM.L_SetDataIsTooLarge = "Navedeni objekat podataka je prevelik."; Strings.OfficeOM.L_DataWriteError = "Greška u pisanju podataka"; Strings.OfficeOM.L_InvalidBindingOperation = "Operacija nevažećeg povezivanja"; Strings.OfficeOM.L_SpecifiedIdNotExist = "Navedeni ID ne postoji."; Strings.OfficeOM.L_FunctionCallFailed = "Poziv funkcije {0} nije uspeo, kod greške: {1}."; Strings.OfficeOM.L_DataNotMatchBindingSize = "Navedeni objekat podataka ne podudara se sa veličinom trenutne selekcije."; Strings.OfficeOM.L_SaveSettingsError = "Greška pri čuvanju postavki"; Strings.OfficeOM.L_InvalidSetStartRowColumn = "Navedene vrednosti za početni red ili početnu kolonu nisu važeće."; Strings.OfficeOM.L_InvalidFormat = "Greška nevažećeg formata"; Strings.OfficeOM.L_BindingNotExist = "Navedeno povezivanje ne postoji."; Strings.OfficeOM.L_SettingNameNotExist = "Navedeno ime postavke ne postoji."; Strings.OfficeOM.L_EventHandlerAdditionFailed = "Dodavanje rukovaoca događajem nije uspelo."; Strings.OfficeOM.L_InvalidAPICall = "Nevažeći API poziv"; Strings.OfficeOM.L_EventRegistrationError = "Greška pri registraciji događaja"; Strings.OfficeOM.L_ElementMissing = "Nismo mogli da oblikujemo ćeliju tabele zato što nedostaju neke vrednosti parametara. Proverite parametre još jednom i probajte ponovo."; Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Nije moguće koristiti parametre za koordinaciju sa tabelom tipa promene kada tabela sadrži objedinjene ćelije."; Strings.OfficeOM.L_NavOutOfBound = "Operacija nije uspela zato što je indeks van opsega."; Strings.OfficeOM.L_RedundantCallbackSpecification = "Povratni poziv ne može biti naveden i u listi argumenata i u opcionalnom objektu."; Strings.OfficeOM.L_CustomXmlError = "Greška u prilagođenim XML."; Strings.OfficeOM.L_SettingsAreStale = "Nije bilo moguće sačuvati postavke jer nisu u toku."; Strings.OfficeOM.L_TooManyOptionalFunction = "višestruke opcionalne funkcije na listi parametara"; Strings.OfficeOM.L_MissingRequiredArguments = "nedostaju neki neophodni argumenti"; Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Nije moguće koristiti parametre za koordinaciju sa tabelom tipa promene kada tabela sadrži objedinjene ćelije."; Strings.OfficeOM.L_HostError = "Greška hosta"; Strings.OfficeOM.L_OutOfRange = "Izvan opsega"; Strings.OfficeOM.L_InvalidSelectionForBindingType = "Nije moguće kreirati povezivanje sa trenutnom selekcijom i navedenim tipom povezivanja."; Strings.OfficeOM.L_TooManyOptionalObjects = "višestruki opcionalni objekti na listi parametara"; Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "Potrebo je da izabrani sadržaj bude u formatu tabele. Oblikujte podatke u vidu tabele i probajte ponovo."; Strings.OfficeOM.L_EventHandlerRemovalFailed = "Uklanjanje rukovaoca događajem nije uspelo."; Strings.OfficeOM.L_BindingToMultipleSelection = "Nekontinuirane selekcije nisu podržane."; Strings.OfficeOM.L_DataReadError = "Greška u čitanju podataka"; Strings.OfficeOM.L_InternalErrorDescription = "Došlo je do unutrašnje greške."; Strings.OfficeOM.L_InvalidDataFormat = "Format navedenog objekta podataka nije važeći."; Strings.OfficeOM.L_DataStale = "Podaci nisu u toku"; Strings.OfficeOM.L_GetSelectionNotSupported = "Trenutna selekcija nije podržana."; Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Note: The number of cells in a table is suggested to be below 20,000 cells."; Strings.OfficeOM.L_InvalidTableOptionValue = "Neki tableOptions parametri imaju vrednosti koje nisu dozvoljene. Proverite vrednosti još jednom i probajte ponovo."; Strings.OfficeOM.L_PermissionDenied = "Dozvola je odbijena"; Strings.OfficeOM.L_InvalidDataObject = "Nevažeći objekat podataka"; Strings.OfficeOM.L_SelectionCannotBound = "Nije moguće izvršiti povezivanje sa trenutnom selekcijom."; Strings.OfficeOM.L_InvalidColumnsForBinding = "Navedene kolone su nevažeće."; Strings.OfficeOM.L_BadSelectorString = "Niska koja je prosleđena u birač nije u ispravnom formatu ili nije podržan."; Strings.OfficeOM.L_InvalidGetRowColumnCounts = "Navedene vrednosti za broj redova ili broj kolona nisu važeće."; Strings.OfficeOM.L_OsfControlTypeNotSupported = "OsfControl tip nije podržan."; Strings.OfficeOM.L_InvalidValue = "Nevažeća vrednost"; Strings.OfficeOM.L_DataNotMatchSelection = "Navedeni objekat podataka nije kompatibilan sa oblikom ili dimenzijama trenutne selekcije."; Strings.OfficeOM.L_InternalError = "Unutrašnja greška"; Strings.OfficeOM.L_NotSupported = "Funkcija {0} nije podržana."; Strings.OfficeOM.L_CustomXmlNodeNotFound = "Nije pronađen navedeni čvor."; Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "Navedeni tip promene nije kompatibilan sa ovim tipom povezivanja."; Strings.OfficeOM.L_TooManyArguments = "previše argumenata"; Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Operacija nije podržana na ovom tipu povezivanja."; Strings.OfficeOM.L_InValidOptionalArgument = "nevažeći opcionalni argument"; Strings.OfficeOM.L_FileTypeNotSupported = "Navedeni tip datoteke nije podržan."; Strings.OfficeOM.L_GetDataParametersConflict = "Navedeni parametri su neusaglašeni."; Strings.OfficeOM.L_CallbackNotAFunction = "Povratni poziv mora biti funkcija tipa, bila je tipa {0}."
Strings.OfficeOM.L_InvalidGetStartRowColumn = "Navedene vrednosti za početni red ili početnu kolonu nisu važeće."; Strings.OfficeOM.L_InvalidSetRows = "Navedeni redovi su nevažeći."; Strings.OfficeOM.L_CannotWriteToSelection = "Upisivanje u trenutnu selekciju nije moguće."; Strings.OfficeOM.L_MissingParameter = "Parametar nedostaje"; Strings.OfficeOM.L_IndexOutOfRange = "Indeks je izvan opsega.";
random_line_split
oldisim_benchmark.py
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs oldisim. oldisim is a framework to support benchmarks that emulate Online Data-Intensive (OLDI) workloads, such as web search and social networking. oldisim includes sample workloads built on top of this framework. With its default config, oldisim models an example search topology. A user query is first processed by a front-end server, which then eventually fans out the query to a large number of leaf nodes. The latency is measured at the root of the tree, and often increases with the increase of fan-out. oldisim reports a scaling efficiency for a given topology. The scaling efficiency is defined as queries per second (QPS) at the current fan-out normalized to QPS at fan-out 1 with ISO root latency. Sample command line: ./pkb.py --benchmarks=oldisim --project='YOUR_PROJECT' --oldisim_num_leaves=4 --oldisim_fanout=1,2,3,4 --oldisim_latency_target=40 --oldisim_latency_metric=avg The above command will build a tree with one root node and four leaf nodes. The average latency target is 40ms. The root node will vary the fanout from 1 to 4 and measure the scaling efficiency. """ import logging import re import time from perfkitbenchmarker import configs from perfkitbenchmarker import flags from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import oldisim_dependencies FLAGS = flags.FLAGS flags.DEFINE_integer('oldisim_num_leaves', 4, 'number of leaf nodes', lower_bound=1, upper_bound=64) flags.DEFINE_list('oldisim_fanout', [], 'a list of fanouts to be tested. ' 'a root can connect to a subset of leaf nodes (fanout). ' 'the value of fanout has to be smaller than num_leaves.') flags.DEFINE_enum('oldisim_latency_metric', 'avg', ['avg', '50p', '90p', '95p', '99p', '99.9p'], 'Allowable metrics for end-to-end latency') flags.DEFINE_float('oldisim_latency_target', '30', 'latency target in ms') NUM_DRIVERS = 1 NUM_ROOTS = 1 BENCHMARK_NAME = 'oldisim' BENCHMARK_CONFIG = """ oldisim: description: > Run oldisim. Specify the number of leaf nodes with --oldisim_num_leaves vm_groups: default: vm_spec: *default_single_core """ def GetConfig(user_config): """Decide number of vms needed to run oldisim.""" config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves + NUM_DRIVERS + NUM_ROOTS) return config def InstallAndBuild(vm): """Install and build oldisim on the target vm. Args: vm: A vm instance that runs oldisim. """ logging.info('prepare oldisim on %s', vm) vm.Install('oldisim_dependencies') def Prepare(benchmark_spec): """Install and build oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms leaf_vms = [vm for vm_idx, vm in enumerate(vms) if vm_idx >= (NUM_DRIVERS + NUM_ROOTS)] if vms: vm_util.RunThreaded(InstallAndBuild, vms) # Launch job on the leaf nodes. leaf_server_bin = oldisim_dependencies.BinaryPath('LeafNode') for vm in leaf_vms: leaf_cmd = '%s --threads=%s' % (leaf_server_bin, vm.num_cpus) vm.RemoteCommand('%s &> /dev/null &' % leaf_cmd) def SetupRoot(root_vm, leaf_vms): """Connect a root node to a list of leaf nodes. Args: root_vm: A root vm instance. leaf_vms: A list of leaf vm instances. """ fanout_args = ' '.join(['--leaf=%s' % i.internal_ip for i in leaf_vms]) root_server_bin = oldisim_dependencies.BinaryPath('ParentNode') root_cmd = '%s --threads=%s %s' % (root_server_bin, root_vm.num_cpus, fanout_args) logging.info('Root cmdline: %s', root_cmd) root_vm.RemoteCommand('%s &> /dev/null &' % root_cmd) def
(oldisim_output): """Parses the output from oldisim. Args: oldisim_output: A string containing the text of oldisim output. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ re_peak = re.compile(r'peak qps = (?P<qps>\S+), latency = (?P<lat>\S+)') re_target = re.compile(r'measured_qps = (?P<qps>\S+), latency = (?P<lat>\S+)') for line in oldisim_output.splitlines(): match = re.search(re_peak, line) if match: peak_qps = float(match.group('qps')) peak_lat = float(match.group('lat')) target_qps = float(peak_qps) target_lat = float(peak_lat) continue match = re.search(re_target, line) if match: target_qps = float(match.group('qps')) target_lat = float(match.group('lat')) return peak_qps, peak_lat, target_qps, target_lat def RunLoadTest(benchmark_spec, fanout): """Run Loadtest for a given topology. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. fanout: Request is first processed by a root node, which then fans out to a subset of leaf nodes. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ assert fanout <= FLAGS.oldisim_num_leaves, ( 'The number of leaf nodes a root node connected to is defined by the ' 'flag fanout. Its current value %s is bigger than the total number of ' 'leaves %s.' % (fanout, FLAGS.oldisim_num_leaves)) vms = benchmark_spec.vms driver_vms = [] root_vms = [] leaf_vms = [] for vm_index, vm in enumerate(vms): if vm_index < NUM_DRIVERS: driver_vms.append(vm) elif vm_index < (NUM_DRIVERS + NUM_ROOTS): root_vms.append(vm) else: leaf_vms.append(vm) leaf_vms = leaf_vms[:fanout] for root_vm in root_vms: SetupRoot(root_vm, leaf_vms) driver_vm = driver_vms[0] driver_binary = oldisim_dependencies.BinaryPath('DriverNode') launch_script = oldisim_dependencies.Path('workloads/search/search_qps.sh') driver_args = ' '.join(['--server=%s' % i.internal_ip for i in root_vms]) # Make sure server is up. time.sleep(5) driver_cmd = '%s -s %s:%s -t 30 -- %s %s --threads=%s --depth=16' % ( launch_script, FLAGS.oldisim_latency_metric, FLAGS.oldisim_latency_target, driver_binary, driver_args, driver_vm.num_cpus) logging.info('Driver cmdline: %s', driver_cmd) stdout, _ = driver_vm.RemoteCommand(driver_cmd, should_log=True) return ParseOutput(stdout) def Run(benchmark_spec): """Run oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ results = [] qps_dict = dict() vms = benchmark_spec.vms vm = vms[0] fanout_list = set([1, FLAGS.oldisim_num_leaves]) for fanout in map(int, FLAGS.oldisim_fanout): if fanout > 1 and fanout < FLAGS.oldisim_num_leaves: fanout_list.add(fanout) metadata = {'num_cpus': vm.num_cpus} metadata.update(vm.GetMachineTypeDict()) for fanout in sorted(fanout_list): qps = RunLoadTest(benchmark_spec, fanout)[2] qps_dict[fanout] = qps if fanout == 1: base_qps = qps name = 'Scaling efficiency of %s leaves' % fanout scaling_efficiency = round(min(qps_dict[fanout] / base_qps, 1), 2) results.append(sample.Sample(name, scaling_efficiency, '', metadata)) return results def Cleanup(benchmark_spec): # pylint: disable=unused-argument """Cleanup oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms for vm_index, vm in enumerate(vms): if vm_index >= NUM_DRIVERS and vm_index < (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill ParentNode') elif vm_index >= (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill LeafNode')
ParseOutput
identifier_name
oldisim_benchmark.py
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs oldisim. oldisim is a framework to support benchmarks that emulate Online Data-Intensive (OLDI) workloads, such as web search and social networking. oldisim includes sample workloads built on top of this framework. With its default config, oldisim models an example search topology. A user query is first processed by a front-end server, which then eventually fans out the query to a large number of leaf nodes. The latency is measured at the root of the tree, and often increases with the increase of fan-out. oldisim reports a scaling efficiency for a given topology. The scaling efficiency is defined as queries per second (QPS) at the current fan-out normalized to QPS at fan-out 1 with ISO root latency. Sample command line: ./pkb.py --benchmarks=oldisim --project='YOUR_PROJECT' --oldisim_num_leaves=4 --oldisim_fanout=1,2,3,4 --oldisim_latency_target=40 --oldisim_latency_metric=avg The above command will build a tree with one root node and four leaf nodes. The average latency target is 40ms. The root node will vary the fanout from 1 to 4 and measure the scaling efficiency. """ import logging import re import time from perfkitbenchmarker import configs from perfkitbenchmarker import flags from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import oldisim_dependencies FLAGS = flags.FLAGS flags.DEFINE_integer('oldisim_num_leaves', 4, 'number of leaf nodes', lower_bound=1, upper_bound=64) flags.DEFINE_list('oldisim_fanout', [], 'a list of fanouts to be tested. ' 'a root can connect to a subset of leaf nodes (fanout). ' 'the value of fanout has to be smaller than num_leaves.') flags.DEFINE_enum('oldisim_latency_metric', 'avg', ['avg', '50p', '90p', '95p', '99p', '99.9p'], 'Allowable metrics for end-to-end latency') flags.DEFINE_float('oldisim_latency_target', '30', 'latency target in ms') NUM_DRIVERS = 1 NUM_ROOTS = 1 BENCHMARK_NAME = 'oldisim' BENCHMARK_CONFIG = """ oldisim: description: > Run oldisim. Specify the number of leaf nodes with --oldisim_num_leaves vm_groups: default: vm_spec: *default_single_core """ def GetConfig(user_config): """Decide number of vms needed to run oldisim.""" config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves + NUM_DRIVERS + NUM_ROOTS) return config def InstallAndBuild(vm): """Install and build oldisim on the target vm. Args: vm: A vm instance that runs oldisim. """ logging.info('prepare oldisim on %s', vm) vm.Install('oldisim_dependencies') def Prepare(benchmark_spec): """Install and build oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms leaf_vms = [vm for vm_idx, vm in enumerate(vms) if vm_idx >= (NUM_DRIVERS + NUM_ROOTS)] if vms: vm_util.RunThreaded(InstallAndBuild, vms) # Launch job on the leaf nodes. leaf_server_bin = oldisim_dependencies.BinaryPath('LeafNode') for vm in leaf_vms: leaf_cmd = '%s --threads=%s' % (leaf_server_bin, vm.num_cpus) vm.RemoteCommand('%s &> /dev/null &' % leaf_cmd) def SetupRoot(root_vm, leaf_vms):
def ParseOutput(oldisim_output): """Parses the output from oldisim. Args: oldisim_output: A string containing the text of oldisim output. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ re_peak = re.compile(r'peak qps = (?P<qps>\S+), latency = (?P<lat>\S+)') re_target = re.compile(r'measured_qps = (?P<qps>\S+), latency = (?P<lat>\S+)') for line in oldisim_output.splitlines(): match = re.search(re_peak, line) if match: peak_qps = float(match.group('qps')) peak_lat = float(match.group('lat')) target_qps = float(peak_qps) target_lat = float(peak_lat) continue match = re.search(re_target, line) if match: target_qps = float(match.group('qps')) target_lat = float(match.group('lat')) return peak_qps, peak_lat, target_qps, target_lat def RunLoadTest(benchmark_spec, fanout): """Run Loadtest for a given topology. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. fanout: Request is first processed by a root node, which then fans out to a subset of leaf nodes. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ assert fanout <= FLAGS.oldisim_num_leaves, ( 'The number of leaf nodes a root node connected to is defined by the ' 'flag fanout. Its current value %s is bigger than the total number of ' 'leaves %s.' % (fanout, FLAGS.oldisim_num_leaves)) vms = benchmark_spec.vms driver_vms = [] root_vms = [] leaf_vms = [] for vm_index, vm in enumerate(vms): if vm_index < NUM_DRIVERS: driver_vms.append(vm) elif vm_index < (NUM_DRIVERS + NUM_ROOTS): root_vms.append(vm) else: leaf_vms.append(vm) leaf_vms = leaf_vms[:fanout] for root_vm in root_vms: SetupRoot(root_vm, leaf_vms) driver_vm = driver_vms[0] driver_binary = oldisim_dependencies.BinaryPath('DriverNode') launch_script = oldisim_dependencies.Path('workloads/search/search_qps.sh') driver_args = ' '.join(['--server=%s' % i.internal_ip for i in root_vms]) # Make sure server is up. time.sleep(5) driver_cmd = '%s -s %s:%s -t 30 -- %s %s --threads=%s --depth=16' % ( launch_script, FLAGS.oldisim_latency_metric, FLAGS.oldisim_latency_target, driver_binary, driver_args, driver_vm.num_cpus) logging.info('Driver cmdline: %s', driver_cmd) stdout, _ = driver_vm.RemoteCommand(driver_cmd, should_log=True) return ParseOutput(stdout) def Run(benchmark_spec): """Run oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ results = [] qps_dict = dict() vms = benchmark_spec.vms vm = vms[0] fanout_list = set([1, FLAGS.oldisim_num_leaves]) for fanout in map(int, FLAGS.oldisim_fanout): if fanout > 1 and fanout < FLAGS.oldisim_num_leaves: fanout_list.add(fanout) metadata = {'num_cpus': vm.num_cpus} metadata.update(vm.GetMachineTypeDict()) for fanout in sorted(fanout_list): qps = RunLoadTest(benchmark_spec, fanout)[2] qps_dict[fanout] = qps if fanout == 1: base_qps = qps name = 'Scaling efficiency of %s leaves' % fanout scaling_efficiency = round(min(qps_dict[fanout] / base_qps, 1), 2) results.append(sample.Sample(name, scaling_efficiency, '', metadata)) return results def Cleanup(benchmark_spec): # pylint: disable=unused-argument """Cleanup oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms for vm_index, vm in enumerate(vms): if vm_index >= NUM_DRIVERS and vm_index < (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill ParentNode') elif vm_index >= (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill LeafNode')
"""Connect a root node to a list of leaf nodes. Args: root_vm: A root vm instance. leaf_vms: A list of leaf vm instances. """ fanout_args = ' '.join(['--leaf=%s' % i.internal_ip for i in leaf_vms]) root_server_bin = oldisim_dependencies.BinaryPath('ParentNode') root_cmd = '%s --threads=%s %s' % (root_server_bin, root_vm.num_cpus, fanout_args) logging.info('Root cmdline: %s', root_cmd) root_vm.RemoteCommand('%s &> /dev/null &' % root_cmd)
identifier_body
oldisim_benchmark.py
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs oldisim. oldisim is a framework to support benchmarks that emulate Online Data-Intensive (OLDI) workloads, such as web search and social networking. oldisim includes sample workloads built on top of this framework. With its default config, oldisim models an example search topology. A user query is first processed by a front-end server, which then eventually fans out the query to a large number of leaf nodes. The latency is measured at the root of the tree, and often increases with the increase of fan-out. oldisim reports a scaling efficiency for a given topology. The scaling efficiency is defined as queries per second (QPS) at the current fan-out normalized to QPS at fan-out 1 with ISO root latency. Sample command line: ./pkb.py --benchmarks=oldisim --project='YOUR_PROJECT' --oldisim_num_leaves=4 --oldisim_fanout=1,2,3,4 --oldisim_latency_target=40 --oldisim_latency_metric=avg The above command will build a tree with one root node and four leaf nodes. The average latency target is 40ms. The root node will vary the fanout from 1 to 4 and measure the scaling efficiency. """ import logging import re import time from perfkitbenchmarker import configs from perfkitbenchmarker import flags from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import oldisim_dependencies FLAGS = flags.FLAGS flags.DEFINE_integer('oldisim_num_leaves', 4, 'number of leaf nodes', lower_bound=1, upper_bound=64) flags.DEFINE_list('oldisim_fanout', [], 'a list of fanouts to be tested. ' 'a root can connect to a subset of leaf nodes (fanout). ' 'the value of fanout has to be smaller than num_leaves.') flags.DEFINE_enum('oldisim_latency_metric', 'avg', ['avg', '50p', '90p', '95p', '99p', '99.9p'], 'Allowable metrics for end-to-end latency') flags.DEFINE_float('oldisim_latency_target', '30', 'latency target in ms') NUM_DRIVERS = 1 NUM_ROOTS = 1 BENCHMARK_NAME = 'oldisim' BENCHMARK_CONFIG = """ oldisim: description: > Run oldisim. Specify the number of leaf nodes with --oldisim_num_leaves vm_groups: default: vm_spec: *default_single_core """ def GetConfig(user_config): """Decide number of vms needed to run oldisim.""" config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves + NUM_DRIVERS + NUM_ROOTS) return config def InstallAndBuild(vm): """Install and build oldisim on the target vm. Args: vm: A vm instance that runs oldisim. """ logging.info('prepare oldisim on %s', vm) vm.Install('oldisim_dependencies') def Prepare(benchmark_spec): """Install and build oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms leaf_vms = [vm for vm_idx, vm in enumerate(vms) if vm_idx >= (NUM_DRIVERS + NUM_ROOTS)] if vms: vm_util.RunThreaded(InstallAndBuild, vms) # Launch job on the leaf nodes. leaf_server_bin = oldisim_dependencies.BinaryPath('LeafNode') for vm in leaf_vms: leaf_cmd = '%s --threads=%s' % (leaf_server_bin, vm.num_cpus) vm.RemoteCommand('%s &> /dev/null &' % leaf_cmd) def SetupRoot(root_vm, leaf_vms): """Connect a root node to a list of leaf nodes. Args: root_vm: A root vm instance. leaf_vms: A list of leaf vm instances. """ fanout_args = ' '.join(['--leaf=%s' % i.internal_ip for i in leaf_vms]) root_server_bin = oldisim_dependencies.BinaryPath('ParentNode') root_cmd = '%s --threads=%s %s' % (root_server_bin, root_vm.num_cpus, fanout_args) logging.info('Root cmdline: %s', root_cmd) root_vm.RemoteCommand('%s &> /dev/null &' % root_cmd) def ParseOutput(oldisim_output): """Parses the output from oldisim. Args: oldisim_output: A string containing the text of oldisim output. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ re_peak = re.compile(r'peak qps = (?P<qps>\S+), latency = (?P<lat>\S+)') re_target = re.compile(r'measured_qps = (?P<qps>\S+), latency = (?P<lat>\S+)') for line in oldisim_output.splitlines(): match = re.search(re_peak, line) if match: peak_qps = float(match.group('qps')) peak_lat = float(match.group('lat')) target_qps = float(peak_qps) target_lat = float(peak_lat) continue match = re.search(re_target, line) if match: target_qps = float(match.group('qps')) target_lat = float(match.group('lat')) return peak_qps, peak_lat, target_qps, target_lat def RunLoadTest(benchmark_spec, fanout): """Run Loadtest for a given topology. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. fanout: Request is first processed by a root node, which then fans out to a subset of leaf nodes. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ assert fanout <= FLAGS.oldisim_num_leaves, ( 'The number of leaf nodes a root node connected to is defined by the ' 'flag fanout. Its current value %s is bigger than the total number of ' 'leaves %s.' % (fanout, FLAGS.oldisim_num_leaves)) vms = benchmark_spec.vms driver_vms = [] root_vms = [] leaf_vms = [] for vm_index, vm in enumerate(vms): if vm_index < NUM_DRIVERS: driver_vms.append(vm) elif vm_index < (NUM_DRIVERS + NUM_ROOTS): root_vms.append(vm) else: leaf_vms.append(vm) leaf_vms = leaf_vms[:fanout] for root_vm in root_vms: SetupRoot(root_vm, leaf_vms) driver_vm = driver_vms[0] driver_binary = oldisim_dependencies.BinaryPath('DriverNode') launch_script = oldisim_dependencies.Path('workloads/search/search_qps.sh') driver_args = ' '.join(['--server=%s' % i.internal_ip for i in root_vms]) # Make sure server is up. time.sleep(5) driver_cmd = '%s -s %s:%s -t 30 -- %s %s --threads=%s --depth=16' % ( launch_script, FLAGS.oldisim_latency_metric, FLAGS.oldisim_latency_target, driver_binary, driver_args, driver_vm.num_cpus) logging.info('Driver cmdline: %s', driver_cmd) stdout, _ = driver_vm.RemoteCommand(driver_cmd, should_log=True) return ParseOutput(stdout) def Run(benchmark_spec): """Run oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ results = [] qps_dict = dict() vms = benchmark_spec.vms vm = vms[0] fanout_list = set([1, FLAGS.oldisim_num_leaves]) for fanout in map(int, FLAGS.oldisim_fanout): if fanout > 1 and fanout < FLAGS.oldisim_num_leaves: fanout_list.add(fanout) metadata = {'num_cpus': vm.num_cpus}
qps_dict[fanout] = qps if fanout == 1: base_qps = qps name = 'Scaling efficiency of %s leaves' % fanout scaling_efficiency = round(min(qps_dict[fanout] / base_qps, 1), 2) results.append(sample.Sample(name, scaling_efficiency, '', metadata)) return results def Cleanup(benchmark_spec): # pylint: disable=unused-argument """Cleanup oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms for vm_index, vm in enumerate(vms): if vm_index >= NUM_DRIVERS and vm_index < (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill ParentNode') elif vm_index >= (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill LeafNode')
metadata.update(vm.GetMachineTypeDict()) for fanout in sorted(fanout_list): qps = RunLoadTest(benchmark_spec, fanout)[2]
random_line_split
oldisim_benchmark.py
# Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs oldisim. oldisim is a framework to support benchmarks that emulate Online Data-Intensive (OLDI) workloads, such as web search and social networking. oldisim includes sample workloads built on top of this framework. With its default config, oldisim models an example search topology. A user query is first processed by a front-end server, which then eventually fans out the query to a large number of leaf nodes. The latency is measured at the root of the tree, and often increases with the increase of fan-out. oldisim reports a scaling efficiency for a given topology. The scaling efficiency is defined as queries per second (QPS) at the current fan-out normalized to QPS at fan-out 1 with ISO root latency. Sample command line: ./pkb.py --benchmarks=oldisim --project='YOUR_PROJECT' --oldisim_num_leaves=4 --oldisim_fanout=1,2,3,4 --oldisim_latency_target=40 --oldisim_latency_metric=avg The above command will build a tree with one root node and four leaf nodes. The average latency target is 40ms. The root node will vary the fanout from 1 to 4 and measure the scaling efficiency. """ import logging import re import time from perfkitbenchmarker import configs from perfkitbenchmarker import flags from perfkitbenchmarker import sample from perfkitbenchmarker import vm_util from perfkitbenchmarker.linux_packages import oldisim_dependencies FLAGS = flags.FLAGS flags.DEFINE_integer('oldisim_num_leaves', 4, 'number of leaf nodes', lower_bound=1, upper_bound=64) flags.DEFINE_list('oldisim_fanout', [], 'a list of fanouts to be tested. ' 'a root can connect to a subset of leaf nodes (fanout). ' 'the value of fanout has to be smaller than num_leaves.') flags.DEFINE_enum('oldisim_latency_metric', 'avg', ['avg', '50p', '90p', '95p', '99p', '99.9p'], 'Allowable metrics for end-to-end latency') flags.DEFINE_float('oldisim_latency_target', '30', 'latency target in ms') NUM_DRIVERS = 1 NUM_ROOTS = 1 BENCHMARK_NAME = 'oldisim' BENCHMARK_CONFIG = """ oldisim: description: > Run oldisim. Specify the number of leaf nodes with --oldisim_num_leaves vm_groups: default: vm_spec: *default_single_core """ def GetConfig(user_config): """Decide number of vms needed to run oldisim.""" config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) config['vm_groups']['default']['vm_count'] = (FLAGS.oldisim_num_leaves + NUM_DRIVERS + NUM_ROOTS) return config def InstallAndBuild(vm): """Install and build oldisim on the target vm. Args: vm: A vm instance that runs oldisim. """ logging.info('prepare oldisim on %s', vm) vm.Install('oldisim_dependencies') def Prepare(benchmark_spec): """Install and build oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms leaf_vms = [vm for vm_idx, vm in enumerate(vms) if vm_idx >= (NUM_DRIVERS + NUM_ROOTS)] if vms: vm_util.RunThreaded(InstallAndBuild, vms) # Launch job on the leaf nodes. leaf_server_bin = oldisim_dependencies.BinaryPath('LeafNode') for vm in leaf_vms: leaf_cmd = '%s --threads=%s' % (leaf_server_bin, vm.num_cpus) vm.RemoteCommand('%s &> /dev/null &' % leaf_cmd) def SetupRoot(root_vm, leaf_vms): """Connect a root node to a list of leaf nodes. Args: root_vm: A root vm instance. leaf_vms: A list of leaf vm instances. """ fanout_args = ' '.join(['--leaf=%s' % i.internal_ip for i in leaf_vms]) root_server_bin = oldisim_dependencies.BinaryPath('ParentNode') root_cmd = '%s --threads=%s %s' % (root_server_bin, root_vm.num_cpus, fanout_args) logging.info('Root cmdline: %s', root_cmd) root_vm.RemoteCommand('%s &> /dev/null &' % root_cmd) def ParseOutput(oldisim_output): """Parses the output from oldisim. Args: oldisim_output: A string containing the text of oldisim output. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ re_peak = re.compile(r'peak qps = (?P<qps>\S+), latency = (?P<lat>\S+)') re_target = re.compile(r'measured_qps = (?P<qps>\S+), latency = (?P<lat>\S+)') for line in oldisim_output.splitlines(): match = re.search(re_peak, line) if match: peak_qps = float(match.group('qps')) peak_lat = float(match.group('lat')) target_qps = float(peak_qps) target_lat = float(peak_lat) continue match = re.search(re_target, line) if match: target_qps = float(match.group('qps')) target_lat = float(match.group('lat')) return peak_qps, peak_lat, target_qps, target_lat def RunLoadTest(benchmark_spec, fanout): """Run Loadtest for a given topology. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. fanout: Request is first processed by a root node, which then fans out to a subset of leaf nodes. Returns: A tuple of (peak_qps, peak_lat, target_qps, target_lat). """ assert fanout <= FLAGS.oldisim_num_leaves, ( 'The number of leaf nodes a root node connected to is defined by the ' 'flag fanout. Its current value %s is bigger than the total number of ' 'leaves %s.' % (fanout, FLAGS.oldisim_num_leaves)) vms = benchmark_spec.vms driver_vms = [] root_vms = [] leaf_vms = [] for vm_index, vm in enumerate(vms): if vm_index < NUM_DRIVERS: driver_vms.append(vm) elif vm_index < (NUM_DRIVERS + NUM_ROOTS): root_vms.append(vm) else: leaf_vms.append(vm) leaf_vms = leaf_vms[:fanout] for root_vm in root_vms: SetupRoot(root_vm, leaf_vms) driver_vm = driver_vms[0] driver_binary = oldisim_dependencies.BinaryPath('DriverNode') launch_script = oldisim_dependencies.Path('workloads/search/search_qps.sh') driver_args = ' '.join(['--server=%s' % i.internal_ip for i in root_vms]) # Make sure server is up. time.sleep(5) driver_cmd = '%s -s %s:%s -t 30 -- %s %s --threads=%s --depth=16' % ( launch_script, FLAGS.oldisim_latency_metric, FLAGS.oldisim_latency_target, driver_binary, driver_args, driver_vm.num_cpus) logging.info('Driver cmdline: %s', driver_cmd) stdout, _ = driver_vm.RemoteCommand(driver_cmd, should_log=True) return ParseOutput(stdout) def Run(benchmark_spec): """Run oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ results = [] qps_dict = dict() vms = benchmark_spec.vms vm = vms[0] fanout_list = set([1, FLAGS.oldisim_num_leaves]) for fanout in map(int, FLAGS.oldisim_fanout): if fanout > 1 and fanout < FLAGS.oldisim_num_leaves: fanout_list.add(fanout) metadata = {'num_cpus': vm.num_cpus} metadata.update(vm.GetMachineTypeDict()) for fanout in sorted(fanout_list): qps = RunLoadTest(benchmark_spec, fanout)[2] qps_dict[fanout] = qps if fanout == 1:
name = 'Scaling efficiency of %s leaves' % fanout scaling_efficiency = round(min(qps_dict[fanout] / base_qps, 1), 2) results.append(sample.Sample(name, scaling_efficiency, '', metadata)) return results def Cleanup(benchmark_spec): # pylint: disable=unused-argument """Cleanup oldisim on the target vm. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ vms = benchmark_spec.vms for vm_index, vm in enumerate(vms): if vm_index >= NUM_DRIVERS and vm_index < (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill ParentNode') elif vm_index >= (NUM_DRIVERS + NUM_ROOTS): vm.RemoteCommand('sudo pkill LeafNode')
base_qps = qps
conditional_block
column.py
from prettytable import PrettyTable import pandas as pd class Column(object): """ A Columns is an in-memory reference to a column in a particular table. You can use it to do some basic DB exploration and you can also use it to execute simple queries. """ def __init__(self, con, query_templates, schema, table, name, dtype, keys_per_column): self._con = con self._query_templates = query_templates self.schema = schema self.table = table self.name = name self.type = dtype self.keys_per_column = keys_per_column self.foreign_keys = [] self.ref_keys = [] def __repr__(self): tbl = PrettyTable(["Table", "Name", "Type", "Foreign Keys", "Reference Keys"]) tbl.add_row([self.table, self.name, self.type, self._str_foreign_keys(), self._str_ref_keys()]) return str(tbl) def __str__(self): return "Column({0})<{1}>".format(self.name, self.__hash__()) def _repr_html_(self): tbl = PrettyTable(["Table", "Name", "Type"]) tbl.add_row([self.table, self.name, self.type]) return tbl.get_html_string() def _str_foreign_keys(self): keys = [] for col in self.foreign_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def _str_ref_keys(self): keys = [] for col in self.ref_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def head(self, n=6): """ Returns first n values of your column as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> LIMIT <n> Parameters ---------- n: int number of rows to return Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.City.head() 0 Sao Jose dos Campos 1 Stuttgart 2 Montreal 3 Oslo 4 Prague 5 Prague Name: City, dtype: object >>> db.tables.Customer.City.head(2) 0 Sao Jose dos Campos 1 Stuttgart Name: City, dtype: object """ q = self._query_templates['column']['head'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def all(self): """ Returns entire column as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.Email.all().head() 0 luisg@embraer.com.br 1 leonekohler@surfeu.de 2 ftremblay@gmail.com 3 bjorn.hansen@yahoo.no 4 frantisekw@jetbrains.com Name: Email, dtype: object >>> df = db.tables.Customer.Email.all() >>> len(df) 59 """ q = self._query_templates['column']['all'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def unique(self): """ Returns all unique values as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.FirstName.unique().head(10) 0 Luis 1 Leonie 2 Francois 3 Bjorn 4 Franti\u0161ek 5 Helena 6 Astrid 7 Daan 8 Kara 9 Eduardo Name: FirstName, dtype: object >>> len(db.tables.Customer.LastName.unique()) 59 """ q = self._query_templates['column']['unique'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def sample(self, n=10): """ Returns random sample of n rows as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> ORDER BY RANDOM() LIMIT <n> Parameters ---------- n: int number of rows to sample Examples (removed from doctest as we can't predict random names...) -------- from db import DemoDB db = DemoDB() db.tables.Artist.Name.sample(10) 0 Pedro Luis & A Parede 1 Santana Feat. Eric Clapton 2 Os Mutantes 3 Banda Black Rio 4 Adrian Leaper & Doreen de Feis 5 Chicago Symphony Orchestra & Fritz Reiner 6 Smashing Pumpkins 7 Spyro Gyra 8 Aaron Copland & London Symphony Orchestra 9 Sir Georg Solti & Wiener Philharmoniker Name: Name, dtype: object >>> from db import DemoDB >>> db = DemoDB() >>> df = db.tables.Artist.Name.sample(10) >>> len(df) 10 """ q = self._query_templates['column']['sample'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def to_dict(self): """ Serialize representation of the column for local caching. """ return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type} class ColumnSet(object): """ Set of Columns. Used for displaying search results in terminal/ipython notebook. """ def __init__(self, columns): self.columns = columns self.pretty_tbl_cols = ["Table", "Column Name", "Type"] self.use_schema = False for col in columns: if col.schema and not self.use_schema: self.use_schema = True self.pretty_tbl_cols.insert(0, "Schema") def
(self, i): return self.columns[i] def _tablify(self): tbl = PrettyTable(self.pretty_tbl_cols) for col in self.pretty_tbl_cols: tbl.align[col] = "l" for col in self.columns: row_data = [col.table, col.name, col.type] if self.use_schema: row_data.insert(0, col.schema) tbl.add_row(row_data) return tbl def __repr__(self): tbl = str(self._tablify()) return tbl def _repr_html_(self): return self._tablify().get_html_string() def to_dict(self): """Serialize representation of the tableset for local caching.""" return {'columns': [col.to_dict() for col in self.columns]}
__getitem__
identifier_name
column.py
from prettytable import PrettyTable import pandas as pd class Column(object): """ A Columns is an in-memory reference to a column in a particular table. You can use it to do some basic DB exploration and you can also use it to execute simple queries. """ def __init__(self, con, query_templates, schema, table, name, dtype, keys_per_column): self._con = con self._query_templates = query_templates self.schema = schema self.table = table self.name = name self.type = dtype self.keys_per_column = keys_per_column self.foreign_keys = [] self.ref_keys = [] def __repr__(self): tbl = PrettyTable(["Table", "Name", "Type", "Foreign Keys", "Reference Keys"]) tbl.add_row([self.table, self.name, self.type, self._str_foreign_keys(), self._str_ref_keys()]) return str(tbl) def __str__(self): return "Column({0})<{1}>".format(self.name, self.__hash__()) def _repr_html_(self): tbl = PrettyTable(["Table", "Name", "Type"]) tbl.add_row([self.table, self.name, self.type]) return tbl.get_html_string() def _str_foreign_keys(self): keys = [] for col in self.foreign_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def _str_ref_keys(self): keys = [] for col in self.ref_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def head(self, n=6): """ Returns first n values of your column as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> LIMIT <n> Parameters ---------- n: int number of rows to return Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.City.head() 0 Sao Jose dos Campos 1 Stuttgart 2 Montreal 3 Oslo 4 Prague 5 Prague Name: City, dtype: object >>> db.tables.Customer.City.head(2) 0 Sao Jose dos Campos 1 Stuttgart Name: City, dtype: object """ q = self._query_templates['column']['head'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def all(self): """ Returns entire column as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.Email.all().head() 0 luisg@embraer.com.br 1 leonekohler@surfeu.de 2 ftremblay@gmail.com 3 bjorn.hansen@yahoo.no 4 frantisekw@jetbrains.com Name: Email, dtype: object >>> df = db.tables.Customer.Email.all() >>> len(df) 59 """ q = self._query_templates['column']['all'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def unique(self): """ Returns all unique values as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.FirstName.unique().head(10) 0 Luis 1 Leonie 2 Francois 3 Bjorn 4 Franti\u0161ek 5 Helena 6 Astrid 7 Daan 8 Kara 9 Eduardo Name: FirstName, dtype: object >>> len(db.tables.Customer.LastName.unique()) 59 """ q = self._query_templates['column']['unique'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def sample(self, n=10): """ Returns random sample of n rows as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> ORDER BY RANDOM() LIMIT <n> Parameters ---------- n: int number of rows to sample Examples (removed from doctest as we can't predict random names...) -------- from db import DemoDB db = DemoDB() db.tables.Artist.Name.sample(10) 0 Pedro Luis & A Parede 1 Santana Feat. Eric Clapton 2 Os Mutantes 3 Banda Black Rio 4 Adrian Leaper & Doreen de Feis 5 Chicago Symphony Orchestra & Fritz Reiner 6 Smashing Pumpkins 7 Spyro Gyra 8 Aaron Copland & London Symphony Orchestra 9 Sir Georg Solti & Wiener Philharmoniker Name: Name, dtype: object >>> from db import DemoDB >>> db = DemoDB() >>> df = db.tables.Artist.Name.sample(10) >>> len(df) 10 """ q = self._query_templates['column']['sample'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def to_dict(self): """ Serialize representation of the column for local caching. """ return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type} class ColumnSet(object): """ Set of Columns. Used for displaying search results in terminal/ipython notebook. """ def __init__(self, columns): self.columns = columns self.pretty_tbl_cols = ["Table", "Column Name", "Type"] self.use_schema = False for col in columns: if col.schema and not self.use_schema: self.use_schema = True self.pretty_tbl_cols.insert(0, "Schema") def __getitem__(self, i): return self.columns[i] def _tablify(self): tbl = PrettyTable(self.pretty_tbl_cols) for col in self.pretty_tbl_cols: tbl.align[col] = "l" for col in self.columns:
return tbl def __repr__(self): tbl = str(self._tablify()) return tbl def _repr_html_(self): return self._tablify().get_html_string() def to_dict(self): """Serialize representation of the tableset for local caching.""" return {'columns': [col.to_dict() for col in self.columns]}
row_data = [col.table, col.name, col.type] if self.use_schema: row_data.insert(0, col.schema) tbl.add_row(row_data)
conditional_block
column.py
from prettytable import PrettyTable import pandas as pd class Column(object): """ A Columns is an in-memory reference to a column in a particular table. You can use it to do some basic DB exploration and you can also use it to execute simple queries. """ def __init__(self, con, query_templates, schema, table, name, dtype, keys_per_column): self._con = con self._query_templates = query_templates self.schema = schema self.table = table self.name = name self.type = dtype self.keys_per_column = keys_per_column self.foreign_keys = [] self.ref_keys = [] def __repr__(self): tbl = PrettyTable(["Table", "Name", "Type", "Foreign Keys", "Reference Keys"]) tbl.add_row([self.table, self.name, self.type, self._str_foreign_keys(), self._str_ref_keys()]) return str(tbl) def __str__(self): return "Column({0})<{1}>".format(self.name, self.__hash__()) def _repr_html_(self): tbl = PrettyTable(["Table", "Name", "Type"]) tbl.add_row([self.table, self.name, self.type]) return tbl.get_html_string() def _str_foreign_keys(self): keys = [] for col in self.foreign_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys)
for col in self.ref_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def head(self, n=6): """ Returns first n values of your column as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> LIMIT <n> Parameters ---------- n: int number of rows to return Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.City.head() 0 Sao Jose dos Campos 1 Stuttgart 2 Montreal 3 Oslo 4 Prague 5 Prague Name: City, dtype: object >>> db.tables.Customer.City.head(2) 0 Sao Jose dos Campos 1 Stuttgart Name: City, dtype: object """ q = self._query_templates['column']['head'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def all(self): """ Returns entire column as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.Email.all().head() 0 luisg@embraer.com.br 1 leonekohler@surfeu.de 2 ftremblay@gmail.com 3 bjorn.hansen@yahoo.no 4 frantisekw@jetbrains.com Name: Email, dtype: object >>> df = db.tables.Customer.Email.all() >>> len(df) 59 """ q = self._query_templates['column']['all'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def unique(self): """ Returns all unique values as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.FirstName.unique().head(10) 0 Luis 1 Leonie 2 Francois 3 Bjorn 4 Franti\u0161ek 5 Helena 6 Astrid 7 Daan 8 Kara 9 Eduardo Name: FirstName, dtype: object >>> len(db.tables.Customer.LastName.unique()) 59 """ q = self._query_templates['column']['unique'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def sample(self, n=10): """ Returns random sample of n rows as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> ORDER BY RANDOM() LIMIT <n> Parameters ---------- n: int number of rows to sample Examples (removed from doctest as we can't predict random names...) -------- from db import DemoDB db = DemoDB() db.tables.Artist.Name.sample(10) 0 Pedro Luis & A Parede 1 Santana Feat. Eric Clapton 2 Os Mutantes 3 Banda Black Rio 4 Adrian Leaper & Doreen de Feis 5 Chicago Symphony Orchestra & Fritz Reiner 6 Smashing Pumpkins 7 Spyro Gyra 8 Aaron Copland & London Symphony Orchestra 9 Sir Georg Solti & Wiener Philharmoniker Name: Name, dtype: object >>> from db import DemoDB >>> db = DemoDB() >>> df = db.tables.Artist.Name.sample(10) >>> len(df) 10 """ q = self._query_templates['column']['sample'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def to_dict(self): """ Serialize representation of the column for local caching. """ return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type} class ColumnSet(object): """ Set of Columns. Used for displaying search results in terminal/ipython notebook. """ def __init__(self, columns): self.columns = columns self.pretty_tbl_cols = ["Table", "Column Name", "Type"] self.use_schema = False for col in columns: if col.schema and not self.use_schema: self.use_schema = True self.pretty_tbl_cols.insert(0, "Schema") def __getitem__(self, i): return self.columns[i] def _tablify(self): tbl = PrettyTable(self.pretty_tbl_cols) for col in self.pretty_tbl_cols: tbl.align[col] = "l" for col in self.columns: row_data = [col.table, col.name, col.type] if self.use_schema: row_data.insert(0, col.schema) tbl.add_row(row_data) return tbl def __repr__(self): tbl = str(self._tablify()) return tbl def _repr_html_(self): return self._tablify().get_html_string() def to_dict(self): """Serialize representation of the tableset for local caching.""" return {'columns': [col.to_dict() for col in self.columns]}
def _str_ref_keys(self): keys = []
random_line_split
column.py
from prettytable import PrettyTable import pandas as pd class Column(object): """ A Columns is an in-memory reference to a column in a particular table. You can use it to do some basic DB exploration and you can also use it to execute simple queries. """ def __init__(self, con, query_templates, schema, table, name, dtype, keys_per_column): self._con = con self._query_templates = query_templates self.schema = schema self.table = table self.name = name self.type = dtype self.keys_per_column = keys_per_column self.foreign_keys = [] self.ref_keys = [] def __repr__(self): tbl = PrettyTable(["Table", "Name", "Type", "Foreign Keys", "Reference Keys"]) tbl.add_row([self.table, self.name, self.type, self._str_foreign_keys(), self._str_ref_keys()]) return str(tbl) def __str__(self): return "Column({0})<{1}>".format(self.name, self.__hash__()) def _repr_html_(self): tbl = PrettyTable(["Table", "Name", "Type"]) tbl.add_row([self.table, self.name, self.type]) return tbl.get_html_string() def _str_foreign_keys(self): keys = [] for col in self.foreign_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def _str_ref_keys(self): keys = [] for col in self.ref_keys: keys.append("%s.%s" % (col.table, col.name)) if self.keys_per_column is not None and len(keys) > self.keys_per_column: keys = keys[0:self.keys_per_column] + ['(+ {0} more)'.format(len(keys) - self.keys_per_column)] return ", ".join(keys) def head(self, n=6): """ Returns first n values of your column as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> LIMIT <n> Parameters ---------- n: int number of rows to return Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.City.head() 0 Sao Jose dos Campos 1 Stuttgart 2 Montreal 3 Oslo 4 Prague 5 Prague Name: City, dtype: object >>> db.tables.Customer.City.head(2) 0 Sao Jose dos Campos 1 Stuttgart Name: City, dtype: object """ q = self._query_templates['column']['head'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name] def all(self): """ Returns entire column as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.Email.all().head() 0 luisg@embraer.com.br 1 leonekohler@surfeu.de 2 ftremblay@gmail.com 3 bjorn.hansen@yahoo.no 4 frantisekw@jetbrains.com Name: Email, dtype: object >>> df = db.tables.Customer.Email.all() >>> len(df) 59 """ q = self._query_templates['column']['all'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def unique(self): """ Returns all unique values as a DataFrame. This is executing: SELECT DISTINCT <name_of_the_column> FROM <name_of_the_table> Examples -------- >>> from db import DemoDB >>> db = DemoDB() >>> db.tables.Customer.FirstName.unique().head(10) 0 Luis 1 Leonie 2 Francois 3 Bjorn 4 Franti\u0161ek 5 Helena 6 Astrid 7 Daan 8 Kara 9 Eduardo Name: FirstName, dtype: object >>> len(db.tables.Customer.LastName.unique()) 59 """ q = self._query_templates['column']['unique'].format(column=self.name, schema=self.schema, table=self.table) return pd.read_sql(q, self._con)[self.name] def sample(self, n=10):
def to_dict(self): """ Serialize representation of the column for local caching. """ return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type} class ColumnSet(object): """ Set of Columns. Used for displaying search results in terminal/ipython notebook. """ def __init__(self, columns): self.columns = columns self.pretty_tbl_cols = ["Table", "Column Name", "Type"] self.use_schema = False for col in columns: if col.schema and not self.use_schema: self.use_schema = True self.pretty_tbl_cols.insert(0, "Schema") def __getitem__(self, i): return self.columns[i] def _tablify(self): tbl = PrettyTable(self.pretty_tbl_cols) for col in self.pretty_tbl_cols: tbl.align[col] = "l" for col in self.columns: row_data = [col.table, col.name, col.type] if self.use_schema: row_data.insert(0, col.schema) tbl.add_row(row_data) return tbl def __repr__(self): tbl = str(self._tablify()) return tbl def _repr_html_(self): return self._tablify().get_html_string() def to_dict(self): """Serialize representation of the tableset for local caching.""" return {'columns': [col.to_dict() for col in self.columns]}
""" Returns random sample of n rows as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> ORDER BY RANDOM() LIMIT <n> Parameters ---------- n: int number of rows to sample Examples (removed from doctest as we can't predict random names...) -------- from db import DemoDB db = DemoDB() db.tables.Artist.Name.sample(10) 0 Pedro Luis & A Parede 1 Santana Feat. Eric Clapton 2 Os Mutantes 3 Banda Black Rio 4 Adrian Leaper & Doreen de Feis 5 Chicago Symphony Orchestra & Fritz Reiner 6 Smashing Pumpkins 7 Spyro Gyra 8 Aaron Copland & London Symphony Orchestra 9 Sir Georg Solti & Wiener Philharmoniker Name: Name, dtype: object >>> from db import DemoDB >>> db = DemoDB() >>> df = db.tables.Artist.Name.sample(10) >>> len(df) 10 """ q = self._query_templates['column']['sample'].format(column=self.name, schema=self.schema, table=self.table, n=n) return pd.read_sql(q, self._con)[self.name]
identifier_body
handle-hash-url.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This code may get compiled by the backend project, so make it work without DOM declarations. declare const window: any; declare const document: any; let already_handled_hash_url: boolean = false; export function handle_hash_url(): void {
if (window == null || document == null) return; // It's critial to only do this once. if (already_handled_hash_url) return; already_handled_hash_url = true; // If there is a big path after the base url the hub (I think) moves all // that part of the url to after a #. This is a hack so that we can put // our whole webapp at app/ instead of having to serve it from tons // of other urls. E.g., // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default // is converted to // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/app#projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default if (window.location.hash.length <= 1) { // nothing to parse. window.cocalc_target = ""; return; } if (window.cocalc_target !== undefined) { // already did the parsing; doing something again would be confusing/bad. return; } const hash = decodeURIComponent(window.location.hash.slice(1)); let cocalc_target = hash; // the location hash could again contain a query param, hence this const i = cocalc_target.indexOf("?"); if (i >= 0) { cocalc_target = cocalc_target.slice(0, i); } // save this so we don't have to parse it later... (TODO: better to store in a Store somewhere?) window.cocalc_target = cocalc_target; let query_params = ""; if (i >= 0) { // We must also preserve the query params query_params = hash.slice(i + 1); } // Finally remove the hash from the url (without refreshing the page, of course). let full_url = document.location.pathname; if (cocalc_target) { full_url += "/" + cocalc_target; } if (query_params) { full_url += "?" + query_params; } window.history.pushState("", "", full_url); }
identifier_body
handle-hash-url.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This code may get compiled by the backend project, so make it work without DOM declarations. declare const window: any; declare const document: any; let already_handled_hash_url: boolean = false; export function handle_hash_url(): void { if (window == null || document == null) return; // It's critial to only do this once. if (already_handled_hash_url) return; already_handled_hash_url = true; // If there is a big path after the base url the hub (I think) moves all // that part of the url to after a #. This is a hack so that we can put // our whole webapp at app/ instead of having to serve it from tons // of other urls. E.g., // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default // is converted to // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/app#projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default if (window.location.hash.length <= 1) { // nothing to parse. window.cocalc_target = ""; return; } if (window.cocalc_target !== undefined) { // already did the parsing; doing something again would be confusing/bad. return; } const hash = decodeURIComponent(window.location.hash.slice(1)); let cocalc_target = hash; // the location hash could again contain a query param, hence this const i = cocalc_target.indexOf("?"); if (i >= 0) { cocalc_target = cocalc_target.slice(0, i); } // save this so we don't have to parse it later... (TODO: better to store in a Store somewhere?) window.cocalc_target = cocalc_target; let query_params = ""; if (i >= 0) { // We must also preserve the query params query_params = hash.slice(i + 1); } // Finally remove the hash from the url (without refreshing the page, of course). let full_url = document.location.pathname;
} if (query_params) { full_url += "?" + query_params; } window.history.pushState("", "", full_url); }
if (cocalc_target) { full_url += "/" + cocalc_target;
random_line_split
handle-hash-url.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This code may get compiled by the backend project, so make it work without DOM declarations. declare const window: any; declare const document: any; let already_handled_hash_url: boolean = false; export function handle_hash_url(): void { if (window == null || document == null) return; // It's critial to only do this once. if (already_handled_hash_url) return; already_handled_hash_url = true; // If there is a big path after the base url the hub (I think) moves all // that part of the url to after a #. This is a hack so that we can put // our whole webapp at app/ instead of having to serve it from tons // of other urls. E.g., // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default // is converted to // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/app#projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default if (window.location.hash.length <= 1) { // nothing to parse. window.cocalc_target = ""; return; } if (window.cocalc_target !== undefined) { // already did the parsing; doing something again would be confusing/bad. return; } const hash = decodeURIComponent(window.location.hash.slice(1)); let cocalc_target = hash; // the location hash could again contain a query param, hence this const i = cocalc_target.indexOf("?"); if (i >= 0) { cocalc_target = cocalc_target.slice(0, i); } // save this so we don't have to parse it later... (TODO: better to store in a Store somewhere?) window.cocalc_target = cocalc_target; let query_params = ""; if (i >= 0) {
// Finally remove the hash from the url (without refreshing the page, of course). let full_url = document.location.pathname; if (cocalc_target) { full_url += "/" + cocalc_target; } if (query_params) { full_url += "?" + query_params; } window.history.pushState("", "", full_url); }
// We must also preserve the query params query_params = hash.slice(i + 1); }
conditional_block
handle-hash-url.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // This code may get compiled by the backend project, so make it work without DOM declarations. declare const window: any; declare const document: any; let already_handled_hash_url: boolean = false; export function han
void { if (window == null || document == null) return; // It's critial to only do this once. if (already_handled_hash_url) return; already_handled_hash_url = true; // If there is a big path after the base url the hub (I think) moves all // that part of the url to after a #. This is a hack so that we can put // our whole webapp at app/ instead of having to serve it from tons // of other urls. E.g., // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default // is converted to // https://cocalc.com/45f4aab5-7698-4ac8-9f63-9fd307401ad7/port/8000/app#projects/f2b471ee-a300-4531-829d-472fa46c7eb7/files/2019-12-16-114812.ipynb?session=default if (window.location.hash.length <= 1) { // nothing to parse. window.cocalc_target = ""; return; } if (window.cocalc_target !== undefined) { // already did the parsing; doing something again would be confusing/bad. return; } const hash = decodeURIComponent(window.location.hash.slice(1)); let cocalc_target = hash; // the location hash could again contain a query param, hence this const i = cocalc_target.indexOf("?"); if (i >= 0) { cocalc_target = cocalc_target.slice(0, i); } // save this so we don't have to parse it later... (TODO: better to store in a Store somewhere?) window.cocalc_target = cocalc_target; let query_params = ""; if (i >= 0) { // We must also preserve the query params query_params = hash.slice(i + 1); } // Finally remove the hash from the url (without refreshing the page, of course). let full_url = document.location.pathname; if (cocalc_target) { full_url += "/" + cocalc_target; } if (query_params) { full_url += "?" + query_params; } window.history.pushState("", "", full_url); }
dle_hash_url():
identifier_name
floatingrendererwindow.py
# -*- coding: utf-8 -*- # # codimension - graphics python two-way code editor and analyzer # Copyright (C) 2010-2019 Sergey Satskiy <sergey.satskiy@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Detached renderer window""" from utils.globals import GlobalData from .qt import (QMainWindow, QTimer, QStackedWidget, QLabel, QVBoxLayout, QWidget, QPalette, Qt, QFrame) from .mainwindowtabwidgetbase import MainWindowTabWidgetBase class DetachedRendererWindow(QMainWindow): """Detached flow ui/markdown renderer window""" def __init__(self, settings, em): QMainWindow.__init__(self, None) self.settings = settings self.em = em self.__widgets = QStackedWidget(self) self.__widgets.setContentsMargins(1, 1, 1, 1) self.__noRenderLabel = QLabel('\nNo rendering available for the current tab') self.__noRenderLabel.setFrameShape(QFrame.StyledPanel) self.__noRenderLabel.setAlignment(Qt.AlignHCenter) self.__noRenderLabel.setAutoFillBackground(True) font = self.__noRenderLabel.font() font.setPointSize(font.pointSize() + 4) self.__noRenderLabel.setFont(font) palette = self.__noRenderLabel.palette() palette.setColor(QPalette.Background, GlobalData().skin['nolexerPaper']) self.__noRenderLabel.setPalette(palette) self.__widgets.addWidget(self.__noRenderLabel) self.setCentralWidget(self.__widgets) self.__ideClosing = False self.__initialisation = True # The size restore is done twice to avoid huge flickering # This one is approximate, the one in restoreWindowPosition() # is precise screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != settings['screenwidth'] or \ screenSize.height() != settings['screenheight']: # The screen resolution has been changed, use the default pos defXPos, defYpos, \ defWidth, defHeight = settings.getDefaultRendererWindowGeometry() self.resize(defWidth, defHeight) self.move(defXPos, defYpos) else: # No changes in the screen resolution self.resize(settings['rendererwidth'], settings['rendererheight']) self.move(settings['rendererxpos'] + settings['xdelta'], settings['rendererypos'] + settings['ydelta']) def closeEvent(self, event): """Renderer is closed: explicit close via X or IDE is closed""" if not self.__ideClosing: # Update the IDE button and memorize the setting self.settings['floatingRenderer'] = not self.settings['floatingRenderer'] GlobalData().mainWindow.floatingRendererButton.setChecked(False) self.hide() return def
(self, widget): """Registers one widget basing on info from the editors manager""" renderLayout = QVBoxLayout() renderLayout.setContentsMargins(0, 0, 0, 0) renderLayout.setSpacing(0) for wid in widget.popRenderingWidgets(): renderLayout.addWidget(wid) renderWidget = QWidget() renderWidget.setLayout(renderLayout) renderWidget.setObjectName(widget.getUUID()) self.__widgets.addWidget(renderWidget) def show(self): """Overwritten show method""" self.__connectSignals() # grab the widgets for index in range(self.em.count()): widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() QMainWindow.show(self) if self.__initialisation: self.restoreWindowPosition() def hide(self): """Overwritten hide method""" QMainWindow.hide(self) self.__disconnectSignals() # return widgets while self.__widgets.count() > 1: widget = self.__widgets.widget(1) uuid = widget.objectName() toBeReturned = [] layout = widget.layout() for index in range(layout.count()): w = layout.itemAt(index).widget() if w is not None: toBeReturned.append(w) for w in toBeReturned: layout.removeWidget(w) self.__widgets.removeWidget(widget) for index in range(self.em.count()): widget = self.em.widget(index) if widget.getUUID() == uuid: widget.pushRenderingWidgets(toBeReturned) break def __connectSignals(self): """Connects to all the required sugnals""" self.em.sigTabClosed.connect(self.__onTabClosed) self.em.currentChanged.connect(self.__onCurrentTabChanged) self.em.sigTextEditorTabAdded.connect(self.__onTextEditorTabAdded) self.em.sigFileTypeChanged.connect(self.__onFileTypeChanged) self.em.sigFileUpdated.connect(self.__onFileUpdated) self.em.sigBufferSavedAs.connect(self.__onBufferSavedAs) def __disconnectSignals(self): """Disconnects the signals""" self.em.sigBufferSavedAs.disconnect(self.__onBufferSavedAs) self.em.sigFileUpdated.disconnect(self.__onFileUpdated) self.em.sigTextEditorTabAdded.disconnect(self.__onTextEditorTabAdded) self.em.currentChanged.disconnect(self.__onCurrentTabChanged) self.em.sigTabClosed.disconnect(self.__onTabClosed) self.em.sigFileTypeChanged.disconnect(self.__onFileTypeChanged) def resizeEvent(self, resizeEv): """Triggered when the window is resized""" del resizeEv # unused argument QTimer.singleShot(1, self.__resizeEventdelayed) def __resizeEventdelayed(self): """Memorizes the new window size""" if self.__initialisation or self.__guessMaximized(): return self.settings['rendererwidth'] = self.width() self.settings['rendererheight'] = self.height() def moveEvent(self, moveEv): """Triggered when the window is moved""" del moveEv # unused argument QTimer.singleShot(1, self.__moveEventDelayed) def __moveEventDelayed(self): """Memorizes the new window position""" if not self.__initialisation and not self.__guessMaximized(): self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() def __guessMaximized(self): """True if the window is maximized""" # Ugly but I don't see any better way. # It is impossible to catch the case when the main window is maximized. # Especially when networked XServer is used (like xming) # So, make a wild guess instead and do not save the status if # maximized. availGeom = GlobalData().application.desktop().availableGeometry() if self.width() + abs(self.settings['xdelta']) > availGeom.width() or \ self.height() + abs(self.settings['ydelta']) > availGeom.height(): return True return False def restoreWindowPosition(self): """Makes sure that the window frame delta is proper""" screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != self.settings['screenwidth'] or \ screenSize.height() != self.settings['screenheight']: # The screen resolution has been changed, save the new values self.settings['screenwidth'] = screenSize.width() self.settings['screenheight'] = screenSize.height() self.settings['xdelta'] = self.settings['xpos'] - self.x() self.settings['ydelta'] = self.settings['ypos'] - self.y() self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() else: # Screen resolution is the same as before if self.settings['rendererxpos'] != self.x() or \ self.settings['rendererypos'] != self.y(): # The saved delta is incorrect, update it self.settings['xdelta'] = self.settings['rendererxpos'] - self.x() + \ self.settings['xdelta'] self.settings['ydelta'] = self.settings['rendererypos'] - self.y() + \ self.settings['ydelta'] self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() self.__initialisation = False def close(self): """Overwritten close method. Called when the IDE is closed""" self.__ideClosing = True while self.__widgets.count() > 0: self.__widgets.removeWidget(self.__widgets.widget(0)) QMainWindow.close(self) def __onTabClosed(self, tabUUID): """Triggered when the editor tab is closed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == tabUUID: self.__widgets.removeWidget(self.__widgets.widget(index)) self.updateCurrent() return def __onCurrentTabChanged(self, index): """Triggered when the current tab is changed""" del index # :nused argument self.updateCurrent() def __onTextEditorTabAdded(self, index): """Triggered when a new text editor window was added""" widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() def __onFileTypeChanged(self, fname, uuid, mime): """Triggered when a file type is changed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onBufferSavedAs(self, fname, uuid): """Triggered when the file was saved under another name""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onFileUpdated(self, fname, uuid): """Triggered when the file is overwritten""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def updateCurrent(self): """Updates the window title and switches to the proper widget""" widget = self.em.widget(self.em.currentIndex()) if widget is None: # May happened when there are no widgets in the em return widgetType = widget.getType() if widgetType == MainWindowTabWidgetBase.PlainTextEditor: editor = widget.getEditor() isPython = editor.isPythonBuffer() isMarkdown = editor.isMarkdownBuffer() if isPython or isMarkdown: title = 'Floating renderer: ' if isPython: title += 'python buffer (' else: title += 'markdown buffer (' title += widget.getShortName() + ')' self.setWindowTitle(title) uuid = widget.getUUID() for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.__widgets.setCurrentIndex(index) break return # Not python, not markdown, i.e. no renderer self.__widgets.setCurrentIndex(0) self.setWindowTitle('Floating renderer: no renderer for the current tab')
__registerWidget
identifier_name
floatingrendererwindow.py
# -*- coding: utf-8 -*- # # codimension - graphics python two-way code editor and analyzer # Copyright (C) 2010-2019 Sergey Satskiy <sergey.satskiy@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Detached renderer window""" from utils.globals import GlobalData from .qt import (QMainWindow, QTimer, QStackedWidget, QLabel, QVBoxLayout, QWidget, QPalette, Qt, QFrame) from .mainwindowtabwidgetbase import MainWindowTabWidgetBase class DetachedRendererWindow(QMainWindow): """Detached flow ui/markdown renderer window""" def __init__(self, settings, em): QMainWindow.__init__(self, None) self.settings = settings self.em = em self.__widgets = QStackedWidget(self) self.__widgets.setContentsMargins(1, 1, 1, 1) self.__noRenderLabel = QLabel('\nNo rendering available for the current tab') self.__noRenderLabel.setFrameShape(QFrame.StyledPanel) self.__noRenderLabel.setAlignment(Qt.AlignHCenter) self.__noRenderLabel.setAutoFillBackground(True) font = self.__noRenderLabel.font() font.setPointSize(font.pointSize() + 4) self.__noRenderLabel.setFont(font) palette = self.__noRenderLabel.palette() palette.setColor(QPalette.Background, GlobalData().skin['nolexerPaper']) self.__noRenderLabel.setPalette(palette) self.__widgets.addWidget(self.__noRenderLabel) self.setCentralWidget(self.__widgets) self.__ideClosing = False self.__initialisation = True # The size restore is done twice to avoid huge flickering # This one is approximate, the one in restoreWindowPosition() # is precise screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != settings['screenwidth'] or \ screenSize.height() != settings['screenheight']: # The screen resolution has been changed, use the default pos defXPos, defYpos, \ defWidth, defHeight = settings.getDefaultRendererWindowGeometry() self.resize(defWidth, defHeight) self.move(defXPos, defYpos) else: # No changes in the screen resolution self.resize(settings['rendererwidth'], settings['rendererheight']) self.move(settings['rendererxpos'] + settings['xdelta'], settings['rendererypos'] + settings['ydelta']) def closeEvent(self, event): """Renderer is closed: explicit close via X or IDE is closed""" if not self.__ideClosing: # Update the IDE button and memorize the setting self.settings['floatingRenderer'] = not self.settings['floatingRenderer'] GlobalData().mainWindow.floatingRendererButton.setChecked(False) self.hide() return def __registerWidget(self, widget): """Registers one widget basing on info from the editors manager""" renderLayout = QVBoxLayout() renderLayout.setContentsMargins(0, 0, 0, 0) renderLayout.setSpacing(0) for wid in widget.popRenderingWidgets(): renderLayout.addWidget(wid) renderWidget = QWidget() renderWidget.setLayout(renderLayout) renderWidget.setObjectName(widget.getUUID()) self.__widgets.addWidget(renderWidget) def show(self): """Overwritten show method""" self.__connectSignals() # grab the widgets for index in range(self.em.count()): widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() QMainWindow.show(self) if self.__initialisation: self.restoreWindowPosition() def hide(self): """Overwritten hide method""" QMainWindow.hide(self) self.__disconnectSignals() # return widgets while self.__widgets.count() > 1: widget = self.__widgets.widget(1) uuid = widget.objectName() toBeReturned = [] layout = widget.layout() for index in range(layout.count()): w = layout.itemAt(index).widget() if w is not None: toBeReturned.append(w) for w in toBeReturned: layout.removeWidget(w) self.__widgets.removeWidget(widget) for index in range(self.em.count()): widget = self.em.widget(index) if widget.getUUID() == uuid: widget.pushRenderingWidgets(toBeReturned) break def __connectSignals(self): """Connects to all the required sugnals""" self.em.sigTabClosed.connect(self.__onTabClosed) self.em.currentChanged.connect(self.__onCurrentTabChanged) self.em.sigTextEditorTabAdded.connect(self.__onTextEditorTabAdded) self.em.sigFileTypeChanged.connect(self.__onFileTypeChanged) self.em.sigFileUpdated.connect(self.__onFileUpdated) self.em.sigBufferSavedAs.connect(self.__onBufferSavedAs) def __disconnectSignals(self): """Disconnects the signals""" self.em.sigBufferSavedAs.disconnect(self.__onBufferSavedAs) self.em.sigFileUpdated.disconnect(self.__onFileUpdated) self.em.sigTextEditorTabAdded.disconnect(self.__onTextEditorTabAdded) self.em.currentChanged.disconnect(self.__onCurrentTabChanged) self.em.sigTabClosed.disconnect(self.__onTabClosed) self.em.sigFileTypeChanged.disconnect(self.__onFileTypeChanged) def resizeEvent(self, resizeEv): """Triggered when the window is resized""" del resizeEv # unused argument QTimer.singleShot(1, self.__resizeEventdelayed) def __resizeEventdelayed(self): """Memorizes the new window size""" if self.__initialisation or self.__guessMaximized(): return self.settings['rendererwidth'] = self.width() self.settings['rendererheight'] = self.height() def moveEvent(self, moveEv): """Triggered when the window is moved""" del moveEv # unused argument QTimer.singleShot(1, self.__moveEventDelayed) def __moveEventDelayed(self): """Memorizes the new window position""" if not self.__initialisation and not self.__guessMaximized(): self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() def __guessMaximized(self): """True if the window is maximized""" # Ugly but I don't see any better way. # It is impossible to catch the case when the main window is maximized. # Especially when networked XServer is used (like xming) # So, make a wild guess instead and do not save the status if # maximized. availGeom = GlobalData().application.desktop().availableGeometry() if self.width() + abs(self.settings['xdelta']) > availGeom.width() or \ self.height() + abs(self.settings['ydelta']) > availGeom.height():
return False def restoreWindowPosition(self): """Makes sure that the window frame delta is proper""" screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != self.settings['screenwidth'] or \ screenSize.height() != self.settings['screenheight']: # The screen resolution has been changed, save the new values self.settings['screenwidth'] = screenSize.width() self.settings['screenheight'] = screenSize.height() self.settings['xdelta'] = self.settings['xpos'] - self.x() self.settings['ydelta'] = self.settings['ypos'] - self.y() self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() else: # Screen resolution is the same as before if self.settings['rendererxpos'] != self.x() or \ self.settings['rendererypos'] != self.y(): # The saved delta is incorrect, update it self.settings['xdelta'] = self.settings['rendererxpos'] - self.x() + \ self.settings['xdelta'] self.settings['ydelta'] = self.settings['rendererypos'] - self.y() + \ self.settings['ydelta'] self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() self.__initialisation = False def close(self): """Overwritten close method. Called when the IDE is closed""" self.__ideClosing = True while self.__widgets.count() > 0: self.__widgets.removeWidget(self.__widgets.widget(0)) QMainWindow.close(self) def __onTabClosed(self, tabUUID): """Triggered when the editor tab is closed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == tabUUID: self.__widgets.removeWidget(self.__widgets.widget(index)) self.updateCurrent() return def __onCurrentTabChanged(self, index): """Triggered when the current tab is changed""" del index # :nused argument self.updateCurrent() def __onTextEditorTabAdded(self, index): """Triggered when a new text editor window was added""" widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() def __onFileTypeChanged(self, fname, uuid, mime): """Triggered when a file type is changed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onBufferSavedAs(self, fname, uuid): """Triggered when the file was saved under another name""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onFileUpdated(self, fname, uuid): """Triggered when the file is overwritten""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def updateCurrent(self): """Updates the window title and switches to the proper widget""" widget = self.em.widget(self.em.currentIndex()) if widget is None: # May happened when there are no widgets in the em return widgetType = widget.getType() if widgetType == MainWindowTabWidgetBase.PlainTextEditor: editor = widget.getEditor() isPython = editor.isPythonBuffer() isMarkdown = editor.isMarkdownBuffer() if isPython or isMarkdown: title = 'Floating renderer: ' if isPython: title += 'python buffer (' else: title += 'markdown buffer (' title += widget.getShortName() + ')' self.setWindowTitle(title) uuid = widget.getUUID() for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.__widgets.setCurrentIndex(index) break return # Not python, not markdown, i.e. no renderer self.__widgets.setCurrentIndex(0) self.setWindowTitle('Floating renderer: no renderer for the current tab')
return True
conditional_block
floatingrendererwindow.py
# -*- coding: utf-8 -*- # # codimension - graphics python two-way code editor and analyzer # Copyright (C) 2010-2019 Sergey Satskiy <sergey.satskiy@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Detached renderer window""" from utils.globals import GlobalData from .qt import (QMainWindow, QTimer, QStackedWidget, QLabel, QVBoxLayout, QWidget, QPalette, Qt, QFrame) from .mainwindowtabwidgetbase import MainWindowTabWidgetBase class DetachedRendererWindow(QMainWindow): """Detached flow ui/markdown renderer window""" def __init__(self, settings, em): QMainWindow.__init__(self, None) self.settings = settings self.em = em self.__widgets = QStackedWidget(self) self.__widgets.setContentsMargins(1, 1, 1, 1) self.__noRenderLabel = QLabel('\nNo rendering available for the current tab') self.__noRenderLabel.setFrameShape(QFrame.StyledPanel) self.__noRenderLabel.setAlignment(Qt.AlignHCenter) self.__noRenderLabel.setAutoFillBackground(True) font = self.__noRenderLabel.font() font.setPointSize(font.pointSize() + 4) self.__noRenderLabel.setFont(font) palette = self.__noRenderLabel.palette() palette.setColor(QPalette.Background, GlobalData().skin['nolexerPaper']) self.__noRenderLabel.setPalette(palette) self.__widgets.addWidget(self.__noRenderLabel) self.setCentralWidget(self.__widgets) self.__ideClosing = False self.__initialisation = True # The size restore is done twice to avoid huge flickering # This one is approximate, the one in restoreWindowPosition() # is precise screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != settings['screenwidth'] or \ screenSize.height() != settings['screenheight']: # The screen resolution has been changed, use the default pos defXPos, defYpos, \ defWidth, defHeight = settings.getDefaultRendererWindowGeometry() self.resize(defWidth, defHeight) self.move(defXPos, defYpos) else: # No changes in the screen resolution self.resize(settings['rendererwidth'], settings['rendererheight']) self.move(settings['rendererxpos'] + settings['xdelta'], settings['rendererypos'] + settings['ydelta']) def closeEvent(self, event): """Renderer is closed: explicit close via X or IDE is closed""" if not self.__ideClosing: # Update the IDE button and memorize the setting self.settings['floatingRenderer'] = not self.settings['floatingRenderer'] GlobalData().mainWindow.floatingRendererButton.setChecked(False) self.hide() return def __registerWidget(self, widget): """Registers one widget basing on info from the editors manager""" renderLayout = QVBoxLayout() renderLayout.setContentsMargins(0, 0, 0, 0) renderLayout.setSpacing(0)
renderWidget.setObjectName(widget.getUUID()) self.__widgets.addWidget(renderWidget) def show(self): """Overwritten show method""" self.__connectSignals() # grab the widgets for index in range(self.em.count()): widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() QMainWindow.show(self) if self.__initialisation: self.restoreWindowPosition() def hide(self): """Overwritten hide method""" QMainWindow.hide(self) self.__disconnectSignals() # return widgets while self.__widgets.count() > 1: widget = self.__widgets.widget(1) uuid = widget.objectName() toBeReturned = [] layout = widget.layout() for index in range(layout.count()): w = layout.itemAt(index).widget() if w is not None: toBeReturned.append(w) for w in toBeReturned: layout.removeWidget(w) self.__widgets.removeWidget(widget) for index in range(self.em.count()): widget = self.em.widget(index) if widget.getUUID() == uuid: widget.pushRenderingWidgets(toBeReturned) break def __connectSignals(self): """Connects to all the required sugnals""" self.em.sigTabClosed.connect(self.__onTabClosed) self.em.currentChanged.connect(self.__onCurrentTabChanged) self.em.sigTextEditorTabAdded.connect(self.__onTextEditorTabAdded) self.em.sigFileTypeChanged.connect(self.__onFileTypeChanged) self.em.sigFileUpdated.connect(self.__onFileUpdated) self.em.sigBufferSavedAs.connect(self.__onBufferSavedAs) def __disconnectSignals(self): """Disconnects the signals""" self.em.sigBufferSavedAs.disconnect(self.__onBufferSavedAs) self.em.sigFileUpdated.disconnect(self.__onFileUpdated) self.em.sigTextEditorTabAdded.disconnect(self.__onTextEditorTabAdded) self.em.currentChanged.disconnect(self.__onCurrentTabChanged) self.em.sigTabClosed.disconnect(self.__onTabClosed) self.em.sigFileTypeChanged.disconnect(self.__onFileTypeChanged) def resizeEvent(self, resizeEv): """Triggered when the window is resized""" del resizeEv # unused argument QTimer.singleShot(1, self.__resizeEventdelayed) def __resizeEventdelayed(self): """Memorizes the new window size""" if self.__initialisation or self.__guessMaximized(): return self.settings['rendererwidth'] = self.width() self.settings['rendererheight'] = self.height() def moveEvent(self, moveEv): """Triggered when the window is moved""" del moveEv # unused argument QTimer.singleShot(1, self.__moveEventDelayed) def __moveEventDelayed(self): """Memorizes the new window position""" if not self.__initialisation and not self.__guessMaximized(): self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() def __guessMaximized(self): """True if the window is maximized""" # Ugly but I don't see any better way. # It is impossible to catch the case when the main window is maximized. # Especially when networked XServer is used (like xming) # So, make a wild guess instead and do not save the status if # maximized. availGeom = GlobalData().application.desktop().availableGeometry() if self.width() + abs(self.settings['xdelta']) > availGeom.width() or \ self.height() + abs(self.settings['ydelta']) > availGeom.height(): return True return False def restoreWindowPosition(self): """Makes sure that the window frame delta is proper""" screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != self.settings['screenwidth'] or \ screenSize.height() != self.settings['screenheight']: # The screen resolution has been changed, save the new values self.settings['screenwidth'] = screenSize.width() self.settings['screenheight'] = screenSize.height() self.settings['xdelta'] = self.settings['xpos'] - self.x() self.settings['ydelta'] = self.settings['ypos'] - self.y() self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() else: # Screen resolution is the same as before if self.settings['rendererxpos'] != self.x() or \ self.settings['rendererypos'] != self.y(): # The saved delta is incorrect, update it self.settings['xdelta'] = self.settings['rendererxpos'] - self.x() + \ self.settings['xdelta'] self.settings['ydelta'] = self.settings['rendererypos'] - self.y() + \ self.settings['ydelta'] self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() self.__initialisation = False def close(self): """Overwritten close method. Called when the IDE is closed""" self.__ideClosing = True while self.__widgets.count() > 0: self.__widgets.removeWidget(self.__widgets.widget(0)) QMainWindow.close(self) def __onTabClosed(self, tabUUID): """Triggered when the editor tab is closed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == tabUUID: self.__widgets.removeWidget(self.__widgets.widget(index)) self.updateCurrent() return def __onCurrentTabChanged(self, index): """Triggered when the current tab is changed""" del index # :nused argument self.updateCurrent() def __onTextEditorTabAdded(self, index): """Triggered when a new text editor window was added""" widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() def __onFileTypeChanged(self, fname, uuid, mime): """Triggered when a file type is changed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onBufferSavedAs(self, fname, uuid): """Triggered when the file was saved under another name""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onFileUpdated(self, fname, uuid): """Triggered when the file is overwritten""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def updateCurrent(self): """Updates the window title and switches to the proper widget""" widget = self.em.widget(self.em.currentIndex()) if widget is None: # May happened when there are no widgets in the em return widgetType = widget.getType() if widgetType == MainWindowTabWidgetBase.PlainTextEditor: editor = widget.getEditor() isPython = editor.isPythonBuffer() isMarkdown = editor.isMarkdownBuffer() if isPython or isMarkdown: title = 'Floating renderer: ' if isPython: title += 'python buffer (' else: title += 'markdown buffer (' title += widget.getShortName() + ')' self.setWindowTitle(title) uuid = widget.getUUID() for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.__widgets.setCurrentIndex(index) break return # Not python, not markdown, i.e. no renderer self.__widgets.setCurrentIndex(0) self.setWindowTitle('Floating renderer: no renderer for the current tab')
for wid in widget.popRenderingWidgets(): renderLayout.addWidget(wid) renderWidget = QWidget() renderWidget.setLayout(renderLayout)
random_line_split
floatingrendererwindow.py
# -*- coding: utf-8 -*- # # codimension - graphics python two-way code editor and analyzer # Copyright (C) 2010-2019 Sergey Satskiy <sergey.satskiy@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Detached renderer window""" from utils.globals import GlobalData from .qt import (QMainWindow, QTimer, QStackedWidget, QLabel, QVBoxLayout, QWidget, QPalette, Qt, QFrame) from .mainwindowtabwidgetbase import MainWindowTabWidgetBase class DetachedRendererWindow(QMainWindow): """Detached flow ui/markdown renderer window""" def __init__(self, settings, em): QMainWindow.__init__(self, None) self.settings = settings self.em = em self.__widgets = QStackedWidget(self) self.__widgets.setContentsMargins(1, 1, 1, 1) self.__noRenderLabel = QLabel('\nNo rendering available for the current tab') self.__noRenderLabel.setFrameShape(QFrame.StyledPanel) self.__noRenderLabel.setAlignment(Qt.AlignHCenter) self.__noRenderLabel.setAutoFillBackground(True) font = self.__noRenderLabel.font() font.setPointSize(font.pointSize() + 4) self.__noRenderLabel.setFont(font) palette = self.__noRenderLabel.palette() palette.setColor(QPalette.Background, GlobalData().skin['nolexerPaper']) self.__noRenderLabel.setPalette(palette) self.__widgets.addWidget(self.__noRenderLabel) self.setCentralWidget(self.__widgets) self.__ideClosing = False self.__initialisation = True # The size restore is done twice to avoid huge flickering # This one is approximate, the one in restoreWindowPosition() # is precise screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != settings['screenwidth'] or \ screenSize.height() != settings['screenheight']: # The screen resolution has been changed, use the default pos defXPos, defYpos, \ defWidth, defHeight = settings.getDefaultRendererWindowGeometry() self.resize(defWidth, defHeight) self.move(defXPos, defYpos) else: # No changes in the screen resolution self.resize(settings['rendererwidth'], settings['rendererheight']) self.move(settings['rendererxpos'] + settings['xdelta'], settings['rendererypos'] + settings['ydelta']) def closeEvent(self, event): """Renderer is closed: explicit close via X or IDE is closed""" if not self.__ideClosing: # Update the IDE button and memorize the setting self.settings['floatingRenderer'] = not self.settings['floatingRenderer'] GlobalData().mainWindow.floatingRendererButton.setChecked(False) self.hide() return def __registerWidget(self, widget): """Registers one widget basing on info from the editors manager""" renderLayout = QVBoxLayout() renderLayout.setContentsMargins(0, 0, 0, 0) renderLayout.setSpacing(0) for wid in widget.popRenderingWidgets(): renderLayout.addWidget(wid) renderWidget = QWidget() renderWidget.setLayout(renderLayout) renderWidget.setObjectName(widget.getUUID()) self.__widgets.addWidget(renderWidget) def show(self): """Overwritten show method""" self.__connectSignals() # grab the widgets for index in range(self.em.count()): widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() QMainWindow.show(self) if self.__initialisation: self.restoreWindowPosition() def hide(self): """Overwritten hide method""" QMainWindow.hide(self) self.__disconnectSignals() # return widgets while self.__widgets.count() > 1: widget = self.__widgets.widget(1) uuid = widget.objectName() toBeReturned = [] layout = widget.layout() for index in range(layout.count()): w = layout.itemAt(index).widget() if w is not None: toBeReturned.append(w) for w in toBeReturned: layout.removeWidget(w) self.__widgets.removeWidget(widget) for index in range(self.em.count()): widget = self.em.widget(index) if widget.getUUID() == uuid: widget.pushRenderingWidgets(toBeReturned) break def __connectSignals(self): """Connects to all the required sugnals""" self.em.sigTabClosed.connect(self.__onTabClosed) self.em.currentChanged.connect(self.__onCurrentTabChanged) self.em.sigTextEditorTabAdded.connect(self.__onTextEditorTabAdded) self.em.sigFileTypeChanged.connect(self.__onFileTypeChanged) self.em.sigFileUpdated.connect(self.__onFileUpdated) self.em.sigBufferSavedAs.connect(self.__onBufferSavedAs) def __disconnectSignals(self): """Disconnects the signals""" self.em.sigBufferSavedAs.disconnect(self.__onBufferSavedAs) self.em.sigFileUpdated.disconnect(self.__onFileUpdated) self.em.sigTextEditorTabAdded.disconnect(self.__onTextEditorTabAdded) self.em.currentChanged.disconnect(self.__onCurrentTabChanged) self.em.sigTabClosed.disconnect(self.__onTabClosed) self.em.sigFileTypeChanged.disconnect(self.__onFileTypeChanged) def resizeEvent(self, resizeEv):
def __resizeEventdelayed(self): """Memorizes the new window size""" if self.__initialisation or self.__guessMaximized(): return self.settings['rendererwidth'] = self.width() self.settings['rendererheight'] = self.height() def moveEvent(self, moveEv): """Triggered when the window is moved""" del moveEv # unused argument QTimer.singleShot(1, self.__moveEventDelayed) def __moveEventDelayed(self): """Memorizes the new window position""" if not self.__initialisation and not self.__guessMaximized(): self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() def __guessMaximized(self): """True if the window is maximized""" # Ugly but I don't see any better way. # It is impossible to catch the case when the main window is maximized. # Especially when networked XServer is used (like xming) # So, make a wild guess instead and do not save the status if # maximized. availGeom = GlobalData().application.desktop().availableGeometry() if self.width() + abs(self.settings['xdelta']) > availGeom.width() or \ self.height() + abs(self.settings['ydelta']) > availGeom.height(): return True return False def restoreWindowPosition(self): """Makes sure that the window frame delta is proper""" screenSize = GlobalData().application.desktop().screenGeometry() if screenSize.width() != self.settings['screenwidth'] or \ screenSize.height() != self.settings['screenheight']: # The screen resolution has been changed, save the new values self.settings['screenwidth'] = screenSize.width() self.settings['screenheight'] = screenSize.height() self.settings['xdelta'] = self.settings['xpos'] - self.x() self.settings['ydelta'] = self.settings['ypos'] - self.y() self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() else: # Screen resolution is the same as before if self.settings['rendererxpos'] != self.x() or \ self.settings['rendererypos'] != self.y(): # The saved delta is incorrect, update it self.settings['xdelta'] = self.settings['rendererxpos'] - self.x() + \ self.settings['xdelta'] self.settings['ydelta'] = self.settings['rendererypos'] - self.y() + \ self.settings['ydelta'] self.settings['rendererxpos'] = self.x() self.settings['rendererypos'] = self.y() self.__initialisation = False def close(self): """Overwritten close method. Called when the IDE is closed""" self.__ideClosing = True while self.__widgets.count() > 0: self.__widgets.removeWidget(self.__widgets.widget(0)) QMainWindow.close(self) def __onTabClosed(self, tabUUID): """Triggered when the editor tab is closed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == tabUUID: self.__widgets.removeWidget(self.__widgets.widget(index)) self.updateCurrent() return def __onCurrentTabChanged(self, index): """Triggered when the current tab is changed""" del index # :nused argument self.updateCurrent() def __onTextEditorTabAdded(self, index): """Triggered when a new text editor window was added""" widget = self.em.widget(index) if widget.getType() == MainWindowTabWidgetBase.PlainTextEditor: self.__registerWidget(widget) self.updateCurrent() def __onFileTypeChanged(self, fname, uuid, mime): """Triggered when a file type is changed""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onBufferSavedAs(self, fname, uuid): """Triggered when the file was saved under another name""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def __onFileUpdated(self, fname, uuid): """Triggered when the file is overwritten""" for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.updateCurrent() return def updateCurrent(self): """Updates the window title and switches to the proper widget""" widget = self.em.widget(self.em.currentIndex()) if widget is None: # May happened when there are no widgets in the em return widgetType = widget.getType() if widgetType == MainWindowTabWidgetBase.PlainTextEditor: editor = widget.getEditor() isPython = editor.isPythonBuffer() isMarkdown = editor.isMarkdownBuffer() if isPython or isMarkdown: title = 'Floating renderer: ' if isPython: title += 'python buffer (' else: title += 'markdown buffer (' title += widget.getShortName() + ')' self.setWindowTitle(title) uuid = widget.getUUID() for index in range(self.__widgets.count()): if self.__widgets.widget(index).objectName() == uuid: self.__widgets.setCurrentIndex(index) break return # Not python, not markdown, i.e. no renderer self.__widgets.setCurrentIndex(0) self.setWindowTitle('Floating renderer: no renderer for the current tab')
"""Triggered when the window is resized""" del resizeEv # unused argument QTimer.singleShot(1, self.__resizeEventdelayed)
identifier_body
test_bcrypt.py
# -*- coding:utf-8 -*- from django import test from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.management import call_command from mock import patch from nose.tools import eq_ class BcryptTests(test.TestCase): def setUp(self): super(BcryptTests, self).setUp() User.objects.create_user('john', 'johndoe@example.com', password='123456') User.objects.create_user('jane', 'janedoe@example.com', password='abc') User.objects.create_user('jude', 'jeromedoe@example.com', password=u'abcéäêëôøà') def test_bcrypt_used(self): """Make sure bcrypt was used as the hash.""" eq_(User.objects.get(username='john').password[:7], 'bcrypt$') eq_(User.objects.get(username='jane').password[:7], 'bcrypt$') eq_(User.objects.get(username='jude').password[:7], 'bcrypt$') def test_bcrypt_auth(self): """Try authenticating.""" assert authenticate(username='john', password='123456') assert authenticate(username='jane', password='abc') assert not authenticate(username='jane', password='123456') assert authenticate(username='jude', password=u'abcéäêëôøà') assert not authenticate(username='jude', password=u'çççbbbààà') @patch.object(settings._wrapped, 'HMAC_KEYS', dict()) def test_nokey(self): """With no HMAC key, no dice.""" assert not authenticate(username='john', password='123456') assert not authenticate(username='jane', password='abc') assert not authenticate(username='jane', password='123456') assert not authenticate(username='jude', password=u'abcéäêëôøà') assert not authenticate(username='jude', password=u'çççbbbààà') def test_password_from_django14(self): """Test that a password generated by django_sha2 with django 1.4 is recognized and changed to a 1.3 version""" # We can't easily call 1.4's hashers so we hardcode the passwords as # returned with the specific salts and hmac_key in 1.4. prefix = 'bcrypt2011_01_01$2a$12$' suffix = '$2011-01-01' raw_hashes = { 'john': '02CfJWdVwLK80jlRe/Xx1u8sTHAR0JUmKV9YB4BS.Os4LK6nsoLie', 'jane': '.ipDt6gRL3CPkVH7FEyR6.8YXeQFXAMyiX3mXpDh4YDBonrdofrcG', 'jude': '6Ol.vgIFxMQw0LBhCLtv7OkV.oyJjen2GVMoiNcLnbsljSfYUkQqe', } u = User.objects.get(username="john") django14_style_password = "%s%s%s" % (prefix, raw_hashes['john'], suffix) u.password = django14_style_password assert u.check_password('123456') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jane") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jane'], suffix) u.password = django14_style_password assert u.check_password('abc') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jude") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jude'], suffix) u.password = django14_style_password assert u.check_password(u'abcéäêëôøà') eq_(u.password[:7], 'bcrypt$') def test_hmac_autoupdate(self): """Auto-update HMAC key if hash in DB is outdated.""" # Get HMAC key IDs to compare old_key_id = max(settings.HMAC_KEYS.keys()) new_key_id = '2020-01-01' # Add a new HMAC key new_keys = settings.HMAC_KEYS.copy() new_keys[new_key_id] = 'a_new_key' with patch.object(settings._wrapped, 'HMAC_KEYS', new_keys): # Make sure the database has the old key ID. john = User.objects.get(username='john') eq_(john.password.rsplit('$', 1)[1], old_key_id) # Log in. assert authenticate(username='john', password='123456') # Make sure the DB now has a new password hash. john = User.objects.get(username='john') eq_(john.password.rsplit('$', 1)[1], new_key_id) def test_rehash(self): """Auto-upgrade to stronger hash if needed.""" # Set a sha256 hash for a user. This one is "123". john = User.objects.get(username='john') john.password = ('sha256$7a49025f024ad3dcacad$aaff1abe5377ffeab6ccc68' '709d94c1950edf11f02d8acb83c75d8fcac1ebeb1') john.save() # The hash should be sha256 now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'sha256') # Log in (should rehash transparently). assert authenticate(username='john', password='123') # Make sure the DB now has a bcrypt hash. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'bcrypt') # Log in again with the new hash. assert authenticate(username='john', password='123') def test_management_command(self): """Test password update flow via management command, from default Django hashes, to hardened hashes, to bcrypt on log in.""" john = User.objects.get(username='john') john.password = 'sha1$3356f$9fd40318e1de9ecd3ab3a5fe944ceaf6a2897eef' john.save() # The hash should be sha1 now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'sha1')
call_command('strengthen_user_passwords') # The hash should be 'hh' now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'hh') # Logging in will convert the hardened hash to bcrypt. assert authenticate(username='john', password='123') # Make sure the DB now has a bcrypt hash. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'bcrypt') # Log in again with the new hash. assert authenticate(username='john', password='123')
# Simulate calling management command
random_line_split
test_bcrypt.py
# -*- coding:utf-8 -*- from django import test from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.management import call_command from mock import patch from nose.tools import eq_ class BcryptTests(test.TestCase): def setUp(self): super(BcryptTests, self).setUp() User.objects.create_user('john', 'johndoe@example.com', password='123456') User.objects.create_user('jane', 'janedoe@example.com', password='abc') User.objects.create_user('jude', 'jeromedoe@example.com', password=u'abcéäêëôøà') def test_bcrypt_used(self): """Make sure bcrypt was used as the hash.""" eq_(User.objects.get(username='john').password[:7], 'bcrypt$') eq_(User.objects.get(username='jane').password[:7], 'bcrypt$') eq_(User.objects.get(username='jude').password[:7], 'bcrypt$') def test_bcrypt_auth(self): """Try authenticating.""" assert authenticate(username='john', password='123456') assert authenticate(username='jane', password='abc') assert not authenticate(username='jane', password='123456') assert authenticate(username='jude', password=u'abcéäêëôøà') assert not authenticate(username='jude', password=u'çççbbbààà') @patch.object(settings._wrapped, 'HMAC_KEYS', dict()) def test_nokey(self): """With no HMAC key, no dice.""" assert not authenticate(username='john', password='123456') assert not authenticate(username='jane', password='abc') assert not authenticate(username='jane', password='123456') assert not authenticate(username='jude', password=u'abcéäêëôøà') assert not authenticate(username='jude', password=u'çççbbbààà') def test_password_from_django14(self): """Test that a password generated by django_sha2 with django 1.4 is recognized and changed to a 1.3 version""" # We can't easily call 1.4's hashers so we hardcode the passwords as # returned with the specific salts and hmac_key in 1.4. prefix = 'bcrypt2011_01_01$2a$12$' suffix = '$2011-01-01' raw_hashes = { 'john': '02CfJWdVwLK80jlRe/Xx1u8sTHAR0JUmKV9YB4BS.Os4LK6nsoLie', 'jane': '.ipDt6gRL3CPkVH7FEyR6.8YXeQFXAMyiX3mXpDh4YDBonrdofrcG', 'jude': '6Ol.vgIFxMQw0LBhCLtv7OkV.oyJjen2GVMoiNcLnbsljSfYUkQqe', } u = User.objects.get(username="john") django14_style_password = "%s%s%s" % (prefix, raw_hashes['john'], suffix) u.password = django14_style_password assert u.check_password('123456') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jane") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jane'], suffix) u.password = django14_style_password assert u.check_password('abc') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jude") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jude'], suffix) u.password = django14_style_password assert u.check_password(u'abcéäêëôøà') eq_(u.password[:7], 'bcrypt$') def test_hmac_autoupdate(self): """Auto-update HMAC key if hash in DB is outdated.""" # Get HMAC key IDs to compare old_key_id = max(settings.HMAC_KEYS.keys()) new_key_id = '2020-01-01' # Add a new HMAC key new_keys = settings.HMAC_KEYS.copy() new_keys[new_key_id] = 'a_new_key' with patch.object(settings._wrapped, 'HMAC_KEYS', new_keys): # Make sure the database has the old key ID. john = User.objects.get(username='john') eq_(john.password.rsplit('$', 1)[1], old_key_id) # Log in. assert authenticate(username='john', password='123456') # Make sure the DB now has a new password hash. john = User.objects.get(username='john') eq_(john.password.rsplit('$', 1)[1], new_key_id) def test_rehash(self): """Auto-upgrade to stronger hash if needed.""" # Set a sha256 hash for a user. This one is "123". john = User.objects.get(username='john') john.password = ('sha256$7a49025f024ad3dcacad$aaff1abe5377ffeab6ccc68' '709d94c1950edf11f02d8acb83c75d8fcac1ebeb1') john.save() # The hash should be sha256 now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'sha256') # Log in (should rehash transparently). assert authenticate(username='john', password='123') # Make sure the DB now has a bcrypt hash. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'bcrypt') # Log in again with the new hash. assert authenticate(username='john', password='123') def test_management_command(self): """Test password update flow via managem
ent command, from default Django hashes, to hardened hashes, to bcrypt on log in.""" john = User.objects.get(username='john') john.password = 'sha1$3356f$9fd40318e1de9ecd3ab3a5fe944ceaf6a2897eef' john.save() # The hash should be sha1 now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'sha1') # Simulate calling management command call_command('strengthen_user_passwords') # The hash should be 'hh' now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'hh') # Logging in will convert the hardened hash to bcrypt. assert authenticate(username='john', password='123') # Make sure the DB now has a bcrypt hash. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'bcrypt') # Log in again with the new hash. assert authenticate(username='john', password='123')
identifier_body
test_bcrypt.py
# -*- coding:utf-8 -*- from django import test from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.management import call_command from mock import patch from nose.tools import eq_ class BcryptTests(test.TestCase): def setUp(self): super(BcryptTests, self).setUp() User.objects.create_user('john', 'johndoe@example.com', password='123456') User.objects.create_user('jane', 'janedoe@example.com', password='abc') User.objects.create_user('jude', 'jeromedoe@example.com', password=u'abcéäêëôøà') def test_bc
"""Make sure bcrypt was used as the hash.""" eq_(User.objects.get(username='john').password[:7], 'bcrypt$') eq_(User.objects.get(username='jane').password[:7], 'bcrypt$') eq_(User.objects.get(username='jude').password[:7], 'bcrypt$') def test_bcrypt_auth(self): """Try authenticating.""" assert authenticate(username='john', password='123456') assert authenticate(username='jane', password='abc') assert not authenticate(username='jane', password='123456') assert authenticate(username='jude', password=u'abcéäêëôøà') assert not authenticate(username='jude', password=u'çççbbbààà') @patch.object(settings._wrapped, 'HMAC_KEYS', dict()) def test_nokey(self): """With no HMAC key, no dice.""" assert not authenticate(username='john', password='123456') assert not authenticate(username='jane', password='abc') assert not authenticate(username='jane', password='123456') assert not authenticate(username='jude', password=u'abcéäêëôøà') assert not authenticate(username='jude', password=u'çççbbbààà') def test_password_from_django14(self): """Test that a password generated by django_sha2 with django 1.4 is recognized and changed to a 1.3 version""" # We can't easily call 1.4's hashers so we hardcode the passwords as # returned with the specific salts and hmac_key in 1.4. prefix = 'bcrypt2011_01_01$2a$12$' suffix = '$2011-01-01' raw_hashes = { 'john': '02CfJWdVwLK80jlRe/Xx1u8sTHAR0JUmKV9YB4BS.Os4LK6nsoLie', 'jane': '.ipDt6gRL3CPkVH7FEyR6.8YXeQFXAMyiX3mXpDh4YDBonrdofrcG', 'jude': '6Ol.vgIFxMQw0LBhCLtv7OkV.oyJjen2GVMoiNcLnbsljSfYUkQqe', } u = User.objects.get(username="john") django14_style_password = "%s%s%s" % (prefix, raw_hashes['john'], suffix) u.password = django14_style_password assert u.check_password('123456') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jane") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jane'], suffix) u.password = django14_style_password assert u.check_password('abc') eq_(u.password[:7], 'bcrypt$') u = User.objects.get(username="jude") django14_style_password = "%s%s%s" % (prefix, raw_hashes['jude'], suffix) u.password = django14_style_password assert u.check_password(u'abcéäêëôøà') eq_(u.password[:7], 'bcrypt$') def test_hmac_autoupdate(self): """Auto-update HMAC key if hash in DB is outdated.""" # Get HMAC key IDs to compare old_key_id = max(settings.HMAC_KEYS.keys()) new_key_id = '2020-01-01' # Add a new HMAC key new_keys = settings.HMAC_KEYS.copy() new_keys[new_key_id] = 'a_new_key' with patch.object(settings._wrapped, 'HMAC_KEYS', new_keys): # Make sure the database has the old key ID. john = User.objects.get(username='john') eq_(john.password.rsplit('$', 1)[1], old_key_id) # Log in. assert authenticate(username='john', password='123456') # Make sure the DB now has a new password hash. john = User.objects.get(username='john') eq_(john.password.rsplit('$', 1)[1], new_key_id) def test_rehash(self): """Auto-upgrade to stronger hash if needed.""" # Set a sha256 hash for a user. This one is "123". john = User.objects.get(username='john') john.password = ('sha256$7a49025f024ad3dcacad$aaff1abe5377ffeab6ccc68' '709d94c1950edf11f02d8acb83c75d8fcac1ebeb1') john.save() # The hash should be sha256 now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'sha256') # Log in (should rehash transparently). assert authenticate(username='john', password='123') # Make sure the DB now has a bcrypt hash. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'bcrypt') # Log in again with the new hash. assert authenticate(username='john', password='123') def test_management_command(self): """Test password update flow via management command, from default Django hashes, to hardened hashes, to bcrypt on log in.""" john = User.objects.get(username='john') john.password = 'sha1$3356f$9fd40318e1de9ecd3ab3a5fe944ceaf6a2897eef' john.save() # The hash should be sha1 now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'sha1') # Simulate calling management command call_command('strengthen_user_passwords') # The hash should be 'hh' now. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'hh') # Logging in will convert the hardened hash to bcrypt. assert authenticate(username='john', password='123') # Make sure the DB now has a bcrypt hash. john = User.objects.get(username='john') eq_(john.password.split('$', 1)[0], 'bcrypt') # Log in again with the new hash. assert authenticate(username='john', password='123')
rypt_used(self):
identifier_name
json-test.js
define("d3/test/xhr/json-test", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ var vows = require("vows"), load = require("../load"), assert = require("../assert"); var suite = vows.describe("d3.json"); suite.addBatch({ "json": { topic: load("xhr/json").expression("d3.json").document(), "on a sample file": { topic: function(json) { json("test/data/sample.json", this.callback); }, "invokes the callback with the loaded JSON": function(json) { assert.deepEqual(json, [{"Hello":42,"World":"\"fish\""}]); }, "overrides the mime type to application/json": function(json) { assert.equal(XMLHttpRequest._last._info.mimeType, "application/json"); } }, "on a file that does not exist": { topic: function(json) { var callback = this.callback; json("//does/not/exist.json", function(error, json) { callback(null, {error: error, value: json}); }); }, "invokes the callback with undefined when an error occurs": function(result) { assert.equal(result.error.status, 404); assert.isUndefined(result.value); } }, "on a file with invalid JSON": { topic: function(json) { var callback = this.callback; json("test/data/sample.tsv", function(error, json) {
assert.isUndefined(result.value); } } } }); suite.export(module); });
callback(null, {error: error, value: json}); }); }, "invokes the callback with undefined when an error occurs": function(result) { assert.equal(result.error.constructor.name, "SyntaxError");
random_line_split
server6127.js
/* * SERVER-6127 : $project uasserts if an expected nested field has a non object parent in a document * * This test validates the SERVER-6127 ticket. Return undefined when retrieving a field along a * path, when the subpath does not exist (this is what happens when a field does not exist and * there is no path). Previous it would uassert causing the aggregation to end. */ /* * 1) Clear and create testing db * 2) Run an aggregation that simply projects a two fields, one with a sub path one without * 3) Assert that the result is what we expected */ // Clear db db.s6127.drop(); // Populate db db.s6127.save({a:1}); db.s6127.save({foo:2}); db.s6127.save({foo:{bar:3}}); // Aggregate checking the field foo and the path foo.bar var s6127 = db.s6127.aggregate( { $project : { _id : 0, 'foo.bar' : 1, field : "$foo", path : "$foo.bar" }} ); /* * The first document should contain nothing as neither field exists, the second document should * contain only field as it has a value in foo, but foo does not have a field bar so it cannot walk * that path, the third document should have both the field and path as foo is an object which has * a field bar */ var s6127result = [ { }, { field : 2 }, { foo : { bar : 3 }, field : { bar : 3 }, path : 3
// Assert assert.eq(s6127.result, s6127result, 's6127 failed');
} ];
random_line_split
test.rs
use std::marker::PhantomData; //TODO merge_left/merge_right/split_left/split_right for lifetimes //TODO existentials: https://github.com/bluss/indexing //This is a transparent wrapper over a slice, with two run-time type tags for the beginning and the //end of the slice pub struct SliceFragment<'a, T: 'a, A, B>( pub &'a mut [T], PhantomData<A>, PhantomData<B> ); impl<'a, T: 'a + Sized, A, B> SliceFragment<'a, T, A, B> { //Creating an empty slice fragment, for demonstration purposes. //Note that the beginning and end markers are the same. pub fn empty(slice: &'a mut [T; 0]) -> SliceFragment<'a, T, A, A> { SliceFragment( slice, PhantomData, PhantomData ) } //Note that the type parameters A and B are user-provided; if they are the same, type safety //goes out the window. A better version would use existential types. pub fn new(slice: &'a mut [T]) -> SliceFragment<'a, T, A, B>
} //Merge is only allowed if the end marker of the first slice fragment coincides with the begin //marker of the second slice fragment pub fn merge<'a, 'b, 'c: 'a + 'b, T: 'a, A, B, C>( SliceFragment(slice1, begin1, _): SliceFragment<'a, T, A, B>, SliceFragment(slice2, _, end2) : SliceFragment<'b, T, B, C> ) -> SliceFragment<'c, T, A, C> { unsafe { let slice = std::slice::from_raw_parts_mut(slice1.as_mut_ptr(), slice1.len() + slice2.len()); SliceFragment(slice, begin1, end2) } } //NOT TYPE SAFE if any of A, B or C are the same type pub fn split<'a, T: 'a, A, B, C>( SliceFragment(slice, begin1, end2): SliceFragment<'a, T, A, C>, index: usize ) -> (SliceFragment<'a, T, A, B>, SliceFragment<'a, T, B, C>) { let end1: PhantomData<B> = PhantomData; let begin2: PhantomData<B> = PhantomData; let (slice1, slice2) = slice.split_at_mut(index); ( SliceFragment(slice1, begin1, end1), SliceFragment(slice2, begin2, end2) ) }
{ SliceFragment( slice, PhantomData, PhantomData ) }
identifier_body
test.rs
use std::marker::PhantomData; //TODO merge_left/merge_right/split_left/split_right for lifetimes //TODO existentials: https://github.com/bluss/indexing //This is a transparent wrapper over a slice, with two run-time type tags for the beginning and the //end of the slice pub struct
<'a, T: 'a, A, B>( pub &'a mut [T], PhantomData<A>, PhantomData<B> ); impl<'a, T: 'a + Sized, A, B> SliceFragment<'a, T, A, B> { //Creating an empty slice fragment, for demonstration purposes. //Note that the beginning and end markers are the same. pub fn empty(slice: &'a mut [T; 0]) -> SliceFragment<'a, T, A, A> { SliceFragment( slice, PhantomData, PhantomData ) } //Note that the type parameters A and B are user-provided; if they are the same, type safety //goes out the window. A better version would use existential types. pub fn new(slice: &'a mut [T]) -> SliceFragment<'a, T, A, B> { SliceFragment( slice, PhantomData, PhantomData ) } } //Merge is only allowed if the end marker of the first slice fragment coincides with the begin //marker of the second slice fragment pub fn merge<'a, 'b, 'c: 'a + 'b, T: 'a, A, B, C>( SliceFragment(slice1, begin1, _): SliceFragment<'a, T, A, B>, SliceFragment(slice2, _, end2) : SliceFragment<'b, T, B, C> ) -> SliceFragment<'c, T, A, C> { unsafe { let slice = std::slice::from_raw_parts_mut(slice1.as_mut_ptr(), slice1.len() + slice2.len()); SliceFragment(slice, begin1, end2) } } //NOT TYPE SAFE if any of A, B or C are the same type pub fn split<'a, T: 'a, A, B, C>( SliceFragment(slice, begin1, end2): SliceFragment<'a, T, A, C>, index: usize ) -> (SliceFragment<'a, T, A, B>, SliceFragment<'a, T, B, C>) { let end1: PhantomData<B> = PhantomData; let begin2: PhantomData<B> = PhantomData; let (slice1, slice2) = slice.split_at_mut(index); ( SliceFragment(slice1, begin1, end1), SliceFragment(slice2, begin2, end2) ) }
SliceFragment
identifier_name
test.rs
use std::marker::PhantomData; //TODO merge_left/merge_right/split_left/split_right for lifetimes //TODO existentials: https://github.com/bluss/indexing //This is a transparent wrapper over a slice, with two run-time type tags for the beginning and the //end of the slice pub struct SliceFragment<'a, T: 'a, A, B>( pub &'a mut [T], PhantomData<A>, PhantomData<B> ); impl<'a, T: 'a + Sized, A, B> SliceFragment<'a, T, A, B> { //Creating an empty slice fragment, for demonstration purposes. //Note that the beginning and end markers are the same. pub fn empty(slice: &'a mut [T; 0]) -> SliceFragment<'a, T, A, A> { SliceFragment( slice, PhantomData, PhantomData ) } //Note that the type parameters A and B are user-provided; if they are the same, type safety //goes out the window. A better version would use existential types. pub fn new(slice: &'a mut [T]) -> SliceFragment<'a, T, A, B> { SliceFragment( slice, PhantomData, PhantomData ) } } //Merge is only allowed if the end marker of the first slice fragment coincides with the begin //marker of the second slice fragment pub fn merge<'a, 'b, 'c: 'a + 'b, T: 'a, A, B, C>( SliceFragment(slice1, begin1, _): SliceFragment<'a, T, A, B>, SliceFragment(slice2, _, end2) : SliceFragment<'b, T, B, C> ) -> SliceFragment<'c, T, A, C> { unsafe { let slice = std::slice::from_raw_parts_mut(slice1.as_mut_ptr(), slice1.len() + slice2.len()); SliceFragment(slice, begin1, end2) }
pub fn split<'a, T: 'a, A, B, C>( SliceFragment(slice, begin1, end2): SliceFragment<'a, T, A, C>, index: usize ) -> (SliceFragment<'a, T, A, B>, SliceFragment<'a, T, B, C>) { let end1: PhantomData<B> = PhantomData; let begin2: PhantomData<B> = PhantomData; let (slice1, slice2) = slice.split_at_mut(index); ( SliceFragment(slice1, begin1, end1), SliceFragment(slice2, begin2, end2) ) }
} //NOT TYPE SAFE if any of A, B or C are the same type
random_line_split
StudentHomeModel.js
/** * Created by Prem on 11/07/17. */ let mongoose = require('mongoose'); let Schema = mongoose.Schema; let messages = new Schema({ from: { type: String, required: false, minLength: 1, trim: true }, to: { type: String, required: false, minLength: 1, trim: true }, message: { type: String,
trim: true } }, {_id: false}); let courses = new Schema({ name: { type: String, required: true, minLength: 1, trim: true }, announcements: { type: [String] }, messages: { type: [messages] }, files: { type: [String] } }, {_id: false}); let StudentHome = mongoose.model('StudentHome', { FullName: { type: String, required: true, minLength: 1, trim: true }, Email: { type: String, required: true, minLength: 1, trim: true }, Sem: { type: String, required: true, minLength: 1, trim: true }, Courses: { type: [courses], required: true, minLength: 1, trim: true }, }); module.exports = {StudentHome};
required: true, minLength: 1,
random_line_split
filters.tsx
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true }, // { fieldName: 'party', dataType: 'string' }, // ]; // const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const assasinatedPresidents = [16, 20, 25, 35]; function pa
tr: string, targetLength: number, padString: string) { // tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed } return padString.slice(0, targetLength) + str; } } const data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
dStart(s
identifier_name
filters.tsx
import * as React from 'react'; import { AppliedFilter, DataTypes, GridFilters, numberWithCommas, ReactPowerTable, withInternalPaging, withInternalSorting } from '../../src/'; import { defaultColumns, partyList, sampledata } from './shared'; // //if coming in from DTO // const availDTO = [ // { fieldName: 'number', dataType: 'int' }, // { fieldName: 'president', dataType: 'string' }, // { fieldName: 'birth_year', dataType: 'int' }, // { fieldName: 'death_year', dataType: 'int', canBeNull: true }, // { fieldName: 'took_office', dataType: 'date' }, // { fieldName: 'left_office', dataType: 'date', canBeNull: true }, // { fieldName: 'party', dataType: 'string' }, // ]; // const availableFiltersMap = createKeyedMap(availDTO.map(m => new DataTypes[m.dataType](m)), m=>m.fieldName); //availableFilters.party = new DataTypes.list(availableFilters.party, partyList); const partyListOptions = partyList.map(m => ({ label: m.label, value: m.label })); //if building in JS const availableFilters = [ new DataTypes.int('number'), new DataTypes.string('president'), new DataTypes.int('birth_year'), new DataTypes.decimal({ fieldName: 'death_year', canBeNull: true }), new DataTypes.date({ fieldName: 'took_office' }), new DataTypes.date({ fieldName: 'left_office', canBeNull: true }), new DataTypes.list('party', partyListOptions), new DataTypes.boolean({ fieldName: 'assasinated', displayName: 'was assasinated' }), new DataTypes.timespan({ fieldName: 'timeBorn', displayName: 'time born' }), ]; //const columns = [...defaultColumns, { field: m => m.timeBorn, width: 80, formatter: formatTimeValue }]; const assasinatedPresidents = [16, 20, 25, 35]; function padStart(str: string, targetLength: number, padString: string) { // tslint:disable-next-line:no-bitwise targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (str.length >= targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) {
return padString.slice(0, targetLength) + str; } } const data = sampledata.map(m => ({ ...m, assasinated: assasinatedPresidents.indexOf(m.number) > -1, timeBorn: padStart(Math.floor((Math.random() * 24)).toString(), 2, '0') + ':00' })); //const availableFiltersMap = createKeyedMap(availableFilters, m => m.fieldName); //availableFiltersMap.number.operations.gt.displayName = 'greater than TEST'; availableFilters.find(m => m.fieldName === 'death_year').operations['null'].displayName = 'still alive'; interface FiltersExampleState { appliedFilters: Array<AppliedFilter<any>>; } const Table = withInternalSorting(withInternalPaging(ReactPowerTable)); export class FiltersExample extends React.Component<never, FiltersExampleState> { constructor(props: never) { super(props); this.state = { appliedFilters: [] }; this.handleFiltersChange = this.handleFiltersChange.bind(this); } handleFiltersChange(newFilters: Array<AppliedFilter<any>>) { console.log('onFiltersChange', newFilters); this.setState({ appliedFilters: newFilters }); } render() { let filteredData = data; this.state.appliedFilters.forEach(m => { filteredData = m.filter.applyFilter(filteredData, m.operation, m.value); }); return ( <div className="row"> <div className="col-md-3"> <div className="grid-filters"> <div className="small"> {numberWithCommas(filteredData.length) + ' Presidents'} &nbsp; </div> <div style={{ marginTop: 10 }} /> <GridFilters availableFilters={availableFilters} appliedFilters={this.state.appliedFilters} onFiltersChange={this.handleFiltersChange} /> </div> </div> <div className="col-md-9"> <Table columns={defaultColumns} keyColumn="number" rows={filteredData} sorting={{ column: 'number' }} /> </div> </div> ); } }
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed }
conditional_block