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 |
|---|---|---|---|---|
parsemode.py | #!/usr/bin/env python
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public L... |
class ParseMode(object):
"""This object represents a Telegram Message Parse Modes."""
MARKDOWN = 'Markdown'
HTML = 'HTML' | # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram
Message Parse Modes.""" | random_line_split |
Example.android.js | identifier: 'Test beacons 1',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 1,
// no minor provided: will detect all minors
};
const region2 = {
identifier: 'Test beacons 2',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 2,
// no minor provided: will detect all minors
};
/**
* Monitors b... | }
);
DeviceEventEmitter.addListener(
'beaconsDidUpdate',
({ beacons: updatedBeacons, region }) => {
console.log('beaconsDidUpdate', updatedBeacons, region);
const { beacons } = this.state;
updatedBeacons.forEach(updatedBeacon => {
const index = beacons.findIn... | return result;
}
}, [])
}); | random_line_split |
Example.android.js | identifier: 'Test beacons 1',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 1,
// no minor provided: will detect all minors
};
const region2 = {
identifier: 'Test beacons 2',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 2,
// no minor provided: will detect all minors
};
/**
* Monitors b... | extends Component {
state = {
scanning: false,
beacons: [],
eddystones: [],
statusText: null,
};
componentDidMount() {
// Initialization, configuration and adding of beacon regions
connect(
'MY_KONTAKTIO_API_KEY',
[IBEACON, EDDYSTONE],
)
.then(() => configure({
... | IBeaconExample | identifier_name |
Example.android.js | : 'Test beacons 1',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 1,
// no minor provided: will detect all minors
};
const region2 = {
identifier: 'Test beacons 2',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 2,
// no minor provided: will detect all minors
};
/**
* Monitors beacons in t... |
// Beacon listeners
DeviceEventEmitter.addListener(
'beaconDidAppear',
({ beacon: newBeacon, region }) => {
console.log('beaconDidAppear', newBeacon, region);
this.setState({
beacons: this.state.beacons.concat(newBeacon)
});
}
);
DeviceEventEmitter.a... | {
// Initialization, configuration and adding of beacon regions
connect(
'MY_KONTAKTIO_API_KEY',
[IBEACON, EDDYSTONE],
)
.then(() => configure({
scanMode: scanMode.BALANCED,
scanPeriod: scanPeriod.create({
activePeriod: 6000,
passivePeriod: 20000,
... | identifier_body |
chordangle.rs | ::from(&a)
}
}
impl<'a> From<&'a Deg> for ChordAngle {
fn from(a: &'a Deg) -> Self {
Angle::from(a).into()
}
}
impl From<Deg> for ChordAngle {
fn from(a: Deg) -> Self {
Angle::from(&a).into()
}
}
impl<'a> From<&'a ChordAngle> for Angle {
/// converts this ChordAngle to an Angle... | assert_eq!(less_than, ca1 < ca2);
assert_eq!(equal, ca1 == ca2);
}
| identifier_body | |
chordangle.rs | 5 * a.rad().min(PI)).sin();
ChordAngle(l * l)
}
}
}
impl From<Angle> for ChordAngle {
/// returns a ChordAngle from the given Angle.
fn from(a: Angle) -> Self {
ChordAngle::from(&a)
}
}
impl<'a> From<&'a Deg> for ChordAngle {
fn from(a: &'a Deg) -> Self {
Angle::... | Deg) -> Self {
Angle::from(&a).into()
}
}
impl<'a> From<&'a ChordAngle> for Angle {
/// converts this ChordAngle to an Angle.
fn from(ca: &'a ChordAngle) -> Self {
if ca.0 < 0. {
Rad(-1.).into()
} else if ca.is_infinite() {
Angle::inf()
} else {
... | (a: | identifier_name |
chordangle.rs | 5 * a.rad().min(PI)).sin();
ChordAngle(l * l)
}
}
}
impl From<Angle> for ChordAngle {
/// returns a ChordAngle from the given Angle.
fn from(a: Angle) -> Self {
ChordAngle::from(&a)
}
}
impl<'a> From<&'a Deg> for ChordAngle {
fn from(a: &'a Deg) -> Self {
Angle::... | Angle::from(&a).into()
}
}
impl<'a> From<&'a ChordAngle> for Angle {
/// converts this ChordAngle to an Angle.
fn from(ca: &'a ChordAngle) -> Self {
if ca.0 < 0. {
Rad(-1.).into()
} else if ca.is_infinite() {
Angle::inf()
} else {
Rad(2. *... | fn from(a: Deg) -> Self { | random_line_split |
chordangle.rs | e if a.is_infinite() {
ChordAngle::inf()
} else {
let l = 2. * (0.5 * a.rad().min(PI)).sin();
ChordAngle(l * l)
}
}
}
impl From<Angle> for ChordAngle {
/// returns a ChordAngle from the given Angle.
fn from(a: Angle) -> Self {
ChordAngle::from(&a)
... | NEGATIVE
} els | conditional_block | |
fixer_util.py | # import is in a one-liner
c = context
while c.next_sibling is not None:
yield c.next_sibling
c = c.next_sibling
context = context.parent
# Can't chain one-liners on one line, so that takes care of that.
p = context.parent
if p is None:
retur... | node = node.children[0]
assert node.type == token.NAME
return set([node.value]) | conditional_block | |
fixer_util.py |
def Minus(prefix=None):
return Leaf(token.MINUS, u'-', prefix=prefix)
def commatize(leafs):
u"""
Accepts/turns: (Name, Name, ..., Name, Name)
Returns/into: (Name, Comma, Name, Comma, ..., Name, Comma, Name)
"""
new_leafs = []
for leaf in leafs:
new_leafs.append(leaf)
new_... | return Leaf(token.DOUBLESTAR, u'**', prefix=prefix) | identifier_body | |
fixer_util.py | u"""
Accepts/turns: (Name, Name, ..., Name, Name)
Returns/into: (Name, Comma, Name, Comma, ..., Name, Comma, Name)
"""
new_leafs = []
for leaf in leafs:
new_leafs.append(leaf)
new_leafs.append(Comma())
del new_leafs[-1]
return new_leafs
def indentation(node):
u"""
... | def commatize(leafs): | random_line_split | |
fixer_util.py |
def indentation_step(node):
u"""
Dirty little trick to get the difference between each indentation level
Implemented by finding the shortest indentation string
(technically, the "least" of all of the indentation strings, but
tabs and spaces mixed won't get this far, so those are synonymous.)
"... | (package, name_to_import, node):
"""Works like `does_tree_import` but adds an import statement at the
top if it was not imported (but below any __future__ imports).
Based on lib2to3.fixer_util.touch_import()
Calling this multiple times adds the imports in reverse order.
Also adds "standar... | touch_import_top | identifier_name |
action_batcher.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// 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 wi... | self.actions.insert(entity_id, Vec::new());
}
self.actions.get_mut(&entity_id).unwrap().push(action);
}
pub fn consume_actions(&mut self) -> HashMap<Index, Vec<Action>> {
let mut consumed = HashMap::new();
mem::swap(&mut consumed, &mut self.actions);
consumed... | if !self.actions.contains_key(&entity_id) { | random_line_split |
action_batcher.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// 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 wi... | {
actions: HashMap<Index, Vec<Action>>,
}
impl ActionBatcher {
pub fn new() -> ActionBatcher {
ActionBatcher { actions: HashMap::new() }
}
pub fn queue_for_entity(&mut self, entity_id: Index, action: Action) {
if !self.actions.contains_key(&entity_id) {
self.actions.insert... | ActionBatcher | identifier_name |
action_batcher.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// 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 wi... |
self.actions.get_mut(&entity_id).unwrap().push(action);
}
pub fn consume_actions(&mut self) -> HashMap<Index, Vec<Action>> {
let mut consumed = HashMap::new();
mem::swap(&mut consumed, &mut self.actions);
consumed
}
}
| {
self.actions.insert(entity_id, Vec::new());
} | conditional_block |
lib.rs | that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]
#![allow(non_snake_case)]
#![deny(unsafe_code)]
#![feature(custom_derive, plugin)]
#![plugin(serde_macros, plugins)]
#[macro_use]
extern crate bitflags;
extern crate hyper;
ext... | {
pub headers: Option<Headers>,
pub status: Option<RawStatus>,
pub body: Option<Vec<u8>>,
pub pipeline_id: PipelineId,
}
pub enum NetworkEvent {
HttpRequest(HttpRequest),
HttpResponse(HttpResponse),
}
impl TimelineMarker {
pub fn start(name: String) -> StartedTimelineMarker {
Star... | HttpResponse | identifier_name |
lib.rs | that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]
#![allow(non_snake_case)]
#![deny(unsafe_code)]
#![feature(custom_derive, plugin)]
#![plugin(serde_macros, plugins)]
#[macro_use]
extern crate bitflags;
extern crate hyper;
ext... | GetDocumentElement(PipelineId, IpcSender<NodeInfo>),
/// Retrieve the details of the child nodes of the given node in the given pipeline.
GetChildren(PipelineId, String, IpcSender<Vec<NodeInfo>>),
/// Retrieve the computed layout properties of the given node in the given pipeline.
GetLayout(Pipeline... | random_line_split | |
headers.py | import collections
import itertools
from marnadi.utils import cached_property, CachedDescriptor
class Header(collections.Mapping):
__slots__ = 'value', 'params'
def __init__(self, *value, **params):
assert len(value) == 1
self.value = value[0]
self.params = params
def __hash__(... |
def __eq__(self, other):
return self.value == other
def __ne__(self, other):
return self.value != other
def __str__(self):
return self.stringify()
def __bytes__(self):
value = self.stringify()
if isinstance(value, bytes): # python 2.x
return valu... | return hash(self.value) | identifier_body |
headers.py | import collections
import itertools
from marnadi.utils import cached_property, CachedDescriptor
class Header(collections.Mapping):
__slots__ = 'value', 'params'
def __init__(self, *value, **params):
assert len(value) == 1
self.value = value[0]
self.params = params
def __hash__(... |
def setdefault(self, header, default=None):
return self._headers.setdefault(header.title(), [default])
def clear(self, *headers):
if headers:
for header in headers:
try:
del self[header]
except KeyError:
pass
... | self.append(header) | conditional_block |
headers.py | import collections
import itertools
from marnadi.utils import cached_property, CachedDescriptor
class Header(collections.Mapping):
__slots__ = 'value', 'params'
def __init__(self, *value, **params):
assert len(value) == 1
self.value = value[0]
self.params = params
def __hash__(... | (self):
value = self.stringify()
if isinstance(value, bytes): # python 2.x
return value
return value.encode(encoding='latin1')
def __getitem__(self, item):
return self.params[item]
def __iter__(self):
return iter(self.params)
def __len__(self):
... | __bytes__ | identifier_name |
headers.py | import collections
import itertools
from marnadi.utils import cached_property, CachedDescriptor
class Header(collections.Mapping):
__slots__ = 'value', 'params'
def __init__(self, *value, **params):
assert len(value) == 1
self.value = value[0]
self.params = params
def __hash__(... |
def __len__(self):
return len(self.params)
def __bool__(self):
return True
def __nonzero__(self):
return self.__bool__()
def stringify(self):
if not self.params:
return str(self.value)
return '{value}; {params}'.format(
value=self.value... | return iter(self.params) | random_line_split |
94-mobile_actuator.js | /**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... |
});
this.on("close", function() {
// Called when the node is shutdown - eg on redeploy.
// Allows ports to be closed, connections dropped etc.
// eg: node.client.disconnect();
});
}
RED.nodes.registerType("mobile actuator",mobileactuatorNode);
}
| {
msg.payload = msg.payload.substr(2)
node.send(msg);
} | conditional_block |
94-mobile_actuator.js | /**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... | // ... this message will get sent at startup so you may not see it in a debug node.
//this.send(msg);
// respond to inputs....
this.on('input', function (msg) {
//node.warn("I saw a payload: "+msg.payload);
// in this example just send it straight on... should pr... | {
// Create a RED node
RED.nodes.createNode(this,n);
// Store local copies of the node configuration (as defined in the .html)
this.topic = n.topic;
this.mobile_type = n.mobile_type;
this.mobile_port = n.mobile_port;
// copy "this" object in case we need it in context of cal... | identifier_body |
94-mobile_actuator.js | /**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... | (n) {
// Create a RED node
RED.nodes.createNode(this,n);
// Store local copies of the node configuration (as defined in the .html)
this.topic = n.topic;
this.mobile_type = n.mobile_type;
this.mobile_port = n.mobile_port;
// copy "this" object in case we need it in context of... | mobileactuatorNode | identifier_name |
mod.rs | use crate::debug_protocol::Expressions;
#[macro_use]
pub mod prelude {
use nom::{
character::complete::{digit1, space0},
error::ParseError,
sequence::delimited,
IResult,
};
pub type Span<'a> = &'a str;
pub fn ws<'a, F: 'a, O, E: ParseError<Span<'a>>>(parser: F) -> impl ... | #[derive(Debug)]
pub enum PreparedExpression {
Native(String),
Simple(String),
Python(String),
}
// Parse expression type and preprocess it.
pub fn prepare(expression: &str, default_type: Expressions) -> PreparedExpression {
let (expr, ty) = get_expression_type(expression, default_type);
match ty {... | random_line_split | |
mod.rs | use crate::debug_protocol::Expressions;
#[macro_use]
pub mod prelude {
use nom::{
character::complete::{digit1, space0},
error::ParseError,
sequence::delimited,
IResult,
};
pub type Span<'a> = &'a str;
pub fn ws<'a, F: 'a, O, E: ParseError<Span<'a>>>(parser: F) -> impl ... | <'a>(expr: &'a str, default_type: Expressions) -> (&'a str, Expressions) {
if expr.starts_with("/nat ") {
(&expr[5..], Expressions::Native)
} else if expr.starts_with("/py ") {
(&expr[4..], Expressions::Python)
} else if expr.starts_with("/se ") {
(&expr[4..], Expressions::Simple)
... | get_expression_type | identifier_name |
veteran_imp_colonel.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def | (core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('veteran_imperial_colonel')
mobileTemplate.setLevel(60)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale... | addTemplate | identifier_name |
veteran_imp_colonel.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def addTemplate(co... | mobileTemplate.setSocialGroup("imperial")
mobileTemplate.setAssistRange(10)
mobileTemplate.setStalker(False)
mobileTemplate.setFaction("imperial")
mobileTemplate.setFactionStatus(FactionStatus.Combatant)
templates = Vector()
templates.add('object/mobile/shared_dressed_imperial_colonel_m.iff')
mobileTemplate... | random_line_split | |
veteran_imp_colonel.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def addTemplate(co... | weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/ranged/carbine/shared_carbine_e11.iff', WeaponType.CARBINE, 1.0, 15, 'energy')
weaponTemplates.add(weapontemplate)
mobileTemplate.setWeaponTemplateVector(weaponTemplates)
attacks = Vector()
mobileTemplate.setDefaultAttack('rangedShot')
m... | mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('veteran_imperial_colonel')
mobileTemplate.setLevel(60)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale(1)
mobi... | identifier_body |
liste.py | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | tableau = Tableau()
tableau.ajouter_colonne("Nom")
tableau.ajouter_colonne("Poste")
tableau.ajouter_colonne("Affectation")
for matelot, nom_poste in matelots:
nom = matelot.nom
nom_poste = nom_poste.capitalize()
titre = "Aucune"
if hasattr... | ge << "|err|Votre équipage ne comprend aucun matelot.|ff|"
return
| conditional_block |
liste.py | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | , personnage, dic_masques):
"""Interprétation du paramètre"""
salle = personnage.salle
if not hasattr(salle, "navire"):
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
equipage = navire.equipage
if not navire.a... | preter(self | identifier_name |
liste.py | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | return
tableau = Tableau()
tableau.ajouter_colonne("Nom")
tableau.ajouter_colonne("Poste")
tableau.ajouter_colonne("Affectation")
for matelot, nom_poste in matelots:
nom = matelot.nom
nom_poste = nom_poste.capitalize()
titre = "Auc... | terprétation du paramètre"""
salle = personnage.salle
if not hasattr(salle, "navire"):
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
equipage = navire.equipage
if not navire.a_le_droit(personnage, "officier"):
... | identifier_body |
liste.py | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | matelots = tuple((m, m.nom_poste) for m in \
equipage.matelots.values())
matelots += tuple(equipage.joueurs.items())
matelots = sorted(matelots, \
key=lambda couple: ORDRE.index(couple[1]), reverse=True)
if len(matelots) == 0:
personnage << "|e... | "navire.|ff|"
return
| random_line_split |
twPreCodeManager.js | -mce-selected]{outline:0!important;box-shadow:1px 2px 3px 3px #3B3A7D!important}";
if(editor.getParam("inline")){
if(!$("#twPreCodeManagerPREcss").length){
$('head').append('<style id="twPreCodeManagerPREcss">'+twPreCodeManagerPREcss+'</style>')
}
}
else{
var thisBody = $("#"+editor.id+"_ifr").c... | node.setAttribute("class", $('.mce-preLanguageTextBox').val());
if(node.firstChild){
node.firstChild.setAttribute("class", $('.mce-codeLanguageTextBox').val());
node.firstChild.innerHTML = code;
}
else{
node.innerHTML = code;
}
editor.selection.select(node);
... | random_line_split | |
twPreCodeManager.js | ce-selected]{outline:0!important;box-shadow:1px 2px 3px 3px #3B3A7D!important}";
if(editor.getParam("inline")){
if(!$("#twPreCodeManagerPREcss").length){
$('head').append('<style id="twPreCodeManagerPREcss">'+twPreCodeManagerPREcss+'</style>')
}
}
else{
var thisBody = $("#"+editor.id+"_ifr").con... |
return {
open: function(editor) {
tinymce.activeEditor.windowManager.open({
title: '<pre><code> Manager',
width : twPreCodeManagerWidth,
height : twPreCodeManagerHeight,
layout: 'fit',
body: [
{
type: 'textbox',
tooltip: 'Enter classes directly and/or use preselects',
... | {
var matches, node = getSelectedCodeSample(editor);
if (node && node.nodeName =='CODE' && node.parentNode.nodeName !=='PRE') {
matches = node.className;
return matches ? matches : '';
}
else if (node && node.firstChild) {
matches = node.firstChild.className;
return matches ? matches : '';
}
ret... | identifier_body |
twPreCodeManager.js | ce-selected]{outline:0!important;box-shadow:1px 2px 3px 3px #3B3A7D!important}";
if(editor.getParam("inline")){
if(!$("#twPreCodeManagerPREcss").length){
$('head').append('<style id="twPreCodeManagerPREcss">'+twPreCodeManagerPREcss+'</style>')
}
}
else{
var thisBody = $("#"+editor.id+"_ifr").con... |
}
},
{
type: 'textbox',
tooltip: 'Enter classes directly and/or use preselects',
label: 'CODE classes',
maxWidth: 200,
value: getCodeCurrentLanguage(editor),
classes: 'codeLanguageTextBox',
onPostRender:function(){
var node = tinymce.activeEditor.selec... | {
$('.mce-preLanguageTextBox').parent().parent().hide();
// $('.mce-preLanguageTextBox').attr("disabled", 1);
} | conditional_block |
twPreCodeManager.js | ce-selected]{outline:0!important;box-shadow:1px 2px 3px 3px #3B3A7D!important}";
if(editor.getParam("inline")){
if(!$("#twPreCodeManagerPREcss").length){
$('head').append('<style id="twPreCodeManagerPREcss">'+twPreCodeManagerPREcss+'</style>')
}
}
else{
var thisBody = $("#"+editor.id+"_ifr").con... | (editor) {
var node = tinymce.activeEditor.selection.getNode();
if (node && node.nodeName =='CODE' && node.parentNode.nodeName !=='PRE' || node.nodeName == 'PRE') {
return node;
}
return null;
}
function getCurrentCode(editor) {
var node = getSelectedCodeSample(editor);
if (node) {
if (node.... | getSelectedCodeSample | identifier_name |
size.js | import store from "@/store";
import { modV } from "@/modv";
import Vue from "vue";
const state = {
width: 200,
height: 200,
previewX: 0,
previewY: 0,
previewWidth: 0,
previewHeight: 0
};
// getters
const getters = {
width: state => state.width,
height: state => state.height,
area: state => state.wid... |
}
commit("setDimensions", { width: widthShadow, height: heightShadow });
let dpr = window.devicePixelRatio || 1;
if (!store.getters["user/useRetina"]) dpr = 1;
modV.resize(state.width, state.height, dpr);
store.dispatch("modVModules/resizeActive");
store.dispatch("layers/re... | {
heightShadow = widthShadow;
} | conditional_block |
size.js | import store from "@/store";
import { modV } from "@/modv";
import Vue from "vue";
const state = {
width: 200,
height: 200,
previewX: 0,
previewY: 0,
previewWidth: 0,
previewHeight: 0
};
// getters
const getters = {
width: state => state.width,
height: state => state.height,
area: state => state.wid... | })
};
// actions
const actions = {
updateSize({ state }) {
store.dispatch("size/setDimensions", {
width: state.width,
height: state.height
});
},
setDimensions({ commit, state }, { width, height }) {
let widthShadow = width;
let heightShadow = height;
const largestWindowReferen... | width: state.previewWidth,
height: state.previewHeight,
x: state.previewX,
y: state.previewY | random_line_split |
size.js | import store from "@/store";
import { modV } from "@/modv";
import Vue from "vue";
const state = {
width: 200,
height: 200,
previewX: 0,
previewY: 0,
previewWidth: 0,
previewHeight: 0
};
// getters
const getters = {
width: state => state.width,
height: state => state.height,
area: state => state.wid... | ,
setDimensions(state, { width, height }) {
Vue.set(state, "width", width);
Vue.set(state, "height", height);
},
setPreviewValues(state, { width, height, x, y }) {
Vue.set(state, "previewWidth", width);
Vue.set(state, "previewHeight", height);
Vue.set(state, "previewX", x);
Vue.set(state, ... | {
Vue.set(state, "height", height);
} | identifier_body |
size.js | import store from "@/store";
import { modV } from "@/modv";
import Vue from "vue";
const state = {
width: 200,
height: 200,
previewX: 0,
previewY: 0,
previewWidth: 0,
previewHeight: 0
};
// getters
const getters = {
width: state => state.width,
height: state => state.height,
area: state => state.wid... | ({ state }) {
store.dispatch("size/setDimensions", {
width: state.width,
height: state.height
});
},
setDimensions({ commit, state }, { width, height }) {
let widthShadow = width;
let heightShadow = height;
const largestWindowReference = store.getters[
"windows/largestWindowRe... | updateSize | identifier_name |
file.rs | use std::fs::{File, create_dir_all};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use error::{Error, Result};
pub fn read_file<T: AsRef<Path>>(path: T) -> Result<Vec<u8>> {
let mut file = File::open(path)?;
let file_len = file.metadata()?.len();
let mut buf = Vec::wit... | result.push((path.to_owned(), file));
}
}
Ok(result)
}
pub fn write_file(path: &Path, content: &[u8]) -> Result<()> {
create_dir_all(path.to_owned().parent().ok_or(Error::DirNotFound)?)?;
let mut file = File::create(path)?;
file.write_all(content)?;
Ok(())
} | let path = entry.path();
if path.is_file() {
let file = read_file(path)?;
let path = path.strip_prefix(&root)?; | random_line_split |
file.rs | use std::fs::{File, create_dir_all};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use error::{Error, Result};
pub fn | <T: AsRef<Path>>(path: T) -> Result<Vec<u8>> {
let mut file = File::open(path)?;
let file_len = file.metadata()?.len();
let mut buf = Vec::with_capacity(file_len as usize + 1);
file.read_to_end(&mut buf)?;
Ok(buf)
}
pub fn read_all_files<T: AsRef<Path>>(root: T) -> Result<Vec<(PathBuf, Vec<u8>)>> {... | read_file | identifier_name |
file.rs | use std::fs::{File, create_dir_all};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use error::{Error, Result};
pub fn read_file<T: AsRef<Path>>(path: T) -> Result<Vec<u8>> |
pub fn read_all_files<T: AsRef<Path>>(root: T) -> Result<Vec<(PathBuf, Vec<u8>)>> {
let mut result = Vec::new();
for dir_entry in WalkDir::new(&root) {
let entry = dir_entry?;
let path = entry.path();
if path.is_file() {
let file = read_file(path)?;
let path = p... | {
let mut file = File::open(path)?;
let file_len = file.metadata()?.len();
let mut buf = Vec::with_capacity(file_len as usize + 1);
file.read_to_end(&mut buf)?;
Ok(buf)
} | identifier_body |
file.rs | use std::fs::{File, create_dir_all};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use error::{Error, Result};
pub fn read_file<T: AsRef<Path>>(path: T) -> Result<Vec<u8>> {
let mut file = File::open(path)?;
let file_len = file.metadata()?.len();
let mut buf = Vec::wit... |
}
Ok(result)
}
pub fn write_file(path: &Path, content: &[u8]) -> Result<()> {
create_dir_all(path.to_owned().parent().ok_or(Error::DirNotFound)?)?;
let mut file = File::create(path)?;
file.write_all(content)?;
Ok(())
}
| {
let file = read_file(path)?;
let path = path.strip_prefix(&root)?;
result.push((path.to_owned(), file));
} | conditional_block |
radiusrand.py | #!/usr/bin/env python
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Thi... | (self):
for id, node in self.selected.iteritems():
if node.tag == inkex.addNS('path','svg'):
d = node.get('d')
p = cubicsuperpath.parsePath(d)
for subpath in p:
for csp in subpath:
if self.options.end:
... | effect | identifier_name |
radiusrand.py | #!/usr/bin/env python
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Thi... | '''
import random, math, inkex, cubicsuperpath
def randomize((x, y), rx, ry, norm):
if norm:
r = abs(random.normalvariate(0.0,0.5*max(rx, ry)))
else:
r = random.uniform(0.0,max(rx, ry))
a = random.uniform(0.0,2*math.pi)
x += math.cos(a)*rx
y += math.sin(a)*ry
return [x, y]
clas... | GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | random_line_split |
radiusrand.py | #!/usr/bin/env python
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Thi... |
node.set('d',cubicsuperpath.formatPath(p))
if __name__ == '__main__':
e = RadiusRandomize()
e.affect()
# vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99
| if self.options.end:
delta=randomize([0,0], self.options.radiusx, self.options.radiusy, self.options.norm)
csp[0][0]+=delta[0]
csp[0][1]+=delta[1]
csp[1][0]+=delta[0]
csp[1][1]+... | conditional_block |
radiusrand.py | #!/usr/bin/env python
'''
Copyright (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Thi... |
class RadiusRandomize(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
self.OptionParser.add_option("--title")
self.OptionParser.add_option("-x", "--radiusx",
action="store", type="float",
dest="radiusx", default=10.0,
... | if norm:
r = abs(random.normalvariate(0.0,0.5*max(rx, ry)))
else:
r = random.uniform(0.0,max(rx, ry))
a = random.uniform(0.0,2*math.pi)
x += math.cos(a)*rx
y += math.sin(a)*ry
return [x, y] | identifier_body |
_aeqdsk.py | p", 1.0, "toroidal magnetic field at magnetic axis in Tesla"),
("btaxv", 1.0, "vacuum toroidal magnetic field at magnetic axis in Tesla"),
("aaq1", 100.0, "minor radius of q=1 surface in cm, 100 if not found"),
("aaq2", 100.0, "minor radius of q=2 surface in cm, 100 if not found"),
("aaq3", 100.0, "mino... | read | identifier_name | |
_aeqdsk.py | "),
(
"qmerci",
0.0,
"Mercier stability criterion on axial q(0), q(0) > QMERCI for stability",
),
("tavem", 0.0, "average time in ms for magnetic and MSE data"),
# ishot > 91000
# The next section is dependent on the EFIT version
# New version of EFIT on 05/24/97 writes a... | value = next(values)
if isinstance(default, int) and not isinstance(value, int):
# Expecting an integer, but didn't get one
warnings.warn("Expecting an integer for '" + key + "' in aeqdsk file")
break
data[key] = value | conditional_block | |
_aeqdsk.py | 0, "q at plasma boundary"),
("olefs", 0.0, ""),
("orighs", 0.0, "outer gap of external second separatrix in cm"),
("otops", 0.0, "top gap of external second separatrix in cm"),
("sibdry", 1.0, ""),
("areao", 100.0, "cross sectional area in cm2"),
("wplasm", 0.0, ""),
("terror", 0.0, "equilib... | fh.write(" " + fu.f2s(data.get("time", 0.0)) + "\n")
| random_line_split | |
_aeqdsk.py | "top gap of external second separatrix in cm"),
("sibdry", 1.0, ""),
("areao", 100.0, "cross sectional area in cm2"),
("wplasm", 0.0, ""),
("terror", 0.0, "equilibrium convergence error"),
("elongm", 0.0, "elongation at magnetic axis"),
("qqmagx", 0.0, "axial safety factor q(0)"),
("cdflux"... | """
data [dict] - keys are given with documentation in the `fields` list.
Also includes
shot [int] - The shot number
time - in ms
"""
# First line identification string
# Default to date > 1997 since that format includes nsilop etc.
fh.write("{0:11s}\n".format(data.get("heade... | identifier_body | |
main.js | angular.module('app', [])
.controller('sendCtrl', function($scope, $http){
$scope.mail = {
name: "",
phone: "",
email: "",
comment: ""
};
$scope.done = false;
$scope.err = false;
$scope.send = function(){
$http.post('mail.php', $scope.mail).success(function(res){
if(res.code==0){
$scope.done = tr... | };
$scope.done = false;
$scope.err = false;
$scope.send = function(){
$http.post('coti.php', $scope.mail).success(function(res){
console.log(res);
if(res.code==1){
$scope.done = true;
} else {
$scope.err = true;
}
}).error(function(){
$scope.err = true;
console.log("Error");
})
}
}... | email: "",
percen: "" | random_line_split |
main.js |
angular.module('app', [])
.controller('sendCtrl', function($scope, $http){
$scope.mail = {
name: "",
phone: "",
email: "",
comment: ""
};
$scope.done = false;
$scope.err = false;
$scope.send = function(){
$http.post('mail.php', $scope.mail).success(function(res){
if(res.code==0){
$scope.done = t... |
}).error(function(){
$scope.err = true;
console.log("Error");
})
}
}) | {
$scope.err = true;
} | conditional_block |
app.py | # caution: this module was written by a Python novice learning on the fly
# you should not assume this is "good" or idiomatic Python.
# Hackathons are fun.
from flask import Flask, Blueprint, render_template, abort, request, jsonify
from flask.ext.login import LoginManager, login_required
import logging
import json
fr... | app.run(host="0.0.0.0") | conditional_block | |
app.py | # caution: this module was written by a Python novice learning on the fly
# you should not assume this is "good" or idiomatic Python.
# Hackathons are fun.
from flask import Flask, Blueprint, render_template, abort, request, jsonify
from flask.ext.login import LoginManager, login_required
import logging
import json
fr... |
# load other blueprints into app
from resource.registration import registration
app.register_blueprint(registration)
from resource.student import student
app.register_blueprint(student)
if __name__ == "__main__":
app.run(host="0.0.0.0") | return app.send_static_file('index.html') | identifier_body |
app.py | # caution: this module was written by a Python novice learning on the fly
# you should not assume this is "good" or idiomatic Python.
# Hackathons are fun.
from flask import Flask, Blueprint, render_template, abort, request, jsonify
from flask.ext.login import LoginManager, login_required
import logging
import json
fr... | (request):
api_key = request.headers.get('Authorization')
if api_key:
api_key = api_key.replace('Basic ', '', 1)
try:
raw = base64.b64decode(api_key)
parts = raw.decode("utf-8").split( ":" )
userName = parts[ 0 ]
password = parts[ 1 ]
record = db.user.getUser(userName, password)
if record:
u... | load_user_from_request | identifier_name |
app.py | # caution: this module was written by a Python novice learning on the fly
# you should not assume this is "good" or idiomatic Python.
# Hackathons are fun.
from flask import Flask, Blueprint, render_template, abort, request, jsonify
from flask.ext.login import LoginManager, login_required
import logging | from user import User
import base64
import db.user
app = Flask(__name__)
# setting up auth ... this should be interesting
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.request_loader
def load_user_from_request(request):
api_key = request.headers.get('Authorization')
if api_key:
api_key... | import json | random_line_split |
gnss.rs | /* vim: set et ts=4 sw=4: */
/* gnss.rs
*
* Copyright (C) 2017 Pelagicore AB.
* Copyright (C) 2017 Zeeshan Ali.
* Copyright (C) 2020 Purism SPC.
*
* GPSShare is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundat... |
impl GNSS {
pub fn new(config: Rc<Config>) -> io::Result<Self> {
match config.dev_path {
Some(ref path) => GNSS::new_for_path(path.as_path()),
None => GNSS::new_detect(),
}
}
fn new_for_path(path: &Path) -> io::Result<Self> {
let port = File::open(path.as_os... |
pub struct GNSS {
reader: BufReader<fs::File>,
} | random_line_split |
gnss.rs | /* vim: set et ts=4 sw=4: */
/* gnss.rs
*
* Copyright (C) 2017 Pelagicore AB.
* Copyright (C) 2017 Zeeshan Ali.
* Copyright (C) 2020 Purism SPC.
*
* GPSShare is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundat... |
}
| {
self.reader.read_line(buffer)
} | identifier_body |
gnss.rs | /* vim: set et ts=4 sw=4: */
/* gnss.rs
*
* Copyright (C) 2017 Pelagicore AB.
* Copyright (C) 2017 Zeeshan Ali.
* Copyright (C) 2020 Purism SPC.
*
* GPSShare is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundat... |
}
false
}
}
impl GPS for GNSS {
fn read_line(&mut self, buffer: &mut String) -> io::Result<usize> {
self.reader.read_line(buffer)
}
}
| {
println!("Failed to read from serial port");
} | conditional_block |
gnss.rs | /* vim: set et ts=4 sw=4: */
/* gnss.rs
*
* Copyright (C) 2017 Pelagicore AB.
* Copyright (C) 2017 Zeeshan Ali.
* Copyright (C) 2020 Purism SPC.
*
* GPSShare is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundat... | (path: &Path) -> io::Result<Self> {
let port = File::open(path.as_os_str())?;
Ok(GNSS {
reader: BufReader::new(port),
})
}
fn new_detect() -> io::Result<Self> {
println!("Attempting to autodetect GNSS device...");
let context = libudev::Context::new()?;
... | new_for_path | identifier_name |
sleeper_list.rs | // Copyright 2013 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.stack.with(|s| s.push(handle.take()));
}
}
pub fn pop(&mut self) -> Option<SchedHandle> {
unsafe {
do self.stack.with |s| {
if !s.is_empty() {
Some(s.pop())
} else {
None
}
... | pub fn push(&mut self, handle: SchedHandle) {
let handle = Cell::new(handle);
unsafe { | random_line_split |
sleeper_list.rs | // Copyright 2013 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 Clone for SleeperList {
fn clone(&self) -> SleeperList {
SleeperList {
stack: self.stack.clone()
}
}
} | {
None
} | conditional_block |
sleeper_list.rs | // Copyright 2013 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) -> SleeperList {
SleeperList {
stack: self.stack.clone()
}
}
} | clone | identifier_name |
sleeper_list.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn pop(&mut self) -> Option<SchedHandle> {
unsafe {
do self.stack.with |s| {
if !s.is_empty() {
Some(s.pop())
} else {
None
}
}
}
}
}
impl Clone for SleeperList {
fn clone(&... | {
let handle = Cell::new(handle);
unsafe {
self.stack.with(|s| s.push(handle.take()));
}
} | identifier_body |
render_thread.rs | use cgmath::{self};
pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;
pub struct RenderPackage<'a> {
pub device: &'a mut gfx_device_gl::Device,
pub graphics_queue: &'a mut gfx::queue::GraphicsQueue<gfx_device_gl::Backend>,
pub frame_semaphore: &'a gfx::handle::... | RenderThread {
_current_frame_index: 0,
from_game_thread: from_game_thread,
_to_content_manifest: to_content_manifest,
_from_content_manifest: from_content_manifest,
to_game_thread_with_input: to_game_thread_with_input,
textures: HashMap::n... | random_line_split | |
render_thread.rs | ;
use cgmath::{self};
pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;
pub struct RenderPackage<'a> {
pub device: &'a mut gfx_device_gl::Device,
pub graphics_queue: &'a mut gfx::queue::GraphicsQueue<gfx_device_gl::Backend>,
pub frame_semaphore: &'a gfx::handle... | ,
_ => (),
}
}
});
frame = swap_chain.acquire_frame(FrameSync::Semaphore(&frame_semaphore));
let frame_view = &views[frame.id()].clone();
frame_data = self.from_game_thread.try_recv();
let frame_data = matc... | {
// TODO
} | conditional_block |
render_thread.rs | ;
use cgmath::{self};
pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;
pub struct RenderPackage<'a> {
pub device: &'a mut gfx_device_gl::Device,
pub graphics_queue: &'a mut gfx::queue::GraphicsQueue<gfx_device_gl::Backend>,
pub frame_semaphore: &'a gfx::handle... |
}
#[derive(Clone)]
pub struct RenderFrame {
pub frame_index: u64,
pub boxes: Option<Vec<BoxRenderData>>,
pub spheres: Option<Vec<SphereRenderData>>,
}
impl RenderFrame {
pub fn new(frame_index: u64, boxes: Option<Vec<BoxRenderData>>, spheres: Option<Vec<SphereRenderData>>) -> RenderFrame {
Re... | {
RenderPackage {
device,
graphics_queue,
frame_semaphore,
draw_semaphore,
frame_fence
}
} | identifier_body |
render_thread.rs | ;
use cgmath::{self};
pub type ColorFormat = gfx::format::Rgba8;
pub type DepthFormat = gfx::format::DepthStencil;
pub struct RenderPackage<'a> {
pub device: &'a mut gfx_device_gl::Device,
pub graphics_queue: &'a mut gfx::queue::GraphicsQueue<gfx_device_gl::Backend>,
pub frame_semaphore: &'a gfx::handle... | {
pub frame_index: u64,
pub boxes: Option<Vec<BoxRenderData>>,
pub spheres: Option<Vec<SphereRenderData>>,
}
impl RenderFrame {
pub fn new(frame_index: u64, boxes: Option<Vec<BoxRenderData>>, spheres: Option<Vec<SphereRenderData>>) -> RenderFrame {
RenderFrame {
frame_index: frame_... | RenderFrame | identifier_name |
parseur_noeuds.py | d" % numero_ligne
print >> sys.stderr, "Cette ligne correspond à une définition de noeud à couvrir (non atteignable)"
print >> sys.stderr, "car vous avez défini debut_noeuds_atteignables=%d"%debut_noeuds_atteignables
print >> sys.stderr, "Format: `n... | t,noeuds_a_couvrir,no | identifier_name | |
parseur_noeuds.py | ]
elif numero_ligne_avec_donnee == 3 and ligne_entiers:
if len(ligne_entiers) != 1:
print >> sys.stderr, "definir_noeuds_depuis_fichier_noeuds(): erreur ligne %d" % numero_ligne
print >> sys.stderr, "Cette ligne définit le rayon de couverture des noeuds atteignables"
... | _aretes)]
if sommets[0] == noeud_depot[0] and avec_numeros:
print '\t%d -- %d [color=%s label=<<font color=\'%s\'>%s</font>>];' \
% (sommets[0],sommets[1],\
couleur,couleur,num_route)
else:
print '\t%d -- %d... | conditional_block | |
parseur_noeuds.py | = []
noeud_depot = []
noeuds_atteignables = []
noeuds_a_couvrir = []
rayon_couverture = 0
nb_vehicules = 0
capacite = 0
for ligne in fichier:
ligne_entiers = parser_ligne(ligne)
if numero_ligne_avec_donnee == 1 and ligne_entiers:
if len(ligne_entiers) != 1... | capacite = ligne_entiers[0]
elif numero_ligne_avec_donnee == 2 and ligne_entiers:
if len(ligne_entiers) != 1:
print >> sys.stderr, "definir_noeuds_depuis_fichier_noeuds(): erreur ligne %d" % numero_ligne
print >> sys.stderr, "Cette ligne correspond au n... | print >> sys.stderr, "definir_noeuds_depuis_fichier_noeuds(): erreur ligne %d" % numero_ligne
print >> sys.stderr, "Cette ligne définit la capacité des camions"
print >> sys.stderr, "Format: `capacité`"
sys.exit(1) | random_line_split |
parseur_noeuds.py | _float_or_int(value):
try:
float(value)
return True
except ValueError:
return False
# Pour parser une chaine de la forme suivante :
# `id_point x_coord y_coord qty_demand...`
# Ex: `1 8 9 90`
# NOTE: ne prend que les nombre_infos premiers éléments entiers
# NOTE: si aucun élément, ren... | int(value)
return int(value)
except ValueError:
return float(value)
def is | identifier_body | |
qprotractor_ru.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ru_RU">
<context>
<name>AboutDialog</name>
<message>
<location filename="about.ui" line="20"/>
<source>About QProtractor</source>
<translation>О QProtractor</translation>
</message>
<message utf8="tr... | <location filename="protractor.cpp" line="113"/>
<source>&Save state</source>
<translation>Сохранить (&S)</translation>
</message>
<message>
<location filename="protractor.cpp" line="116"/>
<source>&About/help</source>
<translation>О программе/справка ... | random_line_split | |
glib.py | import gdb
# This is not quite right, as local vars may override symname
def read_global_var (symname):
return gdb.selected_frame().read_var(symname)
def g_quark_to_string (quark):
if quark == None:
return None
quark = long(quark)
if quark == 0:
return None
try:
val = read_... |
def next(self):
if self.ht == 0:
raise StopIteration
if self.value != None:
v = self.value
self.value = None
return v
while long(self.pos) < long(self.size):
self.pos = self.pos + 1
... | return self | identifier_body |
glib.py | import gdb
# This is not quite right, as local vars may override symname
def read_global_var (symname):
return gdb.selected_frame().read_var(symname)
def g_quark_to_string (quark):
if quark == None:
return None
quark = long(quark)
if quark == 0:
return None
try:
val = read_... | key = key.cast (gdb.lookup_type("char").pointer())
# Queue value for next result
self.value = ('[%dv]'% (self.pos), val)
# Return key
return ('[%dk]'% (self.pos), key)
raise StopIteration
def __ini... | if long (self.hashes[self.pos]) >= 2:
key = self.keys[self.pos]
val = self.values[self.pos]
if self.keys_are_strings: | random_line_split |
glib.py | import gdb
# This is not quite right, as local vars may override symname
def read_global_var (symname):
return gdb.selected_frame().read_var(symname)
def g_quark_to_string (quark):
if quark == None:
return None
quark = long(quark)
if quark == 0:
return None
try:
val = read_... |
else:
t = str(type)
if t == "GList":
return GListNodePrinter(val)
if t == "GSList *":
return GListPrinter(val, "GSList")
return None
def register (obj):
if obj == None:
obj = gdb
obj.pretty_printers.append(pretty_printer_lookup)
class ForeachCo... | return GHashPrinter(val) | conditional_block |
glib.py | import gdb
# This is not quite right, as local vars may override symname
def read_global_var (symname):
return gdb.selected_frame().read_var(symname)
def g_quark_to_string (quark):
if quark == None:
return None
quark = long(quark)
if quark == 0:
return None
try:
val = read_... | (self, head, listtype):
self.link = head
self.listtype = listtype
self.count = 0
def __iter__(self):
return self
def next(self):
if self.link == 0:
raise StopIteration
data = self.link['data']
self.link... | __init__ | identifier_name |
cartesian.js | Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level",
"children": [
{
"name": "Son of B",
"parent": "Level 2: B"
},
{
"name": "Daughter of B",
"parent": "Level 2: B"
... | ) {
d3.select(this).select("rect").transition().duration(750)
.attr("width", boxWidth*1.5).attr("height", boxHeight*1.5)
.style("opacity", 1)
.style("fill", "#c8e4f8").style("stroke", "orange").style("stroke-width", "5px");
d3.select(this).select("text#nodetitle").transition().duration... | ouseover( | identifier_name |
cartesian.js | Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level",
"children": [
{
"name": "Son of B",
"parent": "Level 2: B"
},
{
"name": "Daughter of B",
"parent": "Level 2: B"
... | function dragended(d) {
d3.select(this).classed("dragging", false);
}
d3.json("./flare.json", function(error, json) {
if (error) throw error;
/* https://github.com/mbostock/d3/wiki/Tree-Layout
Runs the tree layout, returning the array of nodes associated with the specified root node.
The tree layout is part of D... |
d3.select(this).attr("x", d.x = d3.event.x).attr("y", d.y = d3.event.y);
}
| identifier_body |
cartesian.js | "parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level",
"children": [
{
"name": "Son of B",
"p... | "name": "Son of A", | random_line_split | |
cartesian.js | Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level",
"children": [
{
"name": "Son of B",
"parent": "Level 2: B"
},
{
"name": "Daughter of B",
"parent": "Level 2: B"
... | hierarchy.nodeSize([boxWidth*1.5, boxHeight*2]);
//hierarchy.size([height, width - 160]);
/** The default comparator is null, which disables sorting and uses tree traversal order.
* Note that if no comparator function is specified to the built-in sort method, the default order is lexicographic
* function comparator(... |
hierarchy = d3.layout.cluster();
}
| conditional_block |
wallet.js | 'use strict';
var RpcClient = require('darkcore').RpcClient;
var fs = require('fs');
var _ = require('lodash');
exports.NAME = 'Dashd';
exports.SUPPORTED_MODULES = ['wallet'];
var SATOSHI_FACTOR = 1e8;
var rpc = null;
var pluginConfig = {
account: ''
};
// TODO: should it happen only once per run... |
callback(null, {
DASH: Math.round(SATOSHI_FACTOR * result.result)
});
});
};
exports.sendBitcoins = function sendBitcoins(address, satoshis, fee, callback) {
var confirmations = 1;
var dashs = (satoshis / SATOSHI_FACTOR).toFixed(8);
console.log('dash: %s', dashs);
rpc.sendFrom(pluginConfig.... | {
return callback(richError(result.error, 'dashdError'));
} | conditional_block |
wallet.js | 'use strict';
var RpcClient = require('darkcore').RpcClient;
var fs = require('fs');
var _ = require('lodash');
exports.NAME = 'Dashd';
exports.SUPPORTED_MODULES = ['wallet'];
var SATOSHI_FACTOR = 1e8;
var rpc = null;
var pluginConfig = {
account: ''
};
// TODO: should it happen only once per run... | (msg, name) {
var err = new Error(msg);
err.name = name;
return err;
}
/*
* initialize RpcClient
*/
function parseConf(confPath) {
var conf = fs.readFileSync(confPath);
var lines = conf.toString().split('\n');
var res = {};
for (var i = 0; i < lines.length; i++) {
var keyVal = lines[i].split('=')... | richError | identifier_name |
wallet.js | 'use strict';
var RpcClient = require('darkcore').RpcClient;
var fs = require('fs');
var _ = require('lodash');
exports.NAME = 'Dashd';
exports.SUPPORTED_MODULES = ['wallet'];
var SATOSHI_FACTOR = 1e8;
var rpc = null;
var pluginConfig = {
account: ''
};
// TODO: should it happen only once per run... | exports.balance = function balance(callback) {
rpc.getBalance(pluginConfig.account, 1, function(err, result) {
if (err) return callback(err);
if (result.error) {
return callback(richError(result.error, 'dashdError'));
}
callback(null, {
DASH: Math.round(SATOSHI_FACTOR * result.result)
... |
// We want a balance that includes all spends (0 conf) but only deposits that
// have at least 1 confirmation. getbalance does this for us automatically. | random_line_split |
wallet.js | 'use strict';
var RpcClient = require('darkcore').RpcClient;
var fs = require('fs');
var _ = require('lodash');
exports.NAME = 'Dashd';
exports.SUPPORTED_MODULES = ['wallet'];
var SATOSHI_FACTOR = 1e8;
var rpc = null;
var pluginConfig = {
account: ''
};
// TODO: should it happen only once per run... |
// initialize Rpc only after 1st configuration is received
exports.config = function config(localConfig) {
if (localConfig) _.merge(pluginConfig, localConfig);
// initialize Rpc only after plugin is configured
initRpc();
};
function richError(msg, name) {
var err = new Error(msg);
err.name = name;
ret... | {
var dashdConf = parseConf(pluginConfig.dashdConfigurationPath);
var rpcConfig = {
protocol: 'http',
user: dashdConf.rpcuser,
pass: dashdConf.rpcpassword
};
rpc = new RpcClient(rpcConfig);
} | identifier_body |
fully_connected_preloaded.py | # Copyright 2015 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 applica... |
# Start input enqueue threads.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# And then after everything is built, start the training loop.
try:
step = 0
while not coord.should_stop():
start_time = time.time()
# Run one s... | # Run the Op to initialize the variables.
sess.run(init_op)
# Instantiate a SummaryWriter to output summaries and the Graph.
summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph) | random_line_split |
fully_connected_preloaded.py | # Copyright 2015 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 applica... | logits = mnist.inference(images, FLAGS.hidden1, FLAGS.hidden2)
# Add to the Graph the Ops for loss calculation.
loss = mnist.loss(logits, labels)
# Add to the Graph the Ops that calculate and apply gradients.
train_op = mnist.training(loss, FLAGS.learning_rate)
# Add the Op to compare the log... | """Train MNIST for a number of epochs."""
# Get the sets of images and labels for training, validation, and
# test on MNIST.
data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)
# Tell TensorFlow that the model will be built into the default Graph.
with tf.Graph().as_default():
with tf... | identifier_body |
fully_connected_preloaded.py | # Copyright 2015 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 applica... | '--hidden2',
type=int,
default=32,
help='Number of units in hidden layer 2.'
)
parser.add_argument(
'--batch_size',
type=int,
default=100,
help='Batch size. Must divide evenly into the dataset sizes.'
)
parser.add_argument(
'--train_dir',
type=str,
... | parser = argparse.ArgumentParser()
parser.add_argument(
'--learning_rate',
type=float,
default=0.01,
help='Initial learning rate.'
)
parser.add_argument(
'--num_epochs',
type=int,
default=2,
help='Number of epochs to run trainer.'
)
parser.add_argument(
'-... | conditional_block |
fully_connected_preloaded.py | # Copyright 2015 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 applica... | ():
"""Train MNIST for a number of epochs."""
# Get the sets of images and labels for training, validation, and
# test on MNIST.
data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)
# Tell TensorFlow that the model will be built into the default Graph.
with tf.Graph().as_default():
w... | run_training | identifier_name |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... | {
AutoCursor,
SpecifiedCursor(Cursor),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::AutoCursor => dest.write_str("auto"),
T::SpecifiedCursor(c) =>... | T | identifier_name |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... | computed_value::T::AutoCursor
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") {
... |
#[inline]
pub fn get_initial_value() -> computed_value::T { | random_line_split |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... |
}
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helpers.single_keyword("pointer-events", "auto none", animatable=False)}
${helpers.single_keyword("-moz-user-input", ... | {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::SpecifiedCursor)
} | conditional_block |
qgsmaplayer.py | # The following has been generated automatically from src/core/qgsmaplayer.h
QgsMapLayer.LayerType = QgsMapLayerType
# monkey patching scoped based enum
QgsMapLayer.VectorLayer = QgsMapLayerType.VectorLayer
QgsMapLayer.VectorLayer.__doc__ = ""
QgsMapLayer.RasterLayer = QgsMapLayerType.RasterLayer
QgsMapLayer.RasterLaye... | QgsMapLayer.AnnotationLayer.__doc__ = "Contains freeform, georeferenced annotations. Added in QGIS 3.16"
QgsMapLayerType.__doc__ = 'Types of layers that can be added to a map\n\n.. versionadded:: 3.8\n\n' + '* ``VectorLayer``: ' + QgsMapLayerType.VectorLayer.__doc__ + '\n' + '* ``RasterLayer``: ' + QgsMapLayerType.Rast... | QgsMapLayer.VectorTileLayer.__doc__ = "Added in 3.14"
QgsMapLayer.AnnotationLayer = QgsMapLayerType.AnnotationLayer | random_line_split |
ButtonBar.tsx | /*
Copyright (C) 2013-2017 Bryan Hughes <bryan@nebri.us>
Aquarium Control is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Aquarium Control ... |
this.setState((previousState) => {
this.props.onItemSelected(newValue);
const newState: IButtonBarState = {
currentValueName: newValue
};
return newState;
});
}
}
| {
return;
} | conditional_block |
ButtonBar.tsx | /*
Copyright (C) 2013-2017 Bryan Hughes <bryan@nebri.us>
Aquarium Control is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Aquarium Control ... | {buttons}
</div>
);
}
private _handleItemClick = (event: React.MouseEvent<HTMLButtonElement>) => {
const newValue = event.currentTarget.name;
if (newValue === this.state.currentValueName) {
return;
}
this.setState((previousState) => {
this.props.onItemSelected(newValu... | {
const props = this.props;
const buttons = props.items.map((item) => {
const className = classNames('btn', 'btn-outline-secondary', {
active: this.state.currentValueName === item.valueName
});
return (
<button
type="button"
className={className}
o... | identifier_body |
ButtonBar.tsx | /*
Copyright (C) 2013-2017 Bryan Hughes <bryan@nebri.us>
Aquarium Control is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Aquarium Control ... |
public render() {
const props = this.props;
const buttons = props.items.map((item) => {
const className = classNames('btn', 'btn-outline-secondary', {
active: this.state.currentValueName === item.valueName
});
return (
<button
type="button"
className={cla... | } | random_line_split |
ButtonBar.tsx | /*
Copyright (C) 2013-2017 Bryan Hughes <bryan@nebri.us>
Aquarium Control is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Aquarium Control ... | () {
const props = this.props;
const buttons = props.items.map((item) => {
const className = classNames('btn', 'btn-outline-secondary', {
active: this.state.currentValueName === item.valueName
});
return (
<button
type="button"
className={className}
... | render | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.