file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
plugin.js | /**
* Copyright (c) 2008- Samuli Jrvel
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html. If redistributing this code,... | title: that.env.texts().get("plugin_archiver_extractAction"),
callback: function(item) { that.onExtract(extractServiceUrl, false); }
}
]
}
}
}
this.onExtract = function(url, allowOverwrite) {
var wd = that.env.dialog().showWait(that.env.texts().get("pleaseWait"));
var params = { overwr... | var that = this;
this.getPluginInfo = function() { return { id: "plugin_archiver" }; }
this.initialize = function(env) {
that.env = env;
that.env.addItemContextProvider(that.getItemContext);
$.getScript(that.env.pluginUrl("Archiver") + "client/texts_" + that.env.texts().locale + ".js");
}
this.getItemC... | identifier_body |
plugin.js | /**
* Copyright (c) 2008- Samuli Jrvel
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html. If redistributing this code,... | {
var that = this;
this.getPluginInfo = function() { return { id: "plugin_archiver" }; }
this.initialize = function(env) {
that.env = env;
that.env.addItemContextProvider(that.getItemContext);
$.getScript(that.env.pluginUrl("Archiver") + "client/texts_" + that.env.texts().locale + ".js");
}
this.getIt... | chiverPlugin() | identifier_name |
plugin.js | /**
* Copyright (c) 2008- Samuli Jrvel
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html. If redistributing this code,... | if (code == 205) {
that.env.dialog().showConfirmation({
title: that.env.texts().get("plugin_archiver_extractFolderAlreadyExistsTitle"),
message: that.env.texts().get("plugin_archiver_extractFolderAlreadyExistsMessage"),
on_confirm: function() { that.onExtract(url, true); }
});
retur... | that.env.fileview().refresh();
},
function(code, error) {
wd.close(); | random_line_split |
setup.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Nahuel Riva
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrigh... |
vstring = '.'.join(components)
return StrictVersion.parse(self, vstring)
version.StrictVersion = NotSoStrictVersion
# Get the base directory
here = os.path.dirname(__file__)
if not here:
here = os.path.curdir
# Text describing the module (reStructured text)
try:
readme = os.path.j... | token = token.strip()
match = re.search('^[0-9]+', token)
if match:
number = token[ match.start() : match.end() ]
components.append(number) | conditional_block |
setup.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Nahuel Riva
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrigh... |
version.StrictVersion = NotSoStrictVersion
# Get the base directory
here = os.path.dirname(__file__)
if not here:
here = os.path.curdir
# Text describing the module (reStructured text)
try:
readme = os.path.join(here, 'README')
long_description = open(readme, 'r').read()
except Exception:
warn("R... | components = []
for token in vstring.split('.'):
token = token.strip()
match = re.search('^[0-9]+', token)
if match:
number = token[ match.start() : match.end() ]
components.append(number)
vstring = '.'.join(... | identifier_body |
setup.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Nahuel Riva
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrigh... | (self, vstring):
components = []
for token in vstring.split('.'):
token = token.strip()
match = re.search('^[0-9]+', token)
if match:
number = token[ match.start() : match.end() ]
components.append(number)
... | parse | identifier_name |
setup.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Nahuel Riva
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrigh... | # Text describing the module (reStructured text)
try:
readme = os.path.join(here, 'README')
long_description = open(readme, 'r').read()
except Exception:
warn("README file not found or unreadable!")
long_description = """pype32 is python library to read and write PE/PE+ binary files."""
# Get the list ... | here = os.path.curdir
| random_line_split |
mod.rs | // library of matrix and vector functions
// a 3 component vector
pub struct Vec3{
pub x: f32,
pub y: f32,
pub z: f32
}
// associated functions of Vec3
impl Vec3{
// used for constructing Vec3 nicely
pub fn new(x:f32,y:f32,z:f32) -> Vec3 {
Vec3{x: x, y: y, z: z}
}
}
// a 3x3 matrix
pub... | (mat1: &Mat3,mat2: &Mat3) -> Mat3{
let mut result = Mat3::new_empty();
// go by row
for i in 0..3{
// go by column
for j in 0..3{
let mut sum :f32 = 0.0;
// get the result of the row,column pair (i,j)
for k in 0..3{
sum = sum + (mat1.valu... | MatXMat3 | identifier_name |
mod.rs | // library of matrix and vector functions
// a 3 component vector
pub struct Vec3{
pub x: f32,
pub y: f32,
pub z: f32
}
// associated functions of Vec3 | }
}
// a 3x3 matrix
pub struct Mat3{
pub values: [[f32;3];3]
}
impl Mat3{
// used for constructing an empty matrix
pub fn new_empty() -> Mat3{
Mat3{values:
[[0.0,0.0,0.0],
[0.0,0.0,0.0],
[0.0,0.0,0.0]]
}
}
}
pub fn dot(vec1:&Vec3,vec2:&Vec3) -> ... | impl Vec3{
// used for constructing Vec3 nicely
pub fn new(x:f32,y:f32,z:f32) -> Vec3 {
Vec3{x: x, y: y, z: z} | random_line_split |
form-row.presets.ts | import { ViewStyle } from "react-native"
import { color, spacing } from "../../theme"
/**
* The size of the border radius.
*/
const RADIUS = 8
/**
* The default style of the container.
*/
const ROOT: ViewStyle = {
borderWidth: 1,
borderColor: color.line,
padding: spacing[2],
}
/**
* What each of the prese... | bottom: {
...ROOT,
borderBottomLeftRadius: RADIUS,
borderBottomRightRadius: RADIUS,
},
/**
* Rounded borders everywhere.
*/
soloRound: {
...ROOT,
borderRadius: RADIUS,
},
/**
* Straight borders everywhere.
*/
soloStraight: {
...ROOT,
},
/**
* Transparent borders ... | */ | random_line_split |
cleanhtml.py | import sys
import re
def cleancss(text):
text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text
... | (text):
text=text.lower()
r=re.compile('\<script.+?/script\>', re.DOTALL)
scripts=r.findall(text)
text=r.sub('<script />', text)
r=re.compile('\<style.+?/style\>', re.DOTALL)
styles=r.findall(text)
text=r.sub('<style />', text)
text=re.compile(
'<(?P<tag>(input|meta|link|hr|br|im... | cleanhtml | identifier_name |
cleanhtml.py | import sys
import re
def cleancss(text):
text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text
... | print cleancss(read_file(file))
if file[-5:]=='.html':
print cleanhtml(read_file(file)) |
file=sys.argv[1]
if file[-4:]=='.css': | random_line_split |
cleanhtml.py | import sys
import re
def cleancss(text):
|
def cleanhtml(text):
text=text.lower()
r=re.compile('\<script.+?/script\>', re.DOTALL)
scripts=r.findall(text)
text=r.sub('<script />', text)
r=re.compile('\<style.+?/style\>', re.DOTALL)
styles=r.findall(text)
text=r.sub('<style />', text)
text=re.compile(
'<(?P<tag>(input|met... | text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text | identifier_body |
cleanhtml.py | import sys
import re
def cleancss(text):
text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text
... |
text='\n'.join(newlines)
text=re.compile('\<div(?P<a>( .+)?)\>\s+\</div\>').sub('<div\g<a>></div>',text)
text=re.compile('\<a(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</a\>').sub('<a\g<a>>\g<b></a>',text)
text=re.compile('\<b(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</b\>').sub('<b\g<a>>\g<b></b>',te... | indent=indent+1 | conditional_block |
remove.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fileService_1 = require("../services/fileService");
const logService_1 = require("../services/logService");
const directoryService_1 = require("../services/directoryService");
class Remove {
constructor() {
this._fileService ... |
else {
this.processFileRemoval('.', fileName);
}
}
removeFileFromSpecifiedDirectory(dir, fileName) {
let directoryName = this._directoryService.findDirectoryByName(dir);
if (directoryName) {
let pathToDirectory = this._directoryService.findDirectory(direc... | {
this._logService.warning('Sorry, this is not a directory you can remove styles from or you may be missing parameters.');
} | conditional_block |
remove.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fileService_1 = require("../services/fileService");
const logService_1 = require("../services/logService");
const directoryService_1 = require("../services/directoryService");
class Remove {
constructor() {
this._fileService ... | (fileName) {
if (!this._fileService.getManifestFile('./')) {
this._logService.warning('Sorry, this is not a directory you can remove styles from or you may be missing parameters.');
}
else {
this.processFileRemoval('.', fileName);
}
}
removeFileFromSpecifi... | removeFileFromCurrentDirectory | identifier_name |
remove.js | class Remove {
constructor() {
this._fileService = new fileService_1.FileService();
this._logService = new logService_1.LogService();
this._directoryService = new directoryService_1.DirectoryService();
}
removeFileFromCurrentDirectory(fileName) {
if (!this._fileService.getMan... | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fileService_1 = require("../services/fileService");
const logService_1 = require("../services/logService");
const directoryService_1 = require("../services/directoryService"); | random_line_split | |
shared.module.ts | /**
* @shared.module.ts
* @description 独立出一个模块,比如,用户登录,用户信息,用户信息设置
* @author 阿虫
* @email ar.insect@gmail.com
* @date 2017-03-13
* @version v1.0
*/
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angu... | identifier_name | ||
shared.module.ts | /**
* @shared.module.ts
* @description 独立出一个模块,比如,用户登录,用户信息,用户信息设置
* @author 阿虫
* @email ar.insect@gmail.com
* @date 2017-03-13
* @version v1.0
*/
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angu... | } | UserLoginComponent,
]
})
export class SharedModule {
| random_line_split |
quickcheck_types.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! QuickCheck support for wire packs.
use quickcheck::{empty_shrinker, Arbitrary, Gen};
use mercurial_types::{Delta, HgNodeHash, MPath, ... | else { None };
// 50% chance of size being present
let size = if bool::arbitrary(g) { Some(2) } else { None };
Some(Metadata { flags, size })
} else {
None
};
Self {
node: HgNodeHash::arbitrary(g),
delta_base,
... | { Some(1) } | conditional_block |
quickcheck_types.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! QuickCheck support for wire packs.
use quickcheck::{empty_shrinker, Arbitrary, Gen};
use mercurial_types::{Delta, HgNodeHash, MPath, ... |
// Not going to get anything out of shrinking this since MPath is not shrinkable.
}
impl Arbitrary for DataEntry {
fn arbitrary(g: &mut Gen) -> Self {
// 20% chance of a fulltext revision
let (delta_base, delta) = if *g.choose(&[0, 1, 2, 3, 4]).unwrap() == 0 {
(NULL_HASH, Delta::ne... | // HistoryEntry depends on the kind of the overall wirepack, so this can't be implemented.
unimplemented!("use WirePackPartSequence::arbitrary instead")
} | random_line_split |
quickcheck_types.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! QuickCheck support for wire packs.
use quickcheck::{empty_shrinker, Arbitrary, Gen};
use mercurial_types::{Delta, HgNodeHash, MPath, ... | (g: &mut Gen) -> Self {
let size = g.size();
let kind = if bool::arbitrary(g) {
Kind::Tree
} else {
Kind::File
};
let file_count = usize::arbitrary(g) % size;
let files = (0..file_count)
.map(|_| FileEntries::arbitrary_params(g, kind)... | arbitrary | identifier_name |
quickcheck_types.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! QuickCheck support for wire packs.
use quickcheck::{empty_shrinker, Arbitrary, Gen};
use mercurial_types::{Delta, HgNodeHash, MPath, ... |
// Not going to get anything out of shrinking this since MPath is not shrinkable.
}
impl Arbitrary for DataEntry {
fn arbitrary(g: &mut Gen) -> Self {
// 20% chance of a fulltext revision
let (delta_base, delta) = if *g.choose(&[0, 1, 2, 3, 4]).unwrap() == 0 {
(NULL_HASH, Delta::n... | {
// HistoryEntry depends on the kind of the overall wirepack, so this can't be implemented.
unimplemented!("use WirePackPartSequence::arbitrary instead")
} | identifier_body |
ListExampleFolder.js | import React from 'react';
import MobileTearSheet from './MobileTearSheet';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import ActionInfo from 'material-ui/lib/svg-icons/action/info';
import Divider from 'material-ui/lib/divider';
import Avatar from 'material-u... | rightIcon={<ActionInfo />}
primaryText="Vacation itinerary"
secondaryText="Jan 20, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={Colors.yellow600} />}
rightIcon={<ActionInfo />}
primaryText="Kitchen remodel"
secon... | <List subheader="Files" insetSubheader={true}>
<ListItem
leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={Colors.blue500} />} | random_line_split |
i64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl CheckedSub for i64 {
#[inline]
fn checked_sub(&self, v: &i64) -> Option<i64> {
unsafe {
let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
// FIXME: #8449: should not be disabled on 32-bit
#[cfg(target_word_size = "6... | }
} | random_line_split |
i64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, v: &i64) -> Option<i64> {
unsafe {
let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
// FIXME: #8449: should not be disabled on 32-bit
#[cfg(target_word_size = "64")]
impl CheckedMul for i64 {
#[inline]
fn checked... | checked_sub | identifier_name |
i64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| {
unsafe {
let (x, y) = intrinsics::i64_mul_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
} | identifier_body |
i64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else { Some(x) }
}
}
}
impl CheckedSub for i64 {
#[inline]
fn checked_sub(&self, v: &i64) -> Option<i64> {
unsafe {
let (x, y) = intrinsics::i64_sub_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
// FIXME: #8449: should not be disabled o... | { None } | conditional_block |
test_main.rs |
#![feature(test)]
#![feature(conservative_impl_trait)]
#![feature(specialization)]
#[macro_use]
extern crate ndarray;
extern crate test;
extern crate rand;
extern crate ndarray_rand;
extern crate num;
extern crate chrono;
extern crate error_chain;
extern crate itertools;
extern crate rustc_serialize;
extern crate csv... | () {
let mut btree: BTreeMap<String, Row<f64>> = BTreeMap::new();
btree.insert("a".to_string(), arr1(&[2., 3., 2.]));
if let Err(ref e) = run() {
use ::std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {... | main | identifier_name |
test_main.rs |
#![feature(test)]
#![feature(conservative_impl_trait)]
#![feature(specialization)]
#[macro_use]
extern crate ndarray;
extern crate test;
extern crate rand;
extern crate ndarray_rand;
extern crate num;
extern crate chrono;
extern crate error_chain;
extern crate itertools;
extern crate rustc_serialize;
extern crate csv... |
}
fn run() -> Result<()> {
let df: Result<DataFrame<InnerType, OuterType>> = DataFrame::read_csv("/Users/suchin/Github/rust-dataframe/src/tests/test.\
csv");
let a = arr2(&[[2., 7.], [3., NAN], [2., 4.]]);
// let b = arr2(&[[2., 6... | {
use ::std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
writeln!(stderr, "caused by: {}", e).expect(errmsg);
}
// The backtra... | conditional_block |
test_main.rs |
#![feature(test)]
#![feature(conservative_impl_trait)]
#![feature(specialization)]
#[macro_use]
extern crate ndarray;
extern crate test;
extern crate rand;
extern crate ndarray_rand;
extern crate num;
extern crate chrono;
extern crate error_chain;
extern crate itertools;
extern crate rustc_serialize;
extern crate csv... | .as_df()?;
let res_1: DataFrame<f64, String> = df.inner_left_join(&df_1).as_df()?;
let concat = df.concat(&df_1, UtahAxis::Row).as_df();
// let b = arr1(&[2., 3., 2.]);
let k: DataFrame<f64, String> = dataframe!(
{
"a" => col!([2., 3., 2.]),
"b" => col!([2., NAN, 2.])
... | {
let df: Result<DataFrame<InnerType, OuterType>> = DataFrame::read_csv("/Users/suchin/Github/rust-dataframe/src/tests/test.\
csv");
let a = arr2(&[[2., 7.], [3., NAN], [2., 4.]]);
// let b = arr2(&[[2., 6.], [3., 4.]]);
let c =... | identifier_body |
test_main.rs | #![feature(test)]
#![feature(conservative_impl_trait)]
#![feature(specialization)]
#[macro_use]
extern crate ndarray;
extern crate test;
extern crate rand;
extern crate ndarray_rand;
extern crate num;
extern crate chrono;
extern crate error_chain;
extern crate itertools;
extern crate rustc_serialize;
extern crate csv;... | let mut df: DataFrame<f64, String> = DataFrame::new(a).columns(&["a", "b"])?
.index(&["1", "2", "3"])?;
let df_1 = DataFrame::new(c).columns(&["c", "d"])?.index(&["1", "2", "3"])?;
let new_data = df.select(&["2"], UtahAxis::Row).as_array()?;
// let df_iter: DataFrameIterator = df_1.df_iter(Utah... | let a = arr2(&[[2., 7.], [3., NAN], [2., 4.]]);
// let b = arr2(&[[2., 6.], [3., 4.]]);
let c = arr2(&[[2., 6.], [3., 4.], [2., 1.]]); | random_line_split |
MultipleFileInputDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
MultipleExternalInputDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'informatio... |
else:
self.lstLayers.setUpdatesEnabled(False)
indexes = sorted(self.lstLayers.selectionModel().selectedIndexes())
for i in reversed(indexes):
self.lstLayers.model().removeRow(i.row())
self.lstLayers.setUpdatesEnabled(True)
| self.lstLayers.model().clear() | conditional_block |
MultipleFileInputDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
MultipleExternalInputDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'informatio... |
self.btnAdd.clicked.connect(self.addFile)
self.btnRemove.clicked.connect(lambda: self.removeRows())
self.btnRemoveAll.clicked.connect(lambda: self.removeRows(True))
self.settings = QgsSettings()
self.restoreGeometry(self.settings.value("/Processing/multipleFileInputDialogGeomet... | random_line_split | |
MultipleFileInputDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
MultipleExternalInputDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'informatio... | (self):
QDialog.reject(self)
def addFile(self):
settings = QgsSettings()
if settings.contains('/Processing/LastInputPath'):
path = settings.value('/Processing/LastInputPath')
else:
path = ''
files, selected_filter = QFileDialog.getOpenFileNames(self,... | reject | identifier_name |
MultipleFileInputDialog.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
MultipleExternalInputDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'informatio... | if removeAll:
self.lstLayers.model().clear()
else:
self.lstLayers.setUpdatesEnabled(False)
indexes = sorted(self.lstLayers.selectionModel().selectedIndexes())
for i in reversed(indexes):
self.lstLayers.model().removeRow(i.row())
self.ls... | identifier_body | |
logname.rs | extern crate libc;
extern crate getopts;
extern crate coreutils;
use libc::funcs::posix88::unistd::getlogin;
use std::c_str::CString;
use std::os;
fn | () {
let args = os::args();
let program = args[0].clone();
let opts = &[
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m)... | main | identifier_name |
logname.rs | extern crate libc;
extern crate getopts;
extern crate coreutils;
use libc::funcs::posix88::unistd::getlogin;
use std::c_str::CString;
use std::os;
fn main() | if matches.opt_present("help") {
println!("Usage: {}", getopts::usage(program.as_slice(), opts));
return;
}
if matches.opt_present("version") {
println!("{}: {}", program, coreutils::version());
return;
}
let login = unsafe {
CString::new(
getlog... | {
let args = os::args();
let program = args[0].clone();
let opts = &[
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), opts) {
Ok(m) =>... | identifier_body |
logname.rs | extern crate libc;
extern crate getopts;
extern crate coreutils;
use libc::funcs::posix88::unistd::getlogin;
use std::c_str::CString;
use std::os;
fn main() {
let args = os::args();
let program = args[0].clone();
let opts = &[
getopts::optflag("h", "help", "display this help and exit"),
... | return;
}
if matches.opt_present("version") {
println!("{}: {}", program, coreutils::version());
return;
}
let login = unsafe {
CString::new(
getlogin() as *const libc::c_char,
false
)
};
match login.as_str() {
Some(usern... | };
if matches.opt_present("help") {
println!("Usage: {}", getopts::usage(program.as_slice(), opts)); | random_line_split |
args.rs | use clap::{arg_enum, Clap};
arg_enum! {
#[derive(Debug)]
pub enum RenderDevice {
Cpu,
Gpu
}
}
impl RenderDevice {
pub fn to_str(&self) -> &str |
}
#[clap(version = env!("CARGO_PKG_VERSION"))]
#[derive(Clap, Debug)]
pub struct Args {
/// Which address to listen on.
#[clap(default_value = "0.0.0.0", long = "address", short = "a")]
pub address: String,
/// By default elmyra uses a bundled version of blender (strongly recommended), you can overr... | {
match self {
Self::Cpu => "CPU",
Self::Gpu => "GPU"
}
} | identifier_body |
args.rs | use clap::{arg_enum, Clap};
arg_enum! {
#[derive(Debug)]
pub enum RenderDevice {
Cpu,
Gpu
}
}
impl RenderDevice {
pub fn to_str(&self) -> &str {
match self {
Self::Cpu => "CPU",
Self::Gpu => "GPU"
}
}
}
#[clap(version = env!("CARGO_PKG_VERSI... | {
/// Which address to listen on.
#[clap(default_value = "0.0.0.0", long = "address", short = "a")]
pub address: String,
/// By default elmyra uses a bundled version of blender (strongly recommended), you can override it with this if you know what you're doing or if would like to play and learn.
... | Args | identifier_name |
args.rs | use clap::{arg_enum, Clap};
arg_enum! {
#[derive(Debug)]
pub enum RenderDevice {
Cpu,
Gpu
}
}
impl RenderDevice {
pub fn to_str(&self) -> &str {
match self {
Self::Cpu => "CPU",
Self::Gpu => "GPU"
}
}
}
#[clap(version = env!("CARGO_PKG_VERSI... | } | random_line_split | |
testNWK.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: TFG
# Author: David Candal
# Description: SDR ZigBee
# Generated: Mon Sep 19 21:01:18 2016
##################################################
if __name__ == '__main__':
import ct... | self.settings = Qt.QSettings("GNU Radio", "testNWK")
self.restoreGeometry(self.settings.value("geometry").toByteArray())
##################################################
# Blocks
##################################################
self.tfg_test_nwk_0 = tfg.test_nwk()
... | def __init__(self):
gr.top_block.__init__(self, "TFG")
Qt.QWidget.__init__(self)
self.setWindowTitle("TFG")
try:
self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
except:
pass
self.top_scroll_layout = Qt.QVBoxLayout()
self.setLayout(se... | identifier_body |
testNWK.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: TFG
# Author: David Candal
# Description: SDR ZigBee
# Generated: Mon Sep 19 21:01:18 2016
##################################################
if __name__ == '__main__':
import ct... | self.settings.setValue("geometry", self.saveGeometry())
event.accept()
def main(top_block_cls=testNWK, options=None):
if gr.enable_realtime_scheduling() != gr.RT_OK:
print "Error: failed to enable real-time scheduling."
from distutils.version import StrictVersion
if StrictVersion(... | random_line_split | |
testNWK.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: TFG
# Author: David Candal
# Description: SDR ZigBee
# Generated: Mon Sep 19 21:01:18 2016
##################################################
if __name__ == '__main__':
import ct... |
qapp = Qt.QApplication(sys.argv)
tb = top_block_cls()
tb.start()
tb.show()
def quitting():
tb.stop()
tb.wait()
qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
qapp.exec_()
if __name__ == '__main__':
main()
| style = gr.prefs().get_string('qtgui', 'style', 'raster')
Qt.QApplication.setGraphicsSystem(style) | conditional_block |
testNWK.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: TFG
# Author: David Candal
# Description: SDR ZigBee
# Generated: Mon Sep 19 21:01:18 2016
##################################################
if __name__ == '__main__':
import ct... | (self):
gr.top_block.__init__(self, "TFG")
Qt.QWidget.__init__(self)
self.setWindowTitle("TFG")
try:
self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
except:
pass
self.top_scroll_layout = Qt.QVBoxLayout()
self.setLayout(self.top_scrol... | __init__ | identifier_name |
grovepi.py |
else:
bus = smbus.SMBus(0)
# I2C Address of Arduino
address = 0x04
# Command Format
# digitalRead() command format header
dRead_cmd = [1]
# digitalWrite() command format header
dWrite_cmd = [2]
# analogRead() command format header
aRead_cmd = [3]
# analogWrite() command format header
aWrite_cmd = [4]... | bus = smbus.SMBus(1) | conditional_block | |
grovepi.py | (number[1], number[2], number[3])
# Read Grove Accelerometer (+/- 1.5g) XYZ value
def acc_xyz():
write_i2c_block(address, acc_xyz_cmd + [unused, unused, unused])
time.sleep(.1)
read_i2c_byte(address)
number = read_i2c_block(address)
if number[1] > 32:
number[1] = - (number[1] - 224)
if number[2] >... | write_i2c_block(address, chainableRgbLedInit_cmd + [pin, numLeds, unused])
time.sleep(.05)
return 1
| random_line_split | |
grovepi.py | # Store color for later use
storeColor_cmd = [90]
# Initialise
chainableRgbLedInit_cmd = [91]
# Initialise and test with a simple color
chainableRgbLedTest_cmd = [92]
# Set one or more leds to the stored color by pattern
chainableRgbLedSetPattern_cmd = [93]
# set one or more leds to the stored color by modulo
... |
# Grove LED Bar - set level
# level: (0-10)
def ledBar_setLevel(pin, level):
write_i2c_block(address, ledBarLevel_cmd + [pin, level, unused])
return 1
# Grove LED Bar - set single led
# led: which led (1-10)
# state: off or on (0-1)
def ledBar_setLed(pin, led, state):
write_i2c_block(address, ledBarSe... | write_i2c_block(address, ledBarOrient_cmd + [pin, orientation, unused])
return 1 | identifier_body |
grovepi.py | # Store color for later use
storeColor_cmd = [90]
# Initialise
chainableRgbLedInit_cmd = [91]
# Initialise and test with a simple color
chainableRgbLedTest_cmd = [92]
# Set one or more leds to the stored color by pattern
chainableRgbLedSetPattern_cmd = [93]
# set one or more leds to the stored color by modulo
... | ():
write_i2c_block(address, rtc_getTime_cmd + [unused, unused, unused])
time.sleep(.1)
read_i2c_byte(address)
number = read_i2c_block(address)
return number
# Read and return temperature and humidity from Grove DHT Pro
def dht(pin, module_type):
write_i2c_block(address, dht_temp_cmd + [pin, module_ty... | rtc_getTime | identifier_name |
config.ts | import { workspace } from "vscode";
import { ExternalModuleName } from "../types";
export class ExtensionConfiguration {
| //#endregion vscode configurations
hasJsModule = false;
hasLuaModule = false;
reload = () => {
const config = workspace.getConfiguration('nginx-conf-hint');
this.enableStrictCompletion = config.get('enableStrictCompletion', true);
this.enableFormatAlign = !!config.get('format', { align: false }).align;
t... | //#region vscode configurations
enableStrictCompletion = true;
enableFormatAlign = false;
externalModules: ExternalModuleName[] = [];
tabSize = 4; | random_line_split |
config.ts | import { workspace } from "vscode";
import { ExternalModuleName } from "../types";
export class | {
//#region vscode configurations
enableStrictCompletion = true;
enableFormatAlign = false;
externalModules: ExternalModuleName[] = [];
tabSize = 4;
//#endregion vscode configurations
hasJsModule = false;
hasLuaModule = false;
reload = () => {
const config = workspace.getConfiguration('nginx-conf-hint');... | ExtensionConfiguration | identifier_name |
bootstrap-dropdown.js | /* ============================================================
* bootstrap-dropdown.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "Lice... | () {
$(toggle).each(function () {
getParent($(this)).removeClass('open')
})
}
function getParent($this) {
var selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[... | clearMenus | identifier_name |
bootstrap-dropdown.js | /* ============================================================
* bootstrap-dropdown.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "Lice... |
/* DROPDOWN PLUGIN DEFINITION
* ========================== */
var old = $.fn.dropdown
$.fn.dropdown = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (type... | {
var selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
return... | identifier_body |
bootstrap-dropdown.js | /* ============================================================
* bootstrap-dropdown.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
* ============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "Lice... | .focus()
}
}
function clearMenus() {
$(toggle).each(function () {
getParent($(this)).removeClass('open')
})
}
function getParent($this) {
var selector = $this.attr('data-target')
, $parent
if (!selector) {
selector = $this.attr('href')
selector = selector ... | if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items
.eq(index) | random_line_split |
Analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mmap
import re
import collections
import math
import detectlanguage
import codecs
detectlanguage.configuration.api_key = "d6ed8c76914a9809b58c2e11904fbaa3"
class Analyzer:
def __init__(self, passwd):
self.evaluation = {}
self._passwd = passwd
... | def replaceNumber(self,testPass):
"""
Replace numbers in the password for letters. (leet/1337)
"""
newPassword = testPass.lower().replace("1","l")
newPassword = newPassword.lower().replace("0","o")
newPassword = newPassword.lower().replace("3","e")
new... | self.isWord(_password) and not foundWord:
self.evaluation['Common word as password'] = True
foundWord = True
self.checkForCommonPasswd(_password)
| conditional_block |
Analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mmap
import re
import collections
import math
import detectlanguage
import codecs
detectlanguage.configuration.api_key = "d6ed8c76914a9809b58c2e11904fbaa3"
class Analyzer:
def __init__(self, passwd):
self.evaluation = {}
self._passwd = passwd
... | lf):
"""
Prints Evalution scores
"""
for key in self.evaluation.keys():
print (key)
| ntEvaluationAndEntropy(se | identifier_name |
Analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mmap
import re
import collections
import math
import detectlanguage
import codecs
detectlanguage.configuration.api_key = "d6ed8c76914a9809b58c2e11904fbaa3"
class Analyzer:
def __init__(self, passwd):
self.evaluation = {}
self._passwd = passwd
... | lastChar = self._passwd[0].lower()
alphabeticalDiff = []
keyboardDiff = []
for value in self._passwd.lower():
alphabeticalDiff.append(abs(ord(lastChar) - ord(value)))
keyboardDiff.append(self.distanceInKeyboard(value, lastChar))
lastChar = value
... | if value > 10:
self.evaluation['Repeated character'] = True
#Check if the password is a alphabetical or keyboard sequence | random_line_split |
Analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mmap
import re
import collections
import math
import detectlanguage
import codecs
detectlanguage.configuration.api_key = "d6ed8c76914a9809b58c2e11904fbaa3"
class Analyzer:
def __init__(self, passwd):
self.evaluation = {}
self._passwd = passwd
... | def replaceSymbol(self,testPass):
"""
Replace symbols in the password for letters. (leet/1337)
"""
newPassword = testPass.lower().replace("@","a")
newPassword = newPassword.lower().replace("$","s")
newPassword = newPassword.lower().replace("&","e")
newPassword ... |
Replace numbers in the password for letters. (leet/1337)
"""
newPassword = testPass.lower().replace("1","l")
newPassword = newPassword.lower().replace("0","o")
newPassword = newPassword.lower().replace("3","e")
newPassword = newPassword.lower().replace("5","s")
... | identifier_body |
strings.js | define({
"drsUrl": "Adatellenőrző szerver URL-címe",
"includeReportedBy": "Ellenőrzést végző szakértő",
"label": "Réteg",
"show": "Foglald bele",
"alias": "Aliasnév",
"warning": "Helytelen adatbevitel",
"defaultSessionId": "Alapértelmezett munkamenet",
"setSource": "Beállítás",
"getCurrentUser": "Beje... | }); | random_line_split | |
issue-14308.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 ... | A(..) => 1i
};
assert_eq!(x, 1);
let x = match A(4) {
A(1) => 1i,
A(..) => 2i
};
assert_eq!(x, 2);
// This next test uses a (..) wildcard match on a nullary struct.
// There's no particularly good reason to support this, but it's currently allowed,
// and this ma... | struct A(int);
struct B;
fn main() {
let x = match A(3) { | random_line_split |
issue-14308.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = match A(3) {
A(..) => 1i
};
assert_eq!(x, 1);
let x = match A(4) {
A(1) => 1i,
A(..) => 2i
};
assert_eq!(x, 2);
// This next test uses a (..) wildcard match on a nullary struct.
// There's no particularly good reason to support this, but it's currently ... | identifier_body | |
issue-14308.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
fn main() {
let x = match A(3) {
A(..) => 1i
};
assert_eq!(x, 1);
let x = match A(4) {
A(1) => 1i,
A(..) => 2i
};
assert_eq!(x, 2);
// This next test uses a (..) wildcard match on a nullary struct.
// There's no particularly good reason to support this, but it... | B | identifier_name |
sync.js | (pattern, options) {
if (!pattern)
throw new Error('must provide pattern')
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
if (!(this instanceof GlobSync))... | GlobSync | identifier_name | |
sync.js |
function GlobSync (pattern, options) {
if (!pattern)
throw new Error('must provide pattern')
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
if (!(this in... | {
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
return new GlobSync(pattern, options).found
} | identifier_body | |
sync.js | , false)
}
this._finish()
}
GlobSync.prototype._finish = function () {
assert(this instanceof GlobSync)
if (this.realpath) {
var self = this
this.matches.forEach(function (matchset, index) {
var set = self.matches[index] = Object.create(null)
for (var p in matchset) {
try {
... | case pattern.length:
this._processSimple(pattern.join('/'), index)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the f... |
// See if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple | random_line_split |
server.ts | // Copyright 2018 The Outline Authors
//
// 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 agre... | {
// Value in US dollars.
usd: number;
}
// Configuration for manual servers. This is the output emitted from the
// shadowbox install script, which is needed for the manager connect to
// shadowbox.
export interface ManualServerConfig {
apiUrl: string;
certSha256: string;
}
// Repository of ManualServer ob... | MonetaryCost | identifier_name |
server.ts | // Copyright 2018 The Outline Authors
//
// 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 agre... | getCertificateFingerprint(): string;
forget(): void;
}
// Managed servers are servers created by the Outline Manager through our
// "magic" user experience, e.g. DigitalOcean.
export interface ManagedServer extends Server {
// Yields how far installation has progressed (0.0 to 1.0).
// Exits when installation... | // Manual servers are servers which the user has independently setup to run
// shadowbox, and can be on any cloud provider.
export interface ManualServer extends Server { | random_line_split |
any.js | var assert = require('assert');
var listXf = require('./helpers/listXf');
var R = require('..');
describe('any', function() {
var odd = function(n) {return n % 2 === 1;};
var T = function() {return true;};
var intoArray = R.into([]);
it('returns true if any element satisfies the predicate', function... | }); | }); | random_line_split |
get-snapshot.ts | import getDatabase from '../database';
import { getSchema } from './get-schema';
import { CollectionsService, FieldsService, RelationsService } from '../services';
import { version } from '../../package.json';
import { Snapshot, SnapshotField, SnapshotRelation } from '../types';
import { Knex } from 'knex';
import { om... |
function omitID(item: Record<string, any>) {
return omit(item, 'meta.id');
}
| {
if (item?.meta?.system === true) return false;
return true;
} | identifier_body |
get-snapshot.ts | import getDatabase from '../database';
import { getSchema } from './get-schema';
import { CollectionsService, FieldsService, RelationsService } from '../services';
import { version } from '../../package.json';
import { Snapshot, SnapshotField, SnapshotRelation } from '../types';
import { Knex } from 'knex';
import { om... | (item: Record<string, any>) {
return omit(item, 'meta.id');
}
| omitID | identifier_name |
get-snapshot.ts | import getDatabase from '../database';
import { getSchema } from './get-schema';
import { CollectionsService, FieldsService, RelationsService } from '../services';
import { version } from '../../package.json';
import { Snapshot, SnapshotField, SnapshotRelation } from '../types';
import { Knex } from 'knex';
import { om... | return omit(item, 'meta.id');
} | random_line_split | |
helper.filters.js | 'use strict';
var utils = require('../integration-utils.js');
var setup = utils.setup;
var algoliasearchHelper = require('../../');
var random = require('lodash/random');
test('[INT][FILTERS] Should retrieve different values for multi facetted records', function(done) {
var indexName = '_circle-algoliasearch-hel... |
if (calls === 2) {
expect(results.hits.length).toBe(1);
expect(results.facets[0].data).toEqual({
f1: 1,
f2: 1
});
helper.toggleRefine('facet', 'f3').search();
}
if (calls === 3) {
expect(results.hits.length).toBe(0);
expect(result... | {
expect(results.hits.length).toBe(2);
expect(results.facets[0].data).toEqual({
f1: 2,
f2: 1,
f3: 1
});
helper.addRefine('facet', 'f2').search();
} | conditional_block |
helper.filters.js | 'use strict';
var utils = require('../integration-utils.js');
var setup = utils.setup;
var algoliasearchHelper = require('../../');
var random = require('lodash/random');
test('[INT][FILTERS] Should retrieve different values for multi facetted records', function(done) {
var indexName = '_circle-algoliasearch-hel... | client.destroy();
}
done();
}
});
helper.addRefine('facet', 'f1').search();
});
}); | if (!process.browser) { | random_line_split |
event_content.rs | //! Implementations of the MessageEventContent and StateEventContent derive macro.
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
DeriveInput, LitStr, Token,
};
/// Parses attributes for `*EventContent` derives.
///
/// `#[ruma_event(type = "m.room.alias")]`
en... | (input: ParseStream) -> syn::Result<Self> {
input.parse::<Token![type]>()?;
input.parse::<Token![=]>()?;
Ok(EventMeta::Type(input.parse::<LitStr>()?))
}
}
/// Create an `EventContent` implementation for a struct.
pub fn expand_event_content(input: DeriveInput) -> syn::Result<TokenStream> {
... | parse | identifier_name |
event_content.rs | //! Implementations of the MessageEventContent and StateEventContent derive macro.
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
DeriveInput, LitStr, Token,
};
/// Parses attributes for `*EventContent` derives.
///
/// `#[ruma_event(type = "m.room.alias")]`
en... |
let event_type = {
let event_meta = event_type_attr.parse_args::<EventMeta>()?;
let EventMeta::Type(lit) = event_meta;
lit
};
Ok(quote! {
impl ::ruma_events::EventContent for #ident {
fn event_type(&self) -> &str {
#event_type
}
... | syn::Error::new(Span::call_site(), msg)
})?; | random_line_split |
event_content.rs | //! Implementations of the MessageEventContent and StateEventContent derive macro.
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{
parse::{Parse, ParseStream},
DeriveInput, LitStr, Token,
};
/// Parses attributes for `*EventContent` derives.
///
/// `#[ruma_event(type = "m.room.alias")]`
en... | {
let ident = input.ident.clone();
let room_ev_content = expand_room_event_content(input)?;
Ok(quote! {
#room_ev_content
impl ::ruma_events::StateEventContent for #ident { }
})
} | identifier_body | |
server.rs | use mio::{Handler, Token, EventLoop, EventSet, PollOpt};
use mio::tcp::TcpListener;
use mio::util::Slab;
use std::net::SocketAddr;
use connection::Connection;
use error::Result;
const SERVER: Token = Token(0);
struct Server {
listener: TcpListener,
connections: Slab<Connection>,
}
impl Server {
fn new(li... | }
}
}
}
impl Handler for Server {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<Server>, token: Token, events: EventSet) {
match token {
SERVER => self.accept_new(event_loop),
_ => {
if events.is... | }
Ok(None) => {}
Err(e) => {
// TODO handle
event_loop.shutdown(); | random_line_split |
server.rs | use mio::{Handler, Token, EventLoop, EventSet, PollOpt};
use mio::tcp::TcpListener;
use mio::util::Slab;
use std::net::SocketAddr;
use connection::Connection;
use error::Result;
const SERVER: Token = Token(0);
struct Server {
listener: TcpListener,
connections: Slab<Connection>,
}
impl Server {
fn new(li... |
}
impl Handler for Server {
type Timeout = ();
type Message = ();
fn ready(&mut self, event_loop: &mut EventLoop<Server>, token: Token, events: EventSet) {
match token {
SERVER => self.accept_new(event_loop),
_ => {
if events.is_readable() {
... | {
match self.listener.accept() {
Ok(Some((socket, addr))) => {
info!("New Connection from {}", addr);
let token = self.connections
.insert_with(|token| Connection::new(socket, token))
.unwrap();
event_loop.regist... | identifier_body |
server.rs | use mio::{Handler, Token, EventLoop, EventSet, PollOpt};
use mio::tcp::TcpListener;
use mio::util::Slab;
use std::net::SocketAddr;
use connection::Connection;
use error::Result;
const SERVER: Token = Token(0);
struct Server {
listener: TcpListener,
connections: Slab<Connection>,
}
impl Server {
fn new(li... |
if events.is_hup() {}
if events.is_error() {}
if self.connections[token].is_closed() {
event_loop.deregister(&self.connections[token].socket);
let _ = self.connections.remove(token);
}
}
}
}
... | {
self.connections[token].write()
} | conditional_block |
server.rs | use mio::{Handler, Token, EventLoop, EventSet, PollOpt};
use mio::tcp::TcpListener;
use mio::util::Slab;
use std::net::SocketAddr;
use connection::Connection;
use error::Result;
const SERVER: Token = Token(0);
struct Server {
listener: TcpListener,
connections: Slab<Connection>,
}
impl Server {
fn new(li... | (addr: SocketAddr) -> Result<()> {
let listener = try!(TcpListener::bind(&addr));
let mut event_loop = try!(EventLoop::new());
try!(event_loop.register(&listener, SERVER, EventSet::readable(), PollOpt::edge()));
let mut server = Self::new(listener);
event_loop.run(&mut server);
... | run | identifier_name |
iframe.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | implements OnChanges {
@ViewChild('iframe') iframe: ElementRef;
@Input() src: string;
@Input() iframeWidth: string;
@Input() iframeHeight: string;
@Input() allowFullscreen: boolean | string;
@Output() loaded?: EventEmitter<HTMLIFrameElement> = new EventEmitter<HTMLIFrameElement>();
loading... | CoreIframeComponent | identifier_name |
iframe.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | iframe.addEventListener('error', () => {
this.loading = false;
this.domUtils.showErrorModal('core.errorloadingcontent', true);
});
if (this.loading) {
setTimeout(() => {
this.loading = false;
}, this.IFRAME_TIMEOUT);
}
... | random_line_split | |
iframe.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
this.initialized = true;
const iframe: HTMLIFrameElement = this.iframe && this.iframe.nativeElement;
this.iframeWidth = this.domUtils.formatPixelsSize(this.iframeWidth) || '100%';
this.iframeHeight = this.domUtils.formatPixelsSize(this.iframeHeight) || '100%';
this.allowFulls... | {
return;
} | conditional_block |
iframe.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
/**
* Init the data.
*/
protected init(): void {
if (this.initialized) {
return;
}
this.initialized = true;
const iframe: HTMLIFrameElement = this.iframe && this.iframe.nativeElement;
this.iframeWidth = this.domUtils.formatPixelsSize(this.iframe... | {
this.logger = logger.getInstance('CoreIframe');
this.loaded = new EventEmitter<HTMLIFrameElement>();
} | identifier_body |
main.ts | // This file is the entry point for the main (browser) process
import env from "common/env";
import { isItchioURL } from "common/util/url";
import { actions } from "common/actions";
import { app, protocol, globalShortcut } from "electron";
import { loadPreferencesSync } from "main/reactors/preboot/load-preferences"... | () {
mainLogger.info(
`${env.appName}@${app.getVersion()} on electron@${
process.versions.electron
} in ${env.production ? "production" : "development"}`
);
if (process.env.CAPSULE_LIBRARY_PATH) {
// disable acceleration when captured by capsule
app.disableHardwareAcceleration();
} else {... | main | identifier_name |
main.ts | // This file is the entry point for the main (browser) process
import env from "common/env";
import { isItchioURL } from "common/util/url";
import { actions } from "common/actions";
import { app, protocol, globalShortcut } from "electron";
import { loadPreferencesSync } from "main/reactors/preboot/load-preferences"... |
if (process.env.ITCH_IGNORE_CERTIFICATE_ERRORS === "1") {
app.commandLine.appendSwitch("ignore-certificate-errors");
}
protocol.registerSchemesAsPrivileged([
{
scheme: "itch-cave",
privileges: {
standard: true,
secure: true,
bypassCSP: true,
supportFetchAPI: tr... | {
mainLogger.info(
`${env.appName}@${app.getVersion()} on electron@${
process.versions.electron
} in ${env.production ? "production" : "development"}`
);
if (process.env.CAPSULE_LIBRARY_PATH) {
// disable acceleration when captured by capsule
app.disableHardwareAcceleration();
} else {
... | identifier_body |
main.ts | // This file is the entry point for the main (browser) process
import env from "common/env";
import { isItchioURL } from "common/util/url";
import { actions } from "common/actions";
import { app, protocol, globalShortcut } from "electron";
import { loadPreferencesSync } from "main/reactors/preboot/load-preferences"... |
store.dispatch(
actions.processUrlArguments({
args: process.argv,
})
);
globalShortcut.register("Control+Alt+Backspace", function () {
store.dispatch(actions.forceCloseLastGame({}));
});
// Emitted when the application is activated. Various actions can trigger
// th... | {
const singleInstanceLockAcquired = app.requestSingleInstanceLock();
if (!singleInstanceLockAcquired) {
app.exit(0);
return;
}
app.on("second-instance", (event, argv, cwd) => {
// we only get inside this callback when another instance
// is launched - so this exe... | conditional_block |
main.ts | // This file is the entry point for the main (browser) process | import env from "common/env";
import { isItchioURL } from "common/util/url";
import { actions } from "common/actions";
import { app, protocol, globalShortcut } from "electron";
import { loadPreferencesSync } from "main/reactors/preboot/load-preferences";
import { Store } from "common/types";
import { mainLogger } fr... | random_line_split | |
weather.py | __author__ = 'Alexandre Menai amenai@amenai.net'
'''
The weather module intends to grab pilot weather from the aviation weather services in the USA
'''
#TODO put the following global parameters into a configuration file later on
WEAHTER_HOSTNAME="aviationweather.gov"
METAR_PATH="/adds/dataserver_current/httpparam?dataS... |
def grab_airfield_weather(self, airfield='KBED', hours_before_now=1):
#construct the path and params
requestPath=METAR_PATH+airfield+"&hoursBeforeNow="+str(hours_before_now)
#initiate the connection
connection=httplib.HTTPConnection(WEAHTER_HOSTNAME)
# Get the METAR
... | """
initializes a weather object.
:param start_date: the start date in epoch
:param duration: the duration of the flight in seconds
:param departure_airfield: is the 4 letter ICAO identifer of the departure airfield
:param destination_airfield: is the 4 letter ICAO identifer of t... | identifier_body |
weather.py | __author__ = 'Alexandre Menai amenai@amenai.net'
'''
The weather module intends to grab pilot weather from the aviation weather services in the USA
'''
#TODO put the following global parameters into a configuration file later on
WEAHTER_HOSTNAME="aviationweather.gov"
METAR_PATH="/adds/dataserver_current/httpparam?dataS... | (self, airfield='KBED', hours_before_now=1):
#construct the path and params
requestPath=METAR_PATH+airfield+"&hoursBeforeNow="+str(hours_before_now)
#initiate the connection
connection=httplib.HTTPConnection(WEAHTER_HOSTNAME)
# Get the METAR
connection.request('GET',reque... | grab_airfield_weather | identifier_name |
weather.py | __author__ = 'Alexandre Menai amenai@amenai.net'
'''
The weather module intends to grab pilot weather from the aviation weather services in the USA
'''
#TODO put the following global parameters into a configuration file later on
WEAHTER_HOSTNAME="aviationweather.gov"
METAR_PATH="/adds/dataserver_current/httpparam?dataS... | deserialized_metar = XML2Py.XML2Py().parse(metar_xml)
return deserialized_metar
#TODO scale down the useless information | #close the connection
connection.close() | random_line_split |
todo.py | #!/usr/bin/env python3
import os.path, sys, json
from collections import OrderedDict
todo_list = OrderedDict()
file_path = os.path.expanduser('~/.todo_list.json')
if os.path.isfile(file_path):
with open(file_path, 'r') as todo_list_file:
todo_list.update(json.load(todo_list_file))
args = sys.argv[1:]
d... |
if len(args) < 1:
args = ["list"]
task_count = len(todo_list)
if args[0] == "add":
if len(args) != 2:
usage()
name = args[1]
todo_list[str(task_count + 1)] = {
"name": name,
"completed": False
}
print("Added " + args[1] + " to todo list")
elif args[0] == "list":
... | usage = """Usage:
todo.py add <task>
todo.py list
todo.py del <task number>
todo.py done <task number>"""
print(usage)
sys.exit(0) | identifier_body |
todo.py | #!/usr/bin/env python3
import os.path, sys, json
from collections import OrderedDict
todo_list = OrderedDict()
file_path = os.path.expanduser('~/.todo_list.json')
if os.path.isfile(file_path):
with open(file_path, 'r') as todo_list_file:
todo_list.update(json.load(todo_list_file))
args = sys.argv[1:]
d... | elif args[0] == "list":
if task_count == 0:
print("Woohoo, nothing to do!")
else:
for i in range(1, task_count + 1):
task = todo_list[str(i)]
print("%d) %s (%s)" % (i, task["name"], "✔" if task["completed"] else "╳"))
elif args[0] == "del":
if len(args) != 2:
... | "completed": False
}
print("Added " + args[1] + " to todo list") | random_line_split |
todo.py | #!/usr/bin/env python3
import os.path, sys, json
from collections import OrderedDict
todo_list = OrderedDict()
file_path = os.path.expanduser('~/.todo_list.json')
if os.path.isfile(file_path):
with open(file_path, 'r') as todo_list_file:
todo_list.update(json.load(todo_list_file))
args = sys.argv[1:]
d... | else:
print("Task #%s does not exist" % idx)
elif args[0] == "done":
if len(args) != 2:
usage()
idx = args[1]
if idx in todo_list:
todo_list[idx]["completed"] = True
else:
print("Task #%s does not exist" % idx)
else:
usage()
with open(file_path, 'w') as todo_list_f... | = keys[i]
todo_list[str(i + 1)] = todo_list[key]
if int(key) >= task_count:
del todo_list[key]
| conditional_block |
todo.py | #!/usr/bin/env python3
import os.path, sys, json
from collections import OrderedDict
todo_list = OrderedDict()
file_path = os.path.expanduser('~/.todo_list.json')
if os.path.isfile(file_path):
with open(file_path, 'r') as todo_list_file:
todo_list.update(json.load(todo_list_file))
args = sys.argv[1:]
d... | ():
usage = """Usage:
todo.py add <task>
todo.py list
todo.py del <task number>
todo.py done <task number>"""
print(usage)
sys.exit(0)
if len(args) < 1:
args = ["list"]
task_count = len(todo_list)
if args[0] == "add":
if len(args) != 2:
usage()
name = args[1]
todo_list[st... | usage | identifier_name |
redshift_yaml_example.py | import os
from ruamel import yaml
import great_expectations as ge
from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest
redshift_username = os.environ.get("REDSHIFT_USERNAME")
redshift_password = os.environ.get("REDSHIFT_PASSWORD")
redshift_host = os.environ.get("REDSHIFT_HOST")
redshift_port =... | expectation_suite_name="test_suite", overwrite_existing=True
)
validator = context.get_validator(
batch_request=batch_request, expectation_suite_name="test_suite"
)
print(validator.head())
# NOTE: The following code is only for testing and can be ignored by users.
assert isinstance(validator, ge.validator.vali... | data_connector_name="default_inferred_data_connector_name",
data_asset_name="taxi_data", # this is the name of the table you want to retrieve
)
context.create_expectation_suite( | random_line_split |
fr.js | /*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013-2021 School of Management and Engineering Vaud, Comem, MEI
* Licensed under the MIT License
*/
/**
* @fileoverview | *
*/
I18n.add("fr" , {
wc: "Nombre de mots",
cc: "Nombre de signes",
data: "Textes",
mean: "Moyenne",
median: "Médiane",
sd: "écart-type",
overview: "Aperçu",
editionStatus: "Édition",
reviewDoneTitle: "Feedbacks terminés",
commentsDoneTitle: "Commentaires Terminés",
review... | * @author Maxence Laurent <maxence.laurent> <gmail.com>
*/
/*
* REGEX
* Accent detection : [^\w\s\d\{\}\[\],.%\*\/\(\)<>@.:\"\\=;|\'-+&#] | random_line_split |
Concurrent.rs | extern crate sync;
use sync::{Arc, Mutex};
fn main () |
// spawn(proc() {
// let numbers = rx.recv();
// println!("{}", numbers[num]);
// })
// }
// let numbers = ~[1,2,3];
// let numbers = Arc::new(numbers);
// for num in range(0, 3) {
// let (tx, rx) = channel();
// tx.send(numbers.clone());
// spawn(proc() {
// let number... | {
// let mut numbers = ~[1, 2, 3, 4];
// let (tx, rx) = channel ();
// numbers[0] = 4;
// tx.send(numbers);
// spawn (proc () {
// let mut numbers = rx.recv ();
// println! ("{}", numbers[0]);
// numbers[0] = 5;
// println! ("{}", numbers[0]);
// tx.send(numbers);
// })
// let numbe... | identifier_body |
Concurrent.rs | extern crate sync;
use sync::{Arc, Mutex};
fn main () {
// let mut numbers = ~[1, 2, 3, 4];
// let (tx, rx) = channel ();
// numbers[0] = 4;
// tx.send(numbers);
// spawn (proc () {
// let mut numbers = rx.recv (); | // println! ("{}", numbers[0]);
// numbers[0] = 5;
// println! ("{}", numbers[0]);
// tx.send(numbers);
// })
// let numbers = ~[1,2,3];
// for num in range(0, 3) {
// let (tx, rx) = channel();
// tx.send(numbers.clone());
// spawn(proc() {
// let numbers = rx.recv();
// ... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.