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 |
|---|---|---|---|---|
system.rs | use std::sync::RwLock;
use std::path::{Path, PathBuf};
use std::fs;
use slog::Logger;
use search::backends::rocksdb::RocksDBStore;
use uuid::Uuid;
use index::Index;
use index::metadata::IndexMetadata;
use cluster::metadata::ClusterMetadata;
pub struct System {
pub log: Logger,
data_dir: PathBuf,
pub met... |
}
}
}
}
Err(error) => {
error!(self.log, "could not open indices directory"; "dir" => indices_dir.to_str().unwrap(), "error" => format!("{}", error));
}
}
}
}
| {
error!(self.log, "load index failed"; "index" => index_name, "error" => e);
} | conditional_block |
system.rs | use std::sync::RwLock;
use std::path::{Path, PathBuf};
use std::fs;
use slog::Logger;
use search::backends::rocksdb::RocksDBStore;
use uuid::Uuid;
use index::Index;
use index::metadata::IndexMetadata;
use cluster::metadata::ClusterMetadata;
pub struct System {
pub log: Logger,
data_dir: PathBuf,
pub met... |
pub fn get_indices_dir(&self) -> PathBuf {
let mut dir = self.data_dir.clone();
dir.push("indices");
dir
}
fn load_index(&self, id: Uuid, name: String, path: &Path) -> Result<Index, String> {
let store = RocksDBStore::open(path)?;
// Load metadata
let mut ... | {
System {
log: log,
data_dir: data_dir,
metadata: RwLock::new(ClusterMetadata::new()),
}
} | identifier_body |
macros-nested.rs | // This test is similar to `macros.rs`, but nested in modules.
// run-pass
// edition:2018
| #![allow(non_camel_case_types)]
mod foo {
// Test that ambiguity errors are not emitted between `self::test` and
// `::test`, assuming the latter (crate) is not in `extern_prelude`.
macro_rules! m1 {
() => {
mod test {
pub struct Foo(pub ());
}
}
... | random_line_split | |
macros-nested.rs | // This test is similar to `macros.rs`, but nested in modules.
// run-pass
// edition:2018
#![allow(non_camel_case_types)]
mod foo {
// Test that ambiguity errors are not emitted between `self::test` and
// `::test`, assuming the latter (crate) is not in `extern_prelude`.
macro_rules! m1 {
() => ... | {
foo::Foo(());
let _ = foo::std_io::stdout();
foo::local_io(());
let _ = io::stdout();
let _ = bar::io::stdout();
} | identifier_body | |
macros-nested.rs | // This test is similar to `macros.rs`, but nested in modules.
// run-pass
// edition:2018
#![allow(non_camel_case_types)]
mod foo {
// Test that ambiguity errors are not emitted between `self::test` and
// `::test`, assuming the latter (crate) is not in `extern_prelude`.
macro_rules! m1 {
() => ... | () {
foo::Foo(());
let _ = foo::std_io::stdout();
foo::local_io(());
let _ = io::stdout();
let _ = bar::io::stdout();
}
| main | identifier_name |
vector_graphics_user_layer.ts | /**
* @license
* Copyright 2016 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... |
});
}
}
this.tabs.add(
'rendering', {label: 'Rendering', order: -100, getter: () => new DisplayOptionsTab(this)});
this.tabs.default = 'rendering';
}
toJSON() {
const x = super.toJSON();
x['type'] = this.getLayerType();
x['source'] = this.vectorGraphicsPath;
x... | {
let renderLayer = this.renderLayer =
new VectorGraphicsLineRenderLayer(vectorGraphics, {
opacity: this.opacity,
lineWidth: this.lineWidth,
color: this.color,
sourceOptions: {}
... | conditional_block |
vector_graphics_user_layer.ts | /**
* @license
* Copyright 2016 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... | element.classList.add('image-dropdown');
let {opacityWidget, lineWidthWidget, colorWidget} = this;
let topRow = document.createElement('div');
topRow.className = 'image-dropdown-top-row';
opacityWidget.promptElement.textContent = 'Opacity';
lineWidthWidget.promptElement.textContent = 'Line Width... | constructor(public layer: VectorGraphicsUserLayer) {
super();
const {groupVisualization, element} = this; | random_line_split |
vector_graphics_user_layer.ts | /**
* @license
* Copyright 2016 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... |
verifyValue(value: any) {
let num = verifyFiniteFloat(value);
// Scale from [0,255] to [0,1]
num = num / 255.0;
if (num < 0.) {
return 0.;
}
if (num > 1.) {
return 1.;
}
return num;
}
updateInput() {
this.inputx.valueAsNumber = Math.round(this.model.value[0] * 2... | {
super(model);
} | identifier_body |
vector_graphics_user_layer.ts | /**
* @license
* Copyright 2016 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... | (model: TrackableVec3) {
super(model);
}
verifyValue(value: any) {
let num = verifyFiniteFloat(value);
// Scale from [0,255] to [0,1]
num = num / 255.0;
if (num < 0.) {
return 0.;
}
if (num > 1.) {
return 1.;
}
return num;
}
updateInput() {
this.inputx.valu... | constructor | identifier_name |
index.js | var MongoClient = require('../lib/mongodb').MongoClient
, mongo = require('../lib/mongodb')
, format = require('util').format
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO... |
console.log("generated");
console.log(">> Inserting data (" + objects.length + ")");
collection.insert(objects, {w:0});
console.log("inserted");
console.log(">> Creating index")
collection.createIndex([['all'], ['_id', 1], ['number', 1], ['rndm', 1], ['msg', 1]], function(err, indexName) {
console.... | {
objects.push({'number':i, 'rndm':((5*Math.random()) + 1), 'msg':messages[parseInt(4*Math.random())]})
} | conditional_block |
index.js | var MongoClient = require('../lib/mongodb').MongoClient
, mongo = require('../lib/mongodb')
, format = require('util').format
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO... |
console.log(">> Inserting data (" + objects.length + ")");
collection.insert(objects, {w:0});
console.log("inserted");
console.log(">> Creating index")
collection.createIndex([['all'], ['_id', 1], ['number', 1], ['rndm', 1], ['msg', 1]], function(err, indexName) {
console.log("created index: " + index... | for(var i = 0; i < objectCount; i++) {
objects.push({'number':i, 'rndm':((5*Math.random()) + 1), 'msg':messages[parseInt(4*Math.random())]})
}
console.log("generated"); | random_line_split |
textdecoder.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::TextDecoderBinding;
use crate::dom::bindings::codegen::Bindings::Tex... |
// https://encoding.spec.whatwg.org/#dom-textdecoder-ignorebom
fn IgnoreBOM(&self) -> bool {
self.ignoreBOM
}
// https://encoding.spec.whatwg.org/#dom-textdecoder-decode
fn Decode(
&self,
input: Option<ArrayBufferViewOrArrayBuffer>,
options: &TextDecodeOptions,
... | {
self.fatal
} | identifier_body |
textdecoder.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::TextDecoderBinding;
use crate::dom::bindings::codegen::Bindings::Tex... | (
&self,
input: Option<ArrayBufferViewOrArrayBuffer>,
options: &TextDecodeOptions,
) -> Fallible<USVString> {
// Step 1.
if !self.do_not_flush.get() {
if self.ignoreBOM {
self.decoder
.replace(self.encoding.new_decoder_without_b... | Decode | identifier_name |
textdecoder.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::TextDecoderBinding;
use crate::dom::bindings::codegen::Bindings::Tex... | // Step 4.
let mut out_stream = String::with_capacity(
decoder
.max_utf8_buffer_length_without_replacement(in_stream.len())
.unwrap(),
);
// Step 5: Implemented by encoding_rs::Decoder.
... | let (remaining, s) = if self.fatal { | random_line_split |
run-tests.py | #! /usr/bin/env python
import sys, os, getopt, struct, unittest
from distutils.spawn import spawn
build = True
verbosity = 2
here = os.path.dirname(os.path.abspath(__file__))
os.chdir(here)
def bits():
"""determine if running on a 32 bit or 64 bit platform
"""
return struct.calcsize("P") * 8
# -- parse... |
# -- build greenlet
if build:
if verbosity == 0:
cmd = [sys.executable, "setup.py", "-q", "build_ext", "-q"]
else:
cmd = [sys.executable, "setup.py", "build_ext"]
spawn(cmd, search_path=0)
# -- find greenlet but skip the one in "."
if not build:
oldpath = sys.path[:]
sys.path.re... | build = False | conditional_block |
run-tests.py | #! /usr/bin/env python
import sys, os, getopt, struct, unittest
from distutils.spawn import spawn
build = True
verbosity = 2
here = os.path.dirname(os.path.abspath(__file__))
os.chdir(here)
def bits():
"""determine if running on a 32 bit or 64 bit platform
"""
return struct.calcsize("P") * 8
# -- parse... | except getopt.GetoptError:
sys.exit("run-tests.py: error: %s" % sys.exc_info()[1])
for o, a in opts:
if o == "-q":
verbosity = 0
elif o == "-n":
build = False
# -- build greenlet
if build:
if verbosity == 0:
cmd = [sys.executable, "setup.py", "-q", "build_ext", "-q"]
else:
... | random_line_split | |
run-tests.py | #! /usr/bin/env python
import sys, os, getopt, struct, unittest
from distutils.spawn import spawn
build = True
verbosity = 2
here = os.path.dirname(os.path.abspath(__file__))
os.chdir(here)
def bits():
|
# -- parse options
try:
opts, args = getopt.getopt(sys.argv[1:], "nq")
if args:
raise getopt.GetoptError("too many arguments")
except getopt.GetoptError:
sys.exit("run-tests.py: error: %s" % sys.exc_info()[1])
for o, a in opts:
if o == "-q":
verbosity = 0
elif o == "-n":
b... | """determine if running on a 32 bit or 64 bit platform
"""
return struct.calcsize("P") * 8 | identifier_body |
run-tests.py | #! /usr/bin/env python
import sys, os, getopt, struct, unittest
from distutils.spawn import spawn
build = True
verbosity = 2
here = os.path.dirname(os.path.abspath(__file__))
os.chdir(here)
def | ():
"""determine if running on a 32 bit or 64 bit platform
"""
return struct.calcsize("P") * 8
# -- parse options
try:
opts, args = getopt.getopt(sys.argv[1:], "nq")
if args:
raise getopt.GetoptError("too many arguments")
except getopt.GetoptError:
sys.exit("run-tests.py: error: %s" % s... | bits | identifier_name |
rnatreemap.js | import {rnaPlot} from './rnaplot.js';
export function rnaTreemapChart() | .showNucleotideLabels(false);
if ('structure' in d) d3.select(this).call(chart)
});
}
var chart = function(selection) {
selection.each(function(data) {
console.log('data:', data)
// initialize the treemap structure
// sample input
... | {
var width = 550;
var height = 400;
function rnaTreemapNode(selection) {
// create a background rectangle for each RNA structure
selection.each(function(d) {
d3.select(this)
.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')' })
... | identifier_body |
rnatreemap.js | import {rnaPlot} from './rnaplot.js';
export function rnaTreemapChart() {
var width = 550;
var height = 400;
| .attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')' })
.append('rect')
.classed('structure-background-rect', true)
.attr('width', function(d) { return Math.max(0, d.dx); })
.attr('height', function(d) { return Math.max(0, d.dy); })
... | function rnaTreemapNode(selection) {
// create a background rectangle for each RNA structure
selection.each(function(d) {
d3.select(this) | random_line_split |
rnatreemap.js | import {rnaPlot} from './rnaplot.js';
export function rnaTreemapChart() {
var width = 550;
var height = 400;
function rnaTreemapNode(selection) {
// create a background rectangle for each RNA structure
selection.each(function(d) {
d3.select(this)
.attr('transform', ... | () {
var chart = function(selection) {
console.log('selection:', selection);
selection.each(function(data) {
console.log('data:', data);
});
}
return chart;
}
| rnaTreemapGridChart | identifier_name |
es.array.slice.js | 'use strict';
var $ = require('../internals/export');
var isObject = require('../internals/is-object');
var isArray = require('../internals/is-array');
var toAbsoluteIndex = require('../internals/to-absolute-index');
var toLength = require('../internals/to-length');
var toIndexedObject = require('../internals/to-indexe... |
}
result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
result.length = n;
return result;
}
});
| {
return nativeSlice.call(O, k, fin);
} | conditional_block |
es.array.slice.js | 'use strict';
var $ = require('../internals/export');
var isObject = require('../internals/is-object');
var isArray = require('../internals/is-array');
var toAbsoluteIndex = require('../internals/to-absolute-index');
var toLength = require('../internals/to-length');
var toIndexedObject = require('../internals/to-indexe... | }); | random_line_split | |
adapt_fit.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... |
# -----------------------------------------------------------------
definition = definition.copy()
# -----------------------------------------------------------------
# The fitting run for which to adapt the configuration
if runs.empty: raise RuntimeError("No fitting runs are present")
elif runs.has_single: definit... | runs = environment.fitting_runs
# -----------------------------------------------------------------
properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"] | random_line_split |
adapt_fit.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... | else: definition.add_required("name", "string", "name of the fitting run", choices=runs.names)
# -----------------------------------------------------------------
# Dust or stellar
definition.add_positional_optional("properties", "string_list", "properties to adapt", default=properties, choices=properties)
# -------... | efinition.add_fixed("name", "name of the fitting run", runs.single_name)
| conditional_block |
no_0023_merge_k_sorted_lists.rs | // Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
use std::cmp::{Ord, Ordering, PartialEq};
use std::colle... | node(ListNode {
val: 1,
next: node(ListNode {
val: 4,
next: node(ListNode::new(5)),
}),
}),
node(ListNode {
val: 1,
next: node(ListNode {
val: 3... | let lists = vec![ | random_line_split |
no_0023_merge_k_sorted_lists.rs | // Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
use std::cmp::{Ord, Ordering, PartialEq};
use std::colle... | .next
}
// 这种是利用数组来生成最终的结果,因为不知道怎么在链表后面插入元素。
pub fn merge_k_lists1(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
if lists.is_empty() {
return None;
}
// 用数组来暂存结果。
let mut ans = Vec::new();
let mut heap = BinaryHeap::new();
// 把第一列... | r.next.as_mut().unwrap();
}
ans | conditional_block |
no_0023_merge_k_sorted_lists.rs | // Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn | (val: i32) -> Self {
ListNode { next: None, val }
}
}
use std::cmp::{Ord, Ordering, PartialEq};
use std::collections::BinaryHeap;
impl Ord for ListNode {
fn cmp(&self, other: &Self) -> Ordering {
// 默认是最大堆,这里颠倒顺序,实现最小堆。
other.val.cmp(&self.val)
}
}
impl PartialOrd for ListNode {
... | new | identifier_name |
no_0023_merge_k_sorted_lists.rs | // Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
use std::cmp::{Ord, Ordering, PartialEq};
use std::colle... | n partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
struct Solution;
impl Solution {
pub fn merge_k_lists(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
if lists.is_empty() {
return None;
}
let mut ans = Box::new(ListNod... | {
// 默认是最大堆,这里颠倒顺序,实现最小堆。
other.val.cmp(&self.val)
}
}
impl PartialOrd for ListNode {
f | identifier_body |
v1_ingress_class_spec.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(se... | result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
)) | conditional_block |
v1_ingress_class_spec.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1IngressClassSpec):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isins... | """For `print` and `pprint`"""
return self.to_str() | identifier_body |
v1_ingress_class_spec.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | (object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (... | V1IngressClassSpec | identifier_name |
v1_ingress_class_spec.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1IngressClassSpec):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinst... |
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str() | random_line_split |
autoderef-method-priority.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 ... | () {
let x = box(GC) 3u;
assert_eq!(x.double(), 6u);
}
| main | identifier_name |
autoderef-method-priority.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 double for uint {
fn double(self) -> uint { self }
}
impl double for Gc<uint> {
fn double(self) -> uint { *self * 2u }
}
pub fn main() {
let x = box(GC) 3u;
assert_eq!(x.double(), 6u);
} | random_line_split | |
autoderef-method-priority.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 double for Gc<uint> {
fn double(self) -> uint { *self * 2u }
}
pub fn main() {
let x = box(GC) 3u;
assert_eq!(x.double(), 6u);
}
| { self } | identifier_body |
asymmetric.spec.js | var axios = require("axios");
var expect = require("chai").expect;
var MockAdapter = require("../src");
describe("MockAdapter asymmetric matchers", function () {
var instance;
var mock;
| mock = new MockAdapter(instance);
});
it("mocks a post request with a body matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("... | beforeEach(function () {
instance = axios.create(); | random_line_split |
index.ts | (setting: string, configuration: any, defaultValue: any){
return typeof configuration[setting] !== 'undefined' ? configuration[setting] : defaultValue;
};
/**
* Set the monitoring variables
* @param context
*/
function initMonitoringConfiguration(context){
try{
const appConfig = getConfiguration();
MONI... | getAppConfigurationSetting | identifier_name | |
index.ts | Config = getConfiguration();
MONITORING_ENABLED = appConfig && typeof appConfig['wazuh.monitoring.enabled'] !== 'undefined'
? appConfig['wazuh.monitoring.enabled'] &&
appConfig['wazuh.monitoring.enabled'] !== 'worker'
: WAZUH_MONITORING_DEFAULT_ENABLED;
MONITORING_FREQUENCY = getAppConfigura... | };
// Update the monitoring template
await context.core.elasticsearch.client.asInternalUser.indices.putTemplate({
name: WAZUH_MONITORING_TEMPLATE_NAME,
body: monitoringTemplate
});
log(
'monitoring:checkTemplate',
'Updated the monitoring template',
'debug'
);
} c... | if (!monitoringTemplate.index_patterns.includes(MONITORING_INDEX_PATTERN)) {
monitoringTemplate.index_patterns.push(MONITORING_INDEX_PATTERN); | random_line_split |
index.ts | = getConfiguration();
MONITORING_ENABLED = appConfig && typeof appConfig['wazuh.monitoring.enabled'] !== 'undefined'
? appConfig['wazuh.monitoring.enabled'] &&
appConfig['wazuh.monitoring.enabled'] !== 'worker'
: WAZUH_MONITORING_DEFAULT_ENABLED;
MONITORING_FREQUENCY = getAppConfigurationSe... | 'monitoring:insertDataToIndex',
`Bulk data to index ${indexName} for ${agents.length} agents completed`,
'debug'
);
}
} catch (error) {
log(
'monitoring:insertDataToIndex',
`Error inserting agent data into elasticsearch. Bulk request failed due to ${error.message ||
... | {
log(
'monitoring:insertDataToIndex',
`Bulk data to index ${indexName} for ${agents.length} agents`,
'debug'
);
const bodyBulk = agents.map(agent => {
const agentInfo = {...agent};
agentInfo['timestamp'] = new Date(Date.now()).toISOString();
agentInfo.... | conditional_block |
index.ts | ;
/**
* Set the monitoring variables
* @param context
*/
function initMonitoringConfiguration(context){
try{
const appConfig = getConfiguration();
MONITORING_ENABLED = appConfig && typeof appConfig['wazuh.monitoring.enabled'] !== 'undefined'
? appConfig['wazuh.monitoring.enabled'] &&
appConf... | {
return typeof configuration[setting] !== 'undefined' ? configuration[setting] : defaultValue;
} | identifier_body | |
resnet.py | # Copyright 2021 DeepMind Technologies Limited. 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 ... | # Stem
out = self.initial_conv(x)
if not self.preactivation:
out = self.activation(self.initial_bn(out, is_training, test_local_stats))
out = hk.max_pool(out, window_shape=(1, 3, 3, 1),
strides=(1, 2, 2, 1), padding='SAME')
if return_metrics:
outputs.update(base.sig... | return_metrics=False):
"""Return the output of the final layer without any [log-]softmax."""
outputs = {} | random_line_split |
resnet.py | # Copyright 2021 DeepMind Technologies Limited. 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 ... | # Return pool before dropout in case we want to regularize it separately.
outputs['pool'] = pool
# Optionally apply dropout
if self.drop_rate > 0.0 and is_training:
pool = hk.dropout(hk.next_rng_key(), self.drop_rate, pool)
outputs['logits'] = self.fc(pool)
return outputs
class ResBlock... | """Return the output of the final layer without any [log-]softmax."""
outputs = {}
# Stem
out = self.initial_conv(x)
if not self.preactivation:
out = self.activation(self.initial_bn(out, is_training, test_local_stats))
out = hk.max_pool(out, window_shape=(1, 3, 3, 1),
str... | identifier_body |
resnet.py | # Copyright 2021 DeepMind Technologies Limited. 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 ... | (hk.Module):
"""ResNet preac block, 1x1->3x3->1x1 with strides and shortcut downsample."""
def __init__(self, out_ch, stride=1, use_projection=False,
activation=jax.nn.relu, which_norm=hk.BatchNorm,
which_conv=hk.Conv2D, use_se=False, se_ratio=0.25,
name=None):
supe... | ResBlockV2 | identifier_name |
resnet.py | # Copyright 2021 DeepMind Technologies Limited. 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 ... |
outputs['logits'] = self.fc(pool)
return outputs
class ResBlockV2(hk.Module):
"""ResNet preac block, 1x1->3x3->1x1 with strides and shortcut downsample."""
def __init__(self, out_ch, stride=1, use_projection=False,
activation=jax.nn.relu, which_norm=hk.BatchNorm,
which_conv... | pool = hk.dropout(hk.next_rng_key(), self.drop_rate, pool) | conditional_block |
wmap.rs | #[macro_use]
extern crate cli_util;
extern crate wlib;
use std::env;
use wlib::window; | #[derive(Copy, Clone)]
enum Mode {
Map,
Unmap
}
fn main() {
let name = cli_util::name(&mut env::args());
parse_args!{
description: "map or unmap window",
flag mode: Mode = Mode::Map,
(&["-m", "--map"], Mode::Map, "map window (default)"),
(&["-u", "--unmap"], Mod... | random_line_split | |
wmap.rs | #[macro_use]
extern crate cli_util;
extern crate wlib;
use std::env;
use wlib::window;
#[derive(Copy, Clone)]
enum Mode {
Map,
Unmap
}
fn main() {
let name = cli_util::name(&mut env::args());
parse_args!{
description: "map or unmap window",
flag mode: Mode = Mode::Map,
(&... | (mode: Mode, wid: window::ID) -> Result<(), &'static str> {
let disp = try!(wlib::Display::open());
let mut win = try!(
disp.window(wid).map_err(|_| "window does not exist")
);
match mode {
Mode::Map => try!(win.map()),
Mode::Unmap => try!(win.unmap())
}
Ok(())
}
| run | identifier_name |
react-dropzone-tests.tsx | ///<reference path='../react/react.d.ts' />
///<reference path='../react-dropzone/react-dropzone.d.ts' />
import * as React from 'react';
import Dropzone = require('react-dropzone');
class Test extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
render() |
onDropRejected={(e: any) => { e.preventDefault(); } }
onDragEnter={(e: any) => { e.preventDefault(); } }
onDragLeave={(e: any) => { e.preventDefault(); } }
style={{ borderStyle: "dashed" }}
activeStyle={{ borderStyle: "dotted" }}
className="regular"
minSize={2000... | {
return (<div>
<Dropzone
onDrop={(e: any) => { e.preventDefault(); } }
onDropAccepted={(e: any) => { e.preventDefault(); } } | identifier_body |
react-dropzone-tests.tsx | ///<reference path='../react/react.d.ts' />
///<reference path='../react-dropzone/react-dropzone.d.ts' />
import * as React from 'react';
import Dropzone = require('react-dropzone');
class Test extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
render() {
return (<div>
... | activeClassName="active"
rejectClassName="reject"
disableClick={true}
multiple={false}
accept="*.png"
/>
</div>);
}
}
export default Test; | activeStyle={{ borderStyle: "dotted" }}
className="regular"
minSize={2000}
maxSize={Infinity} | random_line_split |
react-dropzone-tests.tsx | ///<reference path='../react/react.d.ts' />
///<reference path='../react-dropzone/react-dropzone.d.ts' />
import * as React from 'react';
import Dropzone = require('react-dropzone');
class Test extends React.Component<any, any> {
| (props: any) {
super(props);
}
render() {
return (<div>
<Dropzone
onDrop={(e: any) => { e.preventDefault(); } }
onDropAccepted={(e: any) => { e.preventDefault(); } }
onDropRejected={(e: any) => { e.preventDefault(); } }
onDragEnter={(e: any) => { e.preventDefault(); ... | constructor | identifier_name |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
/// Pin functions (GPIO or up to three additional functions).
#[derive(PartialEq)]
#[allow(missing_docs)]
pub enum Function {
Gpio = 0,
AltFunction1 = 1,
AltFunction2 = 2,
AltFunction3 = 3,
}
impl Copy for Function {}
/// Structure to describe the location of a pin
#[derive(Copy)]
pub struct Pin {
... | Port4,
} | random_line_split |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
fn get_pinsel_reg_and_offset(&self) -> (u8, ®::PINSEL) {
match self.port {
Port0 => match self.pin {
0...15 => (self.pin, ®::PINSEL0),
16...30 => (self.pin-16, ®::PINSEL1),
_ => unsafe { abort() },
},
Port1 => match self.pin {
0...15 => (self.... | {
match self.port {
Port0 => ®::GPIO_0,
Port1 => ®::GPIO_1,
Port2 => ®::GPIO_2,
Port3 => ®::GPIO_3,
Port4 => ®::GPIO_4,
}
} | identifier_body |
pin.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | {
/// Port the pin is attached to
port: Port,
/// Pin number in the port
pin: u8
}
impl Pin {
/// Create and setup a Pin
pub fn new(port: Port, pin_index: u8, function: Function,
gpiodir: Option<::hal::pin::GpioDirection>) -> Pin {
let pin = Pin {
port: port,
pin: pin_index,
};
... | Pin | identifier_name |
upload.js | ($dropzone);
$file_input.on("change", function() {
if (this.files.length > 0 || opts.files) {
var fileobjs = null;
if (opts.files) {
// files added programmatically
fileobjs = opts.files;
delete opts.files;
} else {
// files from input type file
fileobjs = $upload.find(":file... |
function on_upload(e, attachment) {
if (!files || i === files.length - 1) {
$(document).off('upload_complete', on_upload);
frappe.hide_progress();
return;
}
upload_next();
}
},
upload_file: function(fileobj, args, opts) {
if(!fileobj && !args.file_url) {
if(opts.on_no_attach) {
opt... | {
if(files) {
i += 1;
var file = files[i];
args.is_private = file.is_private;
if(!opts.progress) {
frappe.show_progress(__('Uploading'), i, files.length);
}
}
frappe.upload.upload_file(file, args, opts);
} | identifier_body |
upload.js | .append($dropzone);
$file_input.on("change", function() {
if (this.files.length > 0 || opts.files) {
var fileobjs = null;
if (opts.files) {
// files added programmatically
fileobjs = opts.files;
delete opts.files;
} else {
// files from input type file
fileobjs = $upload.find... | (e, attachment) {
if (!files || i === files.length - 1) {
$(document).off('upload_complete', on_upload);
frappe.hide_progress();
return;
}
upload_next();
}
},
upload_file: function(fileobj, args, opts) {
if(!fileobj && !args.file_url) {
if(opts.on_no_attach) {
opts.on_no_attach();
}... | on_upload | identifier_name |
upload.js | .append($dropzone);
$file_input.on("change", function() {
if (this.files.length > 0 || opts.files) {
var fileobjs = null;
if (opts.files) {
// files added programmatically
fileobjs = opts.files;
delete opts.files;
} else {
// files from input type file
fileobjs = $upload.find... | }
},
read_file: function(fileobj, args, opts) {
args.filename = fileobj.name.split(' ').join('_');
args.file_url = null;
if(opts.options && opts.options.toLowerCase()=="image") {
if(!frappe.utils.is_image_file(args.filename)) {
frappe.msgprint(__("Only image extensions (.gif, .jpg, .jpeg, .tiff, .png... |
frappe.upload.upload_to_server(fileobj, args, opts);
}
| random_line_split |
upload.js | _files', attached_files);
// remove row from dom
$uploaded_files_wrapper
.find(`.list-item-container[data-filename="${filename}"]`)
.remove();
if(attached_files.length === 0) {
frappe.upload.show_empty_state($upload);
}
}
});
if(!opts.btn) {
opts.btn = $('<button class="btn ... | {
// validate max file size
frappe.throw(__("File size exceeded the maximum allowed size of {0} MB", [max_file_size / 1048576]));
} | conditional_block | |
__init__.py | #
# Copyright (c) 2015 Open-RnD Sp. z o.o.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy,
# modify, merge, publ... | # SOFTWARE. | random_line_split | |
gid.py |
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# ... |
self.uuid = dict.get("uuid", None)
self.urn = dict.get("urn", None)
self.hrn = dict.get("hrn", None)
self.email = dict.get("email", None)
if self.urn:
self.hrn = urn_to_hrn(self.urn)[0]
##
# Dump the credential to stdout.
#
# @pa... | if data.lower().startswith('uri:http://<params>'):
dict = xmlrpclib.loads(data[11:])[0][0]
else:
spl = data.split(', ')
for val in spl:
if val.lower().startswith('uri:urn:uuid:'):
dict['uuid'] = uuid.UUID(val[4:]).in... | conditional_block |
gid.py |
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# ... | ():
return str(uuid.uuid4().int)
##
# GID is a tuple:
# (uuid, urn, public_key)
#
# UUID is a unique identifier and is created by the python uuid module
# (or the utility function create_uuid() in gid.py).
#
# HRN is a human readable name. It is a dotted form similar to a backward domain
# name. For examp... | create_uuid | identifier_name |
gid.py |
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# ... |
##
# Decode the subject-alt-name field of the X509 certificate into the
# fields of the GID. This is automatically called by the various get_*()
# functions in this class.
def decode(self):
data = self.get_data('subjectAltName')
dict = {}
if data:
if data.lowe... | if self.urn:
urn = self.urn
else:
urn = hrn_to_urn(self.hrn, None)
str = "URI:" + urn
if self.uuid:
str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn
if self.email:
str += ", " + "email:" + self.email
self.... | identifier_body |
gid.py | # rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portion... | #
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the | random_line_split | |
philadelphia.py | from otm1_migrator.migration_rules.standard_otm1 import MIGRATION_RULES
from treemap.models import ITreeCodeOverride, ITreeRegion, User
UDFS = {
'plot': {
'owner_additional_id': {
'udf.name': 'Owner Additional Id'
},
'owner_additional_properties': {
'udf.name': 'Own... |
return species_obj
MIGRATION_RULES['species']['postsave_actions'] = (MIGRATION_RULES['species']
.get('postsave_actions', [])
+ [create_override])
def mutate_boundary(boundary_obj, boundary_dict):
otm1_fields ... | override = ITreeCodeOverride(
instance_species_id=species_obj.pk,
region=ITreeRegion.objects.get(code=region),
itree_code=species_dict['fields']['itree_code'])
override.save_with_user(User.system_user()) | conditional_block |
philadelphia.py | from otm1_migrator.migration_rules.standard_otm1 import MIGRATION_RULES
from treemap.models import ITreeCodeOverride, ITreeRegion, User
UDFS = {
'plot': {
'owner_additional_id': {
'udf.name': 'Owner Additional Id'
},
'owner_additional_properties': {
'udf.name': 'Own... | (species_obj, species_dict):
for region in ['NoEastXXX', 'PiedmtCLT']:
override = ITreeCodeOverride(
instance_species_id=species_obj.pk,
region=ITreeRegion.objects.get(code=region),
itree_code=species_dict['fields']['itree_code'])
override.save_with_user(User.syst... | create_override | identifier_name |
philadelphia.py | from otm1_migrator.migration_rules.standard_otm1 import MIGRATION_RULES
from treemap.models import ITreeCodeOverride, ITreeRegion, User
UDFS = {
'plot': {
'owner_additional_id': {
'udf.name': 'Owner Additional Id'
},
'owner_additional_properties': {
'udf.name': 'Own... | 'Burlington': 4,
'Camden': 5,
'Chester': 6,
'Delaware': 7,
'Gloucester': 8,
'Kent': 9,
'Mercer': 10,
'Montgomery': 11,
'New Castle': 12,
'Salem': 13,
'Sussex': 14,
}
def create_override(species_obj, species_dict):
for region in ['NoEastXXX', 'PiedmtCLT']:
overri... | SORT_ORDER_INDEX = {
'Bucks': 3, | random_line_split |
philadelphia.py | from otm1_migrator.migration_rules.standard_otm1 import MIGRATION_RULES
from treemap.models import ITreeCodeOverride, ITreeRegion, User
UDFS = {
'plot': {
'owner_additional_id': {
'udf.name': 'Owner Additional Id'
},
'owner_additional_properties': {
'udf.name': 'Own... |
MIGRATION_RULES['species']['postsave_actions'] = (MIGRATION_RULES['species']
.get('postsave_actions', [])
+ [create_override])
def mutate_boundary(boundary_obj, boundary_dict):
otm1_fields = boundary_dict.get('fi... | for region in ['NoEastXXX', 'PiedmtCLT']:
override = ITreeCodeOverride(
instance_species_id=species_obj.pk,
region=ITreeRegion.objects.get(code=region),
itree_code=species_dict['fields']['itree_code'])
override.save_with_user(User.system_user())
return species_obj | identifier_body |
bulkimport_users_common.py | import re
from crispy_forms import layout
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import gettext_lazy
from cradmin_l... | css_class='cradmin-globalfields cradmin-legacy-formfield-label-sr-only')
]
def get_buttons(self):
return [
PrimarySubmit('save', self.create_button_label),
]
def get_success_url(self):
return self.request.cradmin_app.reverse_appindexurl()
def im... | random_line_split | |
bulkimport_users_common.py | import re
from crispy_forms import layout
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import gettext_lazy
from cradmin_l... | 'emails': ', '.join(sorted(invalid_emails))
}
)
def __validate_users_blob_usernames(self, usernames):
valid_username_pattern = re.compile(
getattr(settings, 'DEVILRY_VALID_USERNAME_PATTERN', r'^[a-z0... | users_blob_help_text = self.__get_users_blob_help_text()
class UserImportForm(forms.Form):
users_blob = forms.CharField(
widget=forms.Textarea,
required=True,
help_text=users_blob_help_text
)
def __validate_users_blob_emails(s... | identifier_body |
bulkimport_users_common.py | import re
from crispy_forms import layout
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import gettext_lazy
from cradmin_l... |
else:
return gettext_lazy('Type or paste in usernames separated by comma (","), space or one user on each line.')
def __get_users_blob_placeholder(self):
if settings.CRADMIN_LEGACY_USE_EMAIL_AUTH_BACKEND:
return gettext_lazy('jane@example.com\njohn@example.com')
els... | return gettext_lazy('Type or paste in email addresses separated by comma (","), space or one user on each line.') | conditional_block |
bulkimport_users_common.py | import re
from crispy_forms import layout
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import gettext_lazy
from cradmin_l... | (formbase.FormView):
users_blob_split_pattern = re.compile(r'[,;\s]+')
create_button_label = gettext_lazy('Save')
template_name = 'devilry_admin/common/abstract-type-in-users.django.html'
def dispatch(self, request, *args, **kwargs):
requestuser_devilryrole = request.cradmin_instance.get_devilr... | AbstractTypeInUsersView | identifier_name |
defaults-tr_TR.js | /*!
* Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2019 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) ro... | }));
//# sourceMappingURL=defaults-tr_TR.js.map | random_line_split | |
defaults-tr_TR.js | /*!
* Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2019 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) ro... | else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Hiçbiri seçilmedi',
noneResultsText: 'Hiçbir sonuç bulunamadı {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} öğe seçil... | {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} | conditional_block |
escp.py | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software F... | (self):
self._command(CMD_INIT)
def form_feed(self):
self._command(CMD_FORM_FEED)
def set_vertical_position(self, position):
args = struct.pack('b', position)
self._command('J', *args)
def test():
printer = EscPPrinter('/dev/lp0')
printer.send(
'Lorem ipsum do... | done | identifier_name |
escp.py | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software F... |
def set_proportional(self, proportional):
self._command(CMD_PROPORTIONAL, proportional)
def done(self):
self._command(CMD_INIT)
def form_feed(self):
self._command(CMD_FORM_FEED)
def set_vertical_position(self, position):
args = struct.pack('b', position)
self... | self._command(CMD_PRINT_QUALITY, QUALITY_DRAFT) | identifier_body |
escp.py | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software F... |
chars += v
cmd = '%s%s' % (ESC, chars)
self.send(cmd)
def send(self, data):
self.fp.write(data)
self.fp.flush()
def set_draft_mode(self):
self._command(CMD_PRINT_QUALITY, QUALITY_DRAFT)
def set_proportional(self, proportional):
self._command(C... | v = arg | conditional_block |
escp.py | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software F... | # Documentation references:
#
# http://en.wikipedia.org/wiki/ESC/P
# http://www.epson.co.uk/support/manuals/pdf/ESCP/Part_1.pdf
# http://www.epson.co.uk/support/manuals/pdf/ESCP/Part_2.pdf
#
""" Driver for EPSON Esc/P and Esc/P2 printers. """
import struct
ESC = '\x1b'
CMD_INIT = '@'
CMD_PRINT_QUALITY = 'x'
CM... | random_line_split | |
Simple_Ball.ts | import * as R from "ramda";
import {UI_Ball} from "./Simple_UI";
import {CanvasWidth, CanvasHeight } from "../../main/Main";
import {Stream, Transaction, CellLoop} from "sodiumjs";
import { SelfDisposingContainer } from "../../../lib/display/SelfDisposingContainer";
const SPEED = 10;
const RADIUS = 50;
interface Mot... | () {
this.unlistener();
}
} | dispose | identifier_name |
Simple_Ball.ts | import * as R from "ramda";
import {UI_Ball} from "./Simple_UI";
import {CanvasWidth, CanvasHeight } from "../../main/Main";
import {Stream, Transaction, CellLoop} from "sodiumjs";
import { SelfDisposingContainer } from "../../../lib/display/SelfDisposingContainer";
const SPEED = 10;
const RADIUS = 50;
interface Mot... |
} | {
this.unlistener();
} | identifier_body |
Simple_Ball.ts | import * as R from "ramda";
import {UI_Ball} from "./Simple_UI";
import {CanvasWidth, CanvasHeight } from "../../main/Main";
import {Stream, Transaction, CellLoop} from "sodiumjs";
import { SelfDisposingContainer } from "../../../lib/display/SelfDisposingContainer";
const SPEED = 10;
const RADIUS = 50;
interface Mot... |
return motion;
}
dispose() {
this.unlistener();
}
} | {
motion.v *= -1;
} | conditional_block |
Simple_Ball.ts | import * as R from "ramda";
import {UI_Ball} from "./Simple_UI";
import {CanvasWidth, CanvasHeight } from "../../main/Main";
import {Stream, Transaction, CellLoop} from "sodiumjs";
import { SelfDisposingContainer } from "../../../lib/display/SelfDisposingContainer";
const SPEED = 10;
const RADIUS = 50;
interface Mot... | const xMin = RADIUS;
const xMax = CanvasWidth - RADIUS;
const xUpdate = R.clamp(xMin, xMax, _motion.x + dt * _motion.v);
const motion = R.set(R.lensProp("x"), xUpdate, _motion);
if(motion.x == xMin || motion.x == xMax) {
motion.v *= -1;
}
ret... | }
getMotion(dt:number, _motion:Motion):Motion { | random_line_split |
rdfFB.py | ","https://www.facebook.com/groups/partidopiratabrasil/permalink/10151409024509317/"),
("DemocraciaPura06042013.gdf","DemocraciaPura06042013_interactions.gdf",0,"democraciapura","https://www.facebook.com/groups/democraciapura/permalink/310907215704321/"),
("ComputerArt10032013.gdf","ComputerArt10032013_interactions.gdf... | S.fb.triplifyGDF(dpath=dpath,
fname=fnames[0],
fnamei=fnames[1],
fpath=fpath,
scriptpath=scriptpath,
uid=fnames[2],
sid=fnames[3],
fb_link=fnames[4],
eg... | conditional_block | |
rdfFB.py | ://www.facebook.com/groups/democraciapura/permalink/310907215704321/"),
("ComputerArt10032013.gdf","ComputerArt10032013_interactions.gdf",0,"computerart","https://www.facebook.com/groups/computerart/permalink/259389137529870/"),
("RedeTranzmidias02032013.gdf","RedeTranzmidias02032013_interactions.gdf","318333384951196"... | #eurl="http://200.144.255.210:8082/dsfoo"
#path="./publishing/fb2/{}_fb/rdf/".format(fnames[0].split(".")[0])
#P.utils.testRdfs(path,eurl)
# write to the info, meta or discovery graph about the graphs created | random_line_split | |
FindProjection.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************... | (self):
super().__init__()
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
self.tr('Input layer')))
extent_parameter = QgsProcessingParameterExtent(self.TARGET_AREA,
... | __init__ | identifier_name |
FindProjection.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************... | QgsCoordinateTransform,
QgsCoordinateTransformContext,
QgsWkbTypes,
QgsProcessingException,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterExtent,
... | QgsCoordinateReferenceSystem, | random_line_split |
FindProjection.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************... |
def displayName(self):
return self.tr('Find projection')
def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(parameters, self.INPUT, context)
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INP... | return 'findprojection' | identifier_body |
FindProjection.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
FindProjection.py
-----------------
Date : February 2017
Copyright : (C) 2017 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
*****************... |
except:
continue
feedback.setProgress(int(current * total))
if found_results == 0:
feedback.reportError(self.tr('No matching projections found'))
return {self.OUTPUT: dest_id}
| feedback.pushInfo(self.tr('Found candidate CRS: {}').format(candidate_crs.authid()))
f = QgsFeature(fields)
f.setAttributes([candidate_crs.authid()])
sink.addFeature(f, QgsFeatureSink.FastInsert)
found_results += 1 | conditional_block |
index.d.ts | // Type definitions for koa-bodyparser v3.x
// Project: https://github.com/koajs/bodyparser
// Definitions by: Jerry Chin <https://github.com/hellopao/>
// Definitions: https://github.com/hellopao/DefinitelyTyped
/* =================== USAGE ===================
import bodyParser = require("koa-bodyparser");
v... |
/**
* support custom error handle
*/
onerror?: (err: Error, ctx: Koa.Context) => void;
}): Koa.Middleware;
declare namespace bodyParser { }
export = bodyParser; | random_line_split | |
regularExpressions.js | module.exports = {
"url": /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u... | }; | "time": /^(([0-1]{0,1}[0-9])|(2[0-3])):[0-5]{0,1}[0-9]$/ | random_line_split |
role-detail.component.ts | import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Role } from '../role';
import { RoleService ... | private roleService: RoleService,
private formBuilder: FormBuilder,
route: ActivatedRoute
) {
this.subscription = route.params.subscribe(params => {
if (params.id === 'new') {
this.form = this.buildForm();
} else {
this.roleService.getById(params.id).subscribe(role => {
... | private router: Router, | random_line_split |
role-detail.component.ts | import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Role } from '../role';
import { RoleService ... | (role?: Role): FormGroup {
return this.formBuilder.group({
id: [role ? role.id : undefined],
name: [role ? role.name : '', Validators.required],
concurrencyStamp: [role ? role.concurrencyStamp : undefined]
});
}
}
| buildForm | identifier_name |
role-detail.component.ts | import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Role } from '../role';
import { RoleService ... |
save() {
let request: Observable<Role>;
if (!this.form.value.id) {
request = this.roleService.create(this.form.value);
} else {
request = this.roleService.update(this.form.value);
}
request.subscribe(() => {
this.router.navigate(['/roles']);
});
}
private buildForm(r... | {
this.subscription = route.params.subscribe(params => {
if (params.id === 'new') {
this.form = this.buildForm();
} else {
this.roleService.getById(params.id).subscribe(role => {
this.form = this.buildForm(role);
});
}
});
} | identifier_body |
role-detail.component.ts | import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Role } from '../role';
import { RoleService ... | else {
request = this.roleService.update(this.form.value);
}
request.subscribe(() => {
this.router.navigate(['/roles']);
});
}
private buildForm(role?: Role): FormGroup {
return this.formBuilder.group({
id: [role ? role.id : undefined],
name: [role ? role.name : '', Valida... | {
request = this.roleService.create(this.form.value);
} | conditional_block |
unboxed-closures-all-traits.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 z: int = 7;
assert_eq!(a(move |x: int, y| x + y + z), 10);
assert_eq!(b(move |x: int, y| x + y + z), 14);
assert_eq!(c(move |x: int, y| x + y + z), 18);
} | fn c<F:FnOnce(int, int) -> int>(f: F) -> int {
f(5, 6)
} | random_line_split |
unboxed-closures-all-traits.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 ... | <F:FnMut(int, int) -> int>(mut f: F) -> int {
f(3, 4)
}
fn c<F:FnOnce(int, int) -> int>(f: F) -> int {
f(5, 6)
}
fn main() {
let z: int = 7;
assert_eq!(a(move |x: int, y| x + y + z), 10);
assert_eq!(b(move |x: int, y| x + y + z), 14);
assert_eq!(c(move |x: int, y| x + y + z), 18);
}
| b | identifier_name |
unboxed-closures-all-traits.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 c<F:FnOnce(int, int) -> int>(f: F) -> int {
f(5, 6)
}
fn main() {
let z: int = 7;
assert_eq!(a(move |x: int, y| x + y + z), 10);
assert_eq!(b(move |x: int, y| x + y + z), 14);
assert_eq!(c(move |x: int, y| x + y + z), 18);
}
| {
f(3, 4)
} | identifier_body |
models.py | # -*- coding: utf-8 -*-
import os.path
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings as django_settings
from django.db.models import signals
from know.plugins.attachments import settings
from know import managers
from know.models.pluginbase import ... |
filename = self.file.name.split("/")[-1]
return ".".join(filename.split(".")[:-1])
def get_size(self):
"""Used to retrieve the file size and not cause exceptions."""
try:
return self.file.size
except OSError:
return None
except ValueError:
... | return None | conditional_block |
models.py | # -*- coding: utf-8 -*-
import os.path
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings as django_settings
from django.db.models import signals
from know.plugins.attachments import settings
from know import managers
from know.models.pluginbase import ... |
def can_delete(self, user):
return self.can_write(user=user)
class Meta:
verbose_name = _(u'attachment')
verbose_name_plural = _(u'attachments')
app_label = settings.APP_LABEL
def __unicode__(self):
return "%s: %s" % (self.article.current_revision.title, self.orig... | user = kwargs.get('user', None)
if not settings.ANONYMOUS and (not user or user.is_anonymous()):
return False
return ReusablePlugin.can_write(self, **kwargs) | identifier_body |
models.py | # -*- coding: utf-8 -*-
import os.path
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings as django_settings
from django.db.models import signals
from know.plugins.attachments import settings
from know import managers
from know.models.pluginbase import ... | return None
except ValueError:
return None
def save(self, *args, **kwargs):
if (not self.id and
not self.previous_revision and
self.attachment and
self.attachment.current_revision and
self.attachment.current_revision != self):
... | try:
return self.file.size
except OSError: | random_line_split |
models.py | # -*- coding: utf-8 -*-
import os.path
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings as django_settings
from django.db.models import signals
from know.plugins.attachments import settings
from know import managers
from know.models.pluginbase import ... | (self, user):
return self.can_write(user=user)
class Meta:
verbose_name = _(u'attachment')
verbose_name_plural = _(u'attachments')
app_label = settings.APP_LABEL
def __unicode__(self):
return "%s: %s" % (self.article.current_revision.title, self.original_filename)
def... | can_delete | identifier_name |
shared_util.py | # Copyright 2016 The TensorFlow 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 applicab... | rev_inputs = tf.reverse(inputs, 1)
split_rev_inputs = [tf.reshape(t, [hps.batch_size, -1])
for t in tf.split(1, hps.num_art_steps, rev_inputs)]
(_, _, _, _, _, _, h) = block_lstm(
tf.to_int64(hps.num_art_steps),
split_rev_inputs,
w,
... | with tf.variable_scope("birnn_fwd_%d" % j):
w = tf.get_variable(
"w", [hps.word_embedding_size + hps.hidden_size, 4 * hps.hidden_size])
b = tf.get_variable("b", [4 * hps.hidden_size])
split_inputs = [tf.reshape(t, [hps.batch_size, -1])
for t in tf.split(1, hps.num_art_s... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.