code stringlengths 5 1.01M | repo_name stringlengths 5 84 | path stringlengths 4 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 5 1.01M | input_ids listlengths 502 502 | token_type_ids listlengths 502 502 | attention_mask listlengths 502 502 | labels listlengths 502 502 |
|---|---|---|---|---|---|---|---|---|---|
package gui.dragndrop;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DragAndDrop extends Application
{
public void start(Stage stage)
{
AnchorPane root = new AnchorPane();
Label source = new Label("DRAG ME");
source.setLayoutX(50);
source.setLayoutY(100);
source.setScaleX(2.0);
source.setScaleY(2.0);
root.getChildren().add(source);
Label target = new Label("DROP HERE");
target.setLayoutX(250);
target.setLayoutY(100);
target.setScaleX(2.0);
target.setScaleY(2.0);
root.getChildren().add(target);
source.setOnDragDetected(e->onDragDetected(e));
target.setOnDragOver(e->onDragOver(e));
target.setOnDragEntered(e->onDragEntered(e));
target.setOnDragExited(e->onDragExited(e));
target.setOnDragDropped(e->onDragDropped(e));
source.setOnDragDone(e->onDragDone(e));
Scene scene = new Scene(root, 400, 200);
stage.setScene(scene);
stage.setTitle("Drag and Drop");
stage.show();
}
private void onDragDetected(MouseEvent e)
{
System.out.println("onDragDetected");
Label source = (Label)e.getSource();
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
}
private void onDragOver(DragEvent e)
{
System.out.println("onDragOver");
Label target = (Label)e.getSource();
if(e.getGestureSource() != target && e.getDragboard().hasString())
{
e.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
}
private void onDragEntered(DragEvent e)
{
System.out.println("onDragEntered");
Label target = (Label)e.getSource();
if(e.getGestureSource() != target && e.getDragboard().hasString())
{
target.setTextFill(Color.RED);
}
}
private void onDragExited(DragEvent e)
{
System.out.println("onDragExited");
Label target = (Label)e.getSource();
target.setTextFill(Color.BLACK);
}
private void onDragDropped(DragEvent e)
{
System.out.println("onDragDropped");
Label target = (Label)e.getSource();
Dragboard db = e.getDragboard();
boolean success = false;
if(db.hasString())
{
target.setText(db.getString());
success = true;
}
e.setDropCompleted(success);
}
private void onDragDone(DragEvent e)
{
System.out.println("onDragDone");
Label source = (Label)e.getSource();
if (e.getTransferMode() == TransferMode.MOVE)
{
source.setText("");
}
}
public static void main(String[] args)
{
launch(args);
}
} | KonstantinTwardzik/Graphical-User-Interfaces | CodeExamples/src/gui/dragndrop/DragAndDrop.java | Java | unlicense | 3,091 | [
30522,
7427,
26458,
1012,
8011,
4859,
18981,
1025,
12324,
9262,
2546,
2595,
1012,
4646,
1012,
4646,
1025,
12324,
9262,
2546,
2595,
1012,
3496,
1012,
3496,
1025,
12324,
9262,
2546,
2595,
1012,
3496,
1012,
2491,
1012,
1008,
1025,
12324,
9262,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/* eslint-env mocha */
const { expect } = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
});
it('should find valid xpath in react component twice', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
expect(component).to.have.xpath('//blink');
});
describe('when it does not find valid xpath in react component', () => {
it('should throw', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('to have xpath \'//h1\'');
});
it('should throw with outerHTML of the component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('hi</blink>');
});
});
});
| relekang/chai-have-xpath | test/react-tests.js | JavaScript | mit | 1,136 | [
30522,
1013,
1008,
9686,
4115,
2102,
1011,
4372,
2615,
9587,
7507,
1008,
1013,
9530,
3367,
1063,
5987,
1065,
1027,
15775,
2072,
1025,
12324,
10509,
2013,
1005,
1012,
1013,
10509,
1005,
1025,
12324,
3231,
21823,
4877,
2013,
1005,
1012,
1013,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php echo get_header(); ?>
<?php echo get_partial('content_top'); ?>
<?php if ($this->alert->get()) { ?>
<div id="notification">
<div class="container">
<div class="row">
<div class="col-md-12">
<?php echo $this->alert->display(); ?>
</div>
</div>
</div>
</div>
<?php } ?>
<div id="page-content">
<div class="container top-spacing">
<div class="row">
<?php echo get_partial('content_left'); ?>
<?php
if (partial_exists('content_left') AND partial_exists('content_right')) {
$class = "col-sm-6 col-md-6";
} else if (partial_exists('content_left') OR partial_exists('content_right')) {
$class = "col-sm-9 col-md-9";
} else {
$class = "col-md-12";
}
?>
<div class="content-wrap <?php echo $class; ?>">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-none">
<tr>
<td><b><?php echo lang('column_restaurant'); ?></b></td>
<td><?php echo $location_name; ?></td>
</tr>
<tr>
<td><b><?php echo lang('column_sale_id'); ?></b></td>
<td><?php echo $sale_id; ?> - <?php echo ucwords($sale_type); ?></td>
</tr>
<tr>
<td><b><?php echo lang('column_author'); ?></b></td>
<td><?php echo $author; ?></td>
</tr>
<tr>
<td><b><?php echo lang('column_rating'); ?></b></td>
<td>
<ul class="list-inline rating-inline">
<li><b><?php echo lang('label_quality'); ?></b><br />
<div class="rating rating-star" data-score="<?php echo $quality; ?>" data-readonly="true"></div>
</li>
<li><b><?php echo lang('label_delivery'); ?></b><br />
<div class="rating rating-star" data-score="<?php echo $delivery; ?>" data-readonly="true"></div>
</li>
<li><b><?php echo lang('label_service'); ?></b><br />
<div class="rating rating-star" data-score="<?php echo $service; ?>" data-readonly="true"></div>
</li>
</ul>
</td>
</tr>
<tr>
<td><b><?php echo lang('label_review'); ?></b></td>
<td><?php echo $review_text; ?></td>
</tr>
<tr>
<td><b><?php echo lang('label_date'); ?></b></td>
<td><?php echo $date; ?></td>
</tr>
</table>
</div>
</div>
<div class="col-md-12">
<div class="buttons">
<a class="btn btn-default" href="<?php echo $back_url; ?>"><?php echo lang('button_back'); ?></a>
</div>
</div>
</div>
</div>
<?php echo get_partial('content_right'); ?>
<?php echo get_partial('content_bottom'); ?>
</div>
</div>
</div>
<script type="text/javascript"><!--
$(document).ready(function() {
var ratings = <?php echo json_encode(array_values($ratings)); ?>;
displayRatings(ratings);
});
//--></script>
<?php echo get_footer(); ?> | Delitex/test2 | main/views/themes/tastyigniter-orange/account/review_view.php | PHP | gpl-3.0 | 2,971 | [
30522,
1026,
1029,
25718,
9052,
2131,
1035,
20346,
1006,
1007,
1025,
1029,
1028,
1026,
1029,
25718,
9052,
2131,
1035,
30524,
25718,
2065,
1006,
1002,
2023,
1011,
1028,
9499,
1011,
1028,
2131,
1006,
1007,
1007,
1063,
1029,
1028,
1026,
4487,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#include <stdlib.h>
#include <string.h>
#include <check.h>
#include <ike/hashmap.h>
#include <stdio.h>
START_TEST(test_hashmapSimple)
{
ikeHashmap hashmap;
ikeHashmapInit(&hashmap);
int *itest = calloc(1, sizeof(int)); *itest = 7;
ck_assert_msg(ikeHashmapPut(&hashmap, "int", itest) == IKE_HASHMAP_OK, "could not store int");
float *ftest = calloc(1, sizeof(float)); *ftest = 3.4f;
ck_assert_msg(ikeHashmapPut(&hashmap, "float", ftest) == IKE_HASHMAP_OK, "could not store float");
double *dtest = calloc(1, sizeof(double)); *dtest = 3.4;
ck_assert_msg(ikeHashmapPut(&hashmap, "double", dtest) == IKE_HASHMAP_OK, "could not store double");
char *stest = calloc(12, sizeof(char)); strcpy(stest, "hello world");
ck_assert_msg(ikeHashmapPut(&hashmap, "string", stest) == IKE_HASHMAP_OK, "could not store string");
int *itestr;
ck_assert_msg(ikeHashmapGet(&hashmap, "int", (ikeAny *) &itestr) == IKE_HASHMAP_OK, "could not read int");
ck_assert_msg(*itest == *itestr, "stored integer is not equal than expected");
float *ftestr;
ck_assert_msg(ikeHashmapGet(&hashmap, "float", (ikeAny *) &ftestr) == IKE_HASHMAP_OK, "could not read float");
ck_assert_msg(*ftest == *ftestr, "stored float is not equal than expected");
double *dtestr;
ck_assert_msg(ikeHashmapGet(&hashmap, "double", (ikeAny *) &dtestr) == IKE_HASHMAP_OK, "could not read double");
ck_assert_msg(*dtest == *dtestr, "stored double is not equal than expected");
char *stestr;
ck_assert_msg(ikeHashmapGet(&hashmap, "string", (ikeAny *) &stestr) == IKE_HASHMAP_OK, "could not read string");
ck_assert_msg(strcmp(stest, stestr) == 0, "stored string is not equal than expected");
free(itest);
free(ftest);
free(dtest);
free(stest);
ikeHashmapDestroy(&hashmap);
}
END_TEST
static int test_hashmapIterateCount = 0;
static int test_hashmapIterateHelper(ikeAny udata, ikeAny item) {
test_hashmapIterateCount ++;
return IKE_HASHMAP_OK;
}
START_TEST(test_hashmapIterate)
{
ikeHashmap hashmap;
ikeHashmapInit(&hashmap);
char *stest1 = calloc(12, sizeof(char)); strcpy(stest1, "hello world");
char *stest2 = calloc(12, sizeof(char)); strcpy(stest2, "dlrow olleh");
ck_assert_msg(ikeHashmapPut(&hashmap, "regular", stest1) == IKE_HASHMAP_OK, "could not store string (regular)");
ck_assert_msg(ikeHashmapPut(&hashmap, "reverse", stest2) == IKE_HASHMAP_OK, "could not store string (reverse)");
ck_assert_msg(ikeHashmapIterate(&hashmap, test_hashmapIterateHelper, NULL) == IKE_HASHMAP_OK, "could not iterate map");
ck_assert_msg(test_hashmapIterateCount == 2, "unexpected iteration keys count");
free(stest1);
free(stest2);
}
END_TEST
Suite *mat4Suite(void)
{
Suite *s;
TCase *tc_core;
s = suite_create("ike/hashmap");
tc_core = tcase_create("core");
tcase_add_test(tc_core, test_hashmapSimple);
tcase_add_test(tc_core, test_hashmapIterate);
suite_add_tcase(s, tc_core);
return s;
}
int main(void)
{
int numfailed;
Suite *s;
SRunner *sr;
s = mat4Suite();
sr = srunner_create(s);
srunner_run_all(sr, CK_NORMAL);
numfailed = srunner_ntests_failed(sr);
srunner_free(sr);
return (numfailed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| cedmundo/learning-opengl | XX-InfernoKittenEngine/tests/hashmap_test.c | C | mit | 3,316 | [
30522,
1001,
2421,
1026,
2358,
19422,
12322,
1012,
1044,
1028,
1001,
2421,
1026,
5164,
1012,
1044,
1028,
1001,
2421,
1026,
4638,
1012,
1044,
1028,
1001,
2421,
1026,
25209,
1013,
23325,
2863,
2361,
1012,
1044,
1028,
1001,
2421,
1026,
2358,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<html>
<head>
<title>User agent detail - Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>ua-parser/uap-core<br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td> </td><td> </td><td style="border-left: 1px solid #555">Samsung</td><td>gt-b5722</td><td></td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a>
<!-- Modal Structure -->
<div id="modal-test" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Testsuite result detail</h4>
<p><pre><code class="php">Array
(
[user_agent_string] => Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
[family] => Samsung gt-b5722
[brand] => Samsung
[model] => gt-b5722
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td> </td><td> </td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td></td><td style="border-left: 1px solid #555">yes</td><td>General Crawlers</td><td>Bot/Crawler</td><td>0.14101</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a>
<!-- Modal Structure -->
<div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^.*java.*$/
[browser_name_pattern] => *java*
[parent] => General Crawlers
[comment] => General Crawlers
[browser] => General Crawlers
[browser_type] => Bot/Crawler
[browser_bits] => 0
[browser_maker] => unknown
[browser_modus] => unknown
[version] => 0.0
[majorver] => 0
[minorver] => 0
[platform] => unknown
[platform_version] => unknown
[platform_description] => unknown
[platform_bits] => 0
[platform_maker] => unknown
[alpha] =>
[beta] =>
[win16] =>
[win32] =>
[win64] =>
[frames] =>
[iframes] =>
[tables] =>
[cookies] =>
[backgroundsounds] =>
[javascript] =>
[vbscript] =>
[javaapplets] =>
[activexcontrols] =>
[ismobiledevice] =>
[istablet] =>
[issyndicationreader] =>
[crawler] => 1
[cssversion] => 0
[aolversion] => 0
[device_name] => unknown
[device_maker] => unknown
[device_type] => unknown
[device_pointing_method] => unknown
[device_code_name] => unknown
[device_brand_name] => unknown
[renderingengine_name] => unknown
[renderingengine_version] => unknown
[renderingengine_description] => unknown
[renderingengine_maker] => unknown
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>AppleWebKit 530.13</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a>
<!-- Modal Structure -->
<div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] =>
[browser] => AppleWebKit
[version] => 530.13
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Mobile Safari </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.193</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a>
<!-- Modal Structure -->
<div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>NeutrinoApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[mobile_screen_height] => 90
[is_mobile] => 1
[type] => mobile-browser
[mobile_brand] =>
[mobile_model] =>
[version] =>
[is_android] =>
[browser_name] => Mobile Safari
[operating_system_family] => unknown
[operating_system_version] =>
[is_ios] =>
[producer] => Apple Inc.
[operating_system] => unknown
[mobile_screen_width] => 90
[mobile_browser] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>UC Browser 8.5</td><td>WebKit </td><td> </td><td style="border-left: 1px solid #555">Samsung</td><td>gt-b5722</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.009</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a>
<!-- Modal Structure -->
<div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => UC Browser
[short_name] => UC
[version] => 8.5
[engine] => WebKit
)
[operatingSystem] => Array
(
)
[device] => Array
(
[brand] => SA
[brandName] => Samsung
[model] => gt-b5722
[device] => 1
[deviceName] => smartphone
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] =>
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] => 1
[isTablet] =>
[isTV] =>
[isDesktop] =>
[isMobile] => 1
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Mozilla 5.0</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a>
<!-- Modal Structure -->
<div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>SinergiBrowserDetector result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Sinergi\BrowserDetector\Browser Object
(
[userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
)
[name:Sinergi\BrowserDetector\Browser:private] => Mozilla
[version:Sinergi\BrowserDetector\Browser:private] => 5.0
[isRobot:Sinergi\BrowserDetector\Browser:private] =>
[isChromeFrame:Sinergi\BrowserDetector\Browser:private] =>
)
[operatingSystem] => Sinergi\BrowserDetector\Os Object
(
[name:Sinergi\BrowserDetector\Os:private] => unknown
[version:Sinergi\BrowserDetector\Os:private] => unknown
[isMobile:Sinergi\BrowserDetector\Os:private] =>
[userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
)
)
[device] => Sinergi\BrowserDetector\Device Object
(
[name:Sinergi\BrowserDetector\Device:private] => unknown
[userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
)
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>UC Browser 8.5.0</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Samsung</td><td>gt-b5722</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.002</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a>
<!-- Modal Structure -->
<div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] => 8
[minor] => 5
[patch] => 0
[family] => UC Browser
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] =>
[minor] =>
[patch] =>
[patchMinor] =>
[family] => Other
)
[device] => UAParser\Result\Device Object
(
[brand] => Samsung
[model] => gt-b5722
[family] => Samsung gt-b5722
)
[originalUserAgent] => Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>UC Browser </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.068</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a>
<!-- Modal Structure -->
<div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UserAgentStringCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[agent_type] => Mobile Browser
[agent_name] => UC Browser
[agent_version] => --
[os_type] => unknown
[os_name] => unknown
[os_versionName] =>
[os_versionNumber] =>
[os_producer] =>
[os_producerURL] =>
[linux_distibution] => Null
[agent_language] => Portuguese - Brazil
[agent_languageTag] => Pt-br
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>UC Browser 8.5.0.185</td><td>WebKit 530.13</td><td> </td><td style="border-left: 1px solid #555">Samsung</td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.403</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a>
<!-- Modal Structure -->
<div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhatIsMyBrowserCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[operating_system_name] =>
[simple_sub_description_string] =>
[simple_browser_string] => UC Browser 8.5 on Mobile
[browser_version] => 8.5
[extra_info] => Array
(
)
[operating_platform] => Mobile
[extra_info_table] => Array
(
)
[layout_engine_name] => WebKit
[detected_addons] => Array
(
)
[operating_system_flavour_code] =>
[hardware_architecture] =>
[operating_system_flavour] =>
[operating_system_frameworks] => Array
(
)
[browser_name_code] => uc-browser
[operating_system_version] =>
[simple_operating_platform_string] =>
[is_abusive] =>
[layout_engine_version] => 530.13
[browser_capabilities] => Array
(
)
[operating_platform_vendor_name] => Samsung
[operating_system] =>
[operating_system_version_full] =>
[operating_platform_code] => GT-B5722
[browser_name] => UC Browser
[operating_system_name_code] =>
[user_agent] => Mozilla/5.0 (Java; U; Pt-br; samsung gt-b5722) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.5.0.185/82/352/UCWEB Mobile
[browser_version_full] => 8.5.0.185
[browser] => UC Browser 8.5
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>UC Browser 8.5</td><td>Gecko </td><td>Windows Mobile </td><td style="border-left: 1px solid #555">Samsung</td><td>B5722</td><td>mobile:smart</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.011</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a>
<!-- Modal Structure -->
<div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[name] => UC Browser
[version] => 8.5
[type] => browser
)
[engine] => Array
(
[name] => Gecko
)
[os] => Array
(
[name] => Windows Mobile
)
[device] => Array
(
[type] => mobile
[subtype] => smart
[manufacturer] => Samsung
[model] => B5722
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>UC Browser 8</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Feature Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.018</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a>
<!-- Modal Structure -->
<div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => false
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => false
[is_mobile] => true
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => false
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => true
[is_html_preferred] => false
[advertised_device_os] => Android
[advertised_device_os_version] => 4.0
[advertised_browser] => UC Browser
[advertised_browser_version] => 8
[complete_device_name] =>
[form_factor] => Feature Phone
[is_phone] => true
[is_app_webview] => false
)
[all] => Array
(
[brand_name] =>
[model_name] =>
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => true
[device_claims_web_support] => false
[has_qwerty_keyboard] => false
[can_skip_aligned_link_row] => true
[uaprof] =>
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] =>
[mobile_browser] => UCWeb
[mobile_browser_version] => browser_root_ucweb
[device_os_version] =>
[pointing_method] =>
[release_date] => 2002_july
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => true
[is_tablet] => false
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => false
[built_in_back_button_support] => false
[card_title_support] => true
[softkey_support] => false
[table_support] => true
[numbered_menus] => false
[menu_with_select_element_recommended] => false
[menu_with_list_of_links_recommended] => true
[icons_on_menu_items_support] => false
[break_list_of_links_with_br_element_recommended] => true
[access_key_support] => false
[wrap_mode_support] => false
[times_square_mode_support] => false
[deck_prefetch_support] => false
[elective_forms_recommended] => true
[wizards_recommended] => false
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => false
[wml_make_phone_call_string] => wtai://wp/mc;
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => false
[xhtml_honors_bgcolor] => false
[xhtml_supports_forms_in_table] => false
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => false
[xhtml_select_as_dropdown] => false
[xhtml_select_as_radiobutton] => false
[xhtml_select_as_popup] => false
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => false
[xhtml_supports_inline_input] => false
[xhtml_supports_monospace_font] => false
[xhtml_supports_table_for_layout] => false
[xhtml_supports_css_cell_table_coloring] => false
[xhtml_format_as_css_property] => false
[xhtml_format_as_attribute] => false
[xhtml_nowrap_mode] => false
[xhtml_marquee_as_css_property] => false
[xhtml_readable_background_color1] => #FFFFFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => false
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => utf8
[opwv_xhtml_extensions_support] => false
[xhtml_make_phone_call_string] => tel:
[xhtmlmp_preferred_mime_type] => application/vnd.wap.xhtml+xml
[xhtml_table_support] => true
[xhtml_send_sms_string] => none
[xhtml_send_mms_string] => none
[xhtml_file_upload] => not_supported
[cookie_support] => true
[accept_third_party_cookie] => true
[xhtml_supports_iframe] => none
[xhtml_avoid_accesskeys] => false
[xhtml_can_embed_video] => none
[ajax_support_javascript] => false
[ajax_manipulate_css] => false
[ajax_support_getelementbyid] => false
[ajax_support_inner_html] => false
[ajax_xhr_type] => none
[ajax_manipulate_dom] => false
[ajax_support_events] => false
[ajax_support_event_listener] => false
[ajax_preferred_geoloc_api] => none
[xhtml_support_level] => 1
[preferred_markup] => html_wi_oma_xhtmlmp_1_0
[wml_1_1] => true
[wml_1_2] => false
[wml_1_3] => false
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => true
[html_wi_imode_html_1] => false
[html_wi_imode_html_2] => false
[html_wi_imode_html_3] => false
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => false
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => false
[html_web_3_2] => false
[html_web_4_0] => false
[voicexml] => false
[multipart_support] => false
[total_cache_disable_support] => false
[time_to_live_support] => false
[resolution_width] => 128
[resolution_height] => 92
[columns] => 11
[max_image_width] => 120
[max_image_height] => 92
[rows] => 6
[physical_screen_width] => 27
[physical_screen_height] => 27
[dual_orientation] => false
[density_class] => 1.0
[wbmp] => true
[bmp] => false
[epoc_bmp] => false
[gif_animated] => true
[jpg] => true
[png] => true
[tiff] => false
[transparent_png_alpha] => false
[transparent_png_index] => false
[svgt_1_1] => false
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 256
[webp_lossy_support] => false
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => true
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => false
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 9
[wifi] => false
[sdio] => false
[vpn] => false
[has_cellular_radio] => true
[max_deck_size] => 10000
[max_url_length_in_requests] => 256
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => false
[inline_support] => false
[oma_support] => false
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => false
[oma_v_1_0_combined_delivery] => false
[oma_v_1_0_separate_delivery] => false
[streaming_video] => false
[streaming_3gpp] => false
[streaming_mp4] => false
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => -1
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => -1
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => -1
[streaming_acodec_amr] => none
[streaming_acodec_aac] => none
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => none
[wap_push_support] => false
[connectionless_service_indication] => false
[connectionless_service_load] => false
[connectionless_cache_operation] => false
[connectionoriented_unconfirmed_service_indication] => false
[connectionoriented_unconfirmed_service_load] => false
[connectionoriented_unconfirmed_cache_operation] => false
[connectionoriented_confirmed_service_indication] => false
[connectionoriented_confirmed_service_load] => false
[connectionoriented_confirmed_cache_operation] => false
[utf8_support] => true
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => false
[j2me_cldc_1_0] => false
[j2me_cldc_1_1] => false
[j2me_midp_1_0] => false
[j2me_midp_2_0] => false
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 0
[mms_max_height] => 0
[mms_max_width] => 0
[built_in_recorder] => false
[built_in_camera] => false
[mms_jpeg_baseline] => false
[mms_jpeg_progressive] => false
[mms_gif_static] => false
[mms_gif_animated] => false
[mms_png] => false
[mms_bmp] => false
[mms_wbmp] => false
[mms_amr] => false
[mms_wav] => false
[mms_midi_monophonic] => false
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => false
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => false
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => true
[wav] => false
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => false
[midi_polyphonic] => false
[sp_midi] => false
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => false
[awb] => false
[aac] => false
[mp3] => false
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => false
[css_supports_width_as_percentage] => true
[css_border_image] => none
[css_rounded_corners] => none
[css_gradient] => none
[css_spriting] => false
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => false
[progressive_download] => false
[playback_vcodec_h263_0] => -1
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => -1
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => -1
[playback_real_media] => none
[playback_3gpp] => false
[playback_3g2] => false
[playback_mp4] => false
[playback_mov] => false
[playback_acodec_amr] => none
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => false
[html_preferred_dtd] => xhtml_mp1
[viewport_supported] => false
[viewport_width] =>
[viewport_userscalable] =>
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => none
[image_inlining] => false
[is_smarttv] => false
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => none
[is_sencha_touch_ok] => false
[controlcap_is_smartphone] => default
[controlcap_is_ios] => default
[controlcap_is_android] => default
[controlcap_is_robot] => default
[controlcap_is_app] => default
[controlcap_advertised_device_os] => default
[controlcap_advertised_device_os_version] => default
[controlcap_advertised_browser] => default
[controlcap_advertised_browser_version] => default
[controlcap_is_windows_phone] => default
[controlcap_is_full_desktop] => default
[controlcap_is_largescreen] => default
[controlcap_is_mobile] => default
[controlcap_is_touchscreen] => default
[controlcap_is_wml_preferred] => default
[controlcap_is_xhtmlmp_preferred] => default
[controlcap_is_html_preferred] => default
[controlcap_form_factor] => default
[controlcap_complete_device_name] => default
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-02-13 13:33:27</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html> | ThaDafinser/UserAgentParserComparison | v4/user-agent-detail/75/31/75318a63-7dd7-4a48-8311-ab46f3405588.html | HTML | mit | 44,466 | [
30522,
1026,
16129,
1028,
1026,
2132,
1028,
1026,
2516,
1028,
5310,
4005,
6987,
1011,
9587,
5831,
4571,
1013,
1019,
1012,
1014,
1006,
9262,
1025,
1057,
1025,
13866,
1011,
7987,
1025,
19102,
14181,
1011,
1038,
28311,
19317,
1007,
6207,
8545,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package thesis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import termo.component.Compound;
import termo.eos.Cubic;
import termo.eos.EquationsOfState;
import termo.eos.alpha.Alphas;
import termo.matter.Mixture;
import termo.matter.Substance;
import termo.phase.Phase;
import compounds.CompoundReader;
public class CubicFileGenerator extends FileGenerator {
Substance substance;
public CubicFileGenerator(){
CompoundReader reader = new CompoundReader();
Compound heptane = reader.getCompoundByExactName("N-heptane");
substance = new Substance(EquationsOfState.vanDerWaals()
,Alphas.getVanDerWaalsIndependent()
,heptane,Phase.VAPOR);
}
public void cubicEquationPressureVolumeTemperatureFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion Temperatura");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 60;
double pass = (max_volume- min_volume)/n;
int nt =20;
double min_temperature = 150;
double max_temperature = 400;
double tempPass = (max_temperature - min_temperature)/nt;
for(int j = 0; j < nt; j++){
double temperature = min_temperature + tempPass *j ;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure = calculatePressure(volume, temperature);
writer.println(" "+ volume + " " + temperature + " " + pressure);
}
writer.println();
}
writer.close();
}
public double calculatePressure(double volume, double temperature){
return substance.calculatePressure(temperature,volume);
//parametros de van der waals para el heptano
// double a = 3107000.0;
//double b = 0.2049;
// return cubic.calculatePressure(temperature, volume,a,b);
}
public void cubicEquationPressureVolumeFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 100;
double pass = (max_volume- min_volume)/n;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure =calculatePressure(volume, 300);
writer.println(" "+ volume + " " + pressure);
}
writer.close();
}
public void cubicEquationCompresibilitiFactorFiles(String folderName) throws FileNotFoundException, UnsupportedEncodingException{
File directory = new File(folderName);
if(!directory.exists()){
directory.mkdir();
}
Cubic cubic = EquationsOfState.vanDerWaals();
double min_reducedPressure = 0.1;
double max_reducedPressure= 7;
double pressurepass =( max_reducedPressure- min_reducedPressure)/ 100;
double min_reducedTemperature= 1 ;
double max_reducedTemperature=2;
double criticalTemperature = 540.2;
double criticalPressure = 2.74000E+06;
double a = 3107000.0;
double b = 0.2049;
PrintWriter writer= new PrintWriter(folderName + "pz_temp.dat", "UTF-8");
writer.println(" p z rt");
for(double reducedTemperature = min_reducedTemperature; reducedTemperature <= max_reducedTemperature; reducedTemperature +=0.1){
for(double reducedPressure = min_reducedPressure ; reducedPressure <= max_reducedPressure; reducedPressure+= pressurepass){
double temperature = criticalTemperature * reducedTemperature;
double pressure = criticalPressure * reducedPressure;
// double A =cubic.get_A(temperature, pressure, a);
// double B = cubic.get_B(temperature, pressure, b);
substance.setPressure(pressure);
substance.setTemperature(temperature);
double z = substance.calculateCompresibilityFactor();
//double z =cubic.calculateCompresibilityFactor(A, B, Phase.LIQUID);
writer.println(" " + reducedPressure + " " + z + " " + reducedTemperature);
}
writer.println();
}
writer.close();
}
}
| HugoRedon/thesis-examples | src/main/java/thesis/CubicFileGenerator.java | Java | gpl-2.0 | 4,031 | [
30522,
7427,
9459,
1025,
12324,
9262,
1012,
22834,
30524,
1012,
7328,
1025,
12324,
2744,
2080,
1012,
1041,
2891,
1012,
11919,
1025,
12324,
2744,
2080,
1012,
1041,
2891,
1012,
11380,
11253,
9153,
2618,
1025,
12324,
2744,
2080,
1012,
1041,
28... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// vim: set ts=4 sw=4 tw=99 et:
function testUKeyUObject(a, key1, key2, key3) {
a.a = function () { return this.d; }
a.b = function () { return this.e; }
a.c = function() { return this.f; }
a.d = 20;
a.e = "hi";
a.f = 500;
delete a["b"];
Object.defineProperty(a, "b", { get: function () { return function () { return this.e; } } });
assertEq(a[key1](), 20);
assertEq(a[key2](), "hi");
assertEq(a[key3](), 500);
}
for (var i = 0; i < 5; i++)
testUKeyUObject({}, "a", "b", "c");
| glycerine/vj | src/js-1.8.5/js/src/jit-test/tests/jaeger/testPropCallElem2.js | JavaScript | apache-2.0 | 529 | [
30522,
1013,
1013,
6819,
2213,
1024,
2275,
24529,
1027,
1018,
25430,
1027,
1018,
1056,
2860,
1027,
5585,
3802,
1024,
3853,
3231,
15851,
10513,
16429,
20614,
1006,
1037,
1010,
3145,
2487,
1010,
3145,
2475,
1010,
3145,
2509,
1007,
1063,
1037,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// ===============================
// PC-BSD REST API Server
// Available under the 3-clause BSD License
// Written by: Ken Moore <ken@pcbsd.org> DEC 2015
// =================================
// Note: Don't forget to run "AUTHSYSTEM->hasFullAccess(SockAuthToken)"
// To restrict user access to some systems as needed!
// =================================
#include <WebSocket.h>
//sysadm library interface classes
#include "library/sysadm-beadm.h"
#include "library/sysadm-general.h"
#include "library/sysadm-filesystem.h"
#include "library/sysadm-iocage.h"
#include "library/sysadm-iohyve.h"
#include "library/sysadm-lifepreserver.h"
#include "library/sysadm-network.h"
#include "library/sysadm-systemmanager.h"
#include "library/sysadm-update.h"
#include "library/sysadm-zfs.h"
#include "library/sysadm-pkg.h"
#include "library/sysadm-users.h"
#include "library/sysadm-servicemanager.h"
#include "library/sysadm-firewall.h"
#define DEBUG 0
//#define SCLISTDELIM QString("::::") //SysCache List Delimiter
RestOutputStruct::ExitCode WebSocket::AvailableSubsystems(bool allaccess, QJsonObject *out){
//Probe the various subsystems to see what is available through this server
//Output format:
/*<out>{
<namespace1/name1> : <read/write/other>,
<namespace2/name2> : <read/write/other>,
}
*/
// - server settings (always available)
out->insert("rpc/settings","read/write");
out->insert("rpc/logs", allaccess ? "read/write" : "read");
// - beadm
if(QFile::exists("/usr/local/sbin/beadm")){
out->insert("sysadm/beadm", "read/write");
}
// - dispatcher (Internal to server - always available)
//"read" is the event notifications, "write" is the ability to queue up jobs
out->insert("rpc/dispatcher", allaccess ? "read/write" : "read");
// - filesystem
out->insert("sysadm/fs","read/write");
// - network
out->insert("sysadm/network","read/write");
// - lifepreserver
if(QFile::exists("/usr/local/bin/lpreserver")){
out->insert("sysadm/lifepreserver", "read/write");
}
// - iocage
if(QFile::exists("/usr/local/sbin/iocage")){
out->insert("sysadm/iocage", "read/write");
}
// - iohyve
if(QFile::exists("/usr/local/sbin/iohyve")){
out->insert("sysadm/iohyve", "read/write");
}
// - zfs
if(QFile::exists("/sbin/zfs") && QFile::exists("/sbin/zpool")){
out->insert("sysadm/zfs", allaccess ? "read/write" : "read");
}
// - pkg
if(QFile::exists("/usr/local/sbin/pkg")){
out->insert("sysadm/pkg", "read/write");
}
// - Generic system information
out->insert("sysadm/systemmanager","read/write");
// - PC-BSD Updater
if(QFile::exists("/usr/local/bin/pc-updatemanager")){
out->insert("sysadm/update", "read/write");
}
// - User Manager
out->insert("sysadm/users","read/write");
//- Service Manager
out->insert("sysadm/services","read/write");
// - Firewall Manager
out->insert("sysadm/firewall","read/write");
return RestOutputStruct::OK;
}
RestOutputStruct::ExitCode WebSocket::EvaluateBackendRequest(const RestInputStruct &IN, QJsonObject *out){
/*Inputs:
"namesp" - namespace for the request
"name" - name of the request
"args" - JSON input arguments structure
"out" - JSON output arguments structure
*/
//qDebug() << "Evaluate Backend Request:" << IN.namesp << IN.name << IN.id << IN.args << IN.fullaccess;
QString namesp = IN.namesp.toLower(); QString name = IN.name.toLower();
//Get/Verify subsystems
if(namesp=="rpc" && name=="query"){
return AvailableSubsystems(IN.fullaccess, out);
}else{
QJsonObject avail;
AvailableSubsystems(IN.fullaccess, &avail);
if(!avail.contains(namesp+"/"+name)){ return RestOutputStruct::NOTFOUND; }
}
//qDebug() << "Evaluate Backend Request:" << namesp << name;
//Go through and forward this request to the appropriate sub-system
if(namesp=="rpc" && name=="settings"){
return EvaluateSysadmSettingsRequest(IN.args, out);
}else if(namesp=="rpc" && name=="logs"){
return EvaluateSysadmLogsRequest(IN.fullaccess, IN.args, out);
}else if(namesp=="rpc" && name=="dispatcher"){
return EvaluateDispatcherRequest(IN.fullaccess, IN.args, out);
}else if(namesp=="sysadm" && name=="beadm"){
return EvaluateSysadmBEADMRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="fs"){
return EvaluateSysadmFSRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="iocage"){
return EvaluateSysadmIocageRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="iohyve"){
return EvaluateSysadmIohyveRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="lifepreserver"){
return EvaluateSysadmLifePreserverRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="network"){
return EvaluateSysadmNetworkRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="systemmanager"){
return EvaluateSysadmSystemMgmtRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="update"){
return EvaluateSysadmUpdateRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="zfs"){
return EvaluateSysadmZfsRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="pkg"){
return EvaluateSysadmPkgRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="users"){
return EvaluateSysadmUserRequest(IN.fullaccess, AUTHSYSTEM->userForToken(SockAuthToken), IN.args, out);
}else if(namesp=="sysadm" && name=="services"){
return EvaluateSysadmServiceRequest(IN.args, out);
}else if(namesp=="sysadm" && name=="firewall"){
return EvaluateSysadmFirewallRequest(IN.args, out);
}else{
return RestOutputStruct::BADREQUEST;
}
}
// === SYSADM SSL SETTINGS ===
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmSettingsRequest(const QJsonValue in_args, QJsonObject *out){
//qDebug() << "sysadm/settings Request:" << in_args;
if(!in_args.isObject()){ return RestOutputStruct::BADREQUEST; }
QJsonObject argsO = in_args.toObject();
QStringList keys = argsO.keys();
//qDebug() << " - keys:" << keys;
if(!keys.contains("action")){ return RestOutputStruct::BADREQUEST; }
QString act = argsO.value("action").toString();
bool ok = false;
if(act=="register_ssl_cert" && keys.contains("pub_key")){
//Required arguments: "pub_key" (String)
//Optional arguments: "nickname" (String), "email" (String)
QString pub_key, nickname, email;
pub_key = argsO.value("pub_key").toString();
if(keys.contains("nickname")){ nickname = argsO.value("nickname").toString(); }
if(keys.contains("email")){ email = argsO.value("email").toString(); }
if(!pub_key.isEmpty()){
ok = AUTHSYSTEM->RegisterCertificate(SockAuthToken, pub_key, nickname, email);
if(!ok){ return RestOutputStruct::FORBIDDEN; }
}
}else if(act=="list_ssl_certs"){
AUTHSYSTEM->ListCertificates(SockAuthToken, out);
ok = true; //always works for current user (even if nothing found)
}else if(act=="list_ssl_checksums"){
AUTHSYSTEM->ListCertificateChecksums(out);
ok = true;
}else if(act=="revoke_ssl_cert" && keys.contains("pub_key") ){
//Additional arguments: "user" (optional), "pub_key" (String)
QString user; if(keys.contains("user")){ user = argsO.value("user").toString(); }
ok = AUTHSYSTEM->RevokeCertificate(SockAuthToken,argsO.value("pub_key").toString(), user);
}
if(ok){ return RestOutputStruct::OK; }
else{ return RestOutputStruct::BADREQUEST; }
}
// === sysadm/logs ===
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmLogsRequest(bool allaccess, const QJsonValue in_args, QJsonObject *out){
if(!in_args.isObject() || !in_args.toObject().contains("action") ){ return RestOutputStruct::BADREQUEST; }
QString act = in_args.toObject().value("action").toString().toLower();
QJsonObject obj = in_args.toObject();
//Determine the type of action to perform
if(act=="read_logs"){
// OPTIONAL ARGUMENTS:
// "logs" : <string or array of strings> Possible Values: "hostinfo", "dispatcher", "events-dispatcher", "events-lifepreserver", "events-state";
// "time_format" : "<format>" Possible Values: "time_t_seconds", "epoch_mseconds", "relative_[day/month/second]", "<QDateTime String format>"
// See (http://doc.qt.io/qt-5/qdatetime.html#fromString) for details on the QDateTime String format codes
// "start_time" : "<number>" (according to format specified)
// "end_time" : "<number>" (according to format specified)
//First figure out which logs to read
QStringList logs;
if(obj.contains("logs")){
if(obj.value("logs").isString()){ logs << obj.value("logs").toString(); }
else if(obj.value("logs").isArray()){ logs = JsonArrayToStringList(obj.value("logs").toArray()); }
}
if(logs.isEmpty()){
//Use all logs if no particular one(s) are specified
logs << "hostinfo" << "dispatcher" << "events-dispatcher" << "events-lifepreserver" << "events-state";
}
//Get the time range for the logs
QString format = obj.value("time_format").toString();
QDateTime endtime = QDateTime::currentDateTime();
QDateTime starttime = endtime.addSecs( -3600*12); //12 hours back by default
if(!format.isEmpty()){
QString str_endtime = obj.value("end_time").toString();
QString str_starttime = obj.value("start_time").toString();
if(!str_endtime.isEmpty()){
if(format=="time_t_seconds"){ endtime = QDateTime::fromTime_t(str_endtime.toInt()); }
else if(format=="epoch_mseconds"){ endtime = QDateTime::fromMSecsSinceEpoch(str_endtime.toInt()); }
else if(format=="relative_day"){ endtime = endtime.addDays( 0-qAbs(str_endtime.toInt()) ); }
else if(format=="relative_month"){ endtime = endtime.addMonths( 0-qAbs(str_endtime.toInt()) ); }
else if(format=="relative_second"){ endtime = endtime.addSecs( 0-qAbs(str_endtime.toInt()) ); }
else{ endtime = QDateTime::fromString(str_endtime, format); }
}
if(!str_starttime.isEmpty()){
if(format=="time_t_seconds"){ starttime = QDateTime::fromTime_t(str_starttime.toInt()); }
else if(format=="epoch_mseconds"){ starttime = QDateTime::fromMSecsSinceEpoch(str_starttime.toInt()); }
else if(format=="relative_day"){ starttime = endtime.addDays( 0-qAbs(str_starttime.toInt()) ); }
else if(format=="relative_month"){ starttime = endtime.addMonths( 0-qAbs(str_starttime.toInt()) ); }
else if(format=="relative_second"){ starttime = endtime.addSecs( 0-qAbs(str_starttime.toInt()) ); }
else{ starttime = QDateTime::fromString(str_starttime, format); }
}
}
//Now read/return the logs
for(int i=0; i<logs.length(); i++){
int log = -1; //this needs to correspond to the LogManager::LOG_FILE enumeration
if(logs[i]=="hostinfo"){ log = 0; }
else if(logs[i]=="dispatcher"){ log = 1; }
else if(logs[i]=="events-dispatcher"){ log = 2; }
else if(logs[i]=="events-lifepreserver"){ log = 3; }
else if(logs[i]=="events-state"){ log = 4; }
if(log>=0){
QStringList info = LogManager::readLog( (LogManager::LOG_FILE)(log), starttime, endtime);
//REMINDER of format: "[datetime]<message>"
if(info.isEmpty()){ continue; } //nothing here
QJsonObject lobj;
for(int j=0; j<info.length(); j++){
if(log>=2){
//event logs - message is JSON data
lobj.insert(info[j].section("]",0,0).section("[",1,1), QJsonDocument::fromJson( info[j].section("]",1,-1).toLocal8Bit() ).object() );
}else{
//Simple text log
lobj.insert(info[j].section("]",0,0).section("[",1,1), info[j].section("]",1,-1));
}
}//end loop over log info
out->insert( logs[i], lobj);
}
}//end loop over log types
}else{
return RestOutputStruct::BADREQUEST;
}
//Return Success
return RestOutputStruct::OK;
}
//==== DISPATCHER ====
RestOutputStruct::ExitCode WebSocket::EvaluateDispatcherRequest(bool allaccess, const QJsonValue in_args, QJsonObject *out){
//dispatcher only needs a list of sub-commands at the moment (might change later)
if(!in_args.isObject() || !in_args.toObject().contains("action") ){ return RestOutputStruct::BADREQUEST; }
QString act = in_args.toObject().value("action").toString().toLower();
//Determine the type of action to perform
if(act=="run"){
if(!allaccess){ return RestOutputStruct::FORBIDDEN; } //this user does not have permission to queue jobs
QStringList ids = in_args.toObject().keys();
ids.removeAll("action"); //already handled the action
for(int i=0; i<ids.length(); i++){
//Get the list of commands for this id
QStringList cmds;
QJsonValue val = in_args.toObject().value(ids[i]);
if(val.isArray()){ cmds = JsonArrayToStringList(val.toArray()); }
else if(val.isString()){ cmds << val.toString(); }
else{
ids.removeAt(i);
i--;
continue;
}
//queue up this process
DISPATCHER->queueProcess(ids[i], cmds);
}
//Return the PENDING result
LogManager::log(LogManager::HOST, "Client Launched Processes["+SockPeerIP+"]: "+ids.join(",") );
out->insert("started", QJsonArray::fromStringList(ids));
}else if(act=="list"){
QJsonObject info = DISPATCHER->listJobs();
out->insert("jobs", info);
}else if(act=="kill" && in_args.toObject().contains("job_id") ){
if(!allaccess){ return RestOutputStruct::FORBIDDEN; } //this user does not have permission to modify jobs
QStringList ids;
QJsonValue val = in_args.toObject().value("job_id");
if(val.isArray()){ ids = JsonArrayToStringList(val.toArray()); }
else if(val.isString()){ ids << val.toString(); }
else{ return RestOutputStruct::BADREQUEST; }
out->insert("killed", DISPATCHER->killJobs(ids));
}else{
return RestOutputStruct::BADREQUEST;
}
//Return Success
return RestOutputStruct::OK;
}
//==== SYSADM -- BEADM ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmBEADMRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action")).toLower();
if(act=="listbes"){
ok = true;
out->insert("listbes", sysadm::BEADM::listBEs());
}else if(act=="renamebe"){
ok = true;
out->insert("renamebe", sysadm::BEADM::renameBE(in_args.toObject()));
}else if(act=="activatebe"){
ok = true;
out->insert("activatebe", sysadm::BEADM::activateBE(in_args.toObject()));
}else if(act=="createbe"){
ok = true;
out->insert("createbe", sysadm::BEADM::createBE(in_args.toObject()));
}else if(act=="destroybe"){
ok = true;
out->insert("destroybe", sysadm::BEADM::destroyBE(in_args.toObject()));
}else if(act=="mountbe"){
ok = true;
out->insert("mountbe", sysadm::BEADM::mountBE(in_args.toObject()));
}else if(act=="umountbe"){
ok = true;
out->insert("umountbe", sysadm::BEADM::umountBE(in_args.toObject()));
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- FS ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmFSRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action")).toLower();
if(act=="dirlist"){
ok = true;
out->insert("dirlist", sysadm::FS::list_dir(in_args.toObject()));
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- Network ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmNetworkRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action"));
if(act=="list-devices"){
ok = true;
QStringList devs = sysadm::NetDevice::listNetDevices();
for(int i=0; i<devs.length(); i++){
sysadm::NetDevice D(devs[i]);
QJsonObject obj;
//assemble the information about this device into an output object
obj.insert("ipv4", D.ipAsString());
obj.insert("ipv6", D.ipv6AsString());
obj.insert("netmask", D.netmaskAsString());
obj.insert("description", D.desc());
obj.insert("MAC", D.macAsString());
obj.insert("status", D.mediaStatusAsString());
obj.insert("is_active", D.isUp() ? "true" : "false" );
obj.insert("is_dhcp", D.usesDHCP() ? "true" : "false" );
obj.insert("is_wireless", D.isWireless() ? "true" : "false" );
//Add this device info to the main output structure
out->insert(devs[i], obj);
}
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- LifePreserver ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmLifePreserverRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action"));
if(act=="addreplication"){
ok = true;
out->insert("addreplication", sysadm::LifePreserver::addReplication(in_args.toObject()));
}
if(act=="createsnap"){
ok = true;
out->insert("createsnap", sysadm::LifePreserver::createSnapshot(in_args.toObject()));
}
if(act=="cronscrub"){
ok = true;
out->insert("cronscrub", sysadm::LifePreserver::scheduleScrub(in_args.toObject()));
}
if(act=="cronsnap"){
ok = true;
out->insert("cronsnap", sysadm::LifePreserver::scheduleSnapshot(in_args.toObject()));
}
if(act=="initreplication"){
ok = true;
out->insert("initreplication", sysadm::LifePreserver::initReplication(in_args.toObject()));
}
if(act=="listcron"){
ok = true;
out->insert("listcron", sysadm::LifePreserver::listCron());
}
if(act=="listreplication"){
ok = true;
out->insert("listreplication", sysadm::LifePreserver::listReplication());
}
if(act=="listsnap"){
ok = true;
out->insert("listsnap", sysadm::LifePreserver::listSnap(in_args.toObject()));
}
if(act=="removereplication"){
ok = true;
out->insert("removereplication", sysadm::LifePreserver::removeReplication(in_args.toObject()));
}
if(act=="removesnap"){
ok = true;
out->insert("removesnap", sysadm::LifePreserver::removeSnapshot(in_args.toObject()));
}
if(act=="revertsnap"){
ok = true;
out->insert("revertsnap", sysadm::LifePreserver::revertSnapshot(in_args.toObject()));
}
if(act=="runreplication"){
ok = true;
out->insert("runreplication", sysadm::LifePreserver::runReplication(in_args.toObject()));
}
if(act=="savesettings"){
ok = true;
out->insert("savesettings", sysadm::LifePreserver::saveSettings(in_args.toObject()));
}
if(act=="settings"){
ok = true;
out->insert("settings", sysadm::LifePreserver::settings());
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- SysMgmt ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmSystemMgmtRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action"));
if(act=="batteryinfo"){
ok = true;
out->insert("batteryinfo", sysadm::SysMgmt::batteryInfo());
}
if(act=="cpupercentage"){
ok = true;
out->insert("cpupercentage", sysadm::SysMgmt::cpuPercentage());
}
if(act=="cputemps"){
ok = true;
out->insert("cputemps", sysadm::SysMgmt::cpuTemps());
}
if(act=="externalmounts"){
ok = true;
out->insert("externalmounts", sysadm::SysMgmt::externalDevicePaths());
}
if(act=="halt"){
ok = true;
out->insert("halt", sysadm::SysMgmt::systemHalt());
}
if(act=="killproc"){
ok = true;
out->insert("killproc", sysadm::SysMgmt::killProc(in_args.toObject()));
}
if(act=="memorystats"){
ok = true;
out->insert("memorystats", sysadm::SysMgmt::memoryStats());
}
if(act=="procinfo"){
ok = true;
out->insert("procinfo", sysadm::SysMgmt::procInfo());
}
if(act=="reboot"){
ok = true;
out->insert("reboot", sysadm::SysMgmt::systemReboot());
}
if(act=="setsysctl"){
ok = true;
out->insert("setsysctl", sysadm::SysMgmt::setSysctl(in_args.toObject()));
}
if(act=="sysctllist"){
ok = true;
out->insert("sysctllist", sysadm::SysMgmt::sysctlList());
}
if(act=="systeminfo"){
ok = true;
out->insert("systeminfo", sysadm::SysMgmt::systemInfo());
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- Update ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmUpdateRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action"));
if(act=="checkupdates"){
ok = true;
bool fastcheck = true;
fastcheck = in_args.toObject().value("force").toString().toLower()!="true";
out->insert("checkupdates", sysadm::Update::checkUpdates(fastcheck));
}else if(act=="listbranches"){
ok = true;
out->insert("listbranches", sysadm::Update::listBranches());
}else if(act=="startupdate"){
ok = true;
out->insert("startupdate", sysadm::Update::startUpdate(in_args.toObject()) );
}else if(act=="stopupdate"){
ok = true;
out->insert("stopupdate", sysadm::Update::stopUpdate() );
}else if(act=="listsettings"){
ok = true;
out->insert("listsettings", sysadm::Update::readSettings() );
}else if(act=="changesettings"){
ok = true;
out->insert("changesettings", sysadm::Update::writeSettings(in_args.toObject()) );
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- iocage ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmIocageRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action"));
if(act=="execjail"){
ok = true;
out->insert("execjail", sysadm::Iocage::execJail(in_args.toObject()));
}
if(act=="df"){
ok = true;
out->insert("df", sysadm::Iocage::df());
}
if(act=="destroyjail"){
ok = true;
out->insert("destroyjail", sysadm::Iocage::destroyJail(in_args.toObject()));
}
if(act=="createjail"){
ok = true;
out->insert("createjail", sysadm::Iocage::createJail(in_args.toObject()));
}
if(act=="clonejail"){
ok = true;
out->insert("clonejail", sysadm::Iocage::cloneJail(in_args.toObject()));
}
if(act=="cleanall"){
ok = true;
out->insert("cleanall", sysadm::Iocage::cleanAll());
}
if(act=="cleantemplates"){
ok = true;
out->insert("cleantemplates", sysadm::Iocage::cleanTemplates());
}
if(act=="cleanreleases"){
ok = true;
out->insert("cleanreleases", sysadm::Iocage::cleanReleases());
}
if(act=="cleanjails"){
ok = true;
out->insert("cleanjails", sysadm::Iocage::cleanJails());
}
if(act=="capjail"){
ok = true;
out->insert("capjail", sysadm::Iocage::capJail(in_args.toObject()));
}
if(act=="deactivatepool"){
ok = true;
out->insert("deactivatepool", sysadm::Iocage::deactivatePool(in_args.toObject()));
}
if(act=="activatepool"){
ok = true;
out->insert("activatepool", sysadm::Iocage::activatePool(in_args.toObject()));
}
if(act=="stopjail"){
ok = true;
out->insert("stopjail", sysadm::Iocage::stopJail(in_args.toObject()));
}
if(act=="startjail"){
ok = true;
out->insert("startjail", sysadm::Iocage::startJail(in_args.toObject()));
}
if(act=="getdefaultsettings"){
ok = true;
out->insert("getdefaultsettings", sysadm::Iocage::getDefaultSettings());
}
if(act=="getjailsettings"){
ok = true;
out->insert("getjailsettings", sysadm::Iocage::getJailSettings(in_args.toObject()));
}
if(act=="listjails"){
ok = true;
out->insert("listjails", sysadm::Iocage::listJails());
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
//==== SYSADM -- iohyve ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmIohyveRequest(const QJsonValue in_args, QJsonObject *out){
if(in_args.isObject()){
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")){
QString act = JsonValueToString(in_args.toObject().value("action"));
//qDebug() << " - iohyve action:" << act;
if(act=="adddisk"){
ok = true;
out->insert("adddisk", sysadm::Iohyve::addDisk(in_args.toObject()));
}
if(act=="create"){
ok = true;
out->insert("create", sysadm::Iohyve::createGuest(in_args.toObject()));
}
if(act=="delete"){
ok = true;
out->insert("delete", sysadm::Iohyve::deleteGuest(in_args.toObject()));
}
if(act=="deletedisk"){
ok = true;
out->insert("deletedisk", sysadm::Iohyve::deleteDisk(in_args.toObject()));
}
else if(act=="listdisks"){
ok = true;
out->insert("listdisks", sysadm::Iohyve::listDisks(in_args.toObject()));
}
else if(act=="listvms"){
ok = true;
out->insert("listvms", sysadm::Iohyve::listVMs());
}
else if(act=="listisos"){
ok = true;
out->insert("listisos", sysadm::Iohyve::listISOs());
}
else if(act=="fetchiso"){
ok = true;
//DProcess fetchproc;
out->insert("fetchiso", sysadm::Iohyve::fetchISO(in_args.toObject()));
}
else if(act=="install"){
ok = true;
out->insert("install", sysadm::Iohyve::installGuest(in_args.toObject()));
}
else if(act=="issetup"){
ok = true;
out->insert("issetup", sysadm::Iohyve::isSetup());
}
else if(act=="renameiso"){
ok = true;
out->insert("renameiso", sysadm::Iohyve::renameISO(in_args.toObject()));
}
else if(act=="rmiso"){
ok = true;
out->insert("rmiso", sysadm::Iohyve::rmISO(in_args.toObject()));
}
else if(act=="resizedisk"){
ok = true;
out->insert("resizedisk", sysadm::Iohyve::resizeDisk(in_args.toObject()));
}
else if(act=="setup"){
ok = true;
out->insert("setup", sysadm::Iohyve::setupIohyve(in_args.toObject()));
}
else if(act=="start"){
ok = true;
out->insert("start", sysadm::Iohyve::startGuest(in_args.toObject()));
}
else if(act=="stop"){
ok = true;
out->insert("stop", sysadm::Iohyve::stopGuest(in_args.toObject()));
}
else if(act=="version"){
ok = true;
out->insert("version", sysadm::Iohyve::version());
}
//qDebug() << " - iohyve action finished:" << act << ok;
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
}else{ // if(in_args.isArray()){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
// ==== SYSADM ZFS API ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmZfsRequest(const QJsonValue in_args, QJsonObject *out){
if( ! in_args.isObject()){
return RestOutputStruct::BADREQUEST;
}
QStringList keys = in_args.toObject().keys();
bool ok = false;
if(keys.contains("action")) {
QString act = JsonValueToString(in_args.toObject().value("action"));
if(act=="list_pools"){
ok = true;
QJsonObject pools = sysadm::ZFS::zpool_list();
if(!pools.isEmpty()){ out->insert("list_pools",pools); }
}
else if(act=="datasets"){
ok = true;
out->insert("datasets", sysadm::ZFS::zfs_list(in_args.toObject()));
}
} //end of "action" key usage
//If nothing done - return the proper code
if(!ok){
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
// ==== SYSADM PKG API ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmPkgRequest(const QJsonValue in_args, QJsonObject *out){
if(!in_args.isObject() || !in_args.toObject().contains("action") ){ return RestOutputStruct::BADREQUEST; }
//REQUIRED: "action"
QString act = in_args.toObject().value("action").toString();
//OPTIONAL: "repo" (uses local repo database by default)
QString repo = "local";
if(in_args.toObject().contains("repo")){ repo = in_args.toObject().value("repo").toString(); }
//OPTIONAL: "category" (only used if "pkg_origins" is not specified)
QString cat;
if(in_args.toObject().contains("category")){ cat = in_args.toObject().value("category").toString(); }
//OPTIONAL: "pkg_origins" (defaults to everything for listing functions)
QStringList pkgs;
if(in_args.toObject().contains("pkg_origins")){
if(in_args.toObject().value("pkg_origins").isString()){ pkgs << in_args.toObject().value("pkg_origins").toString(); }
else if(in_args.toObject().value("pkg_origins").isArray()){ pkgs = JsonArrayToStringList(in_args.toObject().value("pkg_origins").toArray()); }
}
//Parse the action and perform accordingly
if(act=="pkg_info"){
//OPTIONAL: "pkg_origins" OR "category"
//OPTIONAL: "repo"
//OPTIONAL: "result" = "full" or "simple" (Default: "simple")
bool fullresults = false;
if(in_args.toObject().contains("result")){ fullresults = (in_args.toObject().value("result").toString()=="full"); }
//Now run the info fetch routine
QJsonObject info = sysadm::PKG::pkg_info(pkgs, repo, cat, fullresults);
if(!info.isEmpty()){ out->insert("pkg_info",info); }
else{ return RestOutputStruct::NOCONTENT; }
}else if(act=="pkg_search" && in_args.toObject().contains("search_term")){
//REQUIRED: "search_term" (string to search for)
//OPTIONAL: "repo"
//OPTIONAL: "category"
//OPTIONAL: "search_excludes" (array of string or single string);
QString srch = in_args.toObject().value("search_term").toString();
if(srch.isEmpty()){ return RestOutputStruct::BADREQUEST; }
QStringList exclude;
if(in_args.toObject().contains("search_excludes")){
if(in_args.toObject().value("search_excludes").isString()){ exclude << in_args.toObject().value("search_excludes").toString(); }
else if(in_args.toObject().value("search_excludes").isArray()){ exclude = JsonArrayToStringList( in_args.toObject().value("search_excludes").toArray() ); }
}
QStringList pkgs = sysadm::PKG::pkg_search(repo, srch, exclude, cat);
if(!pkgs.isEmpty()){
QJsonObject info = sysadm::PKG::pkg_info(pkgs, repo, cat, false); //always do simple results for a search
info.insert("results_order", QJsonArray::fromStringList(pkgs));
if(!info.isEmpty()){ out->insert("pkg_search",info); }
}else{
return RestOutputStruct::NOCONTENT;
}
}else if(act=="list_categories"){
//OPTIONAL: "repo"
QJsonArray cats = sysadm::PKG::list_categories(repo);
if(!cats.isEmpty()){ out->insert("list_categories", cats); }
else{ return RestOutputStruct::NOCONTENT; }
}else if(act=="list_repos"){
QJsonArray repos = sysadm::PKG::list_repos();
if(!repos.isEmpty()){ out->insert("list_repos", repos); }
else{ return RestOutputStruct::NOCONTENT; }
}else if(act=="pkg_install" && !pkgs.isEmpty() ){
//REQUIRED: "pkg_origins"
//OPTIONAL: "repo" (pkg will determine the best repo to use if not supplied)
out->insert("pkg_install", sysadm::PKG::pkg_install(pkgs,repo));
}else if(act=="pkg_remove" && !pkgs.isEmpty() ){
//REQUIRED: "pkg_origins"
//OPTIONAL: "recursive"="true" or "false" (default: "true")
bool recursive = true;
if(in_args.toObject().contains("recursive")){ recursive = in_args.toObject().value("recursive").toString()!="false"; }
out->insert("pkg_remove", sysadm::PKG::pkg_remove(pkgs, recursive));
}else if(act=="pkg_lock" && !pkgs.isEmpty() ){
//REQUIRED: "pkg_origins"
out->insert("pkg_lock", sysadm::PKG::pkg_lock(pkgs));
}else if(act=="pkg_unlock" && !pkgs.isEmpty() ){
//REQUIRED: "pkg_origins"
out->insert("pkg_unlock", sysadm::PKG::pkg_unlock(pkgs));
}else if(act=="pkg_update"){
//OPTIONAL: "force" = ["true"/"false"] (default: "false")
bool force = false;
if(in_args.toObject().contains("force")){ force = in_args.toObject().value("force").toString()=="true"; }
out->insert("pkg_update", sysadm::PKG::pkg_update(force));
}else if(act=="pkg_check_upgrade"){
out->insert("pkg_check_upgrade", sysadm::PKG::pkg_check_upgrade());
}else if(act=="pkg_upgrade"){
out->insert("pkg_upgrade", sysadm::PKG::pkg_upgrade());
}else if(act=="pkg_audit"){
out->insert("pkg_audit", sysadm::PKG::pkg_audit());
}else if(act=="pkg_autoremove"){
out->insert("pkg_autoremove", sysadm::PKG::pkg_autoremove());
}else{
//unknown action
return RestOutputStruct::BADREQUEST;
}
return RestOutputStruct::OK;
}
// ==== SYSADM USER API ====
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmUserRequest(bool allaccess, QString user, const QJsonValue in_args, QJsonObject *out){
bool ok = false;
//REQUIRED: "action"
QString action =in_args.toObject().value("action").toString().toLower();
if(action=="usershow"){
ok = sysadm::UserManager::listUsers(out, allaccess, user);
}else if(action=="useradd" && allaccess){ //requires all access to create new users
ok = sysadm::UserManager::addUser(out, in_args.toObject());
}else if(action=="userdelete" && allaccess){ //requires all access to remove users
//REQUIRED: "name"
//OPTIONAL: "clean_home"="false" (true by default)
QString deluser = in_args.toObject().value("name").toString();
if(deluser != user){ //cannot delete the currently-used user
bool clean = true;
if(in_args.toObject().contains("clean_home")){ clean = (in_args.toObject().value("clean_home").toString().toLower() != "false"); }
ok = sysadm::UserManager::removeUser(deluser, clean);
if(ok){ out->insert("result","success"); }
else{ out->insert("error","Could not delete user"); }
}else{
out->insert("error","Cannot delete the current user");
}
}else if(action=="usermod"){
bool go = true;
if(!allaccess){
//ensure that the user being acted on is the current user - otherwise deny access
go = (in_args.toObject().value("name").toString() == user);
}
if(go){ ok = sysadm::UserManager::modifyUser(out, in_args.toObject() ); }
}else if(action=="groupshow"){
ok = sysadm::UserManager::listGroups(out, (allaccess ? "" : user) );
}else if(action=="groupadd" && allaccess){
ok = sysadm::UserManager::addGroup(out, in_args.toObject() );
}else if(action=="groupdelete" && allaccess){
//REQUIRED: "name"
QString name = in_args.toObject().value("name").toString();
if(!name.isEmpty()){
ok = sysadm::UserManager::removeGroup(name);
}
if(ok){ out->insert("result","success"); }
else{ out->insert("error","Could not delete group"); }
}else if(action=="groupmod" && allaccess){
ok = sysadm::UserManager::modifyGroup(out, in_args.toObject() );
}else if(action=="personacrypt_init"){
qDebug() << "got PC init request:" << in_args << allaccess << user;
bool go = true;
if(!allaccess){
//ensure that the user being acted on is the current user - otherwise deny access
go = (in_args.toObject().value("name").toString() == user);
}
if(go){
//REQUIRED: "name", "password","device"
QJsonObject obj = in_args.toObject();
if(obj.contains("name") && obj.contains("password") && obj.contains("device") ){
ok = sysadm::UserManager::InitializePersonaCryptDevice(obj.value("name").toString(), obj.value("password").toString(), obj.value("device").toString() );
if(ok){ out->insert("result","success"); }
else{ out->insert("error","Could not initialize Personacrypt device"); }
}
}
}else if(action=="personacrypt_listdevs"){
QStringList devs = sysadm::UserManager::getAvailablePersonaCryptDevices();
for(int i=0; i<devs.length(); i++){
out->insert(devs[i].section(":",0,0), devs[i].section(":",1,-1).simplified()); //<device>:<info>
}
ok = true;
}
return (ok ? RestOutputStruct::OK : RestOutputStruct::BADREQUEST);
}
// SERVICE MANAGER (sysadm/services)
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmServiceRequest(const QJsonValue in_args, QJsonObject *out){
bool ok = false;
QString action = in_args.toObject().value("action").toString();
sysadm::ServiceManager SMGR;
if(action=="list_services"){
QList<sysadm::Service> list = SMGR.GetServices();
QList<bool> listEnabled = SMGR.isEnabled(list);
QJsonObject services;
for(int i=0; i<list.length(); i++){
QJsonObject S;
S.insert("name", list[i].Name);
S.insert("tag", list[i].Tag);
S.insert("path", list[i].Path);
S.insert("description", list[i].Description);
S.insert("is_enabled", listEnabled[i] ? "true" : "false" );
S.insert("is_running",SMGR.isRunning(list[i]) ? "true" : "false" );
//S.insert("filename", list[i].Directory);
//Need to add status info as well (isRunning, isEnabled);
services.insert(list[i].Name, S);
}
ok = true;
out->insert("services",services);
}else if(action=="start" && in_args.toObject().contains("services") ){
QJsonValue sval = in_args.toObject().value("services");
QStringList services;
if(sval.isString()){ services << sval.toString(); }
else if(sval.isArray()){ services = JsonArrayToStringList(sval.toArray()); }
if(!services.isEmpty()){
QStringList success;
ok = true;
for(int i=0; i<services.length(); i++){
if( SMGR.Start( SMGR.GetService(services[i]) ) ){ success << services[i]; }
}
out->insert("services_started", QJsonArray::fromStringList(success));
}
}else if(action=="stop" && in_args.toObject().contains("services") ){
QJsonValue sval = in_args.toObject().value("services");
QStringList services;
if(sval.isString()){ services << sval.toString(); }
else if(sval.isArray()){ services = JsonArrayToStringList(sval.toArray()); }
if(!services.isEmpty()){
QStringList success;
ok = true;
for(int i=0; i<services.length(); i++){
if( SMGR.Stop( SMGR.GetService(services[i]) ) ){ success << services[i]; }
}
out->insert("services_stopped", QJsonArray::fromStringList(success));
}
}else if(action=="restart" && in_args.toObject().contains("services") ){
QJsonValue sval = in_args.toObject().value("services");
QStringList services;
if(sval.isString()){ services << sval.toString(); }
else if(sval.isArray()){ services = JsonArrayToStringList(sval.toArray()); }
if(!services.isEmpty()){
QStringList success;
ok = true;
for(int i=0; i<services.length(); i++){
if( SMGR.Restart( SMGR.GetService(services[i]) ) ){ success << services[i]; }
}
out->insert("services_restarted", QJsonArray::fromStringList(success));
}
}else if(action=="enable" && in_args.toObject().contains("services") ){
QJsonValue sval = in_args.toObject().value("services");
QStringList services;
if(sval.isString()){ services << sval.toString(); }
else if(sval.isArray()){ services = JsonArrayToStringList(sval.toArray()); }
if(!services.isEmpty()){
QStringList success;
ok = true;
for(int i=0; i<services.length(); i++){
if( SMGR.Enable( SMGR.GetService(services[i]) ) ){ success << services[i]; }
}
out->insert("services_enabled", QJsonArray::fromStringList(success));
}
}else if(action=="disable" && in_args.toObject().contains("services") ){
QJsonValue sval = in_args.toObject().value("services");
QStringList services;
if(sval.isString()){ services << sval.toString(); }
else if(sval.isArray()){ services = JsonArrayToStringList(sval.toArray()); }
if(!services.isEmpty()){
QStringList success;
ok = true;
for(int i=0; i<services.length(); i++){
if( SMGR.Disable( SMGR.GetService(services[i]) ) ){ success << services[i]; }
}
out->insert("services_disabled", QJsonArray::fromStringList(success));
}
}
if(out->keys().isEmpty()){
if(ok){ out->insert("result","success"); }
else{ out->insert("error","error"); }
}
return (ok ? RestOutputStruct::OK : RestOutputStruct::BADREQUEST);
}
// FIREWALL MANAGER (sysadm/firewall)
RestOutputStruct::ExitCode WebSocket::EvaluateSysadmFirewallRequest(const QJsonValue in_args, QJsonObject *out){
bool ok = false;
QString action = in_args.toObject().value("action").toString();
sysadm::Firewall FMGR;
//Now perform actions as needed
if(action=="known_ports"){
ok = true;
QList<sysadm::PortInfo> all = FMGR.allPorts(); //this is all known ports (number/type, name, description) - it does not know about open/closed
for(int i=0; i<all.length(); i++){
QJsonObject obj;
obj.insert("name",all[i].Keyword);
obj.insert("port", QString::number(all[i].Port)+"/"+all[i].Type);
if(all[i].Description.isEmpty() && i>0 && (all[i-1].Keyword == all[i].Keyword) ){
obj.insert("description", all[i-1].Description);
}else{
obj.insert("description", all[i].Description);
}
out->insert(obj.value("port").toString(), obj); //use the port number/type as the unique identifier
}
}else if(action=="list_open"){
ok = true;
QList<sysadm::PortInfo> all = FMGR.OpenPorts(); //this is all ports currently opened
QStringList oports;
for(int i=0; i<all.length(); i++){
oports << QString::number(all[i].Port)+"/"+all[i].Type;
}
out->insert("openports", QJsonArray::fromStringList(oports));
}else if(action=="status"){
ok = true;
out->insert("is_running", FMGR.IsRunning() ? "true" : "false" );
out->insert("is_enabled", FMGR.IsEnabled() ? "true" : "false" );
}else if(action=="open" && in_args.toObject().contains("ports")){
//REQUIRED: "ports" = [<num>/<type>, <num2>/<type2>, etc..]
QJsonValue val = in_args.toObject().value("ports");
QStringList ports;
QList<sysadm::PortInfo> P;
if(val.isString()){ ports << val.toString(); }
else if(val.isArray()){ ports = JsonArrayToStringList(val.toArray()); }
for(int i=0; i<ports.length(); i++){
sysadm::PortInfo info = FMGR.LookUpPort(ports[i].section("/",0,0).toInt(), ports[i].section("/",1,1));
if(info.Port<0 || (info.Type!="tcp" && info.Type!="udp") ){ continue; }
P << info;
}
if(!P.isEmpty()){
ok = true;
FMGR.OpenPort(P);
}
}else if(action=="close" && in_args.toObject().contains("ports")){
//REQUIRED: "ports" = [<num>/<type>, <num2>/<type2>, etc..]
QJsonValue val = in_args.toObject().value("ports");
QStringList ports;
QList<sysadm::PortInfo> P;
if(val.isString()){ ports << val.toString(); }
else if(val.isArray()){ ports = JsonArrayToStringList(val.toArray()); }
for(int i=0; i<ports.length(); i++){
sysadm::PortInfo info = FMGR.LookUpPort(ports[i].section("/",0,0).toInt(), ports[i].section("/",1,1));
if(info.Port<0 || (info.Type!="tcp" && info.Type!="udp") ){ continue; }
P << info;
}
if(!P.isEmpty()){
ok = true;
FMGR.ClosePort(P);
}
}else if(action=="start"){
ok = true;
FMGR.Start();
}else if(action=="stop"){
ok = true;
FMGR.Stop();
}else if(action=="restart"){
ok = true;
FMGR.Restart();
}else if(action=="enable"){
ok = true;
FMGR.Enable();
}else if(action=="disable"){
ok = true;
FMGR.Disable();
}else if(action=="reset-defaults"){
ok = FMGR.RestoreDefaults();
}
//Evaluate outputs
if(out->keys().isEmpty()){
if(ok){ out->insert("result","success"); }
else{ out->insert("error","error"); }
}
return (ok ? RestOutputStruct::OK : RestOutputStruct::BADREQUEST);
}
| c3d2/sysadm | src/server/WebBackend.cpp | C++ | bsd-2-clause | 46,017 | [
30522,
1013,
1013,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1027,
1013,
1013,
7473,
1011,
18667,
20... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
//Change class of "Home" and "About"
function setActive() {
document.getElementById("about").className += "active"
document.getElementById("home").setAttribute('class','no')
}
| losko/CodeNameSite | public/js/helper.js | JavaScript | mit | 184 | [
30522,
1013,
1013,
2689,
2465,
1997,
1000,
2188,
1000,
1998,
1000,
2055,
1000,
3853,
2275,
19620,
1006,
1007,
1063,
6254,
1012,
2131,
12260,
3672,
3762,
3593,
1006,
1000,
2055,
1000,
1007,
1012,
2465,
18442,
1009,
1027,
1000,
3161,
1000,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require 'spec_helper'
describe SingleEventExternalUser do
it "must have a valid email address and a name" do
single_event = FactoryBot.create(:single_event)
expect(single_event.external_users.create(email: "hans#wurst.com", name: "Hans Wurst")).not_to be_valid
expect(single_event.external_users.create(email: nil, name: "Hans Wurst")).not_to be_valid
expect(single_event.external_users.create(email: "hans@wurst.com", name: nil)).not_to be_valid
expect(single_event.external_users.create(email: "hans@wurst.com", name: "Hans Wurst")).to be_valid
end
end
| hacken-in/website | spec/models/single_event_external_user_spec.rb | Ruby | mit | 581 | [
30522,
5478,
1005,
28699,
1035,
2393,
2121,
1005,
6235,
2309,
18697,
10111,
18413,
11795,
2389,
20330,
2079,
2009,
1000,
2442,
2031,
1037,
9398,
10373,
4769,
1998,
1037,
2171,
1000,
2079,
2309,
1035,
2724,
1027,
4713,
18384,
1012,
3443,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Thu Apr 24 20:55:48 UTC 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.core.SolrXMLSerializer.SolrXMLDef (Solr 4.8.0 API)</title>
<meta name="date" content="2014-04-24">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.core.SolrXMLSerializer.SolrXMLDef (Solr 4.8.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/core/SolrXMLSerializer.SolrXMLDef.html" title="class in org.apache.solr.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/core/class-use/SolrXMLSerializer.SolrXMLDef.html" target="_top">Frames</a></li>
<li><a href="SolrXMLSerializer.SolrXMLDef.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.core.SolrXMLSerializer.SolrXMLDef" class="title">Uses of Class<br>org.apache.solr.core.SolrXMLSerializer.SolrXMLDef</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.core.SolrXMLSerializer.SolrXMLDef</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/core/SolrXMLSerializer.SolrXMLDef.html" title="class in org.apache.solr.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/core/class-use/SolrXMLSerializer.SolrXMLDef.html" target="_top">Frames</a></li>
<li><a href="SolrXMLSerializer.SolrXMLDef.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2014 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| dtelaroli/angular-solr-example | solr-4.8.0/docs/solr-core/org/apache/solr/core/class-use/SolrXMLSerializer.SolrXMLDef.html | HTML | mit | 4,890 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
jsonp({"cep":"17036590","logradouro":"Alameda Juara","bairro":"Vale do Igap\u00f3","cidade":"Bauru","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/17036590.jsonp.js | JavaScript | cc0-1.0 | 139 | [
30522,
1046,
3385,
2361,
1006,
1063,
1000,
8292,
2361,
1000,
1024,
1000,
28366,
26187,
21057,
1000,
1010,
1000,
8833,
12173,
8162,
2080,
1000,
1024,
1000,
26234,
11960,
18414,
5400,
1000,
1010,
1000,
21790,
18933,
1000,
1024,
1000,
10380,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Pterocaulon globuliferus W.Fitzg. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Pterocaulon/Pterocaulon globuliferus/README.md | Markdown | apache-2.0 | 183 | [
30522,
1001,
13866,
10624,
3540,
18845,
2078,
1043,
4135,
8569,
15509,
7946,
1059,
1012,
27706,
2290,
1012,
2427,
1001,
1001,
1001,
1001,
3570,
3970,
1001,
1001,
1001,
1001,
2429,
2000,
2248,
3269,
3415,
5950,
1001,
1001,
1001,
1001,
2405,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# The script is based on tutorial written by Antonis Tsakiridis published at:
# https://medium.com/@atsakiridis/continuous-deployment-for-ios-using-travis-ci-55dcea342d9
#
# APPLE_CERT_URL - the URL pointing to Apple certificate (set to
# http://developer.apple.com/certificationauthority/AppleWWDRCA.cer by default)
# DEPLOY_SSH_CERT_URL - the SSH private key used by the 'scp' command to deploy
# the .ipa. It is expected to be encrypted with the $ENCRYPTION_PASSWORD.
# ENCRYPTION_PASSWORD - the password used to decrypt certificate/key files used
# in the script.
# IOS_DEV_CERT_KEY_URL - URL pointing to provisioning profile certificate key
# file (development-key.p12.enc from the tutorial) encrypted with the
# $ENCRYPTION_PASSWORD.
# IOS_DEV_CERT_URL - URL pointing to provisioning profile certificate file
# (development-cert.cer.enc from the tutorial) encrypted with the
# $ENCRYPTION_PASSWORD.
# IOS_DEV_PROV_PROFILE_URL - URL pointing to provisioning profile file
# (profile-development-olympus.mobileprovision.enc from the tutorial) encrypted
# IOS_DEV_WATCH_PROV_PROFILE_URL - URL pointing to watch app provisioning profile file(encrypted).
# with the $ENCRYPTION_PASSWORD.
# IOS_SIGNING_CERT_PASSWORD - the password to the provisioning profile
# certificate key (used to open development-key.p12 from the tutorial).
function echoAndExit1() {
echo $1
exit 1
}
CERT_DIR=$1
if [ -z $CERT_DIR ]; then
echoAndExit1 "First argument must be certificates directory"
fi
if [ -z $APPLE_CERT_URL ]; then
APPLE_CERT_URL="http://developer.apple.com/certificationauthority/AppleWWDRCA.cer"
fi
if [ -z $DEPLOY_SSH_CERT_URL ]; then
echoAndExit1 "DEPLOY_SSH_CERT_URL env var is not defined"
fi
if [ -z $ENCRYPTION_PASSWORD ]; then
echoAndExit1 "ENCRYPTION_PASSWORD env var is not defined"
fi
if [ -z $IOS_DEV_CERT_KEY_URL ]; then
echoAndExit1 "IOS_DEV_CERT_KEY_URL env var is not defined"
fi
if [ -z $IOS_DEV_CERT_URL ]; then
echoAndExit1 "IOS_DEV_CERT_URL env var is not defined"
fi
if [ -z $IOS_DEV_PROV_PROFILE_URL ]; then
echoAndExit1 "IOS_DEV_PROV_PROFILE_URL env var is not defined"
fi
if [ -z $IOS_DEV_WATCH_PROV_PROFILE_URL ]; then
echoAndExit1 "IOS_DEV_WATCH_PROV_PROFILE_URL env var is not defined"
fi
if [ -z $IOS_SIGNING_CERT_PASSWORD ]; then
echoAndExit1 "IOS_SIGNING_CERT_PASSWORD env var is not defined"
fi
# certificates
curl -L -o ${CERT_DIR}/AppleWWDRCA.cer 'http://developer.apple.com/certificationauthority/AppleWWDRCA.cer'
curl -L -o ${CERT_DIR}/dev-cert.cer.enc ${IOS_DEV_CERT_URL}
curl -L -o ${CERT_DIR}/dev-key.p12.enc ${IOS_DEV_CERT_KEY_URL}
curl -L -o ${CERT_DIR}/dev-profile.mobileprovision.enc ${IOS_DEV_PROV_PROFILE_URL}
curl -L -o ${CERT_DIR}/dev-watch-profile.mobileprovision.enc ${IOS_DEV_WATCH_PROV_PROFILE_URL}
openssl aes-256-cbc -k "$ENCRYPTION_PASSWORD" -in ${CERT_DIR}/dev-cert.cer.enc -d -a -out ${CERT_DIR}/dev-cert.cer
openssl aes-256-cbc -k "$ENCRYPTION_PASSWORD" -in ${CERT_DIR}/dev-key.p12.enc -d -a -out ${CERT_DIR}/dev-key.p12
openssl aes-256-cbc -k "$ENCRYPTION_PASSWORD" -in ${CERT_DIR}/dev-profile.mobileprovision.enc -d -a -out ${CERT_DIR}/dev-profile.mobileprovision
openssl aes-256-cbc -k "$ENCRYPTION_PASSWORD" -in ${CERT_DIR}/dev-watch-profile.mobileprovision.enc -d -a -out ${CERT_DIR}/dev-watch-profile.mobileprovision
security create-keychain -p $ENCRYPTION_PASSWORD ios-build.keychain
security default-keychain -s ios-build.keychain
security unlock-keychain -p $ENCRYPTION_PASSWORD ios-build.keychain
security set-keychain-settings -t 3600 -l ~/Library/Keychains/ios-build.keychain
echo "importing Apple cert"
security import ${CERT_DIR}/AppleWWDRCA.cer -k ios-build.keychain -A
echo "importing dev-cert.cer"
security import ${CERT_DIR}/dev-cert.cer -k ios-build.keychain -A
echo "importing dev-key.p12"
security import ${CERT_DIR}/dev-key.p12 -k ios-build.keychain -P $IOS_SIGNING_CERT_PASSWORD -A
echo "will set-key-partition-list"
# Fix for OS X Sierra that hungs in the codesign step
security set-key-partition-list -S apple-tool:,apple: -s -k $ENCRYPTION_PASSWORD ios-build.keychain > /dev/null
echo "done set-key-partition-list"
mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
cp "${CERT_DIR}/dev-profile.mobileprovision" ~/Library/MobileDevice/Provisioning\ Profiles/
cp "${CERT_DIR}/dev-watch-profile.mobileprovision" ~/Library/MobileDevice/Provisioning\ Profiles/
| bgrozev/jitsi-meet | ios/ci/setup-certificates.sh | Shell | apache-2.0 | 4,386 | [
30522,
1001,
1996,
5896,
2003,
2241,
2006,
14924,
4818,
2517,
2011,
9865,
2483,
24529,
8978,
14615,
2483,
2405,
2012,
1024,
1001,
16770,
1024,
1013,
1013,
5396,
1012,
4012,
1013,
1030,
2012,
3736,
23630,
28173,
2015,
1013,
7142,
1011,
10813... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env bash
#
# Copyright IBM Corp. 2020
#
# Check lcov --summary output for info files containing 100% coverage rates
#
STDOUT=summary_full_stdout.log
STDERR=summary_full_stderr.log
$LCOV --summary "${FULLINFO}" >${STDOUT} 2>${STDERR}
RC=$?
cat "${STDOUT}" "${STDERR}"
# Exit code must be zero
if [[ $RC -ne 0 ]] ; then
echo "Error: Non-zero lcov exit code $RC"
exit 1
fi
# There must be output on stdout
if [[ ! -s "${STDOUT}" ]] ; then
echo "Error: Missing output on standard output"
exit 1
fi
# There must not be any output on stderr
if [[ -s "${STDERR}" ]] ; then
echo "Error: Unexpected output on standard error"
exit 1
fi
# Check counts in output
check_counts "$FULLCOUNTS" "${STDOUT}" || exit 1
# Success
exit 0
| linux-test-project/lcov | tests/lcov/summary/full.sh | Shell | gpl-2.0 | 741 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
24234,
1001,
1001,
9385,
9980,
13058,
1012,
12609,
1001,
1001,
4638,
29215,
4492,
1011,
1011,
12654,
6434,
2005,
18558,
6764,
4820,
2531,
1003,
6325,
6165,
1001,
2358,
26797,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.mrlolethan.butteredpd.effects.particles;
import com.watabou.noosa.particles.Emitter;
import com.watabou.noosa.particles.Emitter.Factory;
import com.watabou.noosa.particles.PixelParticle;
import com.watabou.utils.Random;
public class SmokeParticle extends PixelParticle {
public static final Factory FACTORY = new Factory() {
@Override
public void emit( Emitter emitter, int index, float x, float y ) {
((SmokeParticle)emitter.recycle( SmokeParticle.class )).reset( x, y );
}
};
public SmokeParticle() {
super();
color( 0x222222 );
acc.set( 0, -40 );
}
public void reset( float x, float y ) {
revive();
this.x = x;
this.y = y;
left = lifespan = Random.Float( 0.6f, 1f );
speed.set( Random.Float( -4, +4 ), Random.Float( -8, +8 ) );
}
@Override
public void update() {
super.update();
float p = left / lifespan;
am = p > 0.8f ? 2 - 2*p : p * 0.5f;
size( 16 - p * 8 );
}
} | mrlolethan/Buttered-Pixel-Dungeon | src/com/mrlolethan/butteredpd/effects/particles/SmokeParticle.java | Java | gpl-3.0 | 1,728 | [
30522,
1013,
1008,
1008,
22138,
16633,
1008,
9385,
1006,
1039,
1007,
2262,
1011,
2325,
25841,
2079,
2135,
2050,
1008,
1008,
10909,
22138,
16633,
1008,
9385,
1006,
1039,
1007,
2297,
1011,
2325,
9340,
2139,
10609,
3511,
1008,
1008,
2023,
2565... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>parser_extras.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../css/github.css" type="text/css" media="screen" />
<script src="../../../../../../../../../../../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.1.8</span><br />
<h1>
parser_extras.rb
</h1>
<ul class="files">
<li>
../../../../usr/local/share/gems/gems/actionpack-4.1.8/lib/action_dispatch/journey/parser_extras.rb
</li>
<li>Last modified: 2014-11-25 22:16:16 +0530</li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- File only: requires -->
<div class="sectiontitle">Required Files</div>
<ul>
<li>action_dispatch/journey/scanner</li>
<li>action_dispatch/journey/nodes/node</li>
</ul>
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">MODULE</span>
<a href="../../../../../../../../../../../../../../classes/ActionDispatch.html">ActionDispatch</a>
</li>
</ul>
<!-- Methods -->
</div>
</div>
</body>
</html> | delta/DalalStreet | doc/api/files/__/__/__/__/usr/local/share/gems/gems/actionpack-4_1_8/lib/action_dispatch/journey/parser_extras_rb.html | HTML | mit | 2,377 | [
30522,
1026,
1029,
20950,
2544,
1027,
1000,
1015,
1012,
1014,
1000,
17181,
1027,
1000,
21183,
2546,
1011,
1022,
1000,
1029,
1028,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
1060,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
TARGETS=$(patsubst %.c,%,$(wildcard *.c))
LDLIBS += -lpthread
all: $(TARGETS)
conn: conn.c
$(CC) $(CFLAGS) -m32 -o $@ $^
clean:
rm -f $(TARGETS)
| rgbriggs/audit-testsuite | tests/syscall_socketcall/Makefile | Makefile | gpl-2.0 | 151 | [
30522,
7889,
1027,
1002,
1006,
6986,
6342,
5910,
2102,
1003,
1012,
1039,
1010,
1003,
1010,
1002,
1006,
3748,
11522,
1008,
1012,
1039,
1007,
1007,
25510,
29521,
2015,
1009,
1027,
1011,
6948,
2705,
16416,
2094,
2035,
1024,
1002,
1006,
7889,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Index imovel | wdantas/ImobControl | admin/application/views/imovel/index.php | PHP | gpl-2.0 | 12 | [
30522,
5950,
10047,
21818,
2140,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/** @ingroup PN532
* @{
*/
#ifndef PN532_H
#define PN532_H
/*******************| Inclusions |*************************************/
#include <stdint.h>
/*******************| Macros |*****************************************/
//#define PN532_DEBUG
#define PN532_FRAME_PREAMBLE (uint8_t)0x00
#define PN532_FRAME_STARTCODE1 (uint8_t)0x00
#define PN532_FRAME_STARTCODE2 (uint8_t)0xFF
#define PN532_FRAME_TFI_HOSTTOCONTROLLER (uint8_t)0xD4
#define PN532_FRAME_TFI_CONTROLLERTOHOST (uint8_t)0xD5
#define PN532_FRAME_POSTAMBLE (uint8_t)0x00
#define PN532_FRAMEHEADER_LENGTH (uint8_t)0x06
#define PN532_FRAMEFOOTER_LENGTH (uint8_t)0x02
#define PN532_FRAME_LENGTH PN532_FRAMEHEADER_LENGTH + PN532_FRAMEFOOTER_LENGTH
#define PN532_ACKFRAME_LENGTH sizeof(PN532_AckFrame_t)
#define PN532_STATUSRAME_LENGTH (uint8_t)0x01
#define PN532_LOWBYTE(a) (uint8_t)(a&0x00ff)
#define PN532_HIGHBYTEBYTE(a) (uint8_t)(a&0x00ff)
/**
* Defines how often a status byte is requests and check for ready status
* before giving up */
#define PN532_STATUSBYTE_TIMEOUT (uint8_t)0x10
#define PN532_STATUSBYTE_RDY (uint8_t)0x01
/*******************| Type definitions |*******************************/
typedef struct {
uint8_t preamble; /*!< fix 0x00 */
uint16_t startOfPacketCode; /*!< fix 0x00ff */
uint16_t packetCode; /*!< 0x0ff for ACK frame, 0xff00 for NACK frame */
uint8_t postamble; /*!< fix 0x00 */
} PN532_AckFrame_t;
typedef enum {
/* Miscellaneous Communication Commands */
PN532_CommandCode_Diagnose = 0x00,
PN532_CommandCode_GetFirmwareVersion = 0x02,
PN532_CommandCode_GetGeneralStatus = 0x04,
PN532_CommandCode_ReadRegister = 0x06,
PN532_CommandCode_WriteRegister = 0x08,
PN532_CommandCode_ReadGPIO = 0x0c,
PN532_CommandCode_WriteGPIO = 0x0e,
PN532_CommandCode_SetSerialBaudRate = 0x10,
PN532_CommandCode_SetParameters = 0x12,
PN532_CommandCode_SAMConfiguration = 0x14,
PN532_CommandCode_PowerDown = 0x16,
/* RF Communication Commands */
PN532_CommandCode_RFConfiguration = 0x32,
PN532_CommandCode_RFRegulationTest = 0x58,
PN532_CommandCode_InJumpForDEP = 0x56,
PN532_CommandCode_InJumpForPSL = 0x46,
PN532_CommandCode_InListPassiveTarget = 0x4a,
PN532_CommandCode_InATR = 0x50,
PN532_CommandCode_InPSL = 0x4e,
PN532_CommandCode_InDataExchange = 0x40,
PN532_CommandCode_InCommunicateThru = 0x42,
PN532_CommandCode_InDeselect = 0x44,
PN532_CommandCode_InRelease = 0x52,
PN532_CommandCode_InSelect = 0x54,
PN532_CommandCode_InAutoPoll = 0x60,
PN532_CommandCode_TgInitAsTarget = 0x8c,
PN532_CommandCode_TgSetGeneralBytes = 0x92,
PN532_CommandCode_TgGetData = 0x86,
PN532_CommandCode_TgSetData = 0x8e,
PN532_CommandCode_TgSetMetaData = 0x94,
PN532_CommandCode_TgGetInitiatorCommand = 0x88,
PN532_CommandCode_TgResponseToInitiatior = 0x90,
PN532_CommandCode_TgSetTargetStatus = 0x8a
} PN532_CommandCode_t;
typedef uint8_t PN532_Data_t;
/*******************| Global variables |*******************************/
/*******************| Function prototypes |****************************/
class PN532
{
private:
const uint8_t PN532Address;
bool waitForStatusReady();
bool receiveAckFrame();
public:
PN532(uint8_t address);
bool sendCommand(PN532_CommandCode_t command, PN532_Data_t *data, uint8_t length);
uint8_t receiveResponse(PN532_Data_t *data, uint8_t length);
};
#endif
/** @}*/
| kein0r/NFCTool | PN532.h | C | gpl-2.0 | 3,561 | [
30522,
1013,
1008,
1008,
1030,
13749,
22107,
1052,
2078,
22275,
2475,
1008,
1030,
1063,
1008,
1013,
1001,
2065,
13629,
2546,
1052,
2078,
22275,
2475,
1035,
1044,
1001,
9375,
1052,
2078,
22275,
2475,
1035,
1044,
1013,
1008,
1008,
1008,
1008,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Type definitions for non-npm package Atom 1.36
// Project: https://github.com/atom/atom
// Definitions by: GlenCFL <https://github.com/GlenCFL>
// smhxx <https://github.com/smhxx>
// lierdakil <https://github.com/lierdakil>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// NOTE: only those classes exported within this file should be retain that status below.
// https://github.com/atom/atom/blob/v1.36.0/exports/atom.js
/// <reference types="node" />
import { ReadStream, WriteStream } from "fs";
import { ChildProcess } from "child_process";
declare global {
const atom: AtomEnvironment;
interface HTMLElementTagNameMap {
"atom-text-editor": TextEditorElement;
}
}
/**
* Invoke a callback with each filesystem event that occurs beneath a specified path.
* If you only need to watch events within the project's root paths, use
* Project::onDidChangeFiles instead.
*/
export function watchPath(rootPath: string, options: {}, eventCallback: (events:
FilesystemChangeEvent) => void): Promise<PathWatcher>;
// Essential Classes ==========================================================
/**
* Atom global for dealing with packages, themes, menus, and the window.
* An instance of this class is always available as the atom global.
*/
export interface AtomEnvironment {
// Properties
/** A CommandRegistry instance. */
readonly commands: CommandRegistry;
/** A Config instance. */
readonly config: Config;
/** A Clipboard instance. */
readonly clipboard: Clipboard;
/** A ContextMenuManager instance. */
readonly contextMenu: ContextMenuManager;
/** A MenuManager instance. */
readonly menu: MenuManager;
/** A KeymapManager instance. */
readonly keymaps: KeymapManager;
/** A TooltipManager instance. */
readonly tooltips: TooltipManager;
/** A NotificationManager instance. */
readonly notifications: NotificationManager;
/** A Project instance. */
readonly project: Project;
/** A GrammarRegistry instance. */
readonly grammars: GrammarRegistry;
/** A HistoryManager instance. */
readonly history: HistoryManager;
/** A PackageManager instance. */
readonly packages: PackageManager;
/** A ThemeManager instance. */
readonly themes: ThemeManager;
/** A StyleManager instance. */
readonly styles: StyleManager;
/** A DeserializerManager instance. */
readonly deserializers: DeserializerManager;
/** A ViewRegistry instance. */
readonly views: ViewRegistry;
/** A Workspace instance. */
readonly workspace: Workspace;
/** A TextEditorRegistry instance. */
readonly textEditors: TextEditorRegistry;
// Event Subscription
/** Invoke the given callback whenever ::beep is called. */
onDidBeep(callback: () => void): Disposable;
/**
* Invoke the given callback when there is an unhandled error, but before
* the devtools pop open.
*/
onWillThrowError(callback: (event: PreventableExceptionThrownEvent) => void): Disposable;
/** Invoke the given callback whenever there is an unhandled error. */
onDidThrowError(callback: (event: ExceptionThrownEvent) => void): Disposable;
/**
* Invoke the given callback as soon as the shell environment is loaded (or
* immediately if it was already loaded).
*/
whenShellEnvironmentLoaded(callback: () => void): Disposable;
// Atom Details
/** Returns a boolean that is true if the current window is in development mode. */
inDevMode(): boolean;
/** Returns a boolean that is true if the current window is in safe mode. */
inSafeMode(): boolean;
/** Returns a boolean that is true if the current window is running specs. */
inSpecMode(): boolean;
/** Get the version of the Atom application. */
getVersion(): string;
/**
* Gets the release channel of the Atom application.
* Returns the release channel, which can be 'dev', 'beta', or 'stable'.
*/
getReleaseChannel(): "dev"|"beta"|"stable";
/** Returns a boolean that is true if the current version is an official release. */
isReleasedVersion(): boolean;
/** Get the time taken to completely load the current window. */
getWindowLoadTime(): number;
/** Get the load settings for the current window. */
getLoadSettings(): WindowLoadSettings;
// Managing the Atom Window
/** Open a new Atom window using the given options. */
open(params?: {
pathsToOpen: ReadonlyArray<string>,
newWindow?: boolean,
devMode?: boolean,
safeMode?: boolean,
}): void;
/** Close the current window. */
close(): void;
/** Get the size of current window. */
getSize(): { width: number, height: number };
/** Set the size of current window. */
setSize(width: number, height: number): void;
/** Get the position of current window. */
getPosition(): { x: number, y: number };
/** Set the position of current window. */
setPosition(x: number, y: number): void;
/** Prompt the user to select one or more folders. */
pickFolder(callback: (paths: string[]|null) => void): void;
/** Get the current window. */
getCurrentWindow(): object;
/** Move current window to the center of the screen. */
center(): void;
/** Focus the current window. */
focus(): void;
/** Show the current window. */
show(): void;
/** Hide the current window. */
hide(): void;
/** Reload the current window. */
reload(): void;
/** Relaunch the entire application. */
restartApplication(): void;
/** Returns a boolean that is true if the current window is maximized. */
isMaximized(): boolean;
/** Returns a boolean that is true if the current window is in full screen mode. */
isFullScreen(): boolean;
/** Set the full screen state of the current window. */
setFullScreen(fullScreen: boolean): void;
/** Toggle the full screen state of the current window. */
toggleFullScreen(): void;
// Messaging the User
/** Visually and audibly trigger a beep. */
beep(): void;
/**
* A flexible way to open a dialog akin to an alert dialog. If a callback
* is provided, then the confirmation will work asynchronously, which is
* recommended.
*
* If the dialog is closed (via `Esc` key or `X` in the top corner) without
* selecting a button the first button will be clicked unless a "Cancel" or "No"
* button is provided.
*
* Returns the chosen button index number if the buttons option was an array.
* @param response The index of the button that was clicked.
* @param checkboxChecked The checked state of the checkbox if `checkboxLabel` was set.
* Otherwise false.
*/
confirm(options: ConfirmationOptions, callback: (response: number,
checkboxChecked: boolean) => void): void;
/**
* A flexible way to open a dialog akin to an alert dialog. If a callback
* is provided, then the confirmation will work asynchronously, which is
* recommended.
*
* If the dialog is closed (via `Esc` key or `X` in the top corner) without
* selecting a button the first button will be clicked unless a "Cancel" or "No"
* button is provided.
*
* Returns the chosen button index number if the buttons option was an array.
*/
confirm(options: {
message: string,
detailedMessage?: string,
buttons?: ReadonlyArray<string>,
}): void;
/**
* A flexible way to open a dialog akin to an alert dialog. If a callback
* is provided, then the confirmation will work asynchronously, which is
* recommended.
*
* If the dialog is closed (via `Esc` key or `X` in the top corner) without
* selecting a button the first button will be clicked unless a "Cancel" or "No"
* button is provided.
*
* Returns the chosen button index number if the buttons option was an array.
*/
confirm(options: {
message: string,
detailedMessage?: string,
buttons?: {
[key: string]: () => void
},
}): number;
// Managing the Dev Tools
/** Open the dev tools for the current window. */
openDevTools(): Promise<null>;
/** Toggle the visibility of the dev tools for the current window. */
toggleDevTools(): Promise<null>;
/** Execute code in dev tools. */
executeJavaScriptInDevTools(code: string): void;
/** Undocumented: get Atom config directory path */
getConfigDirPath(): string;
}
/**
* A simple color class returned from Config::get when the value at the key path is
* of type 'color'.
*/
export interface Color {
/** Returns a string in the form '#abcdef'. */
toHexString(): string;
/** Returns a string in the form 'rgba(25, 50, 75, .9)'. */
toRGBAString(): string;
}
export interface CommandRegistryTargetMap extends HTMLElementTagNameMap {
[key: string]: EventTarget;
}
export type CommandRegistryListener<TargetType extends EventTarget> = {
didDispatch(event: CommandEvent<TargetType>): void | Promise<void>,
displayName?: string,
description?: string,
hiddenInCommandPalette?: boolean,
} | ((event: CommandEvent<TargetType>) => void | Promise<void>);
/**
* Associates listener functions with commands in a context-sensitive way
* using CSS selectors.
*/
export interface CommandRegistry {
/** Register a single command. */
add<T extends keyof CommandRegistryTargetMap>(
target: T, commandName: string,
listener: CommandRegistryListener<CommandRegistryTargetMap[T]>
): Disposable;
/** Register a single command. */
add<T extends Node>(
target: T, commandName: string,
listener: CommandRegistryListener<T>
): Disposable;
/** Register multiple commands. */
add<T extends keyof CommandRegistryTargetMap>(target: T, commands: {
[key: string]: CommandRegistryListener<CommandRegistryTargetMap[T]>
}): CompositeDisposable;
/** Register multiple commands. */
add<T extends Node>(target: T, commands: {
[key: string]: CommandRegistryListener<T>
}): CompositeDisposable;
/** Find all registered commands matching a query. */
findCommands(params: { target: string|Node }): Array<{
name: string,
displayName: string,
description?: string,
tags?: string[],
}>;
/**
* Simulate the dispatch of a command on a DOM node.
* @return Either a Promise that resolves after all handlers complete or null if
* no handlers were matched.
*/
dispatch(target: Node, commandName: string): Promise<void> | null;
/** Invoke the given callback before dispatching a command event. */
onWillDispatch(callback: (event: CommandEvent) => void): Disposable;
/** Invoke the given callback after dispatching a command event. */
onDidDispatch(callback: (event: CommandEvent) => void): Disposable;
}
/**
* An object that aggregates multiple Disposable instances together into a
* single disposable, so they can all be disposed as a group.
*/
export class CompositeDisposable implements DisposableLike {
/** Construct an instance, optionally with one or more disposables. */
constructor(...disposables: DisposableLike[]);
/**
* Dispose all disposables added to this composite disposable.
* If this object has already been disposed, this method has no effect.
*/
dispose(): void;
// Managing Disposables
/**
* Add disposables to be disposed when the composite is disposed.
* If this object has already been disposed, this method has no effect.
*/
add(...disposables: DisposableLike[]): void;
/** Remove a previously added disposable. */
remove(disposable: DisposableLike): void;
/** Alias to CompositeDisposable::remove. */
delete(disposable: DisposableLike): void;
/**
* Clear all disposables. They will not be disposed by the next call to
* dispose.
*/
clear(): void;
}
/** Used to access all of Atom's configuration details. */
export interface Config {
// Config Subscription
/**
* Add a listener for changes to a given key path. This is different than ::onDidChange in
* that it will immediately call your callback with the current value of the config entry.
*/
observe<T extends keyof ConfigValues>(keyPath: T, callback:
(value: ConfigValues[T]) => void): Disposable;
/**
* Add a listener for changes to a given key path. This is different than ::onDidChange in
* that it will immediately call your callback with the current value of the config entry.
*/
observe<T extends keyof ConfigValues>(keyPath: T, options:
{ scope: string[]|ScopeDescriptor }, callback: (value: ConfigValues[T]) => void):
Disposable;
/**
* Add a listener for changes to a given key path. If keyPath is not specified, your
* callback will be called on changes to any key.
*/
// tslint:disable-next-line:no-any
onDidChange<T = any>(callback: (values: { newValue: T, oldValue: T }) => void):
Disposable;
/**
* Add a listener for changes to a given key path. If keyPath is not specified, your
* callback will be called on changes to any key.
*/
onDidChange<T extends keyof ConfigValues>(keyPath: T, callback: (values: {
newValue: ConfigValues[T],
oldValue?: ConfigValues[T],
}) => void): Disposable;
/**
* Add a listener for changes to a given key path. If keyPath is not specified, your
* callback will be called on changes to any key.
*/
onDidChange<T extends keyof ConfigValues>(keyPath: T, options:
{ scope: string[]|ScopeDescriptor }, callback:
(values: { newValue: ConfigValues[T], oldValue?: ConfigValues[T] }) => void):
Disposable;
// Managing Settings
/** Retrieves the setting for the given key. */
get<T extends keyof ConfigValues>(keyPath: T, options?: { sources?: string[],
excludeSources?: string[], scope?: string[]|ScopeDescriptor }):
ConfigValues[T];
/**
* Sets the value for a configuration setting.
* This value is stored in Atom's internal configuration file.
*/
set<T extends keyof ConfigValues>(keyPath: T, value: ConfigValues[T], options?:
{ scopeSelector?: string, source?: string }): void;
/** Restore the setting at keyPath to its default value. */
unset(keyPath: string, options?: { scopeSelector?: string, source?: string }): void;
/**
* Get all of the values for the given key-path, along with their associated
* scope selector.
*/
getAll<T extends keyof ConfigValues>(keyPath: T, options?: { sources?: string[],
excludeSources?: string[], scope?: ScopeDescriptor }):
Array<{ scopeDescriptor: ScopeDescriptor, value: ConfigValues[T] }>;
/**
* Get an Array of all of the source Strings with which settings have been added
* via ::set.
*/
getSources(): string[];
/**
* Retrieve the schema for a specific key path. The schema will tell you what type
* the keyPath expects, and other metadata about the config option.
*/
getSchema(keyPath: string): object|null;
/** Get the string path to the config file being used. */
getUserConfigPath(): string;
/**
* Suppress calls to handler functions registered with ::onDidChange and ::observe
* for the duration of callback. After callback executes, handlers will be called
* once if the value for their key-path has changed.
*/
transact(callback: () => void): void;
}
/**
* Represents a decoration that follows a DisplayMarker. A decoration is basically
* a visual representation of a marker. It allows you to add CSS classes to line
* numbers in the gutter, lines, and add selection-line regions around marked ranges
* of text.
*/
export interface Decoration {
/** The identifier for this Decoration. */
readonly id: number;
// Construction and Destruction
/**
* Destroy this marker decoration.
* You can also destroy the marker if you own it, which will destroy this decoration.
*/
destroy(): void;
// Event Subscription
/** When the Decoration is updated via Decoration::setProperties. */
onDidChangeProperties(callback: (event: DecorationPropsChangedEvent) => void): Disposable;
/** Invoke the given callback when the Decoration is destroyed. */
onDidDestroy(callback: () => void): Disposable;
// Decoration Details
/** An id unique across all Decoration objects. */
getId(): number;
/** Returns the marker associated with this Decoration. */
getMarker(): DisplayMarker;
/**
* Check if this decoration is of the given type.
* @param type A decoration type, such as `line-number` or `line`. This may also
* be an array of decoration types, with isType returning true if the decoration's
* type matches any in the array.
*/
isType(type: string|string[]): boolean;
// Properties
/** Returns the Decoration's properties. */
getProperties(): DecorationOptions;
/**
* Update the marker with new Properties. Allows you to change the decoration's
* class.
*/
setProperties(newProperties: DecorationOptions): void;
}
/**
* Represents a buffer annotation that remains logically stationary even as the
* buffer changes. This is used to represent cursors, folds, snippet targets,
* misspelled words, and anything else that needs to track a logical location
* in the buffer over time.
*/
export interface DisplayMarker {
// Construction and Destruction
/**
* Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed,
* a marker cannot be restored by undo/redo operations.
*/
destroy(): void;
/** Creates and returns a new DisplayMarker with the same properties as this marker. */
copy(options?: CopyMarkerOptions): DisplayMarker;
// Event Subscription
/** Invoke the given callback when the state of the marker changes. */
onDidChange(callback: (event: DisplayMarkerChangedEvent) => void): Disposable;
/** Invoke the given callback when the marker is destroyed. */
onDidDestroy(callback: () => void): Disposable;
// TextEditorMarker Details
/**
* Returns a boolean indicating whether the marker is valid. Markers can be
* invalidated when a region surrounding them in the buffer is changed.
*/
isValid(): boolean;
/**
* Returns a boolean indicating whether the marker has been destroyed. A marker
* can be invalid without being destroyed, in which case undoing the invalidating
* operation would restore the marker.
*/
isDestroyed(): boolean;
/** Returns a boolean indicating whether the head precedes the tail. */
isReversed(): boolean;
/**
* Returns a boolean indicating whether changes that occur exactly at the marker's
* head or tail cause it to move.
*/
isExclusive(): boolean;
/**
* Get the invalidation strategy for this marker.
* Valid values include: never, surround, overlap, inside, and touch.
*/
getInvalidationStrategy(): string;
/** Returns an Object containing any custom properties associated with the marker. */
getProperties(): object;
/** Merges an Object containing new properties into the marker's existing properties. */
setProperties(properties: object): void;
/** Returns whether this marker matches the given parameters. */
matchesProperties(attributes: FindDisplayMarkerOptions): boolean;
// Comparing to other markers
/** Compares this marker to another based on their ranges. */
compare(other: DisplayMarker): number;
/**
* Returns a boolean indicating whether this marker is equivalent to another
* marker, meaning they have the same range and options.
*/
isEqual(other: DisplayMarker): boolean;
// Managing the marker's range
/** Gets the buffer range of this marker. */
getBufferRange(): Range;
/** Gets the screen range of this marker. */
getScreenRange(): Range;
/** Modifies the buffer range of this marker. */
setBufferRange(bufferRange: RangeCompatible, properties?: { reversed: boolean }):
void;
/** Modifies the screen range of this marker. */
setScreenRange(screenRange: RangeCompatible, options?: { reversed?: boolean,
clipDirection?: "backward"|"forward"|"closest" }): void;
/**
* Retrieves the screen position of the marker's start. This will always be
* less than or equal to the result of DisplayMarker::getEndScreenPosition.
*/
getStartScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }):
Point;
/**
* Retrieves the screen position of the marker's end. This will always be
* greater than or equal to the result of DisplayMarker::getStartScreenPosition.
*/
getEndScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }):
Point;
/** Retrieves the buffer position of the marker's head. */
getHeadBufferPosition(): Point;
/** Sets the buffer position of the marker's head. */
setHeadBufferPosition(bufferPosition: PointCompatible): void;
/** Retrieves the screen position of the marker's head. */
getHeadScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }):
Point;
/** Sets the screen position of the marker's head. */
setHeadScreenPosition(screenPosition: PointCompatible,
options?: { clipDirection: "backward"|"forward"|"closest" }): void;
/** Retrieves the buffer position of the marker's tail. */
getTailBufferPosition(): Point;
/** Sets the buffer position of the marker's tail. */
setTailBufferPosition(bufferPosition: PointCompatible): void;
/** Retrieves the screen position of the marker's tail. */
getTailScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }):
Point;
/** Sets the screen position of the marker's tail. */
setTailScreenPosition(screenPosition: PointCompatible,
options?: { clipDirection: "backward"|"forward"|"closest" }): void;
/**
* Retrieves the buffer position of the marker's start. This will always be less
* than or equal to the result of DisplayMarker::getEndBufferPosition.
*/
getStartBufferPosition(): Point;
/**
* Retrieves the buffer position of the marker's end. This will always be greater
* than or equal to the result of DisplayMarker::getStartBufferPosition.
*/
getEndBufferPosition(): Point;
/** Returns a boolean indicating whether the marker has a tail. */
hasTail(): boolean;
/**
* Plants the marker's tail at the current head position. After calling the
* marker's tail position will be its head position at the time of the call,
* regardless of where the marker's head is moved.
*/
plantTail(): void;
/**
* Removes the marker's tail. After calling the marker's head position will be
* reported as its current tail position until the tail is planted again.
*/
clearTail(): void;
}
/**
* Experimental: A container for a related set of markers at the DisplayLayer level.
* Wraps an underlying MarkerLayer on the TextBuffer.
*
* This API is experimental and subject to change on any release.
*/
export interface DisplayMarkerLayer {
/** The identifier for the underlying MarkerLayer. */
readonly id: string;
// Lifecycle
/** Destroy this layer. */
destroy(): void;
/** Destroy all markers in this layer. */
clear(): void;
/** Determine whether this layer has been destroyed. */
isDestroyed(): boolean;
// Event Subscription
/** Subscribe to be notified synchronously when this layer is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/**
* Subscribe to be notified asynchronously whenever markers are created, updated,
* or destroyed on this layer. Prefer this method for optimal performance when
* interacting with layers that could contain large numbers of markers.
*/
onDidUpdate(callback: () => void): Disposable;
/**
* Subscribe to be notified synchronously whenever markers are created on this
* layer. Avoid this method for optimal performance when interacting with layers
* that could contain large numbers of markers.
*/
onDidCreateMarker(callback: (marker: DisplayMarker|Marker) => void): Disposable;
// Marker creation
/** Create a marker with the given screen range. */
markScreenRange(range: RangeCompatible, options?: { reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", exclusive?:
boolean, clipDirection?: "backward"|"forward"|"closest" }): DisplayMarker;
/**
* Create a marker on this layer with its head at the given screen position
* and no tail.
*/
markScreenPosition(screenPosition: PointCompatible, options?: { invalidate?:
"never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean,
clipDirection?: "backward"|"forward"|"closest" }): DisplayMarker;
/** Create a marker with the given buffer range. */
markBufferRange(range: RangeCompatible, options?: {
reversed?: boolean, invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean }): DisplayMarker;
/**
* Create a marker on this layer with its head at the given buffer position
* and no tail.
*/
markBufferPosition(bufferPosition: PointCompatible, options?: { invalidate?:
"never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean }):
DisplayMarker;
// Querying
/** Get an existing marker by its id. */
getMarker(id: number): DisplayMarker;
/** Get all markers in the layer. */
getMarkers(): DisplayMarker[];
/** Get the number of markers in the marker layer. */
getMarkerCount(): number;
/**
* Find markers in the layer conforming to the given parameters.
*
* This method finds markers based on the given properties. Markers can be associated
* with custom properties that will be compared with basic equality. In addition,
* there are several special properties that will be compared with the range of the
* markers rather than their properties.
*/
findMarkers(properties: FindDisplayMarkerOptions): DisplayMarker[];
}
/** A handle to a resource that can be disposed. */
export class Disposable implements DisposableLike {
/** Ensure that Object correctly implements the Disposable contract. */
static isDisposable(object: object): boolean;
/** Construct a Disposable. */
constructor(disposableAction?: () => void);
/** A callback which will be called within dispose(). */
disposalAction?(): void;
/**
* Perform the disposal action, indicating that the resource associated
* with this disposable is no longer needed.
*/
dispose(): void;
}
/**
* Utility class to be used when implementing event-based APIs that allows
* for handlers registered via ::on to be invoked with calls to ::emit.
*/
// tslint:disable-next-line:no-any
export class Emitter<OptionalEmissions = { [key: string]: any }, RequiredEmissions = {}>
implements DisposableLike {
/** Construct an emitter. */
constructor();
/** Clear out any existing subscribers. */
clear(): void;
/** Unsubscribe all handlers. */
dispose(): boolean;
// Event Subscription
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
// Event Emission
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof OptionalEmissions>(eventName: T, value?:
OptionalEmissions[T]): void;
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof RequiredEmissions>(eventName: T, value:
RequiredEmissions[T]): void;
}
/**
* Represents a decoration that applies to every marker on a given layer. Created via
* TextEditor::decorateMarkerLayer.
*/
export interface LayerDecoration {
/** Destroys the decoration. */
destroy(): void;
/** Determine whether this decoration is destroyed. */
isDestroyed(): boolean;
/** Get this decoration's properties. */
getProperties(): DecorationLayerOptions;
/** Set this decoration's properties. */
setProperties(newProperties: DecorationLayerOptions): void;
/** Override the decoration properties for a specific marker. */
setPropertiesForMarker(marker: DisplayMarker|Marker, properties: DecorationLayerOptions):
void;
}
/**
* Represents a buffer annotation that remains logically stationary even as
* the buffer changes.
*/
export interface Marker {
/** The identifier for this Marker. */
readonly id: number;
// Lifecycle
/**
* Creates and returns a new Marker with the same properties as this
* marker.
*/
copy(options?: CopyMarkerOptions): Marker;
/** Destroys the marker, causing it to emit the "destroyed" event. */
destroy(): void;
// Event Subscription
/** Invoke the given callback when the marker is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/** Invoke the given callback when the state of the marker changes. */
onDidChange(callback: (event: MarkerChangedEvent) => void): Disposable;
// Marker Details
/** Returns the current range of the marker. The range is immutable. */
getRange(): Range;
/** Returns a point representing the marker's current head position. */
getHeadPosition(): Point;
/** Returns a point representing the marker's current tail position. */
getTailPosition(): Point;
/**
* Returns a point representing the start position of the marker, which
* could be the head or tail position, depending on its orientation.
*/
getStartPosition(): Point;
/**
* Returns a point representing the end position of the marker, which
* could be the head or tail position, depending on its orientation.
*/
getEndPosition(): Point;
/** Returns a boolean indicating whether the head precedes the tail. */
isReversed(): boolean;
/** Returns a boolean indicating whether the marker has a tail. */
hasTail(): boolean;
/** Is the marker valid? */
isValid(): boolean;
/** Is the marker destroyed? */
isDestroyed(): boolean;
/**
* Returns a boolean indicating whether changes that occur exactly at
* the marker's head or tail cause it to move.
*/
isExclusive(): boolean;
/** Get the invalidation strategy for this marker. */
getInvalidationStrategy(): string;
// Mutating Markers
/**
* Sets the range of the marker.
* Returns a boolean indicating whether or not the marker was updated.
*/
setRange(range: RangeCompatible, params?: { reversed?: boolean, exclusive?:
boolean }): boolean;
/**
* Sets the head position of the marker.
* Returns a boolean indicating whether or not the marker was updated.
*/
setHeadPosition(position: PointCompatible): boolean;
/**
* Sets the tail position of the marker.
* Returns a boolean indicating whether or not the marker was updated.
*/
setTailPosition(position: PointCompatible): boolean;
/**
* Removes the marker's tail.
* Returns a boolean indicating whether or not the marker was updated.
*/
clearTail(): boolean;
/**
* Plants the marker's tail at the current head position.
* Returns a boolean indicating whether or not the marker was updated.
*/
plantTail(): boolean;
// Comparison
/**
* Returns a boolean indicating whether this marker is equivalent to
* another marker, meaning they have the same range and options.
*/
isEqual(other: Marker): boolean;
/**
* Compares this marker to another based on their ranges.
* Returns "-1" if this marker precedes the argument.
* Returns "0" if this marker is equivalent to the argument.
* Returns "1" if this marker follows the argument.
*/
compare(other: Marker): number;
}
/** Experimental: A container for a related set of markers. */
export interface MarkerLayer {
/** The identifier for this MarkerLayer. */
readonly id: string;
// Lifecycle
/** Create a copy of this layer with markers in the same state and locations. */
copy(): MarkerLayer;
/** Destroy this layer. */
destroy(): boolean;
/** Remove all markers from this layer. */
clear(): void;
/** Determine whether this layer has been destroyed. */
isDestroyed(): boolean;
// Querying
/** Get an existing marker by its id. */
getMarker(id: number): Marker|undefined;
/** Get all existing markers on the marker layer. */
getMarkers(): Marker[];
/** Get the number of markers in the marker layer. */
getMarkerCount(): number;
/** Find markers in the layer conforming to the given parameters. */
findMarkers(params: FindMarkerOptions): Marker[];
/** Get the role of the marker layer e.g. "atom.selection". */
getRole(): string | undefined;
// Marker Creation
/** Create a marker with the given range. */
markRange(range: RangeCompatible, options?: { reversed?: boolean, invalidate?:
"never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean }): Marker;
/** Create a marker at with its head at the given position with no tail. */
markPosition(position: PointCompatible, options?: { invalidate?: "never"|"surround"
|"overlap"|"inside"|"touch", exclusive?: boolean }): Marker;
// Event Subscription
/**
* Subscribe to be notified asynchronously whenever markers are created,
* updated, or destroyed on this layer.
*/
onDidUpdate(callback: () => void): Disposable;
/**
* Subscribe to be notified synchronously whenever markers are created on
* this layer.
*/
onDidCreateMarker(callback: (marker: Marker) => void): Disposable;
/** Subscribe to be notified synchronously when this layer is destroyed. */
onDidDestroy(callback: () => void): Disposable;
}
/** A notification to the user containing a message and type. */
export class Notification {
constructor(type: "warning"|"info"|"success", message: string,
options?: NotificationOptions);
constructor(type: "fatal"|"error", message: string, options?: ErrorNotificationOptions);
// Event Subscription
/** Invoke the given callback when the notification is dismissed. */
onDidDismiss(callback: (notification: Notification) => void): Disposable;
/** Invoke the given callback when the notification is displayed. */
onDidDisplay(callback: (notification: Notification) => void): Disposable;
// Methods
/** Returns the Notification's type. */
getType(): string;
/** Returns the Notification's message. */
getMessage(): string;
/**
* Dismisses the notification, removing it from the UI. Calling this
* programmatically will call all callbacks added via onDidDismiss.
*/
dismiss(): void;
}
/** A notification manager used to create Notifications to be shown to the user. */
export interface NotificationManager {
// Events
/** Invoke the given callback after a notification has been added. */
onDidAddNotification(callback: (notification: Notification) => void): Disposable;
/** Invoke the given callback after the notifications have been cleared. */
onDidClearNotifications(callback: () => void): Disposable;
// Adding Notifications
/** Add a success notification. */
addSuccess(message: string, options?: NotificationOptions): Notification;
/** Add an informational notification. */
addInfo(message: string, options?: NotificationOptions): Notification;
/** Add a warning notification. */
addWarning(message: string, options?: NotificationOptions): Notification;
/** Add an error notification. */
addError(message: string, options?: ErrorNotificationOptions): Notification;
/** Add a fatal error notification. */
addFatalError(message: string, options?: ErrorNotificationOptions): Notification;
// Getting Notifications
/** Get all the notifications. */
getNotifications(): ReadonlyArray<Notification>;
// Managing Notifications
/** Clear all the notifications. */
clear(): void;
}
/** Represents a point in a buffer in row/column coordinates. */
export class Point {
// Properties
/** A zero-indexed number representing the row of the Point. */
row: number;
/** A zero-indexed number representing the column of the Point. */
column: number;
// Construction
/**
* Create a Point from an array containing two numbers representing the
* row and column.
*/
static fromObject(object: PointCompatible, copy?: boolean): Point;
/** Construct a Point object */
constructor(row?: number, column?: number);
/** Returns a new Point with the same row and column. */
copy(): Point;
/** Returns a new Point with the row and column negated. */
negate(): Point;
// Comparison
/** Returns the given Point that is earlier in the buffer. */
static min(point1: PointCompatible, point2: PointCompatible): Point;
/**
* Compare another Point to this Point instance.
* Returns -1 if this point precedes the argument.
* Returns 0 if this point is equivalent to the argument.
* Returns 1 if this point follows the argument.
*/
compare(other: PointCompatible): number;
/**
* Returns a boolean indicating whether this point has the same row and
* column as the given Point.
*/
isEqual(other: PointCompatible): boolean;
/** Returns a Boolean indicating whether this point precedes the given Point. */
isLessThan(other: PointCompatible): boolean;
/**
* Returns a Boolean indicating whether this point precedes or is equal to
* the given Point.
*/
isLessThanOrEqual(other: PointCompatible): boolean;
/** Returns a Boolean indicating whether this point follows the given Point. */
isGreaterThan(other: PointCompatible): boolean;
/**
* Returns a Boolean indicating whether this point follows or is equal to
* the given Point.
*/
isGreaterThanOrEqual(other: PointCompatible): boolean;
// Operations
/** Makes this point immutable and returns itself. */
freeze(): Readonly<Point>;
/**
* Build and return a new point by adding the rows and columns of the
* given point.
*/
translate(other: PointCompatible): Point;
/**
* Build and return a new Point by traversing the rows and columns
* specified by the given point.
*/
traverse(other: PointCompatible): Point;
/** Returns an array of this point's row and column. */
toArray(): [number, number];
/** Returns an array of this point's row and column. */
serialize(): [number, number];
/** Returns a string representation of the point. */
toString(): string;
}
/** Represents a region in a buffer in row/column coordinates. */
export class Range {
// Properties
/** A Point representing the start of the Range. */
start: Point;
/** A Point representing the end of the Range. */
end: Point;
// Construction
/** Convert any range-compatible object to a Range. */
static fromObject(object: RangeCompatible, copy?: boolean): Range;
/** Construct a Range object. */
constructor(pointA?: PointCompatible, pointB?: PointCompatible);
/** Call this with the result of Range::serialize to construct a new Range. */
static deserialize(array: object): Range;
/** Returns a new range with the same start and end positions. */
copy(): Range;
/** Returns a new range with the start and end positions negated. */
negate(): Range;
// Serialization and Deserialization
/** Returns a plain javascript object representation of the Range. */
serialize(): number[][];
// Range Details
/** Is the start position of this range equal to the end position? */
isEmpty(): boolean;
/**
* Returns a boolean indicating whether this range starts and ends on the
* same row.
*/
isSingleLine(): boolean;
/** Get the number of rows in this range. */
getRowCount(): number;
/** Returns an array of all rows in the range. */
getRows(): number[];
// Operations
/**
* Freezes the range and its start and end point so it becomes immutable
* and returns itself.
*/
freeze(): Readonly<Range>;
// NOTE: this function doesn't actually take a range-compatible parameter.
/** Returns a new range that contains this range and the given range. */
union(other: RangeLike): Range;
/**
* Build and return a new range by translating this range's start and end
* points by the given delta(s).
*/
translate(startDelta: PointCompatible, endDelta?: PointCompatible): Range;
/**
* Build and return a new range by traversing this range's start and end
* points by the given delta.
*/
traverse(delta: PointCompatible): Range;
// Comparison
/**
* Compare two Ranges.
* Returns -1 if this range starts before the argument or contains it.
* Returns 0 if this range is equivalent to the argument.
* Returns 1 if this range starts after the argument or is contained by it.
*/
compare(otherRange: RangeCompatible): number;
/**
* Returns a Boolean indicating whether this range has the same start and
* end points as the given Range.
*/
isEqual(otherRange: RangeCompatible): boolean;
// NOTE: this function doesn't actually take a range-compatible parameter.
/**
* Returns a Boolean indicating whether this range starts and ends on the
* same row as the argument.
*/
coversSameRows(otherRange: RangeLike): boolean;
// NOTE: this function doesn't actually take a range-compatible parameter.
/** Determines whether this range intersects with the argument. */
intersectsWith(otherRange: RangeLike, exclusive?: boolean): boolean;
/** Returns a boolean indicating whether this range contains the given range. */
containsRange(otherRange: RangeCompatible, exclusive?: boolean): boolean;
/** Returns a boolean indicating whether this range contains the given point. */
containsPoint(point: PointCompatible, exclusive?: boolean): boolean;
/**
* Returns a boolean indicating whether this range intersects the given
* row number.
*/
intersectsRow(row: number): boolean;
/**
* Returns a boolean indicating whether this range intersects the row range
* indicated by the given startRow and endRow numbers.
*/
intersectsRowRange(startRow: number, endRow: number): boolean;
// Conversion
/** Returns a string representation of the range. */
toString(): string;
}
/**
* This class represents all essential editing state for a single TextBuffer,
* including cursor and selection positions, folds, and soft wraps.
*/
export class TextEditor {
readonly id: number;
// NOTE: undocumented within the public API. Don't go down the rabbit hole.
constructor(options?: object);
// Event Subscription
/** Calls your callback when the buffer's title has changed. */
onDidChangeTitle(callback: (title: string) => void): Disposable;
/** Calls your callback when the buffer's path, and therefore title, has changed. */
onDidChangePath(callback: (path: string) => void): Disposable;
/**
* Invoke the given callback synchronously when the content of the buffer
* changes.
*/
onDidChange(callback: (event: EditorChangedEvent[]) => void): Disposable;
/**
* Invoke callback when the buffer's contents change. It is emit
* asynchronously 300ms after the last buffer change. This is a good place
* to handle changes to the buffer without compromising typing performance.
*/
onDidStopChanging(callback: (event: BufferStoppedChangingEvent) => void): Disposable;
/**
* Calls your callback when a Cursor is moved. If there are multiple cursors,
* your callback will be called for each cursor.
*/
onDidChangeCursorPosition(callback: (event: CursorPositionChangedEvent) => void):
Disposable;
/** Calls your callback when a selection's screen range changes. */
onDidChangeSelectionRange(callback: (event: SelectionChangedEvent) => void): Disposable;
/** Invoke the given callback after the buffer is saved to disk. */
onDidSave(callback: (event: { path: string }) => void): Disposable;
/** Invoke the given callback when the editor is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/** Retrieves the current TextBuffer. */
getBuffer(): TextBuffer;
/** Sets the read-only state for the editor. */
setReadOnly(readonly: boolean): void;
/** Whether or not this editor is in read-only mode. */
isReadOnly(): boolean;
/**
* Calls your callback when a Gutter is added to the editor. Immediately calls
* your callback for each existing gutter.
*/
observeGutters(callback: (gutter: Gutter) => void): Disposable;
/** Calls your callback when a Gutter is added to the editor. */
onDidAddGutter(callback: (gutter: Gutter) => void): Disposable;
/** Calls your callback when a Gutter is removed from the editor. */
onDidRemoveGutter(callback: (name: string) => void): Disposable;
/** Calls your callback when soft wrap was enabled or disabled. */
onDidChangeSoftWrapped(callback: (softWrapped: boolean) => void): Disposable;
/** Calls your callback when the buffer's encoding has changed. */
onDidChangeEncoding(callback: (encoding: string) => void): Disposable;
/**
* Calls your callback when the grammar that interprets and colorizes the text
* has been changed. Immediately calls your callback with the current grammar.
*/
observeGrammar(callback: (grammar: Grammar) => void): Disposable;
/**
* Calls your callback when the grammar that interprets and colorizes the text
* has been changed.
*/
onDidChangeGrammar(callback: (grammar: Grammar) => void): Disposable;
/** Calls your callback when the result of ::isModified changes. */
onDidChangeModified(callback: (modified: boolean) => void): Disposable;
/**
* Calls your callback when the buffer's underlying file changes on disk at a
* moment when the result of ::isModified is true.
*/
onDidConflict(callback: () => void): Disposable;
/** Calls your callback before text has been inserted. */
onWillInsertText(callback: (event: { text: string, cancel(): void }) => void): Disposable;
/** Calls your callback after text has been inserted. */
onDidInsertText(callback: (event: { text: string }) => void): Disposable;
/**
* Calls your callback when a Cursor is added to the editor. Immediately calls
* your callback for each existing cursor.
*/
observeCursors(callback: (cursor: Cursor) => void): Disposable;
/** Calls your callback when a Cursor is added to the editor. */
onDidAddCursor(callback: (cursor: Cursor) => void): Disposable;
/** Calls your callback when a Cursor is removed from the editor. */
onDidRemoveCursor(callback: (cursor: Cursor) => void): Disposable;
/**
* Calls your callback when a Selection is added to the editor. Immediately
* calls your callback for each existing selection.
*/
observeSelections(callback: (selection: Selection) => void): Disposable;
/** Calls your callback when a Selection is added to the editor. */
onDidAddSelection(callback: (selection: Selection) => void): Disposable;
/** Calls your callback when a Selection is removed from the editor. */
onDidRemoveSelection(callback: (selection: Selection) => void): Disposable;
/**
* Calls your callback with each Decoration added to the editor. Calls your
* callback immediately for any existing decorations.
*/
observeDecorations(callback: (decoration: Decoration) => void): Disposable;
/** Calls your callback when a Decoration is added to the editor. */
onDidAddDecoration(callback: (decoration: Decoration) => void): Disposable;
/** Calls your callback when a Decoration is removed from the editor. */
onDidRemoveDecoration(callback: (decoration: Decoration) => void): Disposable;
/** Calls your callback when the placeholder text is changed. */
onDidChangePlaceholderText(callback: (placeholderText: string) => void): Disposable;
// File Details
/**
* Get the editor's title for display in other parts of the UI such as the tabs.
* If the editor's buffer is saved, its title is the file name. If it is unsaved,
* its title is "untitled".
*/
getTitle(): string;
/**
* Get unique title for display in other parts of the UI, such as the window title.
* If the editor's buffer is unsaved, its title is "untitled" If the editor's
* buffer is saved, its unique title is formatted as one of the following,
*
* "" when it is the only editing buffer with this file name.
* " — " when other buffers have this file name.
*/
getLongTitle(): string;
/** Returns the string path of this editor's text buffer. */
getPath(): string|undefined;
/** Returns boolean true if this editor has been modified. */
isModified(): boolean;
/** Returns boolean true if this editor has no content. */
isEmpty(): boolean;
/** Returns the string character set encoding of this editor's text buffer. */
getEncoding(): string;
/** Set the character set encoding to use in this editor's text buffer. */
setEncoding(encoding: string): void;
// File Operations
/**
* Saves the editor's text buffer.
* See TextBuffer::save for more details.
*/
save(): Promise<void>;
/**
* Saves the editor's text buffer as the given path.
* See TextBuffer::saveAs for more details.
*/
saveAs(filePath: string): Promise<void>;
// Reading Text
/** Returns a string representing the entire contents of the editor. */
getText(): string;
/** Get the text in the given range in buffer coordinates. */
getTextInBufferRange(range: RangeCompatible): string;
/** Returns a number representing the number of lines in the buffer. */
getLineCount(): number;
/**
* Returns a number representing the number of screen lines in the editor.
* This accounts for folds.
*/
getScreenLineCount(): number;
/**
* Returns a number representing the last zero-indexed buffer row number of
* the editor.
*/
getLastBufferRow(): number;
/**
* Returns a number representing the last zero-indexed screen row number of
* the editor.
*/
getLastScreenRow(): number;
/**
* Returns a string representing the contents of the line at the given
* buffer row.
*/
lineTextForBufferRow(bufferRow: number): string;
/**
* Returns a string representing the contents of the line at the given
* screen row.
*/
lineTextForScreenRow(screenRow: number): string;
/** Get the range of the paragraph surrounding the most recently added cursor. */
getCurrentParagraphBufferRange(): Range;
// Mutating Text
/** Replaces the entire contents of the buffer with the given string. */
setText(text: string, options?: ReadonlyEditOptions): void;
/** Set the text in the given Range in buffer coordinates. */
setTextInBufferRange(range: RangeCompatible, text: string, options?:
TextEditOptions & ReadonlyEditOptions): Range;
/* For each selection, replace the selected text with the given text. */
insertText(text: string, options?: TextInsertionOptions & ReadonlyEditOptions): Range|false;
/** For each selection, replace the selected text with a newline. */
insertNewline(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete the character following
* the cursor. Otherwise delete the selected text.
*/
delete(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete the character preceding
* the cursor. Otherwise delete the selected text.
*/
backspace(options?: ReadonlyEditOptions): void;
/**
* Mutate the text of all the selections in a single transaction.
* All the changes made inside the given function can be reverted with a single
* call to ::undo.
*/
mutateSelectedText(fn: (selection: Selection, index: number) => void): void;
/**
* For each selection, transpose the selected text.
* If the selection is empty, the characters preceding and following the cursor
* are swapped. Otherwise, the selected characters are reversed.
*/
transpose(options?: ReadonlyEditOptions): void;
/**
* Convert the selected text to upper case.
* For each selection, if the selection is empty, converts the containing word
* to upper case. Otherwise convert the selected text to upper case.
*/
upperCase(options?: ReadonlyEditOptions): void;
/**
* Convert the selected text to lower case.
* For each selection, if the selection is empty, converts the containing word
* to upper case. Otherwise convert the selected text to upper case.
*/
lowerCase(options?: ReadonlyEditOptions): void;
/**
* Toggle line comments for rows intersecting selections.
* If the current grammar doesn't support comments, does nothing.
*/
toggleLineCommentsInSelection(options?: ReadonlyEditOptions): void;
/** For each cursor, insert a newline at beginning the following line. */
insertNewlineBelow(options?: ReadonlyEditOptions): void;
/** For each cursor, insert a newline at the end of the preceding line. */
insertNewlineAbove(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete all characters of the
* containing word that precede the cursor. Otherwise delete the selected text.
*/
deleteToBeginningOfWord(options?: ReadonlyEditOptions): void;
/**
* Similar to ::deleteToBeginningOfWord, but deletes only back to the previous
* word boundary.
*/
deleteToPreviousWordBoundary(options?: ReadonlyEditOptions): void;
/** Similar to ::deleteToEndOfWord, but deletes only up to the next word boundary. */
deleteToNextWordBoundary(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete all characters of the
* containing subword following the cursor. Otherwise delete the selected text.
*/
deleteToBeginningOfSubword(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete all characters of the
* containing subword following the cursor. Otherwise delete the selected text.
*/
deleteToEndOfSubword(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete all characters of the
* containing line that precede the cursor. Otherwise delete the selected text.
*/
deleteToBeginningOfLine(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is not empty, deletes the selection
* otherwise, deletes all characters of the containing line following the cursor.
* If the cursor is already at the end of the line, deletes the following newline.
*/
deleteToEndOfLine(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, delete all characters of the
* containing word following the cursor. Otherwise delete the selected text.
*/
deleteToEndOfWord(options?: ReadonlyEditOptions): void;
/** Delete all lines intersecting selections. */
deleteLine(options?: ReadonlyEditOptions): void;
// History
/** Undo the last change. */
undo(options?: ReadonlyEditOptions): void;
/** Redo the last change. */
redo(options?: ReadonlyEditOptions): void;
/**
* Batch multiple operations as a single undo/redo step.
* Any group of operations that are logically grouped from the perspective of undoing
* and redoing should be performed in a transaction. If you want to abort the transaction,
* call ::abortTransaction to terminate the function's execution and revert any changes
* performed up to the abortion.
*/
transact(fn: () => void): void;
/**
* Batch multiple operations as a single undo/redo step.
* Any group of operations that are logically grouped from the perspective of undoing
* and redoing should be performed in a transaction. If you want to abort the transaction,
* call ::abortTransaction to terminate the function's execution and revert any changes
* performed up to the abortion.
*/
transact(groupingInterval: number, fn: () => void): void;
/**
* Abort an open transaction, undoing any operations performed so far within the
* transaction.
*/
abortTransaction(): void;
/**
* Create a pointer to the current state of the buffer for use with ::revertToCheckpoint
* and ::groupChangesSinceCheckpoint.
*/
createCheckpoint(): number;
/**
* Revert the buffer to the state it was in when the given checkpoint was created.
* The redo stack will be empty following this operation, so changes since the checkpoint
* will be lost. If the given checkpoint is no longer present in the undo history, no
* changes will be made to the buffer and this method will return false.
*/
revertToCheckpoint(checkpoint: number): boolean;
/**
* Group all changes since the given checkpoint into a single transaction for purposes
* of undo/redo.
* If the given checkpoint is no longer present in the undo history, no grouping will be
* performed and this method will return false.
*/
groupChangesSinceCheckpoint(checkpoint: number): boolean;
// TextEditor Coordinates
/** Convert a position in buffer-coordinates to screen-coordinates. */
screenPositionForBufferPosition(bufferPosition: PointCompatible, options?:
{ clipDirection?: "backward"|"forward"|"closest"}): Point;
/** Convert a position in screen-coordinates to buffer-coordinates. */
bufferPositionForScreenPosition(bufferPosition: PointCompatible, options?:
{ clipDirection?: "backward"|"forward"|"closest"}): Point;
/** Convert a range in buffer-coordinates to screen-coordinates. */
screenRangeForBufferRange(bufferRange: RangeCompatible): Range;
/** Convert a range in screen-coordinates to buffer-coordinates. */
bufferRangeForScreenRange(screenRange: RangeCompatible): Range;
/** Clip the given Point to a valid position in the buffer. */
clipBufferPosition(bufferPosition: PointCompatible): Point;
/**
* Clip the start and end of the given range to valid positions in the buffer.
* See ::clipBufferPosition for more information.
*/
clipBufferRange(range: RangeCompatible): Range;
/** Clip the given Point to a valid position on screen. */
clipScreenPosition(screenPosition: PointCompatible, options?:
{ clipDirection?: "backward"|"forward"|"closest"}): Point;
/**
* Clip the start and end of the given range to valid positions on screen.
* See ::clipScreenPosition for more information.
*/
clipScreenRange(range: RangeCompatible, options?: { clipDirection?:
"backward"|"forward"|"closest"}): Range;
// Decorations
/**
* Add a decoration that tracks a DisplayMarker. When the marker moves, is
* invalidated, or is destroyed, the decoration will be updated to reflect
* the marker's state.
*/
decorateMarker(marker: DisplayMarker, decorationParams: DecorationOptions): Decoration;
/**
* Add a decoration to every marker in the given marker layer. Can be used to
* decorate a large number of markers without having to create and manage many
* individual decorations.
*/
decorateMarkerLayer(markerLayer: MarkerLayer|DisplayMarkerLayer,
decorationParams: DecorationLayerOptions): LayerDecoration;
/** Get all decorations. */
getDecorations(propertyFilter?: DecorationOptions): Decoration[];
/** Get all decorations of type 'line'. */
getLineDecorations(propertyFilter?: DecorationOptions): Decoration[];
/** Get all decorations of type 'line-number'. */
getLineNumberDecorations(propertyFilter?: DecorationOptions): Decoration[];
/** Get all decorations of type 'highlight'. */
getHighlightDecorations(propertyFilter?: DecorationOptions): Decoration[];
/** Get all decorations of type 'overlay'. */
getOverlayDecorations(propertyFilter?: DecorationOptions): Decoration[];
// Markers
/**
* Create a marker on the default marker layer with the given range in buffer coordinates.
* This marker will maintain its logical location as the buffer is changed, so if you mark
* a particular word, the marker will remain over that word even if the word's location
* in the buffer changes.
*/
markBufferRange(range: RangeCompatible, properties?: {
maintainHistory?: boolean,
reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
}): DisplayMarker;
/**
* Create a marker on the default marker layer with the given range in screen coordinates.
* This marker will maintain its logical location as the buffer is changed, so if you mark
* a particular word, the marker will remain over that word even if the word's location in
* the buffer changes.
*/
markScreenRange(range: RangeCompatible, properties?: {
maintainHistory?: boolean, reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside" |"touch",
}): DisplayMarker;
/**
* Create a marker on the default marker layer with the given buffer position and no tail.
* To group multiple markers together in their own private layer, see ::addMarkerLayer.
*/
markBufferPosition(bufferPosition: PointCompatible, options?: {
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
}): DisplayMarker;
/**
* Create a marker on the default marker layer with the given screen position and no tail.
* To group multiple markers together in their own private layer, see ::addMarkerLayer.
*/
markScreenPosition(screenPosition: PointCompatible, options?: {
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
clipDirection?: "backward"|"forward"|"closest",
}): DisplayMarker;
/**
* Find all DisplayMarkers on the default marker layer that match the given properties.
*
* This method finds markers based on the given properties. Markers can be associated
* with custom properties that will be compared with basic equality. In addition, there
* are several special properties that will be compared with the range of the markers
* rather than their properties.
*/
findMarkers(properties: FindDisplayMarkerOptions): DisplayMarker[];
/** Create a marker layer to group related markers. */
addMarkerLayer(options?: { maintainHistory?: boolean, persistent?: boolean }):
DisplayMarkerLayer;
/** Get a DisplayMarkerLayer by id. */
getMarkerLayer(id: number): DisplayMarkerLayer|undefined;
/**
* Get the default DisplayMarkerLayer.
* All marker APIs not tied to an explicit layer interact with this default layer.
*/
getDefaultMarkerLayer(): DisplayMarkerLayer;
/** Get the DisplayMarker on the default layer for the given marker id. */
getMarker(id: number): DisplayMarker;
/** Get all DisplayMarkers on the default marker layer. Consider using ::findMarkers. */
getMarkers(): DisplayMarker[];
/** Get the number of markers in the default marker layer. */
getMarkerCount(): number;
// Cursors
/** Get the position of the most recently added cursor in buffer coordinates. */
getCursorBufferPosition(): Point;
/** Get the position of all the cursor positions in buffer coordinates. */
getCursorBufferPositions(): Point[];
/**
* Move the cursor to the given position in buffer coordinates.
* If there are multiple cursors, they will be consolidated to a single cursor.
*/
setCursorBufferPosition(position: PointCompatible, options?: { autoscroll?: boolean }):
void;
/** Get a Cursor at given screen coordinates Point. */
getCursorAtScreenPosition(position: PointCompatible): Cursor|undefined;
/** Get the position of the most recently added cursor in screen coordinates. */
getCursorScreenPosition(): Point;
/** Get the position of all the cursor positions in screen coordinates. */
getCursorScreenPositions(): Point[];
/**
* Move the cursor to the given position in screen coordinates.
* If there are multiple cursors, they will be consolidated to a single cursor.
*/
setCursorScreenPosition(position: PointCompatible, options?: { autoscroll?: boolean }):
void;
/** Add a cursor at the given position in buffer coordinates. */
addCursorAtBufferPosition(bufferPosition: PointCompatible, options?:
{ autoscroll?: boolean }): Cursor;
/** Add a cursor at the position in screen coordinates. */
addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor;
/** Returns a boolean indicating whether or not there are multiple cursors. */
hasMultipleCursors(): boolean;
/** Move every cursor up one row in screen coordinates. */
moveUp(lineCount?: number): void;
/** Move every cursor down one row in screen coordinates. */
moveDown(lineCount?: number): void;
/** Move every cursor left one column. */
moveLeft(columnCount?: number): void;
/** Move every cursor right one column. */
moveRight(columnCount?: number): void;
/** Move every cursor to the beginning of its line in buffer coordinates. */
moveToBeginningOfLine(): void;
/** Move every cursor to the beginning of its line in screen coordinates. */
moveToBeginningOfScreenLine(): void;
/** Move every cursor to the first non-whitespace character of its line. */
moveToFirstCharacterOfLine(): void;
/** Move every cursor to the end of its line in buffer coordinates. */
moveToEndOfLine(): void;
/** Move every cursor to the end of its line in screen coordinates. */
moveToEndOfScreenLine(): void;
/** Move every cursor to the beginning of its surrounding word. */
moveToBeginningOfWord(): void;
/** Move every cursor to the end of its surrounding word. */
moveToEndOfWord(): void;
/**
* Move every cursor to the top of the buffer.
* If there are multiple cursors, they will be merged into a single cursor.
*/
moveToTop(): void;
/**
* Move every cursor to the bottom of the buffer.
* If there are multiple cursors, they will be merged into a single cursor.
*/
moveToBottom(): void;
/** Move every cursor to the beginning of the next word. */
moveToBeginningOfNextWord(): void;
/** Move every cursor to the previous word boundary. */
moveToPreviousWordBoundary(): void;
/** Move every cursor to the next word boundary. */
moveToNextWordBoundary(): void;
/** Move every cursor to the previous subword boundary. */
moveToPreviousSubwordBoundary(): void;
/** Move every cursor to the next subword boundary. */
moveToNextSubwordBoundary(): void;
/** Move every cursor to the beginning of the next paragraph. */
moveToBeginningOfNextParagraph(): void;
/** Move every cursor to the beginning of the previous paragraph. */
moveToBeginningOfPreviousParagraph(): void;
/** Returns the most recently added Cursor. */
getLastCursor(): Cursor;
/** Returns the word surrounding the most recently added cursor. */
getWordUnderCursor(options?: {
wordRegex?: RegExp,
includeNonWordCharacters?: boolean,
allowPrevious?: boolean,
}): string;
/** Get an Array of all Cursors. */
getCursors(): Cursor[];
/**
* Get all Cursors, ordered by their position in the buffer instead of the
* order in which they were added.
*/
getCursorsOrderedByBufferPosition(): Cursor[];
// Selections
/** Get the selected text of the most recently added selection. */
getSelectedText(): string;
/** Get the Range of the most recently added selection in buffer coordinates. */
getSelectedBufferRange(): Range;
/**
* Get the Ranges of all selections in buffer coordinates.
* The ranges are sorted by when the selections were added. Most recent at the end.
*/
getSelectedBufferRanges(): Range[];
/**
* Set the selected range in buffer coordinates. If there are multiple selections,
* they are reduced to a single selection with the given range.
*/
setSelectedBufferRange(bufferRange: RangeCompatible, options?:
{ reversed?: boolean, preserveFolds?: boolean}): void;
/**
* Set the selected ranges in buffer coordinates. If there are multiple selections,
* they are replaced by new selections with the given ranges.
*/
setSelectedBufferRanges(bufferRanges: ReadonlyArray<RangeCompatible>, options?:
{ reversed?: boolean, preserveFolds?: boolean}): void;
/** Get the Range of the most recently added selection in screen coordinates. */
getSelectedScreenRange(): Range;
/**
* Get the Ranges of all selections in screen coordinates.
* The ranges are sorted by when the selections were added. Most recent at the end.
*/
getSelectedScreenRanges(): Range[];
/**
* Set the selected range in screen coordinates. If there are multiple selections,
* they are reduced to a single selection with the given range.
*/
setSelectedScreenRange(screenRange: RangeCompatible, options?: { reversed?: boolean }):
void;
/**
* Set the selected ranges in screen coordinates. If there are multiple selections,
* they are replaced by new selections with the given ranges.
*/
setSelectedScreenRanges(screenRanges: ReadonlyArray<RangeCompatible>, options?:
{ reversed?: boolean }): void;
/** Add a selection for the given range in buffer coordinates. */
addSelectionForBufferRange(bufferRange: RangeCompatible, options?:
{ reversed?: boolean, preserveFolds?: boolean }): Selection;
/** Add a selection for the given range in screen coordinates. */
addSelectionForScreenRange(screenRange: RangeCompatible, options?:
{ reversed?: boolean, preserveFolds?: boolean }): Selection;
/**
* Select from the current cursor position to the given position in buffer coordinates.
* This method may merge selections that end up intersecting.
*/
selectToBufferPosition(position: PointCompatible): void;
/**
* Select from the current cursor position to the given position in screen coordinates.
* This method may merge selections that end up intersecting.
*/
selectToScreenPosition(position: PointCompatible): void;
/**
* Move the cursor of each selection one character upward while preserving the
* selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectUp(rowCount?: number): void;
/**
* Move the cursor of each selection one character downward while preserving
* the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectDown(rowCount?: number): void;
/**
* Move the cursor of each selection one character leftward while preserving
* the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectLeft(columnCount?: number): void;
/**
* Move the cursor of each selection one character rightward while preserving
* the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectRight(columnCount?: number): void;
/**
* Select from the top of the buffer to the end of the last selection in the buffer.
* This method merges multiple selections into a single selection.
*/
selectToTop(): void;
/**
* Selects from the top of the first selection in the buffer to the end of the buffer.
* This method merges multiple selections into a single selection.
*/
selectToBottom(): void;
/**
* Select all text in the buffer.
* This method merges multiple selections into a single selection.
*/
selectAll(): void;
/**
* Move the cursor of each selection to the beginning of its line while preserving
* the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectToBeginningOfLine(): void;
/**
* Move the cursor of each selection to the first non-whitespace character of its
* line while preserving the selection's tail position. If the cursor is already
* on the first character of the line, move it to the beginning of the line.
* This method may merge selections that end up intersecting.
*/
selectToFirstCharacterOfLine(): void;
/**
* Move the cursor of each selection to the end of its line while preserving the
* selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectToEndOfLine(): void;
/**
* Expand selections to the beginning of their containing word.
* Operates on all selections. Moves the cursor to the beginning of the containing
* word while preserving the selection's tail position.
*/
selectToBeginningOfWord(): void;
/**
* Expand selections to the end of their containing word.
* Operates on all selections. Moves the cursor to the end of the containing word
* while preserving the selection's tail position.
*/
selectToEndOfWord(): void;
/**
* For each cursor, select the containing line.
* This method merges selections on successive lines.
*/
selectLinesContainingCursors(): void;
/** Select the word surrounding each cursor. */
selectWordsContainingCursors(): void;
/**
* For each selection, move its cursor to the preceding subword boundary while
* maintaining the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectToPreviousSubwordBoundary(): void;
/**
* For each selection, move its cursor to the next subword boundary while maintaining
* the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectToNextSubwordBoundary(): void;
/**
* For each selection, move its cursor to the preceding word boundary while
* maintaining the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectToPreviousWordBoundary(): void;
/**
* For each selection, move its cursor to the next word boundary while maintaining
* the selection's tail position.
* This method may merge selections that end up intersecting.
*/
selectToNextWordBoundary(): void;
/**
* Expand selections to the beginning of the next word.
* Operates on all selections. Moves the cursor to the beginning of the next word
* while preserving the selection's tail position.
*/
selectToBeginningOfNextWord(): void;
/**
* Expand selections to the beginning of the next paragraph.
* Operates on all selections. Moves the cursor to the beginning of the next
* paragraph while preserving the selection's tail position.
*/
selectToBeginningOfNextParagraph(): void;
/**
* Expand selections to the beginning of the next paragraph.
* Operates on all selections. Moves the cursor to the beginning of the next
* paragraph while preserving the selection's tail position.
*/
selectToBeginningOfPreviousParagraph(): void;
/** For each selection, select the syntax node that contains that selection. */
selectLargerSyntaxNode(): void;
/** Undo the effect a preceding call to `::selectLargerSyntaxNode`. */
selectSmallerSyntaxNode(): void;
/** Select the range of the given marker if it is valid. */
selectMarker(marker: DisplayMarker): Range|undefined;
/** Get the most recently added Selection. */
getLastSelection(): Selection;
/** Get current Selections. */
getSelections(): Selection[];
/**
* Get all Selections, ordered by their position in the buffer instead of the
* order in which they were added.
*/
getSelectionsOrderedByBufferPosition(): Selection[];
// NOTE: this calls into Selection::intersectsBufferRange, which itself calls
// into Range::intersectsWith. Range::intersectsWith is one of the few functions
// which does NOT take a range-compatible array.
/** Determine if a given range in buffer coordinates intersects a selection. */
selectionIntersectsBufferRange(bufferRange: RangeLike): boolean;
// Searching and Replacing
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*
* ::scan functions as the replace method as well via the replace.
*/
scan(regex: RegExp, options: ScanContextOptions, iterator: (params:
ContextualBufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*
* ::scan functions as the replace method as well via the replace.
*/
scan(regex: RegExp, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range, calling the given iterator.
* function on each match.
*/
scanInBufferRange(regex: RegExp, range: RangeCompatible, iterator:
(params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range in reverse order, calling the
* given iterator function on each match.
*/
backwardsScanInBufferRange(regex: RegExp, range: RangeCompatible,
iterator: (params: BufferScanResult) => void): void;
// Tab Behavior
/** Returns a boolean indicating whether softTabs are enabled for this editor. */
getSoftTabs(): boolean;
/** Enable or disable soft tabs for this editor. */
setSoftTabs(softTabs: boolean): void;
/** Toggle soft tabs for this editor. */
toggleSoftTabs(): boolean;
/** Get the on-screen length of tab characters. */
getTabLength(): number;
/**
* Set the on-screen length of tab characters. Setting this to a number will
* override the editor.tabLength setting.
*/
setTabLength(tabLength: number): void;
/** Determine if the buffer uses hard or soft tabs. */
usesSoftTabs(): boolean|undefined;
/**
* Get the text representing a single level of indent.
* If soft tabs are enabled, the text is composed of N spaces, where N is the
* tab length. Otherwise the text is a tab character (\t).
*/
getTabText(): string;
// Soft Wrap Behavior
/** Determine whether lines in this editor are soft-wrapped. */
isSoftWrapped(): boolean;
/** Enable or disable soft wrapping for this editor. */
setSoftWrapped(softWrapped: boolean): boolean;
/** Toggle soft wrapping for this editor. */
toggleSoftWrapped(): boolean;
/** Gets the column at which column will soft wrap. */
getSoftWrapColumn(): number;
// Indentation
/**
* Get the indentation level of the given buffer row.
* Determines how deeply the given row is indented based on the soft tabs and tab
* length settings of this editor. Note that if soft tabs are enabled and the tab
* length is 2, a row with 4 leading spaces would have an indentation level of 2.
*/
indentationForBufferRow(bufferRow: number): number;
/**
* Set the indentation level for the given buffer row.
* Inserts or removes hard tabs or spaces based on the soft tabs and tab length settings
* of this editor in order to bring it to the given indentation level. Note that if soft
* tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an
* indentation level of 2.
*/
setIndentationForBufferRow(bufferRow: number, newLevel: number, options?:
{ preserveLeadingWhitespace?: boolean }): void;
/** Indent rows intersecting selections by one level. */
indentSelectedRows(options?: ReadonlyEditOptions): void;
/** Outdent rows intersecting selections by one level. */
outdentSelectedRows(options?: ReadonlyEditOptions): void;
/**
* Get the indentation level of the given line of text.
* Determines how deeply the given line is indented based on the soft tabs and tab length
* settings of this editor. Note that if soft tabs are enabled and the tab length is 2,
* a row with 4 leading spaces would have an indentation level of 2.
*/
indentLevelForLine(line: string): number;
/** Indent rows intersecting selections based on the grammar's suggested indent level. */
autoIndentSelectedRows(options?: ReadonlyEditOptions): void;
// Grammars
/** Get the current Grammar of this editor. */
getGrammar(): Grammar;
// Managing Syntax Scopes
/**
* Returns a ScopeDescriptor that includes this editor's language.
* e.g. [".source.ruby"], or [".source.coffee"].
*/
getRootScopeDescriptor(): ScopeDescriptor;
/** Get the syntactic scopeDescriptor for the given position in buffer coordinates. */
scopeDescriptorForBufferPosition(bufferPosition: PointCompatible): ScopeDescriptor;
/**
* Get the syntactic tree {ScopeDescriptor} for the given position in buffer
* coordinates or the syntactic {ScopeDescriptor} for TextMate language mode
*/
syntaxTreeScopeDescriptorForBufferPosition(bufferPosition: PointCompatible): ScopeDescriptor;
/**
* Get the range in buffer coordinates of all tokens surrounding the cursor
* that match the given scope selector.
*/
bufferRangeForScopeAtCursor(scopeSelector: string): Range;
/** Determine if the given row is entirely a comment. */
isBufferRowCommented(bufferRow: number): boolean;
// Clipboard Operations
/** For each selection, copy the selected text. */
copySelectedText(): void;
/** For each selection, cut the selected text. */
cutSelectedText(options?: ReadonlyEditOptions): void;
/**
* For each selection, replace the selected text with the contents of the clipboard.
* If the clipboard contains the same number of selections as the current editor,
* each selection will be replaced with the content of the corresponding clipboard
* selection text.
*/
pasteText(options?: TextInsertionOptions & ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, cut all characters of the
* containing screen line following the cursor. Otherwise cut the selected text.
*/
cutToEndOfLine(options?: ReadonlyEditOptions): void;
/**
* For each selection, if the selection is empty, cut all characters of the
* containing buffer line following the cursor. Otherwise cut the selected text.
*/
cutToEndOfBufferLine(options?: ReadonlyEditOptions): void;
// Folds
/**
* Fold the most recent cursor's row based on its indentation level.
* The fold will extend from the nearest preceding line with a lower indentation
* level up to the nearest following row with a lower indentation level.
*/
foldCurrentRow(): void;
/** Unfold the most recent cursor's row by one level. */
unfoldCurrentRow(): void;
/**
* Fold the given row in buffer coordinates based on its indentation level.
* If the given row is foldable, the fold will begin there. Otherwise, it will
* begin at the first foldable row preceding the given row.
*/
foldBufferRow(bufferRow: number): void;
/** Unfold all folds containing the given row in buffer coordinates. */
unfoldBufferRow(bufferRow: number): void;
/** For each selection, fold the rows it intersects. */
foldSelectedLines(): void;
/** Fold all foldable lines. */
foldAll(): void;
/** Unfold all existing folds. */
unfoldAll(): void;
/**
* Fold all foldable lines at the given indent level.
* @param level A zero-indexed number.
*/
foldAllAtIndentLevel(level: number): void;
/**
* Determine whether the given row in buffer coordinates is foldable.
* A foldable row is a row that starts a row range that can be folded.
*/
isFoldableAtBufferRow(bufferRow: number): boolean;
/**
* Determine whether the given row in screen coordinates is foldable.
* A foldable row is a row that starts a row range that can be folded.
*/
isFoldableAtScreenRow(bufferRow: number): boolean;
/** Fold the given buffer row if it isn't currently folded, and unfold it otherwise. */
toggleFoldAtBufferRow(bufferRow: number): void;
/** Determine whether the most recently added cursor's row is folded. */
isFoldedAtCursorRow(): boolean;
/** Determine whether the given row in buffer coordinates is folded. */
isFoldedAtBufferRow(bufferRow: number): boolean;
/** Determine whether the given row in screen coordinates is folded. */
isFoldedAtScreenRow(screenRow: number): boolean;
// Gutters
/** Add a custom Gutter. */
addGutter(options: GutterOptions): Gutter;
/** Get this editor's gutters. */
getGutters(): Gutter[];
/** Get the gutter with the given name. */
gutterWithName(name: string): Gutter|null;
// Scrolling the TextEditor
/** Scroll the editor to reveal the most recently added cursor if it is off-screen. */
scrollToCursorPosition(options?: { center?: boolean }): void;
/** Scrolls the editor to the given buffer position. */
scrollToBufferPosition(bufferPosition: PointCompatible, options?: { center?: boolean }):
void;
/** Scrolls the editor to the given screen position. */
scrollToScreenPosition(screenPosition: PointCompatible, options?: { center?: boolean }):
void;
// TextEditor Rendering
/** Retrieves the rendered line height in pixels. */
getLineHeightInPixels(): number;
/** Retrieves the greyed out placeholder of a mini editor. */
getPlaceholderText(): string;
/**
* Set the greyed out placeholder of a mini editor. Placeholder text will be
* displayed when the editor has no content.
*/
setPlaceholderText(placeholderText: string): void;
/** Undocumented: Buffer range for syntax scope at position */
bufferRangeForScopeAtPosition(scope: string, point: PointCompatible): Range;
/** Undocumented: Get syntax token at buffer position */
tokenForBufferPosition(pos: PointCompatible): {value: string, scopes: string[]};
}
export interface GutterOptions {
/** (required) A unique String to identify this gutter. */
name: string;
/**
* A Number that determines stacking order between gutters.
* Lower priority items are forced closer to the edges of the window. (default: -100)
*/
priority?: number;
/**
* Boolean specifying whether the gutter is visible initially after being created.
* (default: true)
*/
visible?: boolean;
/**
* String specifying the type of gutter to create.
* 'decorated' gutters are useful as a destination for decorations created with
* Gutter::decorateMarker.
* 'line-number' gutters.
*/
type?: 'decorated' | 'line-number';
/** String added to the CSS classnames of the gutter's root DOM element. */
class?: string;
/**
* Function called by a 'line-number' gutter to generate the label for each
* line number element. Should return a String that will be used to label the
* corresponding line.
*/
labelFn?: (lineData: LineDataExtended) => string;
/**
* Function to be called when a mousedown event is received by a line-number
* element within this type: 'line-number' Gutter. If unspecified, the default
* behavior is to select the clicked buffer row.
*/
onMouseDown?: (lineData: LineData) => void;
/**
* Function to be called when a mousemove event occurs on a line-number
* element within within this type: 'line-number' Gutter.
*/
onMouseMove?: (lineData: LineData) => void;
}
export interface LineData {
/** Number indicating the zero-indexed buffer index of a line. */
bufferRow: number;
/** Number indicating the zero-indexed screen index. */
screenRow: number;
}
/** Object containing information about each line to label. */
export interface LineDataExtended extends LineData {
/** Boolean that is true if a fold may be created here. */
foldable: boolean;
/** Boolean if this screen row is the soft-wrapped continuation of the same buffer row. */
softWrapped: boolean;
/** Number the maximum number of digits necessary to represent any known screen row. */
maxDigits: number;
}
export interface PixelPosition {
left: number;
top: number;
}
/**
* Undocumented: Rendering component for TextEditor
*/
export interface TextEditorComponent {
/** Does not clip screenPosition, unlike similar method on TextEditorElement */
pixelPositionForScreenPosition(screenPosition: PointLike): PixelPosition;
screenPositionForPixelPosition(pos: PixelPosition): Point;
pixelPositionForMouseEvent(event: {
clientX: number, clientY: number
}): PixelPosition;
screenPositionForMouseEvent(event: {clientX: number, clientY: number}): Point;
}
/**
* Undocumented: Custom HTML elemnent for TextEditor, atom-text-editor
*/
export interface TextEditorElement extends HTMLElement {
getModel(): TextEditor;
getComponent(): TextEditorComponent;
/**
* Extended: Get a promise that resolves the next time the element's
* DOM is updated in any way.
*/
getNextUpdatePromise(): Promise<void>;
/** Extended: get the width of an `x` character displayed in this element. */
getBaseCharacterWidth(): number;
/** Essential: Scrolls the editor to the top. */
scrollToTop(): void;
/** Essential: Scrolls the editor to the bottom. */
scrollToBottom(): void;
setScrollTop(scrollTop: number): void;
getScrollTop(): number;
setScrollLeft(scrollLeft: number): void;
getScrollLeft(): number;
getScrollHeight(): number;
/** Extended: Converts a buffer position to a pixel position. */
pixelPositionForBufferPosition(bufferPosition: PointLike): PixelPosition;
/** Extended: Converts a screen position to a pixel position. */
pixelPositionForScreenPosition(screenPosition: PointLike): PixelPosition;
// Event subscription
onDidChangeScrollTop(callback: (scrollTop: number) => void): Disposable;
onDidChangeScrollLeft(callback: (scrollLeft: number) => void): Disposable;
/** Called when the editor is attached to the DOM. */
onDidAttach(callback: () => void): Disposable;
/** Called when the editor is detached from the DOM. */
onDidDetach(callback: () => void): Disposable;
}
/** Experimental: This global registry tracks registered TextEditors. */
export interface TextEditorRegistry {
// Managing Text Editors
/** Remove all editors from the registry. */
clear(): void;
/** Register a TextEditor. */
add(editor: TextEditor): Disposable;
/** Remove the given TextEditor from the registry. */
remove(editor: TextEditor): boolean;
/** Keep a TextEditor's configuration in sync with Atom's settings. */
maintainConfig(editor: TextEditor): Disposable;
/**
* Set a TextEditor's grammar based on its path and content, and continue
* to update its grammar as gramamrs are added or updated, or the editor's
* file path changes.
*/
maintainGrammar(editor: TextEditor): Disposable;
/**
* Force a TextEditor to use a different grammar than the one that would
* otherwise be selected for it.
*/
setGrammarOverride(editor: TextEditor, scopeName: string): void;
/**
* Retrieve the grammar scope name that has been set as a grammar override
* for the given TextEditor.
*/
getGrammarOverride(editor: TextEditor): string|null;
/** Remove any grammar override that has been set for the given TextEditor. */
clearGrammarOverride(editor: TextEditor): void;
// Event Subscription
/** Invoke the given callback with all the current and future registered TextEditors. */
observe(callback: (editor: TextEditor) => void): Disposable;
}
export type TooltipPlacement =
|"top"|"bottom"|"left"|"right"
|"auto"|"auto top"|"auto bottom"|"auto left"|"auto right";
/** Associates tooltips with HTML elements or selectors. */
export interface TooltipManager {
/** Add a tooltip to the given element. */
add(target: HTMLElement | JQueryCompatible, options: {
item?: object,
} | {
title?: string|(() => string),
html?: boolean,
keyBindingCommand?: string,
keyBindingTarget?: HTMLElement
} & {
class?: string;
placement?: TooltipPlacement|(() => TooltipPlacement),
trigger?: "click"|"hover"|"focus"|"manual",
delay?: { show: number, hide: number }
}): Disposable;
/** Find the tooltips that have been applied to the given element. */
findTooltips(target: HTMLElement): Tooltip[];
}
/**
* ViewRegistry handles the association between model and view types in Atom.
* We call this association a View Provider. As in, for a given model, this class
* can provide a view via ::getView, as long as the model/view association was
* registered via ::addViewProvider.
*/
export interface ViewRegistry {
/**
* Add a provider that will be used to construct views in the workspace's view
* layer based on model objects in its model layer.
*/
addViewProvider(createView: (model: object) => HTMLElement|undefined): Disposable;
/**
* Add a provider that will be used to construct views in the workspace's view
* layer based on model objects in its model layer.
*/
// tslint:disable-next-line:no-any
addViewProvider<T>(modelConstructor: { new (...args: any[]): T }, createView:
(instance: T) => HTMLElement|undefined): Disposable;
/** Get the view associated with an object in the workspace. */
getView(obj: TextEditor): TextEditorElement;
getView(obj: object): HTMLElement;
}
/** Represents the state of the user interface for the entire window. */
export interface Workspace {
// Event Subscription
/**
* Invoke the given callback with all current and future text editors in
* the workspace.
*/
observeTextEditors(callback: (editor: TextEditor) => void): Disposable;
/**
* Invoke the given callback with all current and future panes items in the
* workspace.
*/
observePaneItems(callback: (item: object) => void): Disposable;
/** Invoke the given callback when the active pane item changes. */
onDidChangeActivePaneItem(callback: (item: object) => void): Disposable;
/** Invoke the given callback when the active pane item stops changing. */
onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable;
/**
* Invoke the given callback when a text editor becomes the active text editor and
* when there is no longer an active text editor.
*/
onDidChangeActiveTextEditor(callback: (editor?: TextEditor) => void): Disposable;
/**
* Invoke the given callback with the current active pane item and with all
* future active pane items in the workspace.
*/
observeActivePaneItem(callback: (item: object) => void): Disposable;
/**
* Invoke the given callback with the current active text editor (if any), with all
* future active text editors, and when there is no longer an active text editor.
*/
observeActiveTextEditor(callback: (editor?: TextEditor) => void): Disposable;
/**
* Invoke the given callback whenever an item is opened. Unlike ::onDidAddPaneItem,
* observers will be notified for items that are already present in the workspace
* when they are reopened.
*/
onDidOpen(callback: (event: PaneItemOpenedEvent) => void): Disposable;
/** Invoke the given callback when a pane is added to the workspace. */
onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback before a pane is destroyed in the workspace. */
onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback when a pane is destroyed in the workspace. */
onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback with all current and future panes in the workspace. */
observePanes(callback: (pane: Pane) => void): Disposable;
/** Invoke the given callback when the active pane changes. */
onDidChangeActivePane(callback: (pane: Pane) => void): Disposable;
/**
* Invoke the given callback with the current active pane and when the
* active pane changes.
*/
observeActivePane(callback: (pane: Pane) => void): Disposable;
/** Invoke the given callback when a pane item is added to the workspace. */
onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/**
* Invoke the given callback when a pane item is about to be destroyed,
* before the user is prompted to save it.
* @param callback The function to be called before pane items are destroyed.
* If this function returns a Promise, then the item will not be destroyed
* until the promise resolves.
*/
onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void|Promise<void>):
Disposable;
/** Invoke the given callback when a pane item is destroyed. */
onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/** Invoke the given callback when a text editor is added to the workspace. */
onDidAddTextEditor(callback: (event: TextEditorObservedEvent) => void): Disposable;
// Opening
/**
* Opens the given URI in Atom asynchronously. If the URI is already open,
* the existing item for that URI will be activated. If no URI is given, or
* no registered opener can open the URI, a new empty TextEditor will be created.
*/
open(uri: string, options?: WorkspaceOpenOptions): Promise<object>;
/**
* Opens the given item in Atom asynchronously. If the item is already open,
* the existing item will be activated. If no item is given, a new empty TextEditor
* will be created.
*/
open<T extends ViewModel = ViewModel>(item: T, options?: WorkspaceOpenOptions):
Promise<T>;
/**
* Opens the given URI in Atom asynchronously. If the URI is already open,
* the existing item for that URI will be activated. If no URI is given, or
* no registered opener can open the URI, a new empty TextEditor will be created.
*/
open(): Promise<TextEditor>;
/**
* Search the workspace for items matching the given URI and hide them.
* Returns a boolean indicating whether any items were found (and hidden).
*/
hide(itemOrURI: object|string): boolean;
/**
* Search the workspace for items matching the given URI. If any are found,
* hide them. Otherwise, open the URL.
* Returns a Promise that resolves when the item is shown or hidden.
*/
toggle(itemOrURI: object|string): Promise<void>;
/**
* Creates a new item that corresponds to the provided URI.
* If no URI is given, or no registered opener can open the URI, a new empty TextEditor
* will be created.
*/
createItemForURI(uri: string): Promise<object|TextEditor>;
/** Returns a boolean that is true if object is a TextEditor. */
isTextEditor(object: object): object is TextEditor;
/**
* Asynchronously reopens the last-closed item's URI if it hasn't already
* been reopened.
*/
reopenItem(): Promise<object|undefined>;
/** Register an opener for a URI. */
addOpener(opener: (uri: string, options?: WorkspaceOpenOptions) =>
ViewModel|undefined): Disposable;
/** Create a new text editor. */
buildTextEditor(params: object): TextEditor;
// Pane Items
/** Get all pane items in the workspace. */
getPaneItems(): object[];
/** Get the active Pane's active item. */
getActivePaneItem(): object;
/** Get all text editors in the workspace. */
getTextEditors(): TextEditor[];
/** Get the workspace center's active item if it is a TextEditor. */
getActiveTextEditor(): TextEditor|undefined;
// Panes
/** Get the most recently focused pane container. */
getActivePaneContainer(): Dock|WorkspaceCenter;
/** Get all panes in the workspace. */
getPanes(): Pane[];
/** Get the active Pane. */
getActivePane(): Pane;
/** Make the next pane active. */
activateNextPane(): boolean;
/** Make the previous pane active. */
activatePreviousPane(): boolean;
/** Get the first pane container that contains an item with the given URI. */
paneContainerForURI(uri: string): Dock|WorkspaceCenter|undefined;
/** Get the first pane container that contains the given item. */
paneContainerForItem(item: object): Dock|WorkspaceCenter|undefined;
/** Get the first Pane with an item for the given URI. */
paneForURI(uri: string): Pane|undefined;
/** Get the Pane containing the given item. */
paneForItem(item: object): Pane|undefined;
// Pane Locations
/** Get the WorkspaceCenter at the center of the editor window. */
getCenter(): WorkspaceCenter;
/** Get the Dock to the left of the editor window. */
getLeftDock(): Dock;
/** Get the Dock to the right of the editor window. */
getRightDock(): Dock;
/** Get the Dock below the editor window. */
getBottomDock(): Dock;
/** Returns all Pane containers. */
getPaneContainers(): [WorkspaceCenter, Dock, Dock, Dock];
// Panels
/** Get an Array of all the panel items at the bottom of the editor window. */
getBottomPanels(): Panel[];
/** Adds a panel item to the bottom of the editor window. */
addBottomPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number,
}): Panel<T>;
/** Get an Array of all the panel items to the left of the editor window. */
getLeftPanels(): Panel[];
/** Adds a panel item to the left of the editor window. */
addLeftPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number,
}): Panel<T>;
/** Get an Array of all the panel items to the right of the editor window. */
getRightPanels(): Panel[];
/** Adds a panel item to the right of the editor window. */
addRightPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number,
}): Panel<T>;
/** Get an Array of all the panel items at the top of the editor window. */
getTopPanels(): Panel[];
/** Adds a panel item to the top of the editor window above the tabs. */
addTopPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number
}): Panel<T>;
/** Get an Array of all the panel items in the header. */
getHeaderPanels(): Panel[];
/** Adds a panel item to the header. */
addHeaderPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number,
}): Panel<T>;
/** Get an Array of all the panel items in the footer. */
getFooterPanels(): Panel[];
/** Adds a panel item to the footer. */
addFooterPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number,
}): Panel<T>;
/** Get an Array of all the modal panel items. */
getModalPanels(): Panel[];
/** Adds a panel item as a modal dialog. */
addModalPanel<T>(options: {
item: T,
visible?: boolean,
priority?: number,
autoFocus?: boolean,
}): Panel<T>;
/**
* Returns the Panel associated with the given item or null when the item
* has no panel.
*/
panelForItem<T>(item: T): Panel<T>|null;
// Searching and Replacing
/** Performs a search across all files in the workspace. */
scan(regex: RegExp, iterator: (result: ScandalResult) => void):
CancellablePromise<string|null>;
/** Performs a search across all files in the workspace. */
scan(regex: RegExp, options: WorkspaceScanOptions, iterator:
(result: ScandalResult) => void): CancellablePromise<string|null>;
/** Performs a replace across all the specified files in the project. */
replace(regex: RegExp, replacementText: string, filePaths: ReadonlyArray<string>,
iterator: (result: { filePath: string|undefined, replacements: number }) => void):
Promise<void>;
}
// https://github.com/atom/atom/blob/master/src/workspace-center.js
/** The central container for the editor window capable of holding items. */
export interface WorkspaceCenter {
// Event Subscription
/**
* Invoke the given callback with all current and future text editors in the
* workspace center.
*/
observeTextEditors(callback: (editor: TextEditor) => void): Disposable;
/**
* Invoke the given callback with all current and future panes items in the
* workspace center.
*/
observePaneItems(callback: (item: object) => void): Disposable;
/** Invoke the given callback when the active pane item changes. */
onDidChangeActivePaneItem(callback: (item: object) => void): Disposable;
/** Invoke the given callback when the active pane item stops changing. */
onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable;
/**
* Invoke the given callback with the current active pane item and with all future
* active pane items in the workspace center.
*/
observeActivePaneItem(callback: (item: object) => void): Disposable;
/** Invoke the given callback when a pane is added to the workspace center. */
onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback before a pane is destroyed in the workspace center. */
onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback when a pane is destroyed in the workspace center. */
onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback with all current and future panes in the workspace center. */
observePanes(callback: (pane: Pane) => void): Disposable;
/** Invoke the given callback when the active pane changes. */
onDidChangeActivePane(callback: (pane: Pane) => void): Disposable;
/**
* Invoke the given callback with the current active pane and when the active pane
* changes.
*/
observeActivePane(callback: (pane: Pane) => void): Disposable;
/** Invoke the given callback when a pane item is added to the workspace center. */
onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/**
* Invoke the given callback when a pane item is about to be destroyed, before the user
* is prompted to save it.
* @param callback The function to be called before pane items are destroyed.
* If this function returns a Promise, then the item will not be destroyed
* until the promise resolves.
*/
onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void|Promise<void>):
Disposable;
/** Invoke the given callback when a pane item is destroyed. */
onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/** Invoke the given callback when a text editor is added to the workspace center. */
onDidAddTextEditor(callback: (event: TextEditorObservedEvent) => void): Disposable;
// Pane Items
/** Get all pane items in the workspace center. */
getPaneItems(): object[];
/** Get the active Pane's active item. */
getActivePaneItem(): object|undefined;
/** Get all text editors in the workspace center. */
getTextEditors(): TextEditor[];
/** Get the active item if it is an TextEditor. */
getActiveTextEditor(): TextEditor|undefined;
/** Save all pane items. */
saveAll(): void;
// Panes
/** Get all panes in the workspace center. */
getPanes(): Pane[];
/** Get the active Pane. */
getActivePane(): Pane;
/** Make the next pane active. */
activateNextPane(): void;
/** Make the previous pane active. */
activatePreviousPane(): void;
/** Retrieve the Pane associated with the given URI. */
paneForURI(uri: string): Pane|undefined;
/** Retrieve the Pane associated with the given item. */
paneForItem(item: object): Pane|undefined;
/** Destroy (close) the active pane. */
destroyActivePane(): void;
}
// Extended Classes ===========================================================
/**
* A wrapper which provides standard error/output line buffering for
* Node's ChildProcess.
*/
export class BufferedProcess {
readonly process?: ChildProcess;
constructor(options: ProcessOptions);
// Event Subscription
/**
* Will call your callback when an error will be raised by the process. Usually
* this is due to the command not being available or not on the PATH. You can
* call handle() on the object passed to your callback to indicate that you
* have handled this error.
*/
onWillThrowError(callback: (errorObject: HandleableErrorEvent) =>
void): Disposable;
// Helper Methods
/** Terminate the process. */
kill(): void;
/** Runs the process. */
start(): void;
}
/**
* Like BufferedProcess, but accepts a Node script as the command to run.
* This is necessary on Windows since it doesn't support shebang #! lines.
*/
export class BufferedNodeProcess extends BufferedProcess {
/** Runs the given Node script by spawning a new child process. */
constructor(options: NodeProcessOptions);
}
/** Represents the clipboard used for copying and pasting in Atom. */
export interface Clipboard {
/** Write the given text to the clipboard. */
write(text: string, metadata?: object): void;
/** Read the text from the clipboard. */
read(): string;
/**
* Read the text from the clipboard and return both the text and the associated
* metadata.
*/
readWithMetadata(): { text: string, metadata: object };
}
/** Provides a registry for commands that you'd like to appear in the context menu. */
export interface ContextMenuManager {
/** Add context menu items scoped by CSS selectors. */
add(itemsBySelector: { [key: string]: ReadonlyArray<ContextMenuOptions> }): Disposable;
}
/**
* The Cursor class represents the little blinking line identifying where text
* can be inserted.
*/
export interface Cursor {
// Event Subscription
/** Calls your callback when the cursor has been moved. */
onDidChangePosition(callback: (event: CursorPositionChangedEvent) => void): Disposable;
/** Calls your callback when the cursor is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/** Calls your callback when the cursor's visibility has changed. */
onDidChangeVisibility(callback: (visibility: boolean) => void): Disposable;
// Managing Cursor Position
/** Moves a cursor to a given screen position. */
setScreenPosition(screenPosition: PointCompatible, options?: { autoscroll?: boolean }):
void;
/** Returns the screen position of the cursor as a Point. */
getScreenPosition(): Point;
/** Moves a cursor to a given buffer position. */
setBufferPosition(bufferPosition: PointCompatible, options?: { autoscroll?: boolean }):
void;
/** Returns the current buffer position as an Array. */
getBufferPosition(): Point;
/** Returns the cursor's current screen row. */
getScreenRow(): number;
/** Returns the cursor's current screen column. */
getScreenColumn(): number;
/** Retrieves the cursor's current buffer row. */
getBufferRow(): number;
/** Returns the cursor's current buffer column. */
getBufferColumn(): number;
/** Returns the cursor's current buffer row of text excluding its line ending. */
getCurrentBufferLine(): string;
/** Returns whether the cursor is at the start of a line. */
isAtBeginningOfLine(): boolean;
/** Returns whether the cursor is on the line return character. */
isAtEndOfLine(): boolean;
// Cursor Position Details
/**
* Returns the underlying DisplayMarker for the cursor. Useful with overlay
* Decorations.
*/
getMarker(): DisplayMarker;
/**
* Identifies if the cursor is surrounded by whitespace.
* "Surrounded" here means that the character directly before and after the cursor
* are both whitespace.
*/
isSurroundedByWhitespace(): boolean;
/** This method returns false if the character before or after the cursor is whitespace. */
isBetweenWordAndNonWord(): boolean;
/** Returns whether this cursor is between a word's start and end. */
isInsideWord(options?: { wordRegex?: RegExp }): boolean;
/** Returns the indentation level of the current line. */
getIndentLevel(): number;
/** Retrieves the scope descriptor for the cursor's current position. */
getScopeDescriptor(): ScopeDescriptor;
/** Retrieves the syntax tree scope descriptor for the cursor's current position. */
getSyntaxTreeScopeDescriptor(): ScopeDescriptor;
/**
* Returns true if this cursor has no non-whitespace characters before its
* current position.
*/
hasPrecedingCharactersOnLine(): boolean;
/**
* Identifies if this cursor is the last in the TextEditor.
* "Last" is defined as the most recently added cursor.
*/
isLastCursor(): boolean;
// Moving the Cursor
/** Moves the cursor up one screen row. */
moveUp(rowCount?: number, options?: { moveToEndOfSelection?: boolean }): void;
/** Moves the cursor down one screen row. */
moveDown(rowCount?: number, options?: { moveToEndOfSelection?: boolean }): void;
/** Moves the cursor left one screen column. */
moveLeft(columnCount?: number, options?: { moveToEndOfSelection?: boolean }): void;
/** Moves the cursor right one screen column. */
moveRight(columnCount?: number, options?: { moveToEndOfSelection?: boolean }): void;
/** Moves the cursor to the top of the buffer. */
moveToTop(): void;
/** Moves the cursor to the bottom of the buffer. */
moveToBottom(): void;
/** Moves the cursor to the beginning of the line. */
moveToBeginningOfScreenLine(): void;
/** Moves the cursor to the beginning of the buffer line. */
moveToBeginningOfLine(): void;
/** Moves the cursor to the beginning of the first character in the line. */
moveToFirstCharacterOfLine(): void;
/** Moves the cursor to the end of the line. */
moveToEndOfScreenLine(): void;
/** Moves the cursor to the end of the buffer line. */
moveToEndOfLine(): void;
/** Moves the cursor to the beginning of the word. */
moveToBeginningOfWord(): void;
/** Moves the cursor to the end of the word. */
moveToEndOfWord(): void;
/** Moves the cursor to the beginning of the next word. */
moveToBeginningOfNextWord(): void;
/** Moves the cursor to the previous word boundary. */
moveToPreviousWordBoundary(): void;
/** Moves the cursor to the next word boundary. */
moveToNextWordBoundary(): void;
/** Moves the cursor to the previous subword boundary. */
moveToPreviousSubwordBoundary(): void;
/** Moves the cursor to the next subword boundary. */
moveToNextSubwordBoundary(): void;
/** Moves the cursor to the beginning of the buffer line, skipping all whitespace. */
skipLeadingWhitespace(): void;
/** Moves the cursor to the beginning of the next paragraph. */
moveToBeginningOfNextParagraph(): void;
/** Moves the cursor to the beginning of the previous paragraph. */
moveToBeginningOfPreviousParagraph(): void;
// Local Positions and Ranges
/**
* Returns buffer position of previous word boundary. It might be on the current
* word, or the previous word.
*/
getPreviousWordBoundaryBufferPosition(options?: { wordRegex?: RegExp }): Point;
/**
* Returns buffer position of the next word boundary. It might be on the current
* word, or the previous word.
*/
getNextWordBoundaryBufferPosition(options?: { wordRegex?: RegExp }): Point;
/** Retrieves the buffer position of where the current word starts. */
getBeginningOfCurrentWordBufferPosition(options?: {
wordRegex?: RegExp,
includeNonWordCharacters?: boolean,
allowPrevious?: boolean
}): Point;
/** Retrieves the buffer position of where the current word ends. */
getEndOfCurrentWordBufferPosition(options?: {
wordRegex?: RegExp,
includeNonWordCharacters?: boolean
}): Point;
/** Retrieves the buffer position of where the next word starts. */
getBeginningOfNextWordBufferPosition(options?: { wordRegex?: RegExp }): Point;
/** Returns the buffer Range occupied by the word located under the cursor. */
getCurrentWordBufferRange(options?: { wordRegex?: RegExp }): Range;
/** Returns the buffer Range for the current line. */
getCurrentLineBufferRange(options?: { includeNewline?: boolean }): Range;
/**
* Retrieves the range for the current paragraph.
* A paragraph is defined as a block of text surrounded by empty lines or comments.
*/
getCurrentParagraphBufferRange(): Range;
/** Returns the characters preceding the cursor in the current word. */
getCurrentWordPrefix(): string;
// Visibility
/** Sets whether the cursor is visible. */
setVisible(visible: boolean): void;
/** Returns the visibility of the cursor. */
isVisible(): boolean;
// Comparing to another cursor
/**
* Compare this cursor's buffer position to another cursor's buffer position.
* See Point::compare for more details.
*/
compare(otherCursor: Cursor): number;
// Utilities
/** Prevents this cursor from causing scrolling. */
clearAutoscroll(): void;
/** Deselects the current selection. */
clearSelection(): void;
/** Get the RegExp used by the cursor to determine what a "word" is. */
wordRegExp(options?: { includeNonWordCharacters?: boolean }): RegExp;
/** Get the RegExp used by the cursor to determine what a "subword" is. */
subwordRegExp(options?: { backwards?: boolean }): RegExp;
}
/** Manages the deserializers used for serialized state. */
export interface DeserializerManager {
/** Register the given class(es) as deserializers. */
add(...deserializers: Deserializer[]): Disposable;
/** Deserialize the state and params. */
deserialize(state: object): object|undefined;
}
/** Represents a directory on disk that can be watched for changes. */
export class Directory {
// Construction
/** Configures a new Directory instance, no files are accessed. */
constructor(directoryPath: string, symlink?: boolean);
/**
* Creates the directory on disk that corresponds to ::getPath() if no such
* directory already exists.
*/
create(mode?: number): Promise<boolean>;
// Event Subscription
/** Invoke the given callback when the directory's contents change. */
onDidChange(callback: () => void): Disposable;
// Directory Metadata
/** Returns a boolean, always false. */
isFile(): this is File;
/** Returns a boolean, always true. */
isDirectory(): this is Directory;
/** Returns a boolean indicating whether or not this is a symbolic link. */
isSymbolicLink(): boolean;
/**
* Returns a promise that resolves to a boolean, true if the directory
* exists, false otherwise.
*/
exists(): Promise<boolean>;
/** Returns a boolean, true if the directory exists, false otherwise. */
existsSync(): boolean;
/**
* Return a boolean, true if this Directory is the root directory of the
* filesystem, or false if it isn't.
*/
isRoot(): boolean;
// Managing Paths
/**
* This may include unfollowed symlinks or relative directory entries.
* Or it may be fully resolved, it depends on what you give it.
*/
getPath(): string;
/**
* All relative directory entries are removed and symlinks are resolved to
* their final destination.
*/
getRealPathSync(): string;
/** Returns the string basename of the directory. */
getBaseName(): string;
/** Returns the relative string path to the given path from this directory. */
relativize(fullPath: string): string;
// Traversing
/** Traverse to the parent directory. */
getParent(): Directory;
/**
* Traverse within this Directory to a child File. This method doesn't actually
* check to see if the File exists, it just creates the File object.
*/
getFile(filename: string): File;
/**
* Traverse within this a Directory to a child Directory. This method doesn't actually
* check to see if the Directory exists, it just creates the Directory object.
*/
getSubdirectory(dirname: string): Directory;
/** Reads file entries in this directory from disk synchronously. */
getEntriesSync(): Array<File|Directory>;
/** Reads file entries in this directory from disk asynchronously. */
getEntries(callback: (error: Error|null, entries: Array<File|Directory>) => void): void;
/**
* Determines if the given path (real or symbolic) is inside this directory. This
* method does not actually check if the path exists, it just checks if the path
* is under this directory.
*/
contains(pathToCheck: string): boolean;
}
/** A container at the edges of the editor window capable of holding items. */
export interface Dock {
// Methods
/** Show the dock and focus its active Pane. */
activate(): void;
/** Show the dock without focusing it. */
show(): void;
/**
* Hide the dock and activate the WorkspaceCenter if the dock was was previously
* focused.
*/
hide(): void;
/**
* Toggle the dock's visibility without changing the Workspace's active pane
* container.
*/
toggle(): void;
/** Check if the dock is visible. */
isVisible(): boolean;
// Event Subscription
/** Invoke the given callback when the visibility of the dock changes. */
onDidChangeVisible(callback: (visible: boolean) => void): Disposable;
/**
* Invoke the given callback with the current and all future visibilities of
* the dock.
*/
observeVisible(callback: (visible: boolean) => void): Disposable;
/** Invoke the given callback with all current and future panes items in the dock. */
observePaneItems(callback: (item: object) => void): Disposable;
/**
* Invoke the given callback when the active pane item changes.
*
* Because observers are invoked synchronously, it's important not to perform any
* expensive operations via this method. Consider ::onDidStopChangingActivePaneItem
* to delay operations until after changes stop occurring.
*/
onDidChangeActivePaneItem(callback: (item: object) => void): Disposable;
/** Invoke the given callback when the active pane item stops changing. */
onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable;
/**
* Invoke the given callback with the current active pane item and with all future
* active pane items in the dock.
*/
observeActivePaneItem(callback: (item: object) => void): Disposable;
/** Invoke the given callback when a pane is added to the dock. */
onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback before a pane is destroyed in the dock. */
onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback when a pane is destroyed in the dock. */
onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable;
/** Invoke the given callback with all current and future panes in the dock. */
observePanes(callback: (pane: Pane) => void): Disposable;
/** Invoke the given callback when the active pane changes. */
onDidChangeActivePane(callback: (pane: Pane) => void): Disposable;
/**
* Invoke the given callback with the current active pane and when the active
* pane changes.
*/
observeActivePane(callback: (pane: Pane) => void): Disposable;
/** Invoke the given callback when a pane item is added to the dock. */
onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/**
* Invoke the given callback when a pane item is about to be destroyed, before the user is
* prompted to save it.
* @param callback The function to be called before pane items are destroyed.
* If this function returns a Promise, then the item will not be destroyed
* until the promise resolves.
*/
onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void|Promise<void>):
Disposable;
/** Invoke the given callback when a pane item is destroyed. */
onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable;
/**
* Invoke the given callback when the hovered state of the dock changes.
* @param hovered Is the dock now hovered?
*/
onDidChangeHovered(callback: (hovered: boolean) => void): Disposable;
// Pane Items
/** Get all pane items in the dock. */
getPaneItems(): object[];
/** Get the active Pane's active item. */
getActivePaneItem(): object;
// Panes
/** Returns an Array of Panes. */
getPanes(): Pane[];
/** Get the active Pane. */
getActivePane(): Pane;
/** Make the next pane active. */
activateNextPane(): boolean;
/** Make the previous pane active. */
activatePreviousPane(): boolean;
}
/** Represents an individual file that can be watched, read from, and written to. */
export class File {
// Construction
/** Configures a new File instance, no files are accessed. */
constructor(filePath: string, symlink?: boolean);
/**
* Creates the file on disk that corresponds to ::getPath() if no such file
* already exists.
*/
create(): Promise<boolean>;
// Event Subscription
/** Invoke the given callback when the file's contents change. */
onDidChange(callback: () => void): Disposable;
/** Invoke the given callback when the file's path changes. */
onDidRename(callback: () => void): Disposable;
/** Invoke the given callback when the file is deleted. */
onDidDelete(callback: () => void): Disposable;
/**
* Invoke the given callback when there is an error with the watch. When
* your callback has been invoked, the file will have unsubscribed from the
* file watches.
*/
onWillThrowWatchError(callback: (event: PathWatchErrorThrownEvent) =>
void): Disposable;
// File Metadata
/** Returns a boolean, always true. */
isFile(): this is File;
/** Returns a boolean, always false. */
isDirectory(): this is Directory;
/** Returns a boolean indicating whether or not this is a symbolic link. */
isSymbolicLink(): boolean;
/**
* Returns a promise that resolves to a boolean, true if the file exists,
* false otherwise.
*/
exists(): Promise<boolean>;
/** Returns a boolean, true if the file exists, false otherwise. */
existsSync(): boolean;
/** Get the SHA-1 digest of this file. */
getDigest(): Promise<string>;
/** Get the SHA-1 digest of this file. */
getDigestSync(): string;
/** Sets the file's character set encoding name. */
setEncoding(encoding: string): void;
/** Returns the string encoding name for this file (default: "utf8"). */
getEncoding(): string;
// Managing Paths
/** Returns the string path for the file. */
getPath(): string;
/** Returns this file's completely resolved string path. */
getRealPathSync(): string;
/**
* Returns a promise that resolves to the file's completely resolved
* string path.
*/
getRealPath(): Promise<string>;
/** Return the string filename without any directory information. */
getBaseName(): string;
// Traversing
/** Return the Directory that contains this file. */
getParent(): Directory;
// Reading and Writing
/** Reads the contents of the file. */
read(flushCache?: boolean): Promise<string | null>;
/** Returns a stream to read the content of the file. */
createReadStream(): ReadStream;
/** Overwrites the file with the given text. */
write(text: string): Promise<undefined>;
/** Returns a stream to write content to the file. */
createWriteStream(): WriteStream;
/** Overwrites the file with the given text. */
writeSync(text: string): undefined;
}
/** Represents the underlying git operations performed by Atom. */
export class GitRepository {
// Construction
/** Creates a new GitRepository instance. */
static open(path: string, options?: { refreshOnWindowFocus?: boolean }): GitRepository;
constructor(path: string, options?: { refreshOnWindowFocus?: boolean, config?: Config,
project?: Project });
// Lifecycle
/** Destroy this GitRepository object. */
destroy(): void;
/** Returns a boolean indicating if this repository has been destroyed. */
isDestroyed(): boolean;
// Event Subscription
/**
* Invoke the given callback when this GitRepository's destroy() method is
* invoked.
*/
onDidDestroy(callback: () => void): Disposable;
/**
* Invoke the given callback when a specific file's status has changed. When
* a file is updated, reloaded, etc, and the status changes, this will be fired.
*/
onDidChangeStatus(callback: (event: RepoStatusChangedEvent) => void): Disposable;
/** Invoke the given callback when a multiple files' statuses have changed. */
onDidChangeStatuses(callback: () => void): Disposable;
// Repository Details
/** A string indicating the type of version control system used by this repository. */
getType(): "git";
/** Returns the string path of the repository. */
getPath(): string;
/** Returns the string working directory path of the repository. */
getWorkingDirectory(): string;
/** Returns true if at the root, false if in a subfolder of the repository. */
isProjectAtRoot(): boolean;
/** Makes a path relative to the repository's working directory. */
relativize(): string;
/** Returns true if the given branch exists. */
hasBranch(branch: string): boolean;
/** Retrieves a shortened version of the HEAD reference value. */
getShortHead(path?: string): string;
/** Is the given path a submodule in the repository? */
isSubmodule(path: string): boolean;
/**
* Returns the number of commits behind the current branch is from the its
* upstream remote branch. The default reference is the HEAD.
* @param reference The branch reference name.
* @param path The path in the repository to get this ifnromation for, only
* needed if the repository contains submodules.
* @return Returns the number of commits behind the current branch is from its
* upstream remote branch.
*/
getAheadBehindCount(reference: string, path?: string): { ahead: number, behind: number };
/**
* Get the cached ahead/behind commit counts for the current branch's
* upstream branch.
*/
getCachedUpstreamAheadBehindCount(path?: string): { ahead: number, behind: number };
/** Returns the git configuration value specified by the key. */
getConfigValue(key: string, path?: string): string;
/** Returns the origin url of the repository. */
getOriginURL(path?: string): string;
/**
* Returns the upstream branch for the current HEAD, or null if there is no
* upstream branch for the current HEAD.
*/
getUpstreamBranch(path?: string): string|null;
/** Gets all the local and remote references. */
getReferences(path?: string): { heads: string[], remotes: string[], tags: string[] };
/** Returns the current string SHA for the given reference. */
getReferenceTarget(reference: string, path?: string): string;
// Reading Status
/** Returns true if the given path is modified. */
isPathModified(path: string): boolean;
/** Returns true if the given path is new. */
isPathNew(path: string): boolean;
/** Is the given path ignored? */
isPathIgnored(path: string): boolean;
/** Get the status of a directory in the repository's working directory. */
getDirectoryStatus(path: string): number;
/** Get the status of a single path in the repository. */
getPathStatus(path: string): number;
/** Get the cached status for the given path. */
getCachedPathStatus(path: string): number|null;
/** Returns true if the given status indicates modification. */
isStatusModified(status: number): boolean;
/** Returns true if the given status indicates a new path. */
isStatusNew(status: number): boolean;
// Retrieving Diffs
/**
* Retrieves the number of lines added and removed to a path.
* This compares the working directory contents of the path to the HEAD version.
*/
getDiffStats(path: string): { added: number, deleted: number };
/**
* Retrieves the line diffs comparing the HEAD version of the given path
* and the given text.
*/
getLineDiffs(path: string, text: string): Array<{ oldStart: number,
newStart: number, oldLines: number, newLines: number }>;
// Checking Out
/**
* Restore the contents of a path in the working directory and index to the
* version at HEAD.
*/
checkoutHead(path: string): boolean;
/** Checks out a branch in your repository. */
checkoutReference(reference: string, create: boolean): boolean;
}
/** Grammar that tokenizes lines of text. */
export interface Grammar {
/** The name of the Grammar. */
readonly name: string;
/** Undocumented: scope name of the Grammar. */
readonly scopeName: string;
// Event Subscription
onDidUpdate(callback: () => void): Disposable;
// Tokenizing
/**
* Tokenize all lines in the given text.
* @param text A string containing one or more lines.
* @return An array of token arrays for each line tokenized.
*/
tokenizeLines(text: string): GrammarToken[][];
/**
* Tokenizes the line of text.
* @param line A string of text to tokenize.
* @param ruleStack An optional array of rules previously returned from this
* method. This should be null when tokenizing the first line in the file.
* @param firstLine A optional boolean denoting whether this is the first line
* in the file which defaults to `false`.
* @return An object representing the result of the tokenize.
*/
tokenizeLine(line: string, ruleStack?: null, firstLine?: boolean): TokenizeLineResult;
/**
* Tokenizes the line of text.
* @param line A string of text to tokenize.
* @param ruleStack An optional array of rules previously returned from this
* method. This should be null when tokenizing the first line in the file.
* @param firstLine A optional boolean denoting whether this is the first line
* in the file which defaults to `false`.
* @return An object representing the result of the tokenize.
*/
tokenizeLine(line: string, ruleStack: GrammarRule[], firstLine?: false):
TokenizeLineResult;
}
/** Registry containing one or more grammars. */
export interface GrammarRegistry {
// Event Subscription
/**
* Invoke the given callback when a grammar is added to the registry.
* @param callback The callback to be invoked whenever a grammar is added.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidAddGrammar(callback: (grammar: Grammar) => void): Disposable;
/**
* Invoke the given callback when a grammar is updated due to a grammar it
* depends on being added or removed from the registry.
* @param callback The callback to be invoked whenever a grammar is updated.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable;
/**
* Invoke the given callback when a grammar is removed from the registry.
* @param callback The callback to be invoked whenever a grammar is removed.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidRemoveGrammar(callback: (grammar: Grammar) => void): Disposable;
// Managing Grammars
/**
* Get all the grammars in this registry.
* @return A non-empty array of Grammar instances.
*/
getGrammars(): Grammar[];
/**
* Get a grammar with the given scope name.
* @param scopeName A string such as `source.js`.
* @return A Grammar or undefined.
*/
grammarForScopeName(scopeName: string): Grammar|undefined;
/**
* Add a grammar to this registry.
* A 'grammar-added' event is emitted after the grammar is added.
* @param grammar The Grammar to add. This should be a value previously returned
* from ::readGrammar or ::readGrammarSync.
* @return Returns a Disposable on which `.dispose()` can be called to remove
* the grammar.
*/
addGrammar(grammar: Grammar): Disposable;
/**
* Remove the given grammar from this registry.
* @param grammar The grammar to remove. This should be a grammar previously
* added to the registry from ::addGrammar.
*/
removeGrammar(grammar: Grammar): void;
/**
* Remove the grammar with the given scope name.
* @param scopeName A string such as `source.js`.
* @return Returns the removed Grammar or undefined.
*/
removeGrammarForScopeName(scopeName: string): Grammar|undefined;
/**
* Read a grammar synchronously but don't add it to the registry.
* @param grammarPath The absolute file path to a grammar.
* @return The newly loaded Grammar.
*/
readGrammarSync(grammarPath: string): Grammar;
/**
* Read a grammar asynchronously but don't add it to the registry.
* @param grammarPath The absolute file path to the grammar.
* @param callback The function to be invoked once the Grammar has been read in.
*/
readGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) =>
void): void;
/**
* Read a grammar synchronously and add it to this registry.
* @param grammarPath The absolute file path to the grammar.
* @return The newly loaded Grammar.
*/
loadGrammarSync(grammarPath: string): Grammar;
/**
* Read a grammar asynchronously and add it to the registry.
* @param grammarPath The absolute file path to the grammar.
* @param callback The function to be invoked once the Grammar has been read in
* and added to the registry.
*/
loadGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) =>
void): void;
/**
* Convert compact tags representation into convenient, space-inefficient tokens.
* @param lineText The text of the tokenized line.
* @param tags The tags returned from a call to Grammar::tokenizeLine().
* @return An array of Token instances decoded from the given tags.
*/
decodeTokens(lineText: string, tags: Array<number|string>): GrammarToken[];
/**
* Set a TextBuffer's language mode based on its path and content, and continue
* to update its language mode as grammars are added or updated, or the buffer's
* file path changes.
* @param buffer The buffer whose language mode will be maintained.
* @return A Disposable that can be used to stop updating the buffer's
* language mode.
*/
maintainLanguageMode(buffer: TextBuffer): Disposable;
/**
* Force a TextBuffer to use a different grammar than the one that would otherwise
* be selected for it.
* @param buffer The buffer whose grammar will be set.
* @param languageId The identifier of the desired language.
* @return Returns a boolean that indicates whether the language was successfully
* found.
*/
assignLanguageMode(buffer: TextBuffer, languageId: string): boolean;
/**
* Remove any language mode override that has been set for the given TextBuffer.
* This will assign to the buffer the best language mode available.
*/
autoAssignLanguageMode(buffer: TextBuffer): void;
/**
* Select a grammar for the given file path and file contents.
*
* This picks the best match by checking the file path and contents against
* each grammar.
* @param filePath A string file path.
* @param fileContents A string of text for that file path.
*/
selectGrammar(filePath: string, fileContents: string): Grammar;
/**
* Returns a number representing how well the grammar matches the
* `filePath` and `contents`.
* @param grammar The grammar to score.
* @param filePath A string file path.
* @param contents A string of text for that file path.
*/
getGrammarScore(grammar: Grammar, filePath: string, contents: string): number;
}
/** Represents a gutter within a TextEditor. */
export interface Gutter {
// Gutter Destruction
/** Destroys the gutter. */
destroy(): void;
// Event Subscription
/** Calls your callback when the gutter's visibility changes. */
onDidChangeVisible(callback: (gutter: Gutter) => void): Disposable;
/** Calls your callback when the gutter is destroyed. */
onDidDestroy(callback: () => void): Disposable;
// Visibility
/** Hide the gutter. */
hide(): void;
/** Show the gutter. */
show(): void;
/** Determine whether the gutter is visible. */
isVisible(): boolean;
/**
* Add a decoration that tracks a DisplayMarker. When the marker moves, is
* invalidated, or is destroyed, the decoration will be updated to reflect
* the marker's state.
*/
decorateMarker(marker: DisplayMarker, decorationParams: DecorationOptions): Decoration;
}
/**
* History manager for remembering which projects have been opened.
* An instance of this class is always available as the atom.history global.
* The project history is used to enable the 'Reopen Project' menu.
*/
export interface HistoryManager {
/** Obtain a list of previously opened projects. */
getProjects(): ProjectHistory[];
/**
* Clear all projects from the history.
* Note: This is not a privacy function - other traces will still exist, e.g.
* window state.
*/
clearProjects(): void;
/** Invoke the given callback when the list of projects changes. */
onDidChangeProjects(callback: (args: { reloaded: boolean }) => void): Disposable;
}
/**
* Allows commands to be associated with keystrokes in a context-sensitive way.
* In Atom, you can access a global instance of this object via `atom.keymaps`.
*/
export interface KeymapManager {
/** Clear all registered key bindings and enqueued keystrokes. For use in tests. */
clear(): void;
/** Unwatch all watched paths. */
destroy(): void;
// Event Subscription
/** Invoke the given callback when one or more keystrokes completely match a key binding. */
onDidMatchBinding(callback: (event: FullKeybindingMatchEvent) => void): Disposable;
/** Invoke the given callback when one or more keystrokes partially match a binding. */
onDidPartiallyMatchBindings(callback: (event: PartialKeybindingMatchEvent) =>
void): Disposable;
/** Invoke the given callback when one or more keystrokes fail to match any bindings. */
onDidFailToMatchBinding(callback: (event: FailedKeybindingMatchEvent) =>
void): Disposable;
/** Invoke the given callback when a keymap file is reloaded. */
onDidReloadKeymap(callback: (event: KeymapLoadedEvent) => void): Disposable;
/** Invoke the given callback when a keymap file is unloaded. */
onDidUnloadKeymap(callback: (event: KeymapLoadedEvent) => void): Disposable;
/** Invoke the given callback when a keymap file not able to be loaded. */
onDidFailToReadFile(callback: (error: FailedKeymapFileReadEvent) => void): Disposable;
// Adding and Removing Bindings
/** Construct KeyBindings from an object grouping them by CSS selector. */
build(source: string, bindings: { [key: string]: { [key: string]: string }},
priority?: number): KeyBinding[];
/** Add sets of key bindings grouped by CSS selector. */
add(source: string, bindings: { [key: string]: { [key: string]: string }},
priority?: number): Disposable;
// Accessing Bindings
/** Get all current key bindings. */
getKeyBindings(): KeyBinding[];
/** Get the key bindings for a given command and optional target. */
findKeyBindings(params?: {
keystrokes?: string, // e.g. 'ctrl-x ctrl-s'
command?: string, // e.g. 'editor:backspace'
target?: Element,
}): KeyBinding[];
// Managing Keymap Files
/** Load the key bindings from the given path. */
loadKeymap(bindingsPath: string, options?: { watch?: boolean, priority?: number }):
void;
/**
* Cause the keymap to reload the key bindings file at the given path whenever
* it changes.
*/
watchKeymap(filePath: string, options?: { priority: number }): void;
// Managing Keyboard Events
/**
* Dispatch a custom event associated with the matching key binding for the
* given `KeyboardEvent` if one can be found.
*/
handleKeyboardEvent(event: KeyboardEvent): void;
/** Translates a keydown event to a keystroke string. */
keystrokeForKeyboardEvent(event: KeyboardEvent): string;
/** Customize translation of raw keyboard events to keystroke strings. */
addKeystrokeResolver(resolver: (event: AddedKeystrokeResolverEvent) => string): Disposable;
/**
* Get the number of milliseconds allowed before pending states caused by
* partial matches of multi-keystroke bindings are terminated.
*/
getPartialMatchTimeout(): number;
}
/** Provides a registry for menu items that you'd like to appear in the application menu. */
export interface MenuManager {
/** Adds the given items to the application menu. */
add(items: ReadonlyArray<MenuOptions>): Disposable;
/** Refreshes the currently visible menu. */
update(): void;
}
/**
* Loads and activates a package's main module and resources such as stylesheets,
* keymaps, grammar, editor properties, and menus.
*/
export interface Package {
/** The name of the Package. */
readonly name: string;
/** The path to the Package on disk. */
readonly path: string;
// Event Subscription
/** Invoke the given callback when all packages have been activated. */
onDidDeactivate(callback: () => void): Disposable;
// Native Module Compatibility
/**
* Are all native modules depended on by this package correctly compiled
* against the current version of Atom?
*/
isCompatible(): boolean;
/**
* Rebuild native modules in this package's dependencies for the current
* version of Atom.
*/
rebuild(): Promise<{ code: number, stdout: string, stderr: string }>;
/** If a previous rebuild failed, get the contents of stderr. */
getBuildFailureOutput(): string|null;
}
/** Package manager for coordinating the lifecycle of Atom packages. */
export interface PackageManager {
// Event Subscription
/** Invoke the given callback when all packages have been loaded. */
onDidLoadInitialPackages(callback: () => void): Disposable;
/** Invoke the given callback when all packages have been activated. */
onDidActivateInitialPackages(callback: () => void): Disposable;
/** Invoke the given callback when a package is activated. */
onDidActivatePackage(callback: (package: Package) => void): Disposable;
/** Invoke the given callback when a package is deactivated. */
onDidDeactivatePackage(callback: (package: Package) => void): Disposable;
/** Invoke the given callback when a package is loaded. */
onDidLoadPackage(callback: (package: Package) => void): Disposable;
/** Invoke the given callback when a package is unloaded. */
onDidUnloadPackage(callback: (package: Package) => void): Disposable;
/** Undocumented: invoke the given callback when an activation hook is triggered */
onDidTriggerActivationHook(hook: string, callback: () => void): Disposable;
// Package System Data
/** Get the path to the apm command. */
getApmPath(): string;
/** Get the paths being used to look for packages. */
getPackageDirPaths(): string[];
// General Package Data
/** Resolve the given package name to a path on disk. */
resolvePackagePath(name: string): string|undefined;
/** Is the package with the given name bundled with Atom? */
isBundledPackage(name: string): boolean;
// Enabling and Disabling Packages
/** Enable the package with the given name. */
enablePackage(name: string): Package|undefined;
/** Disable the package with the given name. */
disablePackage(name: string): Package|undefined;
/** Is the package with the given name disabled? */
isPackageDisabled(name: string): boolean;
// Accessing Active Packages
/** Get an Array of all the active Packages. */
getActivePackages(): Package[];
/** Get the active Package with the given name. */
getActivePackage(name: string): Package|undefined;
/** Is the Package with the given name active? */
isPackageActive(name: string): boolean;
/** Returns a boolean indicating whether package activation has occurred. */
hasActivatedInitialPackages(): boolean;
// Accessing Loaded Packages
/** Get an Array of all the loaded Packages. */
getLoadedPackages(): Package[];
/** Get the loaded Package with the given name. */
getLoadedPackage(name: string): Package|undefined;
/** Is the package with the given name loaded? */
isPackageLoaded(name: string): boolean;
/** Returns a boolean indicating whether package loading has occurred. */
hasLoadedInitialPackages(): boolean;
// Accessing Available Packages
/** Returns an Array of strings of all the available package paths. */
getAvailablePackagePaths(): string[];
/** Returns an Array of strings of all the available package names. */
getAvailablePackageNames(): string[];
/** Returns an Array of strings of all the available package metadata. */
getAvailablePackageMetadata(): string[];
/** Activate a single package by name or path. */
activatePackage(nameOrPath: string): Promise<Package>;
/** Deactivate a single package by name or path. */
deactivatePackage(nameOrPath: string, suppressSerialization?: boolean): Promise<void>;
/** Triggers the given package activation hook. */
triggerActivationHook(hook: string): void;
/** Trigger all queued activation hooks immediately. */
triggerDeferredActivationHooks(): void;
}
/** A container for presenting content in the center of the workspace. */
export interface Pane {
// Event Subscription
/** Invoke the given callback when the pane resizes. */
onDidChangeFlexScale(callback: (flexScale: number) => void): Disposable;
/** Invoke the given callback with the current and future values of ::getFlexScale. */
observeFlexScale(callback: (flexScale: number) => void): Disposable;
/** Invoke the given callback when the pane is activated. */
onDidActivate(callback: () => void): Disposable;
/** Invoke the given callback before the pane is destroyed. */
onWillDestroy(callback: () => void): Disposable;
/** Invoke the given callback when the pane is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/** Invoke the given callback when the value of the ::isActive property changes. */
onDidChangeActive(callback: (active: boolean) => void): Disposable;
/**
* Invoke the given callback with the current and future values of the ::isActive
* property.
*/
observeActive(callback: (active: boolean) => void): Disposable;
/** Invoke the given callback when an item is added to the pane. */
onDidAddItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable;
/** Invoke the given callback when an item is removed from the pane. */
onDidRemoveItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable;
/** Invoke the given callback before an item is removed from the pane. */
onWillRemoveItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable;
/** Invoke the given callback when an item is moved within the pane. */
onDidMoveItem(callback: (event: PaneItemMovedEvent) => void): Disposable;
/** Invoke the given callback with all current and future items. */
observeItems(callback: (item: object) => void): Disposable;
/** Invoke the given callback when the value of ::getActiveItem changes. */
onDidChangeActiveItem(callback: (activeItem: object) => void): Disposable;
/**
* Invoke the given callback when ::activateNextRecentlyUsedItem has been called,
* either initiating or continuing a forward MRU traversal of pane items.
*/
onChooseNextMRUItem(callback: (nextRecentlyUsedItem: object) => void): Disposable;
/**
* Invoke the given callback when ::activatePreviousRecentlyUsedItem has been called,
* either initiating or continuing a reverse MRU traversal of pane items.
*/
onChooseLastMRUItem(callback: (previousRecentlyUsedItem: object) => void): Disposable;
/**
* Invoke the given callback when ::moveActiveItemToTopOfStack has been called,
* terminating an MRU traversal of pane items and moving the current active item
* to the top of the stack. Typically bound to a modifier (e.g. CTRL) key up event.
*/
onDoneChoosingMRUItem(callback: () => void): Disposable;
/** Invoke the given callback with the current and future values of ::getActiveItem. */
observeActiveItem(callback: (activeItem: object) => void): Disposable;
/** Invoke the given callback before items are destroyed. */
onWillDestroyItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable;
// Items
/** Get the items in this pane. */
getItems(): object[];
/** Get the active pane item in this pane. */
getActiveItem(): object;
/** Return the item at the given index. */
itemAtIndex(index: number): object|undefined;
/** Makes the next item active. */
activateNextItem(): void;
/** Makes the previous item active. */
activatePreviousItem(): void;
/** Move the active tab to the right. */
moveItemRight(): void;
/** Move the active tab to the left. */
moveItemLeft(): void;
/** Get the index of the active item. */
getActiveItemIndex(): number;
/** Activate the item at the given index. */
activateItemAtIndex(index: number): void;
/** Make the given item active, causing it to be displayed by the pane's view. */
activateItem(item: object, options?: { pending: boolean }): void;
/** Add the given item to the pane. */
addItem(item: object, options?: { index?: number, pending?: boolean }): object;
/** Add the given items to the pane. */
addItems(items: object[], index?: number): object[];
/** Move the given item to the given index. */
moveItem(item: object, index: number): void;
/** Move the given item to the given index on another pane. */
moveItemToPane(item: object, pane: Pane, index: number): void;
/** Destroy the active item and activate the next item. */
destroyActiveItem(): Promise<boolean>;
/** Destroy the given item. */
destroyItem(item: object, force?: boolean): Promise<boolean>;
/** Destroy all items. */
destroyItems(): Promise<boolean[]>;
/** Destroy all items except for the active item. */
destroyInactiveItems(): Promise<boolean[]>;
/** Save the active item. */
saveActiveItem<T = void>(nextAction?: (error?: Error) => T):
Promise<T>|undefined;
/**
* Prompt the user for a location and save the active item with the path
* they select.
*/
saveActiveItemAs<T = void>(nextAction?: (error?: Error) => T):
Promise<T>|undefined;
/** Save the given item. */
saveItem<T = void>(item: object, nextAction?: (error?: Error) => T):
Promise<T>|undefined;
/**
* Prompt the user for a location and save the active item with the path
* they select.
*/
saveItemAs<T = void>(item: object, nextAction?: (error?: Error) => T):
Promise<T>|undefined;
/** Save all items. */
saveItems(): void;
/** Return the first item that matches the given URI or undefined if none exists. */
itemForURI(uri: string): object|undefined;
/** Activate the first item that matches the given URI. */
activateItemForURI(uri: string): boolean;
// Lifecycle
/** Determine whether the pane is active. */
isActive(): boolean;
/** Makes this pane the active pane, causing it to gain focus. */
activate(): void;
/** Close the pane and destroy all its items. */
destroy(): void;
/** Determine whether this pane has been destroyed. */
isDestroyed(): boolean;
// Splitting
/** Create a new pane to the left of this pane. */
splitLeft(params?: {
items?: object[],
copyActiveItem?: boolean,
}): Pane;
/** Create a new pane to the right of this pane. */
splitRight(params?: {
items?: object[],
copyActiveItem?: boolean,
}): Pane;
/** Creates a new pane above the receiver. */
splitUp(params?: {
items?: object[],
copyActiveItem?: boolean,
}): Pane;
/** Creates a new pane below the receiver. */
splitDown(params?: {
items?: object[],
copyActiveItem?: boolean,
}): Pane;
}
/**
* A container representing a panel on the edges of the editor window. You
* should not create a Panel directly, instead use Workspace::addTopPanel and
* friends to add panels.
*/
export interface Panel<T = object> {
/** Whether or not the Panel is visible. */
readonly visible: boolean;
// Construction and Destruction
/** Destroy and remove this panel from the UI. */
destroy(): void;
// Event Subscription
/** Invoke the given callback when the pane hidden or shown. */
onDidChangeVisible(callback: (visible: boolean) => void): Disposable;
/** Invoke the given callback when the pane is destroyed. */
onDidDestroy(callback: (panel: Panel<T>) => void): Disposable;
// Panel Details
/** Returns the panel's item. */
getItem(): T;
/** Returns a number indicating this panel's priority. */
getPriority(): number;
/** Returns a boolean true when the panel is visible. */
isVisible(): boolean;
/** Hide this panel. */
hide(): void;
/** Show this panel. */
show(): void;
}
/** Manage a subscription to filesystem events that occur beneath a root directory. */
export interface PathWatcher extends DisposableLike {
/**
* Return a Promise that will resolve when the underlying native watcher is
* ready to begin sending events.
*/
getStartPromise(): Promise<void>;
/** Invokes a function when any errors related to this watcher are reported. */
onDidError(callback: (error: Error) => void): Disposable;
/**
* Unsubscribe all subscribers from filesystem events. Native resources will be
* released asynchronously, but this watcher will stop broadcasting events
* immediately.
*/
dispose(): void;
}
/** Represents a project that's opened in Atom. */
export interface Project {
// Event Subscription
/** Invoke the given callback when the project paths change. */
onDidChangePaths(callback: (projectPaths: string[]) => void): Disposable;
/** Invoke the given callback when a text buffer is added to the project. */
onDidAddBuffer(callback: (buffer: TextBuffer) => void): Disposable;
/**
* Invoke the given callback with all current and future text buffers in
* the project.
*/
observeBuffers(callback: (buffer: TextBuffer) => void): Disposable;
/** Invoke a callback when a filesystem change occurs within any open project path. */
onDidChangeFiles(callback: (events: FilesystemChangeEvent) => void): Disposable;
/** Invoke a callback whenever the project's configuration has been replaced. */
onDidReplace(callback: (projectSpec: ProjectSpecification | null | undefined) => void):
Disposable;
// Accessing the Git Repository
/**
* Get an Array of GitRepositorys associated with the project's directories.
*
* This method will be removed in 2.0 because it does synchronous I/O.
*/
getRepositories(): GitRepository[];
/** Invoke the given callback with all current and future repositories in the project. */
observeRepositories(callback: (repository: GitRepository) => void): Disposable;
/** Invoke the given callback when a repository is added to the project. */
onDidAddRepository(callback: (repository: GitRepository) => void): Disposable;
/** Get the repository for a given directory asynchronously. */
repositoryForDirectory(directory: Directory): Promise<GitRepository|null>;
// Managing Paths
/** Get an Array of strings containing the paths of the project's directories. */
getPaths(): string[];
/** Set the paths of the project's directories. */
setPaths(projectPaths: string[]): void;
/** Add a path to the project's list of root paths. */
addPath(projectPath: string): void;
/**
* Access a promise that resolves when the filesystem watcher associated with a
* project root directory is ready to begin receiving events.
*/
getWatcherPromise(projectPath: string): Promise<PathWatcher>;
/** Remove a path from the project's list of root paths. */
removePath(projectPath: string): void;
/** Get an Array of Directorys associated with this project. */
getDirectories(): Directory[];
/** Get the relative path from the project directory to the given path. */
relativize(fullPath: string): string;
/**
* Get the path to the project directory that contains the given path, and
* the relative path from that project directory to the given path.
*/
relativizePath(fullPath: string): [string|null, string];
/**
* Determines whether the given path (real or symbolic) is inside the
* project's directory.
*/
contains(pathToCheck: string): boolean;
}
/**
* Wraps an array of strings. The Array describes a path from the root of the
* syntax tree to a token including all scope names for the entire path.
*/
export interface ScopeDescriptor {
/** Returns all scopes for this descriptor. */
getScopesArray(): ReadonlyArray<string>;
}
/** Represents a selection in the TextEditor. */
export interface Selection {
// Event Subscription
/** Calls your callback when the selection was moved. */
onDidChangeRange(callback: (event: SelectionChangedEvent) => void): Disposable;
/** Calls your callback when the selection was destroyed. */
onDidDestroy(callback: () => void): Disposable;
// Managing the selection range
/** Returns the screen Range for the selection. */
getScreenRange(): Range;
/** Modifies the screen range for the selection. */
setScreenRange(screenRange: RangeCompatible, options?: {
preserveFolds?: boolean,
autoscroll?: boolean
}): void;
/** Returns the buffer Range for the selection. */
getBufferRange(): Range;
/** Modifies the buffer Range for the selection. */
setBufferRange(bufferRange: RangeCompatible, options?: {
preserveFolds?: boolean,
autoscroll?: boolean,
}): void;
/** Returns the starting and ending buffer rows the selection is highlighting. */
getBufferRowRange(): [number, number];
// Info about the selection
/** Determines if the selection contains anything. */
isEmpty(): boolean;
/**
* Determines if the ending position of a marker is greater than the starting position.
* This can happen when, for example, you highlight text "up" in a TextBuffer.
*/
isReversed(): boolean;
/** Returns whether the selection is a single line or not. */
isSingleScreenLine(): boolean;
/** Returns the text in the selection. */
getText(): string;
// NOTE: this calls into Range.intersectsWith(), which is one of the few functions
// that doesn't take a range-compatible range, despite what the API says.
/** Identifies if a selection intersects with a given buffer range. */
intersectsBufferRange(bufferRange: RangeLike): boolean;
/** Identifies if a selection intersects with another selection. */
intersectsWith(otherSelection: Selection): boolean;
// Modifying the selected range
/** Clears the selection, moving the marker to the head. */
clear(options?: { autoscroll?: boolean }): void;
/** Selects the text from the current cursor position to a given screen position. */
selectToScreenPosition(position: PointCompatible): void;
/** Selects the text from the current cursor position to a given buffer position. */
selectToBufferPosition(position: PointCompatible): void;
/** Selects the text one position right of the cursor. */
selectRight(columnCount?: number): void;
/** Selects the text one position left of the cursor. */
selectLeft(columnCount?: number): void;
/** Selects all the text one position above the cursor. */
selectUp(rowCount?: number): void;
/** Selects all the text one position below the cursor. */
selectDown(rowCount?: number): void;
/**
* Selects all the text from the current cursor position to the top of the
* buffer.
*/
selectToTop(): void;
/**
* Selects all the text from the current cursor position to the bottom of
* the buffer.
*/
selectToBottom(): void;
/** Selects all the text in the buffer. */
selectAll(): void;
/**
* Selects all the text from the current cursor position to the beginning of
* the line.
*/
selectToBeginningOfLine(): void;
/**
* Selects all the text from the current cursor position to the first character
* of the line.
*/
selectToFirstCharacterOfLine(): void;
/**
* Selects all the text from the current cursor position to the end of the
* screen line.
*/
selectToEndOfLine(): void;
/**
* Selects all the text from the current cursor position to the end of the
* buffer line.
*/
selectToEndOfBufferLine(): void;
/**
* Selects all the text from the current cursor position to the beginning
* of the word.
*/
selectToBeginningOfWord(): void;
/** Selects all the text from the current cursor position to the end of the word. */
selectToEndOfWord(): void;
/**
* Selects all the text from the current cursor position to the beginning of
* the next word.
*/
selectToBeginningOfNextWord(): void;
/** Selects text to the previous word boundary. */
selectToPreviousWordBoundary(): void;
/** Selects text to the next word boundary. */
selectToNextWordBoundary(): void;
/** Selects text to the previous subword boundary. */
selectToPreviousSubwordBoundary(): void;
/** Selects text to the next subword boundary. */
selectToNextSubwordBoundary(): void;
/**
* Selects all the text from the current cursor position to the beginning of
* the next paragraph.
*/
selectToBeginningOfNextParagraph(): void;
/**
* Selects all the text from the current cursor position to the beginning of
* the previous paragraph.
*/
selectToBeginningOfPreviousParagraph(): void;
/** Modifies the selection to encompass the current word. */
selectWord(): void;
/**
* Expands the newest selection to include the entire word on which the
* cursors rests.
*/
expandOverWord(): void;
/** Selects an entire line in the buffer. */
selectLine(row: number): void;
/**
* Expands the newest selection to include the entire line on which the cursor
* currently rests.
* It also includes the newline character.
*/
expandOverLine(): void;
// Modifying the selected text
/** Replaces text at the current selection. */
insertText(text: string, options?: TextInsertionOptions & ReadonlyEditOptions): void;
/**
* Removes the first character before the selection if the selection is empty
* otherwise it deletes the selection.
*/
backspace(options?: ReadonlyEditOptions): void;
/**
* Removes the selection or, if nothing is selected, then all characters from
* the start of the selection back to the previous word boundary.
*/
deleteToPreviousWordBoundary(options?: ReadonlyEditOptions): void;
/**
* Removes the selection or, if nothing is selected, then all characters from
* the start of the selection up to the next word boundary.
*/
deleteToNextWordBoundary(options?: ReadonlyEditOptions): void;
/**
* Removes from the start of the selection to the beginning of the current
* word if the selection is empty otherwise it deletes the selection.
*/
deleteToBeginningOfWord(options?: ReadonlyEditOptions): void;
/**
* Removes from the beginning of the line which the selection begins on all
* the way through to the end of the selection.
*/
deleteToBeginningOfLine(options?: ReadonlyEditOptions): void;
/**
* Removes the selection or the next character after the start of the selection
* if the selection is empty.
*/
delete(options?: ReadonlyEditOptions): void;
/**
* If the selection is empty, removes all text from the cursor to the end of
* the line. If the cursor is already at the end of the line, it removes the following
* newline. If the selection isn't empty, only deletes the contents of the selection.
*/
deleteToEndOfLine(options?: ReadonlyEditOptions): void;
/**
* Removes the selection or all characters from the start of the selection to
* the end of the current word if nothing is selected.
*/
deleteToEndOfWord(options?: ReadonlyEditOptions): void;
/**
* Removes the selection or all characters from the start of the selection to
* the end of the current word if nothing is selected.
*/
deleteToBeginningOfSubword(options?: ReadonlyEditOptions): void;
/**
* Removes the selection or all characters from the start of the selection to
* the end of the current word if nothing is selected.
*/
deleteToEndOfSubword(options?: ReadonlyEditOptions): void;
/** Removes only the selected text. */
deleteSelectedText(options?: ReadonlyEditOptions): void;
/**
* Removes the line at the beginning of the selection if the selection is empty
* unless the selection spans multiple lines in which case all lines are removed.
*/
deleteLine(options?: ReadonlyEditOptions): void;
/**
* Joins the current line with the one below it. Lines will be separated by a single space.
* If there selection spans more than one line, all the lines are joined together.
*/
joinLines(options?: ReadonlyEditOptions): void;
/** Removes one level of indent from the currently selected rows. */
outdentSelectedRows(options?: ReadonlyEditOptions): void;
/**
* Sets the indentation level of all selected rows to values suggested by the
* relevant grammars.
*/
autoIndentSelectedRows(options?: ReadonlyEditOptions): void;
/**
* Wraps the selected lines in comments if they aren't currently part of a comment.
* Removes the comment if they are currently wrapped in a comment.
*/
toggleLineComments(options?: ReadonlyEditOptions): void;
/** Cuts the selection until the end of the screen line. */
cutToEndOfLine(maintainClipboard?: boolean, options?: ReadonlyEditOptions): void;
/** Cuts the selection until the end of the buffer line. */
cutToEndOfBufferLine(maintainClipboard?: boolean, options?: ReadonlyEditOptions): void;
/** Copies the selection to the clipboard and then deletes it. */
cut(maintainClipboard?: boolean, fullLine?: boolean, options?: ReadonlyEditOptions): void;
/** Copies the current selection to the clipboard. */
copy(maintainClipboard?: boolean, fullLine?: boolean): void;
/** Creates a fold containing the current selection. */
fold(): void;
/** If the selection spans multiple rows, indent all of them. */
indentSelectedRows(options?: ReadonlyEditOptions): void;
// Managing multiple selections
/** Moves the selection down one row. */
addSelectionBelow(): void;
/** Moves the selection up one row. */
addSelectionAbove(): void;
/**
* Combines the given selection into this selection and then destroys the
* given selection.
*/
merge(otherSelection: Selection, options?: { preserveFolds?: boolean,
autoscroll?: boolean }): void;
// Comparing to other selections
/**
* Compare this selection's buffer range to another selection's buffer range.
* See Range::compare for more details.
*/
compare(otherSelection: Selection): number;
}
/**
* A singleton instance of this class available via atom.styles, which you can
* use to globally query and observe the set of active style sheets.
*/
export interface StyleManager {
// Event Subscription
/** Invoke callback for all current and future style elements. */
observeStyleElements(callback: (styleElement: StyleElementObservedEvent) =>
void): Disposable;
/** Invoke callback when a style element is added. */
onDidAddStyleElement(callback: (styleElement: StyleElementObservedEvent) =>
void): Disposable;
/** Invoke callback when a style element is removed. */
onDidRemoveStyleElement(callback: (styleElement: HTMLStyleElement) => void): Disposable;
/** Invoke callback when an existing style element is updated. */
onDidUpdateStyleElement(callback: (styleElement: StyleElementObservedEvent) =>
void): Disposable;
// Reading Style Elements
/** Get all loaded style elements. */
getStyleElements(): HTMLStyleElement[];
// Paths
/** Get the path of the user style sheet in ~/.atom. */
getUserStyleSheetPath(): string;
}
/** Run a node script in a separate process. */
export class Task {
// NOTE: this is actually the best we can do here with the REST parameter for
// this appearing in the middle of the parameter list, which isn't aligned with
// the ES6 spec. Maybe when they rewrite it in JavaScript this will change.
/** A helper method to easily launch and run a task once. */
// tslint:disable-next-line:no-any
static once(taskPath: string, ...args: any[]): Task;
/** Creates a task. You should probably use .once */
constructor(taskPath: string);
// NOTE: this is actually the best we can do here with the REST parameter
// for this appearing in the beginning of the parameter list, which isn't
// aligned with the ES6 spec.
/**
* Starts the task.
* Throws an error if this task has already been terminated or if sending a
* message to the child process fails.
*/
// tslint:disable-next-line:no-any
start(...args: any[]): void;
/**
* Send message to the task.
* Throws an error if this task has already been terminated or if sending a
* message to the child process fails.
*/
// tslint:disable-next-line:no-any
send(message: string | number | boolean | object | null | any[]): void;
/** Call a function when an event is emitted by the child process. */
// tslint:disable-next-line:no-any
on(eventName: string, callback: (param: any) => void): Disposable;
/**
* Forcefully stop the running task.
* No more events are emitted once this method is called.
*/
terminate(): void;
/** Cancel the running task and emit an event if it was canceled. */
cancel(): boolean;
}
export interface TextBufferFileBackend {
/** A {Function} that returns the {String} path to the file. */
getPath(): string;
/**
* A {Function} that returns a `Readable` stream
* that can be used to load the file's content.
*/
createReadStream(): ReadStream;
/**
* A {Function} that returns a `Writable` stream
* that can be used to save content to the file.
*/
createWriteStream(): WriteStream;
/** A {Function} that returns a {Boolean}, true if the file exists, false otherwise. */
existsSync(): boolean;
/**
* A {Function} that invokes its callback argument
* when the file changes. The method should return a {Disposable} that
* can be used to prevent further calls to the callback.
*/
onDidChange?(callback: () => void): Disposable;
/**
* A {Function} that invokes its callback argument
* when the file is deleted. The method should return a {Disposable} that
* can be used to prevent further calls to the callback.
*/
onDidDelete?(callback: () => void): Disposable;
/**
* A {Function} that invokes its callback argument
* when the file is renamed. The method should return a {Disposable} that
* can be used to prevent further calls to the callback.
*/
onDidRename?(callback: () => void): Disposable;
}
/**
* A mutable text container with undo/redo support and the ability to
* annotate logical regions in the text.
*/
export class TextBuffer {
/** The unique identifier for this buffer. */
readonly id: string;
/** The number of retainers for the buffer. */
readonly refcount: number;
/** Whether or not the bufffer has been destroyed. */
readonly destroyed: boolean;
/** Create a new buffer backed by the given file path. */
static load(
filePath: string | TextBufferFileBackend,
params?: BufferLoadOptions): Promise<TextBuffer>;
/**
* Create a new buffer backed by the given file path. For better performance,
* use TextBuffer.load instead.
*/
static loadSync(filePath: string, params?: BufferLoadOptions): TextBuffer;
/**
* Restore a TextBuffer based on an earlier state created using the
* TextBuffer::serialize method.
*/
static deserialize(params: object): Promise<TextBuffer>;
/** Create a new buffer with the given starting text. */
constructor(text: string);
/** Create a new buffer with the given params. */
constructor(params?: {
/** The initial string text of the buffer. */
text?: string
/**
* A function that returns a Boolean indicating whether the buffer should
* be destroyed if its file is deleted.
*/
shouldDestroyOnFileDelete?(): boolean
});
/** Returns a plain javascript object representation of the TextBuffer. */
serialize(options?: { markerLayers?: boolean, history?: boolean }): object;
/** Returns the unique identifier for this buffer. */
getId(): string;
// Event Subscription
/**
* Invoke the given callback synchronously before the content of the buffer
* changes.
*/
onWillChange(callback: (event: BufferChangingEvent) => void): Disposable;
/**
* Invoke the given callback synchronously when the content of the buffer
* changes. You should probably not be using this in packages.
*/
onDidChange(callback: (event: BufferChangedEvent) => void): Disposable;
/**
* Invoke the given callback synchronously when a transaction finishes with
* a list of all the changes in the transaction.
*/
onDidChangeText(callback: (event: BufferStoppedChangingEvent) => void): Disposable;
/**
* Invoke the given callback asynchronously following one or more changes after
* ::getStoppedChangingDelay milliseconds elapse without an additional change.
*/
onDidStopChanging(callback: (event: BufferStoppedChangingEvent) => void):
Disposable;
/**
* Invoke the given callback when the in-memory contents of the buffer become
* in conflict with the contents of the file on disk.
*/
onDidConflict(callback: () => void): Disposable;
/** Invoke the given callback if the value of ::isModified changes. */
onDidChangeModified(callback: (modified: boolean) => void): Disposable;
/**
* Invoke the given callback when all marker ::onDidChange observers have been
* notified following a change to the buffer.
*/
onDidUpdateMarkers(callback: () => void): Disposable;
onDidCreateMarker(callback: (marker: Marker) => void): Disposable;
/** Invoke the given callback when the value of ::getPath changes. */
onDidChangePath(callback: (path: string) => void): Disposable;
/** Invoke the given callback when the value of ::getEncoding changes. */
onDidChangeEncoding(callback: (encoding: string) => void): Disposable;
/**
* Invoke the given callback before the buffer is saved to disk. If the
* given callback returns a promise, then the buffer will not be saved until
* the promise resolves.
*/
onWillSave(callback: () => Promise<void>|void): Disposable;
/** Invoke the given callback after the buffer is saved to disk. */
onDidSave(callback: (event: FileSavedEvent) => void): Disposable;
/** Invoke the given callback after the file backing the buffer is deleted. */
onDidDelete(callback: () => void): Disposable;
/**
* Invoke the given callback before the buffer is reloaded from the contents
* of its file on disk.
*/
onWillReload(callback: () => void): Disposable;
/**
* Invoke the given callback after the buffer is reloaded from the contents
* of its file on disk.
*/
onDidReload(callback: () => void): Disposable;
/** Invoke the given callback when the buffer is destroyed. */
onDidDestroy(callback: () => void): Disposable;
/** Invoke the given callback when there is an error in watching the file. */
onWillThrowWatchError(callback: (errorObject: HandleableErrorEvent) => void):
Disposable;
/**
* Get the number of milliseconds that will elapse without a change before
* ::onDidStopChanging observers are invoked following a change.
*/
getStoppedChangingDelay(): number;
// File Details
/**
* Determine if the in-memory contents of the buffer differ from its contents
* on disk.
* If the buffer is unsaved, always returns true unless the buffer is empty.
*/
isModified(): boolean;
/**
* Determine if the in-memory contents of the buffer conflict with the on-disk
* contents of its associated file.
*/
isInConflict(): boolean;
/** Get the path of the associated file. */
getPath(): string|undefined;
/** Set the path for the buffer's associated file. */
setPath(filePath: string): void;
/** Experimental: Set a custom {TextBufferFileBackend} object as the buffer's backing store. */
setFile(fileBackend: TextBufferFileBackend): void;
/** Sets the character set encoding for this buffer. */
setEncoding(encoding: string): void;
/** Returns the string encoding of this buffer. */
getEncoding(): string;
/** Get the path of the associated file. */
getUri(): string;
// Reading Text
/** Determine whether the buffer is empty. */
isEmpty(): boolean;
/** Get the entire text of the buffer. */
getText(): string;
/** Get the text in a range. */
getTextInRange(range: RangeCompatible): string;
/** Get the text of all lines in the buffer, without their line endings. */
getLines(): string[];
/** Get the text of the last line of the buffer, without its line ending. */
getLastLine(): string;
/**
* Get the text of the line at the given 0-indexed row, without its line ending.
* @param row A number representing the row.
*/
lineForRow(row: number): string|undefined;
/** Get the line ending for the given 0-indexed row. */
lineEndingForRow(row: number): string|undefined;
/**
* Get the length of the line for the given 0-indexed row, without its line
* ending.
*/
lineLengthForRow(row: number): number;
/** Determine if the given row contains only whitespace. */
isRowBlank(row: number): boolean;
/**
* Given a row, find the first preceding row that's not blank.
* Returns a number or null if there's no preceding non-blank row.
*/
previousNonBlankRow(startRow: number): number|null;
/**
* Given a row, find the next row that's not blank.
* Returns a number or null if there's no next non-blank row.
*/
nextNonBlankRow(startRow: number): number|null;
/**
* Return true if the buffer contains any astral-plane Unicode characters that
* are encoded as surrogate pairs.
*/
hasAstral(): boolean;
// Mutating Text
/** Replace the entire contents of the buffer with the given text. */
setText(text: string): Range;
/**
* Replace the current buffer contents by applying a diff based on the
* given text.
*/
setTextViaDiff(text: string): void;
/** Set the text in the given range. */
setTextInRange(range: RangeCompatible, text: string, options?: TextEditOptions): Range;
/** Insert text at the given position. */
insert(position: PointCompatible, text: string, options?: TextEditOptions): Range;
/** Append text to the end of the buffer. */
append(text: string, options?: TextEditOptions): Range;
/** Delete the text in the given range. */
delete(range: RangeCompatible): Range;
/**
* Delete the line associated with a specified 0-indexed row.
* @param row A number representing the row to delete.
*/
deleteRow(row: number): Range;
/**
* Delete the lines associated with the specified 0-indexed row range.
*
* If the row range is out of bounds, it will be clipped. If the `startRow`
* is greater than the `endRow`, they will be reordered.
*/
deleteRows(startRow: number, endRow: number): Range;
// Markers
/** Create a layer to contain a set of related markers. */
addMarkerLayer(options?: { maintainHistory?: boolean, persistent?: boolean, role?: string }):
MarkerLayer;
/**
* Get a MarkerLayer by id.
* Returns a MarkerLayer or undefined if no layer exists with the given id.
*/
getMarkerLayer(id: string): MarkerLayer|undefined;
/** Get the default MarkerLayer. */
getDefaultMarkerLayer(): MarkerLayer;
/** Create a marker with the given range in the default marker layer. */
markRange(range: RangeCompatible, properties?: { reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean }): Marker;
/** Create a marker at the given position with no tail in the default marker layer. */
markPosition(position: PointCompatible, options?: { invalidate?: "never"|"surround"
|"overlap"|"inside"|"touch", exclusive?: boolean }): Marker;
/** Get all existing markers on the default marker layer. */
getMarkers(): Marker[];
/** Get an existing marker by its id from the default marker layer. */
getMarker(id: number): Marker;
/** Find markers conforming to the given parameters in the default marker layer. */
findMarkers(params: FindMarkerOptions): Marker[];
/** Get the number of markers in the default marker layer. */
getMarkerCount(): number;
// History
/**
* Undo the last operation. If a transaction is in progress, aborts it.
* @return A boolean of whether or not a change was made.
*/
undo(options?: HistoryTraversalOptions): boolean;
/**
* Redo the last operation.
* @return A boolean of whether or not a change was made.
*/
redo(options?: HistoryTraversalOptions): boolean;
/** Batch multiple operations as a single undo/redo step. */
transact<T>(optionsOrInterval: number | { groupingInterval?: number } &
HistoryTransactionOptions, fn: () => T): T;
/** Batch multiple operations as a single undo/redo step. */
transact<T>(fn: () => T): T;
/**
* Abort the currently running transaction.
*
* Only intended to be called within the `fn` option to `::transact`.
*/
abortTransaction(): void;
/** Clear the undo stack. */
clearUndoStack(): void;
/**
* Create a pointer to the current state of the buffer for use with
* `::revertToCheckpoint` and `::groupChangesSinceCheckpoint`.
* @return A checkpoint ID value.
*/
createCheckpoint(options?: HistoryTransactionOptions): number;
/**
* Revert the buffer to the state it was in when the given checkpoint was created.
* @return A boolean indicating whether the operation succeeded.
*/
revertToCheckpoint(checkpoint: number, options?: HistoryTraversalOptions):
boolean;
/**
* Group all changes since the given checkpoint into a single transaction for
* purposes of undo/redo.
* @return A boolean indicating whether the operation succeeded.
*/
groupChangesSinceCheckpoint(checkpoint: number, options?: HistoryTransactionOptions): boolean;
/**
* Group the last two text changes for purposes of undo/redo.
*
* This operation will only succeed if there are two changes on the undo stack.
* It will not group past the beginning of an open transaction.
* @return A boolean indicating whether the operation succeeded.
*/
groupLastChanges(): boolean;
/**
* Returns a list of changes since the given checkpoint.
* If the given checkpoint is no longer present in the undo history, this method
* will return an empty Array.
*/
getChangesSinceCheckpoint(checkpoint: number): Array<{
/** A Point representing where the change started. */
start: Point,
/** A Point representing the replaced extent. */
oldExtent: Point,
/** A Point representing the replacement extent. */
newExtent: Point,
/** A String representing the replacement text. */
newText: string
}>;
// Search and Replace
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*/
scan(regex: RegExp, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*/
scan(regex: RegExp, options: ScanContextOptions, iterator: (params:
ContextualBufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer in reverse order,
* calling the given iterator function on each match.
*/
backwardsScan(regex: RegExp, iterator: (params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in the entire buffer in reverse order,
* calling the given iterator function on each match.
*/
backwardsScan(regex: RegExp, options: ScanContextOptions, iterator: (params:
ContextualBufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range , calling the given
* iterator function on each match.
*/
scanInRange(regex: RegExp, range: RangeCompatible, iterator:
(params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range , calling the given
* iterator function on each match.
*/
scanInRange(regex: RegExp, range: RangeCompatible, options: ScanContextOptions,
iterator: (params: ContextualBufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range in reverse order,
* calling the given iterator function on each match.
*/
backwardsScanInRange(regex: RegExp, range: RangeCompatible, iterator:
(params: BufferScanResult) => void): void;
/**
* Scan regular expression matches in a given range in reverse order,
* calling the given iterator function on each match.
*/
backwardsScanInRange(regex: RegExp, range: RangeCompatible, options: ScanContextOptions,
iterator: (params: ContextualBufferScanResult) => void): void;
/** Replace all regular expression matches in the entire buffer. */
replace(regex: RegExp, replacementText: string): number;
// Buffer Range Details
/** Get the range spanning from [0, 0] to ::getEndPosition. */
getRange(): Range;
/** Get the number of lines in the buffer. */
getLineCount(): number;
/** Get the last 0-indexed row in the buffer. */
getLastRow(): number;
/** Get the first position in the buffer, which is always [0, 0]. */
getFirstPosition(): Point;
/** Get the maximal position in the buffer, where new text would be appended. */
getEndPosition(): Point;
/** Get the length of the buffer's text. */
getLength(): number;
/** Get the length of the buffer in characters. */
getMaxCharacterIndex(): number;
/**
* Get the range for the given row.
* @param row A number representing a 0-indexed row.
* @param includeNewline A boolean indicating whether or not to include the
* newline, which results in a range that extends to the start of the next line.
* (default: false)
*/
rangeForRow(row: number, includeNewline?: boolean): Range;
/**
* Convert a position in the buffer in row/column coordinates to an absolute
* character offset, inclusive of line ending characters.
*/
characterIndexForPosition(position: PointCompatible): number;
/**
* Convert an absolute character offset, inclusive of newlines, to a position
* in the buffer in row/column coordinates.
*/
positionForCharacterIndex(offset: number): Point;
/** Clip the given range so it starts and ends at valid positions. */
clipRange(range: RangeCompatible): Range;
/** Clip the given point so it is at a valid position in the buffer. */
clipPosition(position: PointCompatible): Point;
// Buffer Operations
/** Save the buffer. */
save(): Promise<void>;
/** Save the buffer at a specific path. */
saveAs(filePath: string): Promise<void>;
/** Reload the buffer's contents from disk. */
reload(): void;
/** Destroy the buffer, even if there are retainers for it. */
destroy(): void;
/** Returns whether or not this buffer is alive. */
isAlive(): boolean;
/** Returns whether or not this buffer has been destroyed. */
isDestroyed(): boolean;
/** Returns whether or not this buffer has a retainer. */
isRetained(): boolean;
/**
* Places a retainer on the buffer, preventing its destruction until the
* final retainer has called ::release().
*/
retain(): TextBuffer;
/**
* Releases a retainer on the buffer, destroying the buffer if there are
* no additional retainers.
*/
release(): TextBuffer;
/** Identifies if the buffer belongs to multiple editors. */
hasMultipleEditors(): boolean;
}
/** Handles loading and activating available themes. */
export interface ThemeManager {
// Event Subscription
/**
* Invoke callback when style sheet changes associated with updating the
* list of active themes have completed.
*/
onDidChangeActiveThemes(callback: () => void): Disposable;
// Accessing Loaded Themes
/** Returns an Array of strings of all the loaded theme names. */
getLoadedThemeNames(): string[]|undefined;
/** Returns an Array of all the loaded themes. */
getLoadedThemes(): Package[]|undefined;
// Managing Enabled Themes
/** Returns an Array of strings all the active theme names. */
getActiveThemeNames(): string[]|undefined;
/** Returns an Array of all the active themes. */
getActiveThemes(): Package[]|undefined;
// Managing Enabled Themes
/** Get the enabled theme names from the config. */
getEnabledThemeNames(): string[];
}
// Events =====================================================================
// The event objects that are passed into the callbacks which the user provides to
// specific API calls.
export interface AddedKeystrokeResolverEvent {
/**
* The currently resolved keystroke string. If your function returns a falsy
* value, this is how Atom will resolve your keystroke.
*/
keystroke: string;
/**
* The raw DOM 3 `KeyboardEvent` being resolved. See the DOM API documentation
* for more details.
*/
event: KeyboardEvent;
/** The OS-specific name of the current keyboard layout. */
layoutName: string;
/**
* An object mapping DOM 3 `KeyboardEvent.code` values to objects with the
* typed character for that key in each modifier state, based on the current
* operating system layout.
*/
keymap: object;
}
export interface BufferChangingEvent {
/** Range of the old text. */
oldRange: Range;
}
export interface BufferChangedEvent {
/**
* An array of objects summarizing the aggregated changes that occurred
* during the transaction.
*/
changes: Array<{
/**
* The Range of the deleted text in the contents of the buffer as it existed
* before the batch of changes reported by this event.
*/
oldRange: Range;
/** The Range of the inserted text in the current contents of the buffer. */
newRange: Range;
}>;
/** Range of the old text. */
oldRange: Range;
/** Range of the new text. */
newRange: Range;
/** String containing the text that was replaced. */
oldText: string;
/** String containing the text that was inserted. */
newText: string;
}
export interface BufferStoppedChangingEvent {
changes: TextChange[];
}
/**
* This custom subclass of CustomEvent exists to provide the ::abortKeyBinding
* method, as well as versions of the ::stopPropagation methods that record the
* intent to stop propagation so event bubbling can be properly simulated for
* detached elements.
*/
export interface CommandEvent<CurrentTarget extends EventTarget = EventTarget> extends CustomEvent {
keyBindingAborted: boolean;
propagationStopped: boolean;
abortKeyBinding(): void;
stopPropagation(): CustomEvent;
stopImmediatePropagation(): CustomEvent;
currentTarget: CurrentTarget;
}
export interface CursorPositionChangedEvent {
oldBufferPosition: Point;
oldScreenPosition: Point;
newBufferPosition: Point;
newScreenPosition: Point;
textChanged: boolean;
cursor: Cursor;
}
export interface DecorationPropsChangedEvent {
/** Object the old parameters the decoration used to have. */
oldProperties: DecorationOptions;
/** Object the new parameters the decoration now has */
newProperties: DecorationOptions;
}
export interface DisplayMarkerChangedEvent {
/** Point representing the former head buffer position. */
oldHeadBufferPosition: Point;
/** Point representing the new head buffer position. */
newHeadBufferPosition: Point;
// Point representing the former tail buffer position. */
oldTailBufferPosition: Point;
/** Point representing the new tail buffer position. */
newTailBufferPosition: Point;
/** Point representing the former head screen position. */
oldHeadScreenPosition: Point;
/** Point representing the new head screen position. */
newHeadScreenPosition: Point;
/** Point representing the former tail screen position. */
oldTailScreenPosition: Point;
/** Point representing the new tail screen position. */
newTailScreenPosition: Point;
/** Boolean indicating whether the marker was valid before the change. */
wasValid: boolean;
/** Boolean indicating whether the marker is now valid. */
isValid: boolean;
/** Boolean indicating whether the marker had a tail before the change. */
hadTail: boolean;
/** Boolean indicating whether the marker now has a tail */
hasTail: boolean;
/**
* -DEPRECATED- Object containing the marker's custom properties before the change.
* @deprecated
*/
oldProperties: object;
/**
* -DEPRECATED- Object containing the marker's custom properties after the change.
* @deprecated
*/
newProperties: object;
/**
* Boolean indicating whether this change was caused by a textual change to the
* buffer or whether the marker was manipulated directly via its public API.
*/
textChanged: boolean;
}
export interface EditorChangedEvent {
/** A Point representing where the change started. */
start: Point;
/** A Point representing the replaced extent. */
oldExtent: Point;
/** A Point representing the replacement extent. */
newExtent: Point;
}
export interface ExceptionThrownEvent {
originalError: Error;
message: string;
url: string;
line: number;
column: number;
}
export interface FailedKeybindingMatchEvent {
/** The string of keystrokes that failed to match the binding. */
keystrokes: string;
/** The DOM element that was the target of the most recent keyboard event. */
keyboardEventTarget: Element;
}
export interface FailedKeymapFileReadEvent {
/** The error message. */
message: string;
/** The error stack trace. */
stack: string;
}
export interface FileSavedEvent {
/** The path to which the buffer was saved. */
path: string;
}
export interface FilesystemChangeBasic<
Action extends "created"|"modified"|"deleted"|"renamed"
= "created"|"modified"|"deleted"
> {
/** A string describing the filesystem action that occurred. */
action: Action;
/** The absolute path to the filesystem entry that was acted upon. */
path: string;
}
export interface FilesystemChangeRename extends FilesystemChangeBasic<"renamed"> {
/**
* For rename events, a string containing the filesystem entry's former
* absolute path.
*/
oldPath: string;
}
export type FilesystemChange = FilesystemChangeBasic|FilesystemChangeRename;
export type FilesystemChangeEvent = FilesystemChange[];
export interface FullKeybindingMatchEvent {
/** The string of keystrokes that matched the binding. */
keystrokes: string;
/** The KeyBinding that the keystrokes matched. */
binding: KeyBinding;
/** The DOM element that was the target of the most recent keyboard event. */
keyboardEventTarget: Element;
}
export interface HandleableErrorEvent {
/** The error object. */
error: Error;
/**
* Call this function to indicate you have handled the error.
* The error will not be thrown if this function is called.
*/
handle(): void;
}
export interface KeymapLoadedEvent {
/** The path of the keymap file. */
path: string;
}
export interface MarkerChangedEvent {
/** Point representing the former head position. */
oldHeadPosition: Point;
/** Point representing the new head position. */
newHeadPosition: Point;
/** Point representing the former tail position. */
oldTailPosition: Point;
/** Point representing the new tail position. */
newTailPosition: Point;
/** Boolean indicating whether the marker was valid before the change. */
wasValid: boolean;
/** Boolean indicating whether the marker is now valid. */
isValid: boolean;
/** Boolean indicating whether the marker had a tail before the change. */
hadTail: boolean;
/** Boolean indicating whether the marker now has a tail. */
hasTail: boolean;
/**
* -DEPRECATED- Object containing the marker's custom properties before the change.
* @deprecated
*/
oldProperties: object;
/**
* -DEPRECATED- Object containing the marker's custom properties after the change.
* @deprecated
*/
newProperties: object;
/**
* Boolean indicating whether this change was caused by a textual
* change to the buffer or whether the marker was manipulated directly
* via its public API.
*/
textChanged: boolean;
}
export interface PaneItemObservedEvent {
item: object;
pane: Pane;
index: number;
}
export interface PaneListItemShiftedEvent {
/** The pane item that was added or removed. */
item: object;
/** A number indicating where the item is located. */
index: number;
}
export interface PaneItemMovedEvent {
/** The removed pane item. */
item: object;
/** A number indicating where the item was located. */
oldIndex: number;
/** A number indicating where the item is now located. */
newIndex: number;
}
export interface PaneItemOpenedEvent extends PaneItemObservedEvent {
uri: string;
}
export interface PartialKeybindingMatchEvent {
/** The string of keystrokes that matched the binding. */
keystrokes: string;
/** The KeyBindings that the keystrokes partially matched. */
partiallyMatchedBindings: KeyBinding[];
/** DOM element that was the target of the most recent keyboard event. */
keyboardEventTarget: Element;
}
export interface PathWatchErrorThrownEvent {
/** The error object. */
error: Error;
/**
* Call this function to indicate you have handled the error.
* The error will not be thrown if this function is called.
*/
handle(): void;
}
export interface PreventableExceptionThrownEvent extends ExceptionThrownEvent {
preventDefault(): void;
}
export interface RepoStatusChangedEvent {
path: string;
/**
* This value can be passed to ::isStatusModified or ::isStatusNew to get more
* information.
*/
pathStatus: number;
}
export interface SelectionChangedEvent {
oldBufferRange: Range;
oldScreenRange: Range;
newBufferRange: Range;
newScreenRange: Range;
selection: Selection;
}
export interface StyleElementObservedEvent extends HTMLStyleElement {
sourcePath: string;
context: string;
}
export interface TextEditorObservedEvent {
textEditor: TextEditor;
pane: Pane;
index: number;
}
// Extendables ================================================================
// Interfaces which can be augmented in order to provide additional type
// information under certain contexts.
// NOTE: the config schema with these defaults can be found here:
// https://github.com/atom/atom/blob/v1.36.0/src/config-schema.js
/**
* Allows you to strongly type Atom configuration variables. Additional key:value
* pairings merged into this interface will result in configuration values under
* the value of each key being templated by the type of the associated value.
*/
export interface ConfigValues {
/**
* List of glob patterns. Files and directories matching these patterns will be
* ignored by some packages, such as the fuzzy finder and tree view. Individual
* packages might have additional config settings for ignoring names.
*/
"core.ignoredNames": string[];
/**
* Files and directories ignored by the current project's VCS system will be ignored
* by some packages, such as the fuzzy finder and find and replace. For example,
* projects using Git have these paths defined in the .gitignore file. Individual
* packages might have additional config settings for ignoring VCS ignored files and
* folders.
*/
"core.excludeVcsIgnoredPaths": boolean;
/**
* Follow symbolic links when searching files and when opening files with the fuzzy
* finder.
*/
"core.followSymlinks": boolean;
/** List of names of installed packages which are not loaded at startup. */
"core.disabledPackages": string[];
/** List of names of installed packages which are not automatically updated. */
"core.versionPinnedPackages": string[];
/**
* Associates scope names (e.g. "source.coffee") with arrays of file extensions
* and file names (e.g. ["Cakefile", ".coffee2"]).
*/
"core.customFileTypes": {
[key: string]: string[];
};
/** Names of UI and syntax themes which will be used when Atom starts. */
"core.themes": string[];
/**
* Trigger the system's beep sound when certain actions cannot be executed or
* there are no results.
*/
"core.audioBeep": boolean;
/** Close corresponding editors when a file is deleted outside Atom. */
"core.closeDeletedFileTabs": boolean;
/** When the last tab of a pane is closed, remove that pane as well. */
"core.destroyEmptyPanes": boolean;
/**
* When a window with no open tabs or panes is given the 'Close Tab' command,
* close that window.
*/
"core.closeEmptyWindows": boolean;
/** Default character set encoding to use when reading and writing files. */
"core.fileEncoding": FileEncoding;
/**
* When checked opens an untitled editor when loading a blank environment (such as
* with 'File > New Window' or when "Restore Previous Windows On Start" is unchecked);
* otherwise, no editor is opened when loading a blank environment.
* This setting has no effect when restoring a previous state.
*/
"core.openEmptyEditorOnStart": boolean;
/**
* When selected 'no', a blank environment is loaded. When selected 'yes' and Atom
* is started from the icon or `atom` by itself from the command line, restores the
* last state of all Atom windows; otherwise a blank environment is loaded. When
* selected 'always', restores the last state of all Atom windows always, no matter
* how Atom is started.
*/
"core.restorePreviousWindowsOnStart": "no"|"yes"|"always";
/** How many recent projects to show in the Reopen Project menu. */
"core.reopenProjectMenuCount": number;
/** Automatically update Atom when a new release is available. */
"core.automaticallyUpdate": boolean;
/** Use detected proxy settings when calling the `apm` command-line tool. */
"core.useProxySettingsWhenCallingApm": boolean;
/**
* Allow items to be previewed without adding them to a pane permanently, such as
* when single clicking files in the tree view.
*/
"core.allowPendingPaneItems": boolean;
/**
* Allow usage statistics and exception reports to be sent to the Atom team to help
* improve the product.
*/
"core.telemetryConsent": "limited"|"no"|"undecided";
/** Warn before opening files larger than this number of megabytes. */
"core.warnOnLargeFileLimit": number;
/**
* Choose the underlying implementation used to watch for filesystem changes. Emulating
* changes will miss any events caused by applications other than Atom, but may help
* prevent crashes or freezes.
*/
"core.fileSystemWatcher": "native"|"experimental"|"poll"|"atom";
/** Experimental: Use the new Tree-sitter parsing system for supported languages. */
"core.useTreeSitterParsers": boolean;
/**
* Specify whether Atom should use the operating system's color profile (recommended)
* or an alternative color profile.
*/
"core.colorProfile": "default"|"srgb";
"editor.commentStart": string|null;
"editor.commentEnd": string|null;
"editor.increaseIndentPattern": string|null;
"editor.decreaseIndentPattern": string|null;
"editor.foldEndPattern": string|null;
/** The name of the font family used for editor text. */
"editor.fontFamily": string;
/** Height in pixels of editor text. */
"editor.fontSize": number;
/** Height of editor lines, as a multiplier of font size. */
"editor.lineHeight": string|number;
/** Show cursor while there is a selection. */
"editor.showCursorOnSelection": boolean;
/** Render placeholders for invisible characters, such as tabs, spaces and newlines. */
"editor.showInvisibles": boolean;
/** Show indentation indicators in the editor. */
"editor.showIndentGuide": boolean;
/** Show line numbers in the editor's gutter. */
"editor.showLineNumbers": boolean;
/** Skip over tab-length runs of leading whitespace when moving the cursor. */
"editor.atomicSoftTabs": boolean;
/** Automatically indent the cursor when inserting a newline. */
"editor.autoIndent": boolean;
/** Automatically indent pasted text based on the indentation of the previous line. */
"editor.autoIndentOnPaste": boolean;
/** A string of non-word characters to define word boundaries. */
"editor.nonWordCharacters": string;
/**
* Identifies the length of a line which is used when wrapping text with the
* `Soft Wrap At Preferred Line Length` setting enabled, in number of characters.
*/
"editor.preferredLineLength": number;
/**
* Defines the maximum width of the editor window before soft wrapping is enforced,
* in number of characters.
*/
"editor.maxScreenLineLength": number;
/** Number of spaces used to represent a tab. */
"editor.tabLength": number;
/**
* Wraps lines that exceed the width of the window. When `Soft Wrap At Preferred
* Line Length` is set, it will wrap to the number of characters defined by the
* `Preferred Line Length` setting.
*/
"editor.softWrap": boolean;
/**
* If the `Tab Type` config setting is set to "auto" and autodetection of tab type
* from buffer content fails, then this config setting determines whether a soft tab
* or a hard tab will be inserted when the Tab key is pressed.
*/
"editor.softTabs": boolean;
/**
* Determine character inserted when Tab key is pressed. Possible values: "auto",
* "soft" and "hard". When set to "soft" or "hard", soft tabs (spaces) or hard tabs
* (tab characters) are used. When set to "auto", the editor auto-detects the tab
* type based on the contents of the buffer (it uses the first leading whitespace
* on a non-comment line), or uses the value of the Soft Tabs config setting if
* auto-detection fails.
*/
"editor.tabType": "auto"|"soft"|"hard";
/**
* Instead of wrapping lines to the window's width, wrap lines to the number of
* characters defined by the `Preferred Line Length` setting. This will only take
* effect when the soft wrap config setting is enabled globally or for the current
* language.
* **Note:** If you want to hide the wrap guide (the vertical line) you can disable
* the `wrap-guide` package.
*/
"editor.softWrapAtPreferredLineLength": boolean;
/**
* When soft wrap is enabled, defines length of additional indentation applied to
* wrapped lines, in number of characters.
*/
"editor.softWrapHangingIndent": number;
/** Determines how fast the editor scrolls when using a mouse or trackpad. */
"editor.scrollSensitivity": number;
/** Allow the editor to be scrolled past the end of the last line. */
"editor.scrollPastEnd": boolean;
/**
* Time interval in milliseconds within which text editing operations will be
* grouped together in the undo history.
*/
"editor.undoGroupingInterval": number;
/**
* Show confirmation dialog when checking out the HEAD revision and discarding
* changes to current file since last commit.
*/
"editor.confirmCheckoutHeadRevision": boolean;
/**
* A hash of characters Atom will use to render whitespace characters. Keys are
* whitespace character types, values are rendered characters (use value false to
* turn off individual whitespace character types).
*/
"editor.invisibles": Invisibles;
/**
* Change the editor font size when pressing the Ctrl key and scrolling the mouse
* up/down.
*/
"editor.zoomFontWhenCtrlScrolling": boolean;
// tslint:disable-next-line:no-any
[key: string]: any;
}
// Options ====================================================================
// The option objects that the user is expected to fill out and provide to
// specific API call.
export interface BufferLoadOptions {
/** The file's encoding. */
encoding?: string;
/**
* A function that returns a boolean indicating whether the buffer should
* be destroyed if its file is deleted.
*/
shouldDestroyOnFileDelete?(): boolean;
}
export interface BuildEnvironmentOptions {
/**
* An object responsible for Atom's interaction with the browser process and host OS.
* Use buildDefaultApplicationDelegate for a default instance.
*/
applicationDelegate?: object;
/** A window global. */
window?: Window;
/** A document global. */
document?: Document;
/** A path to the configuration directory (usually ~/.atom). */
configDirPath?: string;
/**
* A boolean indicating whether the Atom environment should save or load state
* from the file system. You probably want this to be false.
*/
enablePersistence?: boolean;
}
export interface ConfirmationOptions {
/** The type of the confirmation prompt. */
type?: "none"|"info"|"error"|"question"|"warning";
/** The text for the buttons. */
buttons?: ReadonlyArray<string>;
/** The index for the button to be selected by default in the prompt. */
defaultId?: number;
/** The title for the prompt. */
title?: string;
/** The content of the message box. */
message?: string;
/** Additional information regarding the message. */
detail?: string;
/** If provided, the message box will include a checkbox with the given label. */
checkboxLabel?: string;
/** Initial checked state of the checkbox. false by default. */
checkboxChecked?: boolean;
/** An Electron NativeImage to use as the prompt's icon. */
icon?: object;
/**
* The index of the button to be used to cancel the dialog, via the `Esc` key.
* By default this is assigned to the first button with "cancel" or "no" as the
* label. If no such labeled buttons exist and this option is not set, 0 will be
* used as the return value or callback response.
*
* This option is ignored on Windows.
*/
cancelId?: number;
/**
* On Windows, Electron will try to figure out which one of the buttons are
* common buttons (like `Cancel` or `Yes`), and show the others as command links
* in the dialog. This can make the dialog appear in the style of modern Windows
* apps. If you don't like this behavior, you can set noLink to true.
*/
noLink?: boolean;
/**
* Normalize the keyboard access keys across platforms.
* Atom defaults this to true.
*/
normalizeAccessKeys?: boolean;
}
export interface ContextMenuItemOptions {
/** The menu item's label. */
label?: string;
/**
* The command to invoke on the target of the right click that invoked the
* context menu.
*/
command?: string;
/**
* Whether the menu item should be clickable. Disabled menu items typically
* appear grayed out. Defaults to true.
*/
enabled?: boolean;
/** An array of additional items. */
submenu?: ReadonlyArray<ContextMenuOptions>;
/** Whether the menu item should appear in the menu. Defaults to true. */
visible?: boolean;
/**
* A function that is called on the item each time a context menu is created
* via a right click.
*/
created?(event: Event): void;
/**
* A function that is called to determine whether to display this item on a
* given context menu deployment.
*/
shouldDisplay?(event: Event): void;
/** Place this menu item before the menu items representing the given commands. */
before?: ReadonlyArray<string>;
/** Place this menu item after the menu items representing the given commands. */
after?: ReadonlyArray<string>;
/**
* Place this menu item's group before the containing group of the menu items
* representing the given commands.
*/
beforeGroupContaining?: ReadonlyArray<string>;
/**
* Place this menu item's group after the containing group of the menu items
* representing the given commands.
*/
afterGroupContaining?: ReadonlyArray<string>;
}
export type ContextMenuOptions = ContextMenuItemOptions | { type: "separator" };
export interface CopyMarkerOptions {
/** Whether or not the marker should be tailed. */
tailed?: boolean;
/** Creates the marker in a reversed orientation. */
reversed?: boolean;
/** Determines the rules by which changes to the buffer invalidate the marker. */
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch";
/**
* Indicates whether insertions at the start or end of the marked range should
* be interpreted as happening outside the marker.
*/
exclusive?: boolean;
/** -DEPRECATED- Custom properties to be associated with the marker. */
properties?: object;
}
export interface DecorationLayerOptions extends SharedDecorationOptions {
/** One of several supported decoration types. */
type?: "line"|"line-number"|"text"|"highlight"|"block"|"cursor";
}
export interface DecorationOptions extends SharedDecorationOptions {
/** One of several supported decoration types. */
type?: "line"|"line-number"|"text"|"highlight"|"overlay"|"gutter"|"block"|"cursor";
/** The name of the gutter we're decorating, if type is "gutter". */
gutterName?: string;
}
export interface ErrorNotificationOptions extends NotificationOptions {
stack?: string;
}
export interface FindDisplayMarkerOptions {
/** Only include markers starting at this Point in buffer coordinates. */
startBufferPosition?: PointCompatible;
/** Only include markers ending at this Point in buffer coordinates. */
endBufferPosition?: PointCompatible;
/** Only include markers starting at this Point in screen coordinates. */
startScreenPosition?: PointCompatible;
/** Only include markers ending at this Point in screen coordinates. */
endScreenPosition?: PointCompatible;
/** Only include markers starting inside this Range in buffer coordinates. */
startsInBufferRange?: RangeCompatible;
/** Only include markers ending inside this Range in buffer coordinates. */
endsInBufferRange?: RangeCompatible;
/** Only include markers starting inside this Range in screen coordinates. */
startsInScreenRange?: RangeCompatible;
/** Only include markers ending inside this Range in screen coordinates. */
endsInScreenRange?: RangeCompatible;
/** Only include markers starting at this row in buffer coordinates. */
startBufferRow?: number;
/** Only include markers ending at this row in buffer coordinates. */
endBufferRow?: number;
/** Only include markers starting at this row in screen coordinates. */
startScreenRow?: number;
/** Only include markers ending at this row in screen coordinates. */
endScreenRow?: number;
/**
* Only include markers intersecting this Array of [startRow, endRow] in
* buffer coordinates.
*/
intersectsBufferRowRange?: [number, number];
/**
* Only include markers intersecting this Array of [startRow, endRow] in
* screen coordinates.
*/
intersectsScreenRowRange?: [number, number];
/** Only include markers containing this Range in buffer coordinates. */
containsBufferRange?: RangeCompatible;
/** Only include markers containing this Point in buffer coordinates. */
containsBufferPosition?: PointCompatible;
/** Only include markers contained in this Range in buffer coordinates. */
containedInBufferRange?: RangeCompatible;
/** Only include markers contained in this Range in screen coordinates. */
containedInScreenRange?: RangeCompatible;
/** Only include markers intersecting this Range in buffer coordinates. */
intersectsBufferRange?: RangeCompatible;
/** Only include markers intersecting this Range in screen coordinates. */
intersectsScreenRange?: RangeCompatible;
}
export interface FindMarkerOptions {
/** Only include markers that start at the given Point. */
startPosition?: PointCompatible;
/** Only include markers that end at the given Point. */
endPosition?: PointCompatible;
/** Only include markers that start inside the given Range. */
startsInRange?: RangeCompatible;
/** Only include markers that end inside the given Range. */
endsInRange?: RangeCompatible;
/** Only include markers that contain the given Point, inclusive. */
containsPoint?: PointCompatible;
/** Only include markers that contain the given Range, inclusive. */
containsRange?: RangeCompatible;
/** Only include markers that start at the given row number. */
startRow?: number;
/** Only include markers that end at the given row number. */
endRow?: number;
/** Only include markers that intersect the given row number. */
intersectsRow?: number;
}
export interface HistoryTransactionOptions {
/** When provided, skip taking snapshot for other selections markerLayers except given one. */
selectionsMarkerLayer?: MarkerLayer;
}
export interface HistoryTraversalOptions {
/** Restore snapshot of selections marker layer to given selectionsMarkerLayer. */
selectionsMarkerLayer?: MarkerLayer;
}
export interface MenuOptions {
/** The menu itme's label. */
label: string;
/** An array of sub menus. */
submenu?: ReadonlyArray<MenuOptions>;
/** The command to trigger when the item is clicked. */
command?: string;
}
export interface NodeProcessOptions {
/** The command to execute. */
command: string;
/** The array of arguments to pass to the command. */
args?: ReadonlyArray<string>;
/** The options object to pass to Node's ChildProcess.spawn method. */
options?: SpawnProcessOptions;
/**
* The callback that receives a single argument which contains the standard
* output from the command.
*/
stdout?(data: string): void;
/**
* The callback that receives a single argument which contains the standard
* error output from the command.
*/
stderr?(data: string): void;
/** The callback which receives a single argument containing the exit status. */
exit?(code: number): void;
}
export interface NotificationOptions {
buttons?: Array<{
className?: string;
onDidClick?(event: MouseEvent): void;
text?: string;
}>;
description?: string;
detail?: string;
dismissable?: boolean;
icon?: string;
}
export interface ProcessOptions extends NodeProcessOptions {
/**
* Whether the command will automatically start when this BufferedProcess is
* created.
*/
autoStart?: boolean;
}
export interface ReadonlyEditOptions {
/** Whether the readonly protections on the text editor should be ignored. */
bypassReadOnly?: boolean;
}
export interface ScanContextOptions {
/** The number of lines before the matched line to include in the results object. */
leadingContextLineCount?: number;
/** The number of lines after the matched line to include in the results object. */
trailingContextLineCount?: number;
}
export interface SharedDecorationOptions {
/**
* This CSS class will be applied to the decorated line number, line, highlight,
* or overlay.
*/
class?: string;
/**
* An Object containing CSS style properties to apply to the relevant DOM
* node. Currently this only works with a type of cursor or text.
*/
style?: object;
/**
* An HTMLElement or a model Object with a corresponding view registered. Only
* applicable to the gutter, overlay and block types.
*/
item?: object;
/**
* If true, the decoration will only be applied to the head of the DisplayMarker.
* Only applicable to the line and line-number types.
*/
onlyHead?: boolean;
/**
* If true, the decoration will only be applied if the associated DisplayMarker
* is empty. Only applicable to the gutter, line, and line-number types.
*/
onlyEmpty?: boolean;
/**
* If true, the decoration will only be applied if the associated DisplayMarker
* is non-empty. Only applicable to the gutter, line, and line-number types.
*/
onlyNonEmpty?: boolean;
/**
* If false, the decoration will be applied to the last row of a non-empty
* range, even if it ends at column 0. Defaults to true. Only applicable
* to the gutter, line, and line-number decoration types.
*/
omitEmptyLastRow?: boolean;
/**
* Only applicable to decorations of type overlay and block. Controls where the
* view is positioned relative to the TextEditorMarker. Values can be
* 'head' (the default) or 'tail' for overlay decorations, and 'before' (the default)
* or 'after' for block decorations.
*/
position?: "head"|"tail"|"before"|"after";
/**
* Only applicable to decorations of type block. Controls where the view is
* positioned relative to other block decorations at the same screen row.
* If unspecified, block decorations render oldest to newest.
*/
order?: number;
/**
* Only applicable to decorations of type overlay. Determines whether the decoration
* adjusts its horizontal or vertical position to remain fully visible when it would
* otherwise overflow the editor. Defaults to true.
*/
avoidOverflow?: boolean;
}
export interface SpawnProcessOptions {
/** Current working directory of the child process. */
cwd?: string;
/** Environment key-value pairs. */
env?: { [key: string]: string };
/** The child's stdio configuration. */
stdio?: string|Array<string|number>;
/** Prepare child to run independently of its parent process. */
detached?: boolean;
/** Sets the user identity of the process. */
uid?: number;
/** Sets the group identity of the process. */
gid?: number;
/**
* If true, runs command inside of a shell. Uses "/bin/sh" on UNIX, and process.env.ComSpec
* on Windows. A different shell can be specified as a string.
*/
shell?: boolean | string;
}
export interface TextEditOptions {
/** If true, all line endings will be normalized to match the editor's current mode. */
normalizeLineEndings?: boolean;
/**
* If skip, skips the undo stack for this operation.
* @deprecated Call groupLastChanges() on the TextBuffer afterward instead.
*/
undo?: "skip";
}
export interface TextInsertionOptions extends TextEditOptions {
/** If true, selects the newly added text. */
select?: boolean;
/** If true, indents all inserted text appropriately. */
autoIndent?: boolean;
/** If true, indent newline appropriately. */
autoIndentNewline?: boolean;
/**
* If true, decreases indent level appropriately (for example, when a closing
* bracket is inserted).
*/
autoDecreaseIndent?: boolean;
/**
* By default, when pasting multiple lines, Atom attempts to preserve the relative
* indent level between the first line and trailing lines, even if the indent
* level of the first line has changed from the copied text. If this option is
* true, this behavior is suppressed.
*/
preserveTrailingLineIndentation?: boolean;
}
/** The options for a Bootstrap 3 Tooltip class, which Atom uses a variant of. */
export interface TooltipOptions {
/** Apply a CSS fade transition to the tooltip. */
animation?: boolean;
/** Appends the tooltip to a specific element. */
container?: string|HTMLElement|false;
/**
* Delay showing and hiding the tooltip (ms) - does not apply to manual
* trigger type.
*/
delay?: number|{ show: number, hide: number };
/** Allow HTML in the tooltip. */
html?: boolean;
/** How to position the tooltip. */
placement?: "top"|"bottom"|"left"|"right"|"auto";
/**
* If a selector is provided, tooltip objects will be delegated to the
* specified targets.
*/
selector?: string;
/** Base HTML to use when creating the tooltip. */
template?: string;
/**
* Default title value if title attribute isn't present.
* If a function is given, it will be called with its this reference set to
* the element that the tooltip is attached to.
*/
title?: string|HTMLElement|(() => string);
/**
* How tooltip is triggered - click | hover | focus | manual.
* You may pass multiple triggers; separate them with a space.
*/
trigger?: string;
}
export interface WorkspaceOpenOptions {
/** A number indicating which row to move the cursor to initially. Defaults to 0. */
initialLine?: number;
/** A number indicating which column to move the cursor to initially. Defaults to 0. */
initialColumn?: number;
/**
* Either 'left', 'right', 'up' or 'down'. If 'left', the item will be opened in
* leftmost pane of the current active pane's row. If 'right', the item will be
* opened in the rightmost pane of the current active pane's row. If only one pane
* exists in the row, a new pane will be created. If 'up', the item will be opened
* in topmost pane of the current active pane's column. If 'down', the item will be
* opened in the bottommost pane of the current active pane's column. If only one pane
* exists in the column, a new pane will be created.
*/
split?: "left"|"right"|"up"|"down";
/**
* A boolean indicating whether to call Pane::activate on containing pane.
* Defaults to true.
*/
activatePane?: boolean;
/**
* A boolean indicating whether to call Pane::activateItem on containing pane.
* Defaults to true.
*/
activateItem?: boolean;
/**
* A Boolean indicating whether or not the item should be opened in a pending state.
* Existing pending items in a pane are replaced with new pending items when they
* are opened.
*/
pending?: boolean;
/**
* A boolean. If true, the workspace will attempt to activate an existing item for
* the given URI on any pane. If false, only the active pane will be searched for
* an existing item for the same URI. Defaults to false.
*/
searchAllPanes?: boolean;
/**
* A String containing the name of the location in which this item should be opened.
* If omitted, Atom will fall back to the last location in which a user has placed
* an item with the same URI or, if this is a new URI, the default location specified
* by the item.
* NOTE: This option should almost always be omitted to honor user preference.
*/
location?: "left"|"right"|"bottom"|"center";
}
export interface WorkspaceScanOptions {
/** An array of glob patterns to search within. */
paths?: ReadonlyArray<string>;
/** A function to be periodically called with the number of paths searched. */
onPathsSearched?(pathsSearched: number): void;
/** The number of lines before the matched line to include in the results object. */
leadingContextLineCount?: number;
/** The number of lines after the matched line to include in the results object. */
trailingContextLineCount?: number;
}
// Interfaces =================================================================
// The requirements placed on object parameters for specific API calls.
export interface Deserializer {
name: string;
deserialize(state: object): object;
}
export interface DisposableLike {
dispose(): void;
}
export interface JQueryCompatible<Element extends Node = HTMLElement> extends Iterable<Element> {
jquery: string;
}
/** The types usable when constructing a point via the Point::fromObject method. */
export type PointCompatible = PointLike|[number, number];
/** The interface that should be implemented for all "point-compatible" objects. */
export interface PointLike {
/** A zero-indexed number representing the row of the Point. */
row: number;
/** A zero-indexed number representing the column of the Point. */
column: number;
}
/** The types usable when constructing a range via the Range::fromObject method. */
export type RangeCompatible =
| RangeLike
| [PointLike, PointLike]
| [PointLike, [number, number]]
| [[number, number], PointLike]
| [[number, number], [number, number]];
/** The interface that should be implemented for all "range-compatible" objects. */
export interface RangeLike {
/** A Point representing the start of the Range. */
start: PointLike;
/** A Point representing the end of the Range. */
end: PointLike;
}
/** An interface which all custom test runners should implement. */
export type TestRunner = (params: TestRunnerParams) => Promise<number>;
// Structures =================================================================
// The structures that are passed to the user by Atom following specific API calls.
export interface BufferScanResult {
buffer: TextBuffer;
lineText: string;
match: RegExpExecArray;
matchText: string;
range: Range;
replace(replacementText: string): void;
stop(): void;
stopped: boolean;
}
export interface CancellablePromise<T> extends Promise<T> {
cancel(): void;
}
export interface ContextualBufferScanResult extends BufferScanResult {
leadingContextLines: string[];
trailingContextLines: string[];
}
export type FileEncoding =
| "iso88596" // Arabic (ISO 8859-6)
| "windows1256" // Arabic (Windows 1256)
| "iso88594" // Baltic (ISO 8859-4)
| "windows1257" // Baltic (Windows 1257)
| "iso885914" // Celtic (ISO 8859-14)
| "iso88592" // Central European (ISO 8859-2)
| "windows1250" // Central European (Windows 1250)
| "gb18030" // Chinese (GB18030)
| "gbk" // Chinese (GBK)
| "cp950" // Traditional Chinese (Big5)
| "big5hkscs" // Traditional Chinese (Big5-HKSCS)
| "cp866" // Cyrillic (CP 866)
| "iso88595" // Cyrillic (ISO 8859-5)
| "koi8r" // Cyrillic (KOI8-R)
| "koi8u" // Cyrillic (KOI8-U)
| "windows1251" // Cyrillic (Windows 1251)
| "cp437" // DOS (CP 437)
| "cp850" // DOS (CP 850)
| "iso885913" // Estonian (ISO 8859-13)
| "iso88597" // Greek (ISO 8859-7)
| "windows1253" // Greek (Windows 1253)
| "iso88598" // Hebrew (ISO 8859-8)
| "windows1255" // Hebrew (Windows 1255)
| "cp932" // Japanese (CP 932)
| "eucjp" // Japanese (EUC-JP)
| "shiftjis" // Japanese (Shift JIS)
| "euckr" // Korean (EUC-KR)
| "iso885910" // Nordic (ISO 8859-10)
| "iso885916" // Romanian (ISO 8859-16)
| "iso88599" // Turkish (ISO 8859-9)
| "windows1254" // Turkish (Windows 1254)
| "utf8" // Unicode (UTF-8)
| "utf16le" // Unicode (UTF-16 LE)
| "utf16be" // Unicode (UTF-16 BE)
| "windows1258" // Vietnamese (Windows 1258)
| "iso88591" // Western (ISO 8859-1)
| "iso88593" // Western (ISO 8859-3)
| "iso885915" // Western (ISO 8859-15)
| "macroman" // Western (Mac Roman)
| "windows1252"; // Western (Windows 1252)
export interface GrammarRule {
// https://github.com/atom/first-mate/blob/v7.0.7/src/rule.coffee
// This is private. Don't go down the rabbit hole.
rule: object;
scopeName: string;
contentScopeName: string;
}
export interface GrammarToken {
value: string;
scopes: string[];
}
export interface Invisibles {
/**
* Character used to render newline characters (\n) when the `Show Invisibles`
* setting is enabled.
*/
eol?: boolean|string;
/**
* Character used to render leading and trailing space characters when the
* `Show Invisibles` setting is enabled.
*/
space?: boolean|string;
/**
* Character used to render hard tab characters (\t) when the `Show Invisibles`
* setting is enabled.
*/
tab?: boolean|string;
/**
* Character used to render carriage return characters (for Microsoft-style line
* endings) when the `Show Invisibles` setting is enabled.
*/
cr?: boolean|string;
}
export interface KeyBinding {
// Properties
enabled: boolean;
source: string;
command: string;
keystrokes: string;
keystrokeArray: string[];
keystrokeCount: number;
selector: string;
specificity: number;
// Comparison
/** Determines whether the given keystroke matches any contained within this binding. */
matches(keystroke: string): boolean;
/**
* Compare another KeyBinding to this instance.
* Returns <= -1 if the argument is considered lesser or of lower priority.
* Returns 0 if this binding is equivalent to the argument.
* Returns >= 1 if the argument is considered greater or of higher priority.
*/
compare(other: KeyBinding): number;
}
export interface ProjectHistory {
paths: string[];
lastOpened: Date;
}
export interface ProjectSpecification {
paths: string[];
originPath: string;
config?: ConfigValues;
}
export interface ScandalResult {
filePath: string;
matches: Array<{
matchText: string;
lineText: string;
lineTextOffset: number;
range: [[number, number], [number, number]];
leadingContextLines: string[];
trailingContextLines: string[];
}>;
}
export interface TestRunnerParams {
/** An array of paths to tests to run. Could be paths to files or directories. */
testPaths: string[];
/**
* A function that can be called to construct an instance of the atom global.
* No atom global will be explicitly assigned, but you can assign one in your
* runner if desired.
*/
buildAtomEnvironment(options: BuildEnvironmentOptions): AtomEnvironment;
/**
* A function that builds a default instance of the application delegate, suitable
* to be passed as the applicationDelegate parameter to buildAtomEnvironment.
*/
buildDefaultApplicationDelegate(): object;
/** An optional path to a log file to which test output should be logged. */
logFile: string;
/**
* A boolean indicating whether or not the tests are being run from the command
* line via atom --test.
*/
headless: boolean;
}
export interface TextChange {
newExtent: Point;
oldExtent: Point;
newRange: Range;
oldRange: Range;
newText: string;
oldText: string;
start: Point;
}
/** Result returned by `Grammar.tokenizeLine`. */
export interface TokenizeLineResult {
/** The string of text that was tokenized. */
line: string;
/**
* An array of integer scope ids and strings. Positive ids indicate the
* beginning of a scope, and negative tags indicate the end. To resolve ids
* to scope names, call GrammarRegistry::scopeForId with the absolute
* value of the id.
*/
tags: Array<number|string>;
/**
* This is a dynamic property. Invoking it will incur additional overhead,
* but will automatically translate the `tags` into token objects with `value`
* and `scopes` properties.
*/
tokens: GrammarToken[];
/**
* An array of rules representing the tokenized state at the end of the line.
* These should be passed back into this method when tokenizing the next line
* in the file.
*/
ruleStack: GrammarRule[];
}
/**
* This tooltip class is derived from Bootstrap 3, but modified to not require
* jQuery, which is an expensive dependency we want to eliminate.
*/
export interface Tooltip {
readonly options: TooltipOptions;
readonly enabled: boolean;
readonly timeout: number;
readonly hoverState: "in"|"out"|null;
readonly element: HTMLElement;
getTitle(): string;
getTooltipElement(): HTMLElement;
getArrowElement(): HTMLElement;
enable(): void;
disable(): void;
toggleEnabled(): void;
toggle(): void;
recalculatePosition(): void;
}
export interface ViewModel {
getTitle: () => string;
}
export interface WindowLoadSettings {
readonly appVersion: string;
readonly atomHome: string;
readonly devMode: boolean;
readonly resourcePath: string;
readonly safeMode: boolean;
readonly env?: { [key: string]: string|undefined };
readonly profileStartup?: boolean;
}
| borisyankov/DefinitelyTyped | types/atom/index.d.ts | TypeScript | mit | 251,344 | [
30522,
1013,
1013,
2828,
15182,
2005,
2512,
1011,
27937,
2213,
7427,
13787,
1015,
1012,
4029,
1013,
1013,
2622,
1024,
16770,
1024,
1013,
1013,
21025,
2705,
12083,
30524,
1013,
13787,
1013,
1013,
15182,
2011,
1024,
8904,
2278,
10258,
1026,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
""" Loads hyperspy as a regular python library, creates a spectrum with random numbers and plots it to a file"""
import hyperspy.api as hs
import numpy as np
import matplotlib.pyplot as plt
s = hs.signals.Spectrum(np.random.rand(1024))
s.plot()
plt.savefig("testSpectrum.png")
| to266/hyperspy | examples/hyperspy_as_library/minimal_example.py | Python | gpl-3.0 | 280 | [
30522,
1000,
1000,
1000,
15665,
23760,
13102,
2100,
2004,
1037,
3180,
18750,
3075,
1010,
9005,
1037,
8674,
2007,
6721,
3616,
1998,
14811,
2009,
2000,
1037,
5371,
1000,
1000,
1000,
12324,
23760,
13102,
2100,
1012,
17928,
2004,
26236,
12324,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<div id="ws_visible_users_dialog" title="Select Visible Users" class="hidden">
<div id="ws_user_selection_panels">
<div id="ws_user_selection_source_panel" class="ws_user_selection_panel">
<label for="ws_available_user_query" class="hidden">Search users</label>
<input type="text" name="ws_available_user_query" id="ws_available_user_query"
placeholder="Search and hit Enter to add a user">
<div class="ws_user_list_wrapper">
<table id="ws_available_users" class="widefat striped ws_user_selection_list" title="Add user"></table>
</div>
<div id="ws_loading_users_indicator" class="spinner"></div>
</div>
<div id="ws_user_selection_target_panel" class="ws_user_selection_panel">
<div id="ws_selected_users_caption">Selected users</div>
<div class="ws_user_list_wrapper" title="">
<table id="ws_selected_users" class="widefat ws_user_selection_list"></table>
</div>
</div>
</div>
<div class="ws_dialog_buttons">
<?php submit_button('Save Changes', 'primary', 'ws_ame_save_visible_users', false); ?>
<input type="button" class="button ws_close_dialog" value="Cancel">
</div>
</div> | liemdotv/loan | wp-content/plugins/admin-menu-editor-pro/extras/modules/visible-users/visible-users-template.php | PHP | gpl-2.0 | 1,145 | [
30522,
1026,
4487,
2615,
8909,
1027,
1000,
1059,
2015,
1035,
5710,
1035,
5198,
1035,
13764,
8649,
1000,
2516,
1027,
1000,
7276,
5710,
5198,
1000,
2465,
1027,
1000,
5023,
1000,
1028,
1026,
4487,
2615,
8909,
1027,
1000,
1059,
2015,
1035,
53... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/*
Template Name: Signin Template
*/
?>
<?php get_header(); ?>
<div class="container">
<div id="content" class="clearfix row">
<div id="main" class="col-md-12 clearfix" role="main">
<?php if ( function_exists('custom_breadcrumb') ) { custom_breadcrumb(); } ?>
<section class="page-content entry-content clearfix" itemprop="articleBody">
<div class="formheight">
<form class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</section>
</div>
</div>
</div>
<?php get_footer(); ?>
| jreid423/wp-starter-theme | wp-content/themes/brew-master/signup.php | PHP | gpl-2.0 | 1,139 | [
30522,
1026,
1029,
25718,
1013,
1008,
23561,
2171,
1024,
3696,
2378,
23561,
1008,
1013,
1029,
1028,
1026,
1029,
25718,
2131,
1035,
20346,
1006,
1007,
1025,
1029,
1028,
1026,
4487,
2615,
2465,
1027,
1000,
11661,
1000,
1028,
1026,
4487,
2615,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env python
"""
@author: Tobias
"""
"""@brief List of register classes"""
_registerClasses = [
['al', 'ah', 'ax', 'eax', 'rax'],
['bl', 'bh', 'bx', 'ebx', 'rbx'],
['cl', 'ch', 'cx', 'ecx', 'rcx'],
['dl', 'dh', 'dx', 'edx', 'rdx'],
['bpl', 'bp', 'ebp', 'rbp'],
['dil', 'di', 'edi', 'rdi'],
['sil', 'si', 'esi', 'rsi'],
['spl', 'sp', 'esp', 'rsp'],
['r8l', 'r8w', 'r8d', 'r8'],
['r9l', 'r9w', 'r9d', 'r9'],
['r10l', 'r10w', 'r10d', 'r10'],
['r11l', 'r11w', 'r11d', 'r11'],
['r12l', 'r12w', 'r12d', 'r12'],
['r13l', 'r13w', 'r13d', 'r13'],
['r14l', 'r14w', 'r14d', 'r14'],
['r15l', 'r15w', 'r15d', 'r15']
]
def get_reg_class(reg):
"""
@brief Determines the register class of a given reg.
All different register names that address the same register
belong to the same register class e.g.: 'ax' and 'eax'
@param reg name of register
@return register class
"""
lreg = reg.lower()
ret_value = None
for pos, reg_list in enumerate(_registerClasses):
for reg in reg_list:
found = False
if reg == lreg:
found = True
ret_value = pos
break
if found:
break
return ret_value
def get_reg_by_size(reg_class, reg_size):
"""
@brief Determines the register by its size and class
@param reg_class The register class of the register
@param reg_size The size of the register
@return Name of the register
"""
if reg_class >= len(_registerClasses):
return None
num_regs = len(_registerClasses[reg_class])
if num_regs < 4:
return None
reg_index = -1
if reg_size > 32: # 64-bit regs
reg_index = num_regs - 1
elif reg_size > 16: # 32-bit regs
reg_index = num_regs - 2
elif reg_size > 8: # 16-bit regs
reg_index = num_regs - 3
elif reg_size > 0: # 8-bit regs
reg_index = 0
else:
return None
return _registerClasses[reg_class][reg_index]
def get_size_by_reg(reg):
"""
@brief Determines the size of the given register
@param reg Register
@return Size of register
"""
reg_class = get_reg_class(reg)
num_regs = len(_registerClasses[reg_class])
for index, test_reg in enumerate(_registerClasses[reg_class]):
if test_reg == reg:
break
else: # no break
return None
if index == (num_regs-1):
return 64
elif index == (num_regs-2):
return 32
elif index == (num_regs-3):
return 16
else:
return 8
def get_reg_class_lst(reg_class):
"""
@return Returns the whole list of a given register class
"""
return _registerClasses[reg_class]
| anatolikalysch/VMAttack | lib/Register.py | Python | mit | 2,772 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
18750,
1000,
1000,
1000,
1030,
3166,
1024,
16858,
1000,
1000,
1000,
1000,
1000,
1000,
1030,
4766,
2862,
1997,
4236,
4280,
1000,
1000,
1000,
1035,
4236,
26266,
2229,
1027,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
@interface _MSRulerData : MSModelObject
{
long long _base; // 8 = 0x8
MSArray *_guides; // 16 = 0x10
}
@property(copy, nonatomic) MSArray *guides; // @synthesize guides=_guides;
@property(nonatomic) long long base; // @synthesize base=_base;
- (void).cxx_destruct;
- (BOOL)isEqualForSync:(id)arg1;
- (void)syncPropertiesMatchingReference:(id)arg1 withObject:(id)arg2;
- (void)copyPropertiesToObjectCopy:(id)arg1;
- (void)setAsParentOnChildren;
- (void)decodePropertiesWithCoder:(id)arg1;
- (void)encodePropertiesWithCoder:(id)arg1;
- (void)fillInEmptyObjects;
- (BOOL)hasDefaultValues;
- (void)initEmptyObject;
- (void)setPrimitiveGuides:(id)arg1;
- (id)primitiveGuides;
- (void)setPrimitiveBase:(long long)arg1;
- (long long)primitiveBase;
- (void)enumerateChildProperties:(CDUnknownBlockType)arg1;
- (void)enumerateProperties:(CDUnknownBlockType)arg1;
@end
| dameleon/sketch-layout-generator | data/sketch_classes/_MSRulerData.h | C | mit | 859 | [
30522,
1030,
8278,
1035,
5796,
6820,
3917,
2850,
2696,
1024,
30524,
1013,
2385,
1027,
1014,
2595,
10790,
1065,
1030,
3200,
1006,
6100,
1010,
2512,
10610,
7712,
1007,
5796,
2906,
9447,
1008,
12468,
1025,
1013,
1013,
1030,
24203,
2229,
4697,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Sparse Arrays
Internally the V8 engine can represent `Array`s following one of two approaches:
- **Fast Elements**: linear storage for compact keys sets.
- **Dictionary Elements**: hash table storage (more expensive to access on runtime).
If you want V8 to represent your `Array` in the `Fast Elements` form, you need to take into account the following:
- Use contiguous keys starting at `0`.
- Don't pre-allocate large `Array` (e.g. *> 64K* elements) that you don't use.
- Don't delete elements, specially in numeric `Array`s.
- Don't load uninitialized or deleted elements.
Another consideration: any name used as property name that is not a `String` will be serialized, read more at [Properties Names](v8-tips/properties-names).
| Kikobeats/js-mythbusters | docs/v8-tips/sparse-arrays.md | Markdown | mit | 739 | [
30522,
1001,
20288,
27448,
16058,
1996,
15754,
3194,
2064,
5050,
1036,
9140,
1036,
1055,
2206,
2028,
1997,
2048,
8107,
1024,
1011,
1008,
1008,
3435,
3787,
1008,
1008,
1024,
7399,
5527,
2005,
9233,
6309,
4520,
1012,
1011,
1008,
1008,
9206,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Reflection;
namespace Light.DataCore
{
static class DataMapperConfiguration
{
static object locker = new object();
static string DirectoryPath;
static List<string> FileNames = new List<string>();
static bool Initialed;
static Dictionary<Type, DataTableMapperSetting> SettingDict;
static List<IConfigurationRoot> Configurations = new List<IConfigurationRoot>();
public static void SetDirectoryPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentNullException(nameof(path));
DirectoryPath = path;
}
public static void SetFileName(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
FileNames.Add(name);
}
static void Initial()
{
if (FileNames.Count == 0) {
FileNames.Add("lightdata.json");
}
foreach (string fileName in FileNames) {
var builder = new ConfigurationBuilder();
if (DirectoryPath != null) {
builder.SetBasePath(DirectoryPath);
}
else {
builder.SetBasePath(Directory.GetCurrentDirectory());
}
builder.AddJsonFile(fileName, true);
var configuration = builder.Build();
Configurations.Add(configuration);
}
LoadData();
Initialed = true;
}
static void LoadData()
{
var settings = new Dictionary<Type, DataTableMapperSetting>();
foreach (IConfigurationRoot configuration in Configurations) {
IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.Configure<LightMapperOptions>(configuration.GetSection("lightMapper"));
var options = services.BuildServiceProvider().GetService<IOptions<LightMapperOptions>>().Value;
if (options.DataTypes != null && options.DataTypes.Length > 0) {
int typeIndex = 0;
foreach (DataTypeSection typeConfig in options.DataTypes) {
typeIndex++;
var typeName = typeConfig.Type;
if (typeName == null) {
throw new LightDataException(string.Format(SR.ConfigDataTypeNameIsNull, typeIndex));
}
var dataType = Type.GetType(typeName, true);
var dataTableMap = new DataTableMapperConfig(dataType);
var setting = new DataTableMapperSetting(dataTableMap);
dataTableMap.TableName = typeConfig.TableName;
dataTableMap.IsEntityTable = typeConfig.IsEntityTable;
var configParam = new ConfigParamSet();
var paramConfigs = typeConfig.ConfigParams;
if (paramConfigs != null && paramConfigs.Length > 0) {
foreach (ConfigParamSection paramConfig in paramConfigs) {
configParam.SetParamValue(paramConfig.Name, paramConfig.Value);
}
}
dataTableMap.ConfigParams = configParam;
var dataFieldConfigs = typeConfig.DataFields;
if (dataFieldConfigs != null && dataFieldConfigs.Length > 0) {
int fieldIndex = 0;
foreach (var fieldConfig in dataFieldConfigs) {
fieldIndex++;
var fieldName = fieldConfig.FieldName;
if (fieldName == null) {
throw new LightDataException(string.Format(SR.ConfigDataFieldNameIsNull, typeName, fieldIndex));
}
var property = dataType.GetProperty(fieldName);
if (property == null) {
throw new LightDataException(string.Format(SR.ConfigDataFieldIsNotExists, typeName, fieldName));
}
var dataFieldMap = new DataFieldMapperConfig(fieldName);
dataFieldMap.Name = fieldConfig.Name;
dataFieldMap.IsPrimaryKey = fieldConfig.IsPrimaryKey;
dataFieldMap.IsIdentity = fieldConfig.IsIdentity;
dataFieldMap.DbType = fieldConfig.DbType;
dataFieldMap.DataOrder = fieldConfig.DataOrder;
dataFieldMap.IsNullable = fieldConfig.IsNullable;
var defaultValue = fieldConfig.DefaultValue;
if (!string.IsNullOrEmpty(defaultValue)) {
Type type = property.PropertyType;
TypeInfo info = type.GetTypeInfo();
if (info.IsGenericType) {
Type frameType = type.GetGenericTypeDefinition();
if (frameType.FullName == "System.Nullable`1") {
Type[] arguments = type.GetGenericArguments();
type = arguments[0];
}
}
object valueObj;
if (type == typeof(string)) {
valueObj = defaultValue;
}
else if (info.IsEnum) {
try {
valueObj = Enum.Parse(type, defaultValue, true);
}
catch (Exception ex) {
throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
}
}
else {
if (type == typeof(DateTime)) {
if (DateTime.TryParse(defaultValue, out DateTime dt)) {
valueObj = dt;
}
else {
try {
valueObj = Enum.Parse(typeof(DefaultTime), defaultValue, true);
}
catch (Exception ex) {
throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
}
}
}
else {
try {
valueObj = Convert.ChangeType(defaultValue, type);
}
catch (Exception ex) {
throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
}
}
}
dataFieldMap.DefaultValue = valueObj;
}
setting.AddDataFieldMapConfig(fieldName, dataFieldMap);
}
}
var relationFieldConfigs = typeConfig.RelationFields;
if (relationFieldConfigs != null && relationFieldConfigs.Length > 0) {
int fieldIndex = 0;
foreach (var fieldConfig in relationFieldConfigs) {
fieldIndex++;
if (fieldConfig.RelationPairs != null && fieldConfig.RelationPairs.Length > 0) {
var fieldName = fieldConfig.FieldName;
if (fieldName == null) {
throw new LightDataException(string.Format(SR.ConfigDataFieldNameIsNull, typeName, fieldIndex));
}
var property = dataType.GetProperty(fieldName);
if (property == null) {
throw new LightDataException(string.Format(SR.ConfigDataFieldIsNotExists, typeName, fieldName));
}
var dataFieldMap = new RelationFieldMapConfig(fieldName);
foreach (var pair in fieldConfig.RelationPairs) {
dataFieldMap.AddRelationKeys(pair.MasterKey, pair.RelateKey);
}
setting.AddRelationFieldMapConfig(fieldName, dataFieldMap);
}
}
}
settings[dataType] = setting;
}
}
}
SettingDict = settings;
}
private static void CheckData()
{
if (!Initialed) {
lock (locker) {
if (!Initialed) {
Initial();
}
}
}
}
public static DataTableMapperSetting GetSetting(Type type)
{
CheckData();
SettingDict.TryGetValue(type, out DataTableMapperSetting setting);
return setting;
}
}
}
| aquilahkj/Light.DataCore | Light.DataCore/Config/DataMapperConfiguration.cs | C# | mit | 10,738 | [
30522,
2478,
2291,
1025,
2478,
2291,
1012,
22834,
1025,
2478,
2291,
1012,
6407,
1012,
12391,
1025,
2478,
7513,
1012,
14305,
1012,
9563,
1025,
2478,
7513,
1012,
14305,
1012,
24394,
2378,
20614,
3258,
1025,
2478,
7513,
1012,
14305,
1012,
7047... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using GenericTagHelperExample.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace GenericTagHelperExample.Data
{
public class GenericDbContext : DbContext
{
public DbSet<FormModel> FormModels { get; set; }
public DbSet<Customer> Customers { get; set; }
public GenericDbContext(DbContextOptions<GenericDbContext> options)
: base(options)
{
}
public GenericDbContext()
{
}
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured) return;
//Called by parameterless ctor Usually Migrations
var environmentName = Environment.GetEnvironmentVariable("Development") ?? "";
optionsBuilder.UseSqlServer(
new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", optional: false, reloadOnChange: false)
.Build()
.GetConnectionString("Default")
);
}
}
}
| HouseAlwaysWin/GenericTagHelper | GenericTagHelperExample/Data/GenericDbContext.cs | C# | mit | 1,296 | [
30522,
2478,
12391,
15900,
16001,
4842,
10288,
16613,
2571,
1012,
4275,
1025,
2478,
7513,
1012,
9178,
15643,
6198,
17345,
1025,
2478,
7513,
1012,
14305,
1012,
9563,
1025,
2478,
2291,
1025,
2478,
2291,
1012,
6407,
1012,
12391,
1025,
2478,
22... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
"""
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reason="POSIX-only tests (clock_gettime(3))",
)
needs_macos = pytest.mark.skipif(
platform.system() != "Darwin",
reason="macOS-only tests (mach_absolute_time(3))",
)
@pytest.fixture
def errno_value():
"""
A particular errno.
"""
return errno.EINVAL
@pytest.fixture
def strerror(errno_value):
"""
The string representation of a particular errno
"""
return "[Errno {}] Invalid argument".format(errno_value)
@pytest.fixture
def apply_failing_clock_call(monkeypatch):
"""
Return a callable that patches in a failing system call fake that
fails and return a list of calls to that fake.
"""
def _apply_failing_clock_call(name, errno_value):
calls = []
def _failing_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
monkeypatch.setattr(_api.ffi, "errno", errno.EINVAL)
return -1
monkeypatch.setattr(_api, name, _failing_clock_call)
return calls
return _apply_failing_clock_call
@pytest.fixture
def apply_timespec(monkeypatch):
"""
Return a callable that patches in a fake over the specified clock
call that sets the specified resolution and returns a list of
calls to that fake.
"""
def _apply_timespec(name, goal_timespec):
calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
assert namespace.x == 1
def test_repr(self):
"""
The instance's repr reflects its C{__dict__}
"""
namespace = _api._SimpleNamespace()
namespace.y = 2
assert repr(namespace) == "namespace(y=2)"
def test_eq(self):
"""
Two instances with equal C{__dict__}s are equal.
"""
assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1)
@needs_posix
class TestGetClockInfoPosix(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_failure(self, apply_failing_clock_call, errno_value, strerror):
"""
A failure in C{clock_getres} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_getres', errno_value)
with pytest.raises(OSError) as exc:
get_clock_info("monotonic")
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@given(
clock_getres_spec=st.fixed_dictionaries({
"tv_sec": st.sampled_from([0, 1]),
"tv_nsec": st.sampled_from([0, 1]),
}),
)
def test_info(self, clock_getres_spec, apply_timespec):
"""
The reported info always includes a nanosecond resolution when
C{clock_getres} indicates nanosecond resolution.
"""
calls = apply_timespec(
"_clock_getres",
_bindings.ffi.new("struct timespec *", clock_getres_spec),
)
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="clock_gettime(MONOTONIC)",
monotonic=True,
resolution=None, # checked separately
)
if clock_getres_spec['tv_nsec']:
expected_resolution = 1e-09
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
@needs_macos
class TestGetClockInfoMacOS(object):
"""
Tests for L{get_clock_info}.
"""
def test_non_monotonic(self):
"""
L{get_clock_info} only knows about the monotonic clock.
"""
with pytest.raises(ValueError):
get_clock_info("not monotonic")
def test_info(self):
"""
The reported info always includes a nanosecond resolution.
"""
expected_info = _api._SimpleNamespace(
adjustable=False,
implementation="mach_absolute_time()",
monotonic=True,
resolution=None, # checked separately
)
expected_resolution = 1e-09
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
@needs_posix
def test_monotonic_fails_posix(apply_failing_clock_call,
errno_value,
strerror):
"""
A failure in C{clock_gettime} results in an L{OSError} that
presents the failure's errno.
"""
calls = apply_failing_clock_call('_clock_gettime', errno_value)
with pytest.raises(OSError) as exc:
monotonic()
assert len(calls) == 1
assert calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
assert str(exc.value) == strerror
@needs_posix
@given(
clock_gettime_spec=st.fixed_dictionaries({
"tv_sec": st.integers(min_value=0, max_value=2 ** 32 - 1),
"tv_nsec": st.integers(min_value=0, max_value=2 ** 32 - 1),
}),
)
def test_clock(clock_gettime_spec, apply_timespec):
"""
For any given time resolution, the monotonic time equals the
sum of the seconds and nanoseconds.
"""
clock_gettime_calls = apply_timespec(
'_clock_gettime',
_bindings.ffi.new("struct timespec *", clock_gettime_spec),
)
# we a float, representing the current seconds plus the
# nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bindings.lib.CLOCK_MONOTONIC
def test_clock_increases():
"""
A monotonic moment is never greater than a succeeding monotonic
moment.
"""
assert monotonic() <= monotonic()
| mrwsr/monotone | test/test_monotone.py | Python | mit | 7,143 | [
30522,
1000,
1000,
1000,
5852,
2005,
1048,
1063,
18847,
5524,
1065,
1012,
1000,
1000,
1000,
2013,
10744,
12324,
2445,
1010,
9942,
2004,
2358,
12324,
9413,
19139,
2013,
18847,
5524,
12324,
2131,
1035,
5119,
1035,
18558,
1010,
18847,
25009,
2... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.asterix.external.feed.management;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.external.feed.api.IFeedLifecycleEventSubscriber;
public class FeedLifecycleEventSubscriber implements IFeedLifecycleEventSubscriber {
private LinkedBlockingQueue<FeedLifecycleEvent> inbox;
public FeedLifecycleEventSubscriber() {
this.inbox = new LinkedBlockingQueue<FeedLifecycleEvent>();
}
@Override
public void handleFeedEvent(FeedLifecycleEvent event) {
inbox.add(event);
}
@Override
public void assertEvent(FeedLifecycleEvent event) throws AsterixException, InterruptedException {
boolean eventOccurred = false;
FeedLifecycleEvent e = null;
Iterator<FeedLifecycleEvent> eventsSoFar = inbox.iterator();
while (eventsSoFar.hasNext()) {
e = eventsSoFar.next();
assertNoFailure(e);
eventOccurred = e.equals(event);
}
while (!eventOccurred) {
e = inbox.take();
eventOccurred = e.equals(event);
if (!eventOccurred) {
assertNoFailure(e);
}
}
}
private void assertNoFailure(FeedLifecycleEvent e) throws AsterixException {
if (e.equals(FeedLifecycleEvent.FEED_INTAKE_FAILURE) || e.equals(FeedLifecycleEvent.FEED_COLLECT_FAILURE)) {
throw new AsterixException("Failure in feed");
}
}
}
| kisskys/incubator-asterixdb | asterixdb/asterix-external-data/src/main/java/org/apache/asterix/external/feed/management/FeedLifecycleEventSubscriber.java | Java | apache-2.0 | 2,359 | [
30522,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
1008,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
1008,
5500,
2007,
2023,
2147,
2005,
3176,
2592,
1008,
4953,
9385,
6095,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/time.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
TEST(WaitableEventTest, ManualBasics) {
WaitableEvent event(true, false);
EXPECT_FALSE(event.IsSignaled());
event.Signal();
EXPECT_TRUE(event.IsSignaled());
EXPECT_TRUE(event.IsSignaled());
event.Reset();
EXPECT_FALSE(event.IsSignaled());
EXPECT_FALSE(event.TimedWait(TimeDelta::FromMilliseconds(10)));
event.Signal();
event.Wait();
EXPECT_TRUE(event.TimedWait(TimeDelta::FromMilliseconds(10)));
}
TEST(WaitableEventTest, AutoBasics) {
WaitableEvent event(false, false);
EXPECT_FALSE(event.IsSignaled());
event.Signal();
EXPECT_TRUE(event.IsSignaled());
EXPECT_FALSE(event.IsSignaled());
event.Reset();
EXPECT_FALSE(event.IsSignaled());
EXPECT_FALSE(event.TimedWait(TimeDelta::FromMilliseconds(10)));
event.Signal();
event.Wait();
EXPECT_FALSE(event.TimedWait(TimeDelta::FromMilliseconds(10)));
event.Signal();
EXPECT_TRUE(event.TimedWait(TimeDelta::FromMilliseconds(10)));
}
TEST(WaitableEventTest, WaitManyShortcut) {
WaitableEvent* ev[5];
for (unsigned i = 0; i < 5; ++i)
ev[i] = new WaitableEvent(false, false);
ev[3]->Signal();
EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 3u);
ev[3]->Signal();
EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 3u);
ev[4]->Signal();
EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 4u);
ev[0]->Signal();
EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 0u);
for (unsigned i = 0; i < 5; ++i)
delete ev[i];
}
class WaitableEventSignaler : public PlatformThread::Delegate {
public:
WaitableEventSignaler(double seconds, WaitableEvent* ev)
: seconds_(seconds),
ev_(ev) {
}
void ThreadMain() {
PlatformThread::Sleep(TimeDelta::FromSeconds(static_cast<int>(seconds_)));
ev_->Signal();
}
private:
const double seconds_;
WaitableEvent *const ev_;
};
TEST(WaitableEventTest, WaitMany) {
WaitableEvent* ev[5];
for (unsigned i = 0; i < 5; ++i)
ev[i] = new WaitableEvent(false, false);
WaitableEventSignaler signaler(0.1, ev[2]);
PlatformThreadHandle thread;
PlatformThread::Create(0, &signaler, &thread);
EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 2u);
PlatformThread::Join(thread);
for (unsigned i = 0; i < 5; ++i)
delete ev[i];
}
} // namespace base
| xzmagic/src | graphics/skia/third_party/base/synchronization/waitable_event_unittest.cc | C++ | gpl-2.0 | 2,570 | [
30522,
1013,
1013,
9385,
1006,
1039,
1007,
2249,
1996,
10381,
21716,
5007,
6048,
1012,
2035,
2916,
9235,
1012,
1013,
1013,
2224,
1997,
2023,
3120,
3642,
2003,
9950,
2011,
1037,
18667,
2094,
1011,
2806,
6105,
2008,
2064,
2022,
1013,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
jaleela_protestor_leader = Creature:new {
objectName = "",
socialGroup = "thug",
faction = "thug",
level = 17,
chanceHit = 0.320000,
damageMin = 180,
damageMax = 190,
baseXp = 1102,
baseHAM = 2400,
baseHAMmax = 3000,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = ATTACKABLE + ENEMY + AGGRESSIVE,
creatureBitmask = PACK,
optionsBitmask = 128,
diet = HERBIVORE,
templates = { "object/mobile/dressed_criminal_thug_human_male_01.iff" },
lootGroups = {
{
groups = {
{group = "junk", chance = 4000000},
{group = "wearables_common", chance = 3000000},
{group = "loot_kit_parts", chance = 2000000},
{group = "tailor_components", chance = 1000000},
}
}
},
weapons = {"pirate_weapons_heavy"},
attacks = merge(brawlermaster,marksmanmaster)
}
CreatureTemplates:addCreatureTemplate(jaleela_protestor_leader, "jaleela_protestor_leader")
| lasko2112/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/quest/rori/jaleela_protestor_leader.lua | Lua | agpl-3.0 | 1,034 | [
30522,
14855,
10559,
2721,
1035,
6186,
2953,
1035,
3003,
1027,
6492,
1024,
2047,
1063,
4874,
18442,
1027,
1000,
1000,
1010,
2591,
17058,
1027,
1000,
26599,
1000,
1010,
10233,
1027,
1000,
26599,
1000,
1010,
2504,
1027,
2459,
1010,
3382,
1658... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*!
* Font Awesome 3.2.0
* the iconic font designed for Bootstrap
* ------------------------------------------------------------------------------
* The full suite of pictographic icons, examples, and documentation can be
* found at http://fontawesome.io. Stay up to date on Twitter at
* http://twitter.com/fontawesome.
*
* License
* ------------------------------------------------------------------------------
* - The Font Awesome font is licensed under SIL OFL 1.1 -
* http://scripts.sil.org/OFL
* - Font Awesome CSS, LESS, and SASS files are licensed under MIT License -
* http://opensource.org/licenses/mit-license.html
* - Font Awesome documentation licensed under CC BY 3.0 -
* http://creativecommons.org/licenses/by/3.0/
* - Attribution is no longer required in Font Awesome 3.0, but much appreciated:
* "Font Awesome by Dave Gandy - http://fontawesome.io"
*
* Author - Dave Gandy
* ------------------------------------------------------------------------------
* Email: dave@fontawesome.io
* Twitter: http://twitter.com/byscuits
* Work: Lead Product Designer @ Kyruus - http://kyruus.com
*/
.icon-large{font-size:1.3333333333333333em;margin-top:-4px;padding-top:3px;margin-bottom:-4px;padding-bottom:3px;vertical-align:middle;}
.nav [class^="icon-"],.nav [class*=" icon-"]{vertical-align:inherit;margin-top:-4px;padding-top:3px;margin-bottom:-4px;padding-bottom:3px;}.nav [class^="icon-"].icon-large,.nav [class*=" icon-"].icon-large{vertical-align:-25%;}
.nav-pills [class^="icon-"].icon-large,.nav-tabs [class^="icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large{line-height:.75em;margin-top:-7px;padding-top:5px;margin-bottom:-5px;padding-bottom:4px;}
.btn [class^="icon-"].pull-left,.btn [class*=" icon-"].pull-left,.btn [class^="icon-"].pull-right,.btn [class*=" icon-"].pull-right{vertical-align:inherit;}
.btn [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large{margin-top:-0.5em;}
a [class^="icon-"],a [class*=" icon-"]{cursor:pointer;}
.icon-glass{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-music{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-search{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-envelope-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-heart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-user{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-film{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-th-large{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-th{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-th-list{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ok{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-remove{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-zoom-in{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-zoom-out{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-power-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-signal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cog{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-trash{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-home{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-time{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-road{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-download-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-download{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-upload{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-inbox{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-play-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-repeat{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rotate-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-refresh{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-lock{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flag{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-headphones{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-volume-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-volume-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-volume-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-qrcode{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-barcode{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tag{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tags{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-book{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bookmark{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-print{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-camera{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-font{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bold{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-italic{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-text-height{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-text-width{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-center{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-align-justify{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-indent-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-indent-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-facetime-video{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-picture{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pencil{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-map-marker{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-adjust{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tint{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-edit{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-share{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-move{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-step-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fast-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-backward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-play{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pause{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-stop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fast-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-step-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eject{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-minus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-remove-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ok-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-question-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-info-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-screenshot{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-remove-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ok-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ban-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-share-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mail-forward{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-resize-full{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-resize-small{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-minus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-asterisk{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-exclamation-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gift{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-leaf{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fire{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eye-open{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eye-close{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-warning-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plane{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-calendar{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-random{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comment{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-magnet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-retweet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-shopping-cart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-folder-close{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-folder-open{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-resize-vertical{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-resize-horizontal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bar-chart{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-twitter-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-facebook-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-camera-retro{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-key{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cogs{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comments{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-up-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-down-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-half{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-heart-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-signout{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-linkedin-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pushpin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-external-link{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-signin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-trophy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-github-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-upload-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-lemon{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-phone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unchecked{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bookmark-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-phone-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-twitter{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-facebook{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-github{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unlock{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-credit-card{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rss{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hdd{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bullhorn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bell{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-certificate{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hand-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-globe{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-wrench{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tasks{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-filter{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-briefcase{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fullscreen{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-group{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-link{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cloud{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-beaker{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cut{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-copy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-paper-clip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-paperclip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-save{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sign-blank{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-reorder{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list-ul{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-list-ol{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-strikethrough{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-underline{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-table{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-magic{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-truck{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pinterest{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-pinterest-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-google-plus-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-google-plus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-money{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-caret-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-columns{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-envelope{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-linkedin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-undo{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rotate-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-legal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dashboard{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comment-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-comments-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bolt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sitemap{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-umbrella{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-paste{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-lightbulb{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-exchange{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cloud-download{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cloud-upload{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-user-md{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-stethoscope{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-suitcase{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bell-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-coffee{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-food{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file-text-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-building{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-hospital{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ambulance{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-medkit{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fighter-jet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-beer{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-h-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-plus-sign-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-double-angle-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-double-angle-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-double-angle-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-double-angle-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-angle-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-desktop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-laptop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tablet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mobile-phone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle-blank{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-quote-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-quote-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-spinner{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-circle{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-reply{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mail-reply{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-github-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-folder-close-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-folder-open-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-expand-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-collapse-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-smile{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-frown{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-meh{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gamepad{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-keyboard{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flag-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flag-checkered{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-terminal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-code{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-reply-all{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-mail-reply-all{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-half-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-star-half-full{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-location-arrow{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-crop{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-code-fork{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unlink{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-question{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-info{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-exclamation{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-superscript{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-subscript{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eraser{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-puzzle-piece{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-microphone{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-microphone-off{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-shield{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-calendar-empty{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-fire-extinguisher{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rocket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-maxcdn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-sign-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-sign-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-sign-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-chevron-sign-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-html5{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-css3{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-anchor{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-unlock-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bullseye{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ellipsis-horizontal{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ellipsis-vertical{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rss-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-play-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-ticket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-minus-sign-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check-minus{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-level-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-level-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-check-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-edit-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-external-link-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-share-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-compass{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-collapse{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-collapse-top{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-expand{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-eur{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-euro{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gbp{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-usd{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dollar{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-inr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-rupee{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-jpy{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-yen{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-cny{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-renminbi{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-krw{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-won{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-btc{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bitcoin{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-file-text{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-alphabet{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-alphabet-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-attributes{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-attributes-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-order{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sort-by-order-alt{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-thumbs-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-youtube-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-youtube{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-xing{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-xing-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-youtube-play{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dropbox{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-stackexchange{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-instagram{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-flickr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-adn{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bitbucket{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bitbucket-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tumblr{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-tumblr-sign{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-long-arrow-down{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-long-arrow-up{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-long-arrow-left{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-long-arrow-right{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-apple{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-windows{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-android{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-linux{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-dribble{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-skype{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-foursquare{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-trello{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-female{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-male{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-gittip{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-sun{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-moon{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-archive{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-bug{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-vk{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-weibo{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
.icon-renren{*zoom:expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '');}
| oniiru/html | sendy/css/font-awesome-ie7.min.css | CSS | gpl-2.0 | 38,749 | [
30522,
1013,
1008,
999,
1008,
15489,
12476,
1017,
1012,
1016,
1012,
1014,
1008,
1996,
14430,
15489,
2881,
2005,
6879,
6494,
2361,
1008,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jme3.input.vr.oculus;
import com.jme3.app.VREnvironment;
import com.jme3.input.vr.HmdType;
import com.jme3.input.vr.VRAPI;
import com.jme3.math.*;
import com.jme3.renderer.Camera;
import com.jme3.texture.*;
import org.lwjgl.*;
import org.lwjgl.ovr.*;
import java.nio.IntBuffer;
import java.util.logging.Logger;
import static org.lwjgl.BufferUtils.createPointerBuffer;
import static org.lwjgl.ovr.OVR.*;
import static org.lwjgl.ovr.OVRErrorCode.ovrSuccess;
import static org.lwjgl.ovr.OVRUtil.ovr_Detect;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Oculus VR (LibOVR 1.3.0) Native support.
* <p>
* A few notes about the Oculus coordinate system:
* <ul>
* <li>Matrices should be transposed</li>
* <li>Quaternions should be inverted<li/>
* <li>Vectors should have their X and Z axes flipped, but apparently not Y.</li>
* </ul>
*
* @author Campbell Suter (znix@znix.xyz)
*/
public class OculusVR implements VRAPI {
private static final Logger LOGGER = Logger.getLogger(OculusVR.class.getName());
private final VREnvironment environment;
private boolean initialized;
/**
* Pointer to the HMD object
*/
private long session;
/**
* Information about the VR session (should the app quit, is
* it visible or is the universal menu open, etc)
*/
private OVRSessionStatus sessionStatus;
/**
* HMD information, such as product name and manufacturer.
*/
private OVRHmdDesc hmdDesc;
/**
* The horizontal resolution of the HMD
*/
private int resolutionW;
/**
* The vertical resolution of the HMD
*/
private int resolutionH;
/**
* Field-of-view data for each eye (how many degrees from the
* center can the user see).
*/
private final OVRFovPort fovPorts[] = new OVRFovPort[2];
/**
* Data about each eye to be rendered - in particular, the
* offset from the center of the HMD to the eye.
*/
private final OVREyeRenderDesc eyeRenderDesc[] = new OVREyeRenderDesc[2];
/**
* Store the projections for each eye, so we don't have to malloc
* and recalculate them each frame.
*/
private final OVRMatrix4f[] projections = new OVRMatrix4f[2];
/**
* Store the poses for each eye, relative to the HMD.
*
* @see #getHMDMatrixPoseLeftEye()
*/
private final Matrix4f[] hmdRelativeEyePoses = new Matrix4f[2];
/**
* Store the positions for each eye, relative to the HMD.
*
* @see #getHMDVectorPoseLeftEye()
*/
private final Vector3f[] hmdRelativeEyePositions = new Vector3f[2];
/**
* The current state of the tracked components (HMD, touch)
*/
private OVRTrackingState trackingState;
/**
* The position and orientation of the user's head.
*/
private OVRPosef headPose;
/**
* The state of the Touch controllers.
*/
private OculusVRInput input;
// The size of the texture drawn onto the HMD
private int textureW;
private int textureH;
// Layers to render into
private PointerBuffer layers;
private OVRLayerEyeFov layer0;
/**
* Chain texture set thing.
*/
private long chains[];
/**
* Frame buffers we can draw into.
*/
private FrameBuffer framebuffers[][];
public OculusVR(VREnvironment environment) {
this.environment = environment;
}
@Override
public OculusVRInput getVRinput() {
return input;
}
@Override
public String getName() {
return "OVR";
}
@Override
public int getDisplayFrequency() {
// TODO find correct frequency. I'm not sure
// if LibOVR has a way to do that, though.
return 60;
}
@Override
public boolean initialize() {
// Check to make sure the HMD is connected
OVRDetectResult detect = OVRDetectResult.calloc();
ovr_Detect(0, detect);
boolean connected = detect.IsOculusHMDConnected();
LOGGER.config("OVRDetectResult.IsOculusHMDConnected = " + connected);
LOGGER.config("OVRDetectResult.IsOculusServiceRunning = " + detect.IsOculusServiceRunning());
detect.free();
if (!connected) {
LOGGER.info("Oculus Rift not connected");
return false;
}
initialized = true;
// Set up the HMD
OVRLogCallback callback = new OVRLogCallback() {
@Override
public void invoke(long userData, int level, long message) {
LOGGER.fine("LibOVR [" + userData + "] [" + level + "] " + memASCII(message));
}
};
OVRInitParams initParams = OVRInitParams.calloc();
initParams.LogCallback(callback);
if (ovr_Initialize(initParams) != ovrSuccess) {
LOGGER.severe("LibOVR Init Failed");
return false; // TODO fix memory leak - destroy() is not called
}
LOGGER.config("LibOVR Version " + ovr_GetVersionString());
initParams.free();
// Get access to the HMD
LOGGER.info("Initialize HMD Session");
PointerBuffer pHmd = memAllocPointer(1);
OVRGraphicsLuid luid = OVRGraphicsLuid.calloc();
if (ovr_Create(pHmd, luid) != ovrSuccess) {
LOGGER.severe("Failed to create HMD");
return false; // TODO fix memory leak - destroy() is not called
}
session = pHmd.get(0);
memFree(pHmd);
luid.free();
sessionStatus = OVRSessionStatus.calloc();
// Get the information about the HMD
LOGGER.fine("Get HMD properties");
hmdDesc = OVRHmdDesc.malloc();
ovr_GetHmdDesc(session, hmdDesc);
if (hmdDesc.Type() == ovrHmd_None) {
LOGGER.warning("No HMD connected");
return false; // TODO fix memory leak - destroy() is not called
}
resolutionW = hmdDesc.Resolution().w();
resolutionH = hmdDesc.Resolution().h();
LOGGER.config("HMD Properties: "
+ "\t Manufacturer: " + hmdDesc.ManufacturerString()
+ "\t Product: " + hmdDesc.ProductNameString()
+ "\t Serial: <hidden>" // + hmdDesc.SerialNumberString() // Hidden for privacy reasons
+ "\t Type: " + hmdDesc.Type()
+ "\t Resolution (total): " + resolutionW + "," + resolutionH);
if (resolutionW == 0) {
LOGGER.severe("HMD witdth=0 : aborting");
return false; // TODO fix memory leak - destroy() is not called
}
// Find the FOV for each eye
for (int eye = 0; eye < 2; eye++) {
fovPorts[eye] = hmdDesc.DefaultEyeFov(eye);
}
// Get the pose for each eye, and cache it for later.
for (int eye = 0; eye < 2; eye++) {
// Create the projection objects
projections[eye] = OVRMatrix4f.malloc();
hmdRelativeEyePoses[eye] = new Matrix4f();
hmdRelativeEyePositions[eye] = new Vector3f();
// Find the eye render information - we use this in the
// view manager for giving LibOVR its timewarp information.
eyeRenderDesc[eye] = OVREyeRenderDesc.malloc();
ovr_GetRenderDesc(session, eye, fovPorts[eye], eyeRenderDesc[eye]);
// Get the pose of the eye
OVRPosef pose = eyeRenderDesc[eye].HmdToEyePose();
// Get the position and rotation of the eye
vecO2J(pose.Position(), hmdRelativeEyePositions[eye]);
Quaternion rotation = quatO2J(pose.Orientation(), new Quaternion());
// Put it into a matrix for the get eye pose functions
hmdRelativeEyePoses[eye].loadIdentity();
hmdRelativeEyePoses[eye].setTranslation(hmdRelativeEyePositions[eye]);
hmdRelativeEyePoses[eye].setRotationQuaternion(rotation);
}
// Recenter the HMD. The game itself should do this too, but just in case / before they do.
reset();
// Do this so others relying on our texture size (the GUI in particular) get it correct.
findHMDTextureSize();
// Allocate the memory for the tracking state - we actually
// set it up later, but Input uses it so calloc it now.
trackingState = OVRTrackingState.calloc();
// Set up the input
input = new OculusVRInput(this, session, sessionStatus, trackingState);
// TODO find some way to get in ovrTrackingOrigin_FloorLevel
// throw new UnsupportedOperationException("Not yet implemented!");
return true;
}
@Override
public void updatePose() {
double ftiming = ovr_GetPredictedDisplayTime(session, 0);
ovr_GetTrackingState(session, ftiming, true, trackingState);
ovr_GetSessionStatus(session, sessionStatus);
input.updateControllerStates();
headPose = trackingState.HeadPose().ThePose();
}
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public void destroy() {
// fovPorts: contents are managed by LibOVR, no need to do anything.
// Clean up the input
input.dispose();
// Check if we've set up rendering - if so, clean that up.
if (chains != null) {
// Destroy our set of huge buffer images.
for (long chain : chains) {
ovr_DestroyTextureSwapChain(session, chain);
}
// Free up the layer
layer0.free();
// The layers array apparently takes care of itself (and crashes if we try to free it)
}
for (OVREyeRenderDesc eye : eyeRenderDesc) {
eye.free();
}
for (OVRMatrix4f projection : projections) {
projection.free();
}
hmdDesc.free();
trackingState.free();
sessionStatus.free();
// Wrap everything up
ovr_Destroy(session);
ovr_Shutdown();
}
@Override
public void reset() {
// Reset the coordinate system - where the user's head is now is facing forwards from [0,0,0]
ovr_RecenterTrackingOrigin(session);
}
@Override
public void getRenderSize(Vector2f store) {
if (!isInitialized()) {
throw new IllegalStateException("Cannot call getRenderSize() before initialized!");
}
store.x = textureW;
store.y = textureH;
}
@Override
public float getInterpupillaryDistance() {
return 0.065f; // TODO
}
@Override
public Quaternion getOrientation() {
return quatO2J(headPose.Orientation(), new Quaternion());
}
@Override
public Vector3f getPosition() {
return vecO2J(headPose.Position(), new Vector3f());
}
@Override
public void getPositionAndOrientation(Vector3f storePos, Quaternion storeRot) {
storePos.set(getPosition());
storeRot.set(getOrientation());
}
private Matrix4f calculateProjection(int eye, Camera cam) {
Matrix4f mat = new Matrix4f();
// Get LibOVR to find the correct projection
OVRUtil.ovrMatrix4f_Projection(fovPorts[eye], cam.getFrustumNear(), cam.getFrustumFar(), OVRUtil.ovrProjection_None, projections[eye]);
matrixO2J(projections[eye], mat);
return mat;
}
@Override
public Matrix4f getHMDMatrixProjectionLeftEye(Camera cam) {
return calculateProjection(ovrEye_Left, cam);
}
@Override
public Matrix4f getHMDMatrixProjectionRightEye(Camera cam) {
return calculateProjection(ovrEye_Right, cam);
}
@Override
public Vector3f getHMDVectorPoseLeftEye() {
return hmdRelativeEyePositions[ovrEye_Left];
}
@Override
public Vector3f getHMDVectorPoseRightEye() {
return hmdRelativeEyePositions[ovrEye_Right];
}
@Override
public Vector3f getSeatedToAbsolutePosition() {
throw new UnsupportedOperationException();
}
@Override
public Matrix4f getHMDMatrixPoseLeftEye() {
return hmdRelativeEyePoses[ovrEye_Left];
}
@Override
public Matrix4f getHMDMatrixPoseRightEye() {
return hmdRelativeEyePoses[ovrEye_Left];
}
@Override
public HmdType getType() {
return HmdType.OCULUS_RIFT;
}
@Override
public boolean initVRCompositor(boolean set) {
if (!set) {
throw new UnsupportedOperationException("Cannot use LibOVR without compositor!");
}
setupLayers();
framebuffers = new FrameBuffer[2][];
for (int eye = 0; eye < 2; eye++)
setupFramebuffers(eye);
// TODO move initialization code here from VRViewManagerOculus
return true;
}
@Override
public void printLatencyInfoToConsole(boolean set) {
throw new UnsupportedOperationException("Not yet implemented!");
}
@Override
public void setFlipEyes(boolean set) {
throw new UnsupportedOperationException("Not yet implemented!");
}
@Override
public Void getCompositor() {
throw new UnsupportedOperationException("Not yet implemented!");
}
@Override
public Void getVRSystem() {
throw new UnsupportedOperationException("Not yet implemented!");
}
// Rendering-type stuff
public void findHMDTextureSize() {
// Texture sizes
float pixelScaling = 1.0f; // pixelsPerDisplayPixel
OVRSizei leftTextureSize = OVRSizei.malloc();
ovr_GetFovTextureSize(session, ovrEye_Left, fovPorts[ovrEye_Left], pixelScaling, leftTextureSize);
OVRSizei rightTextureSize = OVRSizei.malloc();
ovr_GetFovTextureSize(session, ovrEye_Right, fovPorts[ovrEye_Right], pixelScaling, rightTextureSize);
if (leftTextureSize.w() != rightTextureSize.w()) {
throw new IllegalStateException("Texture sizes do not match [horizontal]");
}
if (leftTextureSize.h() != rightTextureSize.h()) {
throw new IllegalStateException("Texture sizes do not match [vertical]");
}
textureW = leftTextureSize.w();
textureH = leftTextureSize.h();
leftTextureSize.free();
rightTextureSize.free();
}
private long setupTextureChain() {
// Set up the information for the texture buffer chain thing
OVRTextureSwapChainDesc swapChainDesc = OVRTextureSwapChainDesc.calloc()
.Type(ovrTexture_2D)
.ArraySize(1)
.Format(OVR_FORMAT_R8G8B8A8_UNORM_SRGB)
.Width(textureW)
.Height(textureH)
.MipLevels(1)
.SampleCount(1)
.StaticImage(false); // ovrFalse
// Create the chain
PointerBuffer textureSetPB = createPointerBuffer(1);
if (OVRGL.ovr_CreateTextureSwapChainGL(session, swapChainDesc, textureSetPB) != ovrSuccess) {
throw new RuntimeException("Failed to create Swap Texture Set");
}
swapChainDesc.free();
return textureSetPB.get(); // TODO is this a memory leak?
}
public void setupLayers() {
//Layers
layer0 = OVRLayerEyeFov.calloc();
layer0.Header().Type(ovrLayerType_EyeFov);
layer0.Header().Flags(ovrLayerFlag_TextureOriginAtBottomLeft);
chains = new long[2];
for (int eye = 0; eye < 2; eye++) {
long eyeChain = setupTextureChain();
chains[eye] = eyeChain;
OVRRecti viewport = OVRRecti.calloc();
viewport.Pos().x(0);
viewport.Pos().y(0);
viewport.Size().w(textureW);
viewport.Size().h(textureH);
layer0.ColorTexture(eye, eyeChain);
layer0.Viewport(eye, viewport);
layer0.Fov(eye, fovPorts[eye]);
viewport.free();
// we update pose only when we have it in the render loop
}
layers = createPointerBuffer(1);
layers.put(0, layer0);
}
/**
* Create a framebuffer for an eye.
*/
public void setupFramebuffers(int eye) {
// Find the chain length
IntBuffer length = BufferUtils.createIntBuffer(1);
ovr_GetTextureSwapChainLength(session, chains[eye], length);
int chainLength = length.get();
LOGGER.fine("HMD Eye #" + eye + " texture chain length: " + chainLength);
// Create the frame buffers
framebuffers[eye] = new FrameBuffer[chainLength];
for (int i = 0; i < chainLength; i++) {
// find the GL texture ID for this texture
IntBuffer textureIdB = BufferUtils.createIntBuffer(1);
OVRGL.ovr_GetTextureSwapChainBufferGL(session, chains[eye], i, textureIdB);
int textureId = textureIdB.get();
// TODO less hacky way of getting our texture into JMonkeyEngine
Image img = new Image();
img.setId(textureId);
img.setFormat(Image.Format.RGBA8);
img.setWidth(textureW);
img.setHeight(textureH);
Texture2D tex = new Texture2D(img);
FrameBuffer buffer = new FrameBuffer(textureW, textureH, 1);
buffer.setDepthBuffer(Image.Format.Depth);
buffer.setColorTexture(tex);
framebuffers[eye][i] = buffer;
}
}
// UTILITIES
// TODO move to helper class
/**
* Copy the values from a LibOVR matrix into a jMonkeyEngine matrix.
*
* @param from The matrix to copy from.
* @param to The matrix to copy to.
* @return The {@code to} argument.
*/
public static Matrix4f matrixO2J(OVRMatrix4f from, Matrix4f to) {
to.loadIdentity(); // For the additional columns (unless I'm badly misunderstanding matricies)
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
float val = from.M(x + y * 4); // TODO verify this
to.set(x, y, val);
}
}
to.transposeLocal(); // jME vs LibOVR coordinate spaces - Yay!
return to;
}
/**
* Copy the values from a LibOVR quaternion into a jMonkeyEngine quaternion.
*
* @param from The quaternion to copy from.
* @param to The quaternion to copy to.
* @return The {@code to} argument.
*/
public static Quaternion quatO2J(OVRQuatf from, Quaternion to) {
// jME and LibOVR do their coordinate spaces differently for rotations, so flip Y and W (thanks, jMonkeyVR).
to.set(
from.x(),
-from.y(),
from.z(),
-from.w()
);
to.normalizeLocal();
return to;
}
/**
* Copy the values from a LibOVR vector into a jMonkeyEngine vector.
*
* @param from The vector to copy from.
* @param to The vector to copy to.
* @return The {@code to} argument.
*/
public static Vector3f vecO2J(OVRVector3f from, Vector3f to) {
// jME and LibOVR disagree on which way X and Z are, too.
to.set(
-from.x(),
from.y(),
-from.z()
);
return to;
}
// Getters, intended for VRViewManager.
public long getSessionPointer() {
return session;
}
public long getChain(int eye) {
return chains[eye];
}
public FrameBuffer[] getFramebuffers(int eye) {
return framebuffers[eye];
}
public PointerBuffer getLayers() {
return layers;
}
public OVRLayerEyeFov getLayer0() {
return layer0;
}
public OVRFovPort getFovPort() {
return fovPorts[ovrEye_Left]; // TODO checking the left and right eyes match
}
public OVRPosef getHeadPose() {
return headPose;
}
public OVRPosef getEyePose(int eye) {
return eyeRenderDesc[eye].HmdToEyePose();
}
public VREnvironment getEnvironment() {
return environment;
}
}
/* vim: set ts=4 softtabstop=0 sw=4 expandtab: */
| zzuegg/jmonkeyengine | jme3-vr/src/main/java/com/jme3/input/vr/oculus/OculusVR.java | Java | bsd-3-clause | 20,261 | [
30522,
1013,
1008,
1008,
2000,
2689,
2023,
6105,
20346,
1010,
5454,
6105,
20346,
2015,
1999,
2622,
5144,
1012,
1008,
2000,
2689,
2023,
23561,
5371,
1010,
5454,
5906,
1064,
23561,
2015,
1008,
1998,
2330,
1996,
23561,
1999,
1996,
3559,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
:root {
--palette-red-50: rgb(255, 235, 238);
--palette-red-100: rgb(255, 205, 210);
--palette-red-200: rgb(239, 154, 154);
--palette-red-300: rgb(229, 115, 115);
--palette-red-400: rgb(239, 83, 80);
--palette-red-500: rgb(244, 67, 54);
--palette-red-600: rgb(229, 57, 53);
--palette-red-700: rgb(211, 47, 47);
--palette-red-800: rgb(198, 40, 40);
--palette-red-900: rgb(183, 28, 28);
--palette-red-a100: rgb(255, 138, 128);
--palette-red-a200: rgb(255, 82, 82);
--palette-red-a400: rgb(255, 23, 68);
--palette-red-a700: rgb(213, 0, 0);
--palette-pink-50: rgb(252, 228, 236);
--palette-pink-100: rgb(248, 187, 208);
--palette-pink-200: rgb(244, 143, 177);
--palette-pink-300: rgb(240, 98, 146);
--palette-pink-400: rgb(236, 64, 122);
--palette-pink-500: rgb(233, 30, 99);
--palette-pink-600: rgb(216, 27, 96);
--palette-pink-700: rgb(194, 24, 91);
--palette-pink-800: rgb(173, 20, 87);
--palette-pink-900: rgb(136, 14, 79);
--palette-pink-a100: rgb(255, 128, 171);
--palette-pink-a200: rgb(255, 64, 129);
--palette-pink-a400: rgb(245, 0, 87);
--palette-pink-a700: rgb(197, 17, 98);
--palette-purple-50: rgb(243, 229, 245);
--palette-purple-100: rgb(225, 190, 231);
--palette-purple-200: rgb(206, 147, 216);
--palette-purple-300: rgb(186, 104, 200);
--palette-purple-400: rgb(171, 71, 188);
--palette-purple-500: rgb(156, 39, 176);
--palette-purple-600: rgb(142, 36, 170);
--palette-purple-700: rgb(123, 31, 162);
--palette-purple-800: rgb(106, 27, 154);
--palette-purple-900: rgb(74, 20, 140);
--palette-purple-a100: rgb(234, 128, 252);
--palette-purple-a200: rgb(224, 64, 251);
--palette-purple-a400: rgb(213, 0, 249);
--palette-purple-a700: rgb(170, 0, 255);
--palette-deep-purple-50: rgb(237, 231, 246);
--palette-deep-purple-100: rgb(209, 196, 233);
--palette-deep-purple-200: rgb(179, 157, 219);
--palette-deep-purple-300: rgb(149, 117, 205);
--palette-deep-purple-400: rgb(126, 87, 194);
--palette-deep-purple-500: rgb(103, 58, 183);
--palette-deep-purple-600: rgb(94, 53, 177);
--palette-deep-purple-700: rgb(81, 45, 168);
--palette-deep-purple-800: rgb(69, 39, 160);
--palette-deep-purple-900: rgb(49, 27, 146);
--palette-deep-purple-a100: rgb(179, 136, 255);
--palette-deep-purple-a200: rgb(124, 77, 255);
--palette-deep-purple-a400: rgb(101, 31, 255);
--palette-deep-purple-a700: rgb(98, 0, 234);
--palette-indigo-50: rgb(232, 234, 246);
--palette-indigo-100: rgb(197, 202, 233);
--palette-indigo-200: rgb(159, 168, 218);
--palette-indigo-300: rgb(121, 134, 203);
--palette-indigo-400: rgb(92, 107, 192);
--palette-indigo-500: rgb(63, 81, 181);
--palette-indigo-600: rgb(57, 73, 171);
--palette-indigo-700: rgb(48, 63, 159);
--palette-indigo-800: rgb(40, 53, 147);
--palette-indigo-900: rgb(26, 35, 126);
--palette-indigo-a100: rgb(140, 158, 255);
--palette-indigo-a200: rgb(83, 109, 254);
--palette-indigo-a400: rgb(61, 90, 254);
--palette-indigo-a700: rgb(48, 79, 254);
--palette-blue-50: rgb(227, 242, 253);
--palette-blue-100: rgb(187, 222, 251);
--palette-blue-200: rgb(144, 202, 249);
--palette-blue-300: rgb(100, 181, 246);
--palette-blue-400: rgb(66, 165, 245);
--palette-blue-500: rgb(33, 150, 243);
--palette-blue-600: rgb(30, 136, 229);
--palette-blue-700: rgb(25, 118, 210);
--palette-blue-800: rgb(21, 101, 192);
--palette-blue-900: rgb(13, 71, 161);
--palette-blue-a100: rgb(130, 177, 255);
--palette-blue-a200: rgb(68, 138, 255);
--palette-blue-a400: rgb(41, 121, 255);
--palette-blue-a700: rgb(41, 98, 255);
--palette-light-blue-50: rgb(225, 245, 254);
--palette-light-blue-100: rgb(179, 229, 252);
--palette-light-blue-200: rgb(129, 212, 250);
--palette-light-blue-300: rgb(79, 195, 247);
--palette-light-blue-400: rgb(41, 182, 246);
--palette-light-blue-500: rgb(3, 169, 244);
--palette-light-blue-600: rgb(3, 155, 229);
--palette-light-blue-700: rgb(2, 136, 209);
--palette-light-blue-800: rgb(2, 119, 189);
--palette-light-blue-900: rgb(1, 87, 155);
--palette-light-blue-a100: rgb(128, 216, 255);
--palette-light-blue-a200: rgb(64, 196, 255);
--palette-light-blue-a400: rgb(0, 176, 255);
--palette-light-blue-a700: rgb(0, 145, 234);
--palette-cyan-50: rgb(224, 247, 250);
--palette-cyan-100: rgb(178, 235, 242);
--palette-cyan-200: rgb(128, 222, 234);
--palette-cyan-300: rgb(77, 208, 225);
--palette-cyan-400: rgb(38, 198, 218);
--palette-cyan-500: rgb(0, 188, 212);
--palette-cyan-600: rgb(0, 172, 193);
--palette-cyan-700: rgb(0, 151, 167);
--palette-cyan-800: rgb(0, 131, 143);
--palette-cyan-900: rgb(0, 96, 100);
--palette-cyan-a100: rgb(132, 255, 255);
--palette-cyan-a200: rgb(24, 255, 255);
--palette-cyan-a400: rgb(0, 229, 255);
--palette-cyan-a700: rgb(0, 184, 212);
--palette-teal-50: rgb(224, 242, 241);
--palette-teal-100: rgb(178, 223, 219);
--palette-teal-200: rgb(128, 203, 196);
--palette-teal-300: rgb(77, 182, 172);
--palette-teal-400: rgb(38, 166, 154);
--palette-teal-500: rgb(0, 150, 136);
--palette-teal-600: rgb(0, 137, 123);
--palette-teal-700: rgb(0, 121, 107);
--palette-teal-800: rgb(0, 105, 92);
--palette-teal-900: rgb(0, 77, 64);
--palette-teal-a100: rgb(167, 255, 235);
--palette-teal-a200: rgb(100, 255, 218);
--palette-teal-a400: rgb(29, 233, 182);
--palette-teal-a700: rgb(0, 191, 165);
--palette-green-50: rgb(232, 245, 233);
--palette-green-100: rgb(200, 230, 201);
--palette-green-200: rgb(165, 214, 167);
--palette-green-300: rgb(129, 199, 132);
--palette-green-400: rgb(102, 187, 106);
--palette-green-500: rgb(76, 175, 80);
--palette-green-600: rgb(67, 160, 71);
--palette-green-700: rgb(56, 142, 60);
--palette-green-800: rgb(46, 125, 50);
--palette-green-900: rgb(27, 94, 32);
--palette-green-a100: rgb(185, 246, 202);
--palette-green-a200: rgb(105, 240, 174);
--palette-green-a400: rgb(0, 230, 118);
--palette-green-a700: rgb(0, 200, 83);
--palette-light-green-50: rgb(241, 248, 233);
--palette-light-green-100: rgb(220, 237, 200);
--palette-light-green-200: rgb(197, 225, 165);
--palette-light-green-300: rgb(174, 213, 129);
--palette-light-green-400: rgb(156, 204, 101);
--palette-light-green-500: rgb(139, 195, 74);
--palette-light-green-600: rgb(124, 179, 66);
--palette-light-green-700: rgb(104, 159, 56);
--palette-light-green-800: rgb(85, 139, 47);
--palette-light-green-900: rgb(51, 105, 30);
--palette-light-green-a100: rgb(204, 255, 144);
--palette-light-green-a200: rgb(178, 255, 89);
--palette-light-green-a400: rgb(118, 255, 3);
--palette-light-green-a700: rgb(100, 221, 23);
--palette-lime-50: rgb(249, 251, 231);
--palette-lime-100: rgb(240, 244, 195);
--palette-lime-200: rgb(230, 238, 156);
--palette-lime-300: rgb(220, 231, 117);
--palette-lime-400: rgb(212, 225, 87);
--palette-lime-500: rgb(205, 220, 57);
--palette-lime-600: rgb(192, 202, 51);
--palette-lime-700: rgb(175, 180, 43);
--palette-lime-800: rgb(158, 157, 36);
--palette-lime-900: rgb(130, 119, 23);
--palette-lime-a100: rgb(244, 255, 129);
--palette-lime-a200: rgb(238, 255, 65);
--palette-lime-a400: rgb(198, 255, 0);
--palette-lime-a700: rgb(174, 234, 0);
--palette-yellow-50: rgb(255, 253, 231);
--palette-yellow-100: rgb(255, 249, 196);
--palette-yellow-200: rgb(255, 245, 157);
--palette-yellow-300: rgb(255, 241, 118);
--palette-yellow-400: rgb(255, 238, 88);
--palette-yellow-500: rgb(255, 235, 59);
--palette-yellow-600: rgb(253, 216, 53);
--palette-yellow-700: rgb(251, 192, 45);
--palette-yellow-800: rgb(249, 168, 37);
--palette-yellow-900: rgb(245, 127, 23);
--palette-yellow-a100: rgb(255, 255, 141);
--palette-yellow-a200: rgb(255, 255, 0);
--palette-yellow-a400: rgb(255, 234, 0);
--palette-yellow-a700: rgb(255, 214, 0);
--palette-amber-50: rgb(255, 248, 225);
--palette-amber-100: rgb(255, 236, 179);
--palette-amber-200: rgb(255, 224, 130);
--palette-amber-300: rgb(255, 213, 79);
--palette-amber-400: rgb(255, 202, 40);
--palette-amber-500: rgb(255, 193, 7);
--palette-amber-600: rgb(255, 179, 0);
--palette-amber-700: rgb(255, 160, 0);
--palette-amber-800: rgb(255, 143, 0);
--palette-amber-900: rgb(255, 111, 0);
--palette-amber-a100: rgb(255, 229, 127);
--palette-amber-a200: rgb(255, 215, 64);
--palette-amber-a400: rgb(255, 196, 0);
--palette-amber-a700: rgb(255, 171, 0);
--palette-orange-50: rgb(255, 243, 224);
--palette-orange-100: rgb(255, 224, 178);
--palette-orange-200: rgb(255, 204, 128);
--palette-orange-300: rgb(255, 183, 77);
--palette-orange-400: rgb(255, 167, 38);
--palette-orange-500: rgb(255, 152, 0);
--palette-orange-600: rgb(251, 140, 0);
--palette-orange-700: rgb(245, 124, 0);
--palette-orange-800: rgb(239, 108, 0);
--palette-orange-900: rgb(230, 81, 0);
--palette-orange-a100: rgb(255, 209, 128);
--palette-orange-a200: rgb(255, 171, 64);
--palette-orange-a400: rgb(255, 145, 0);
--palette-orange-a700: rgb(255, 109, 0);
--palette-deep-orange-50: rgb(251, 233, 231);
--palette-deep-orange-100: rgb(255, 204, 188);
--palette-deep-orange-200: rgb(255, 171, 145);
--palette-deep-orange-300: rgb(255, 138, 101);
--palette-deep-orange-400: rgb(255, 112, 67);
--palette-deep-orange-500: rgb(255, 87, 34);
--palette-deep-orange-600: rgb(244, 81, 30);
--palette-deep-orange-700: rgb(230, 74, 25);
--palette-deep-orange-800: rgb(216, 67, 21);
--palette-deep-orange-900: rgb(191, 54, 12);
--palette-deep-orange-a100: rgb(255, 158, 128);
--palette-deep-orange-a200: rgb(255, 110, 64);
--palette-deep-orange-a400: rgb(255, 61, 0);
--palette-deep-orange-a700: rgb(221, 44, 0);
--palette-brown-50: rgb(239, 235, 233);
--palette-brown-100: rgb(215, 204, 200);
--palette-brown-200: rgb(188, 170, 164);
--palette-brown-300: rgb(161, 136, 127);
--palette-brown-400: rgb(141, 110, 99);
--palette-brown-500: rgb(121, 85, 72);
--palette-brown-600: rgb(109, 76, 65);
--palette-brown-700: rgb(93, 64, 55);
--palette-brown-800: rgb(78, 52, 46);
--palette-brown-900: rgb(62, 39, 35);
--palette-grey-50: rgb(250, 250, 250);
--palette-grey-100: rgb(245, 245, 245);
--palette-grey-200: rgb(238, 238, 238);
--palette-grey-300: rgb(224, 224, 224);
--palette-grey-400: rgb(189, 189, 189);
--palette-grey-500: rgb(158, 158, 158);
--palette-grey-600: rgb(117, 117, 117);
--palette-grey-700: rgb(97, 97, 97);
--palette-grey-800: rgb(66, 66, 66);
--palette-grey-900: rgb(33, 33, 33);
--palette-blue-grey-50: rgb(236, 239, 241);
--palette-blue-grey-100: rgb(207, 216, 220);
--palette-blue-grey-200: rgb(176, 190, 197);
--palette-blue-grey-300: rgb(144, 164, 174);
--palette-blue-grey-400: rgb(120, 144, 156);
--palette-blue-grey-500: rgb(96, 125, 139);
--palette-blue-grey-600: rgb(84, 110, 122);
--palette-blue-grey-700: rgb(69, 90, 100);
--palette-blue-grey-800: rgb(55, 71, 79);
--palette-blue-grey-900: rgb(38, 50, 56);
--color-black: rgb(0, 0, 0);
--color-white: rgb(255, 255, 255);
--color-dark-contrast: var(--color-white);
--color-light-contrast: var(--color-black);
}
:root {
--color-divider: var(--palette-grey-200);
--color-background: var(--color-white);
--color-text: var(--palette-grey-900);
--color-text-secondary: var(--palette-grey-600);
--color-primary: var(--palette-indigo-500);
--color-primary-dark: var(--palette-indigo-700);
--color-accent: var(--palette-pink-a200);
--color-accent-dark: var(--palette-pink-700);
--color-primary-contrast: var(--color-dark-contrast);
--color-accent-contrast: var(--color-dark-contrast);
--unit: 10px;
--preferred-font: 'Roboto', 'Helvetica', 'Arial', sans-serif;
--font-size: calc(1.6 * var(--unit));
--font-size-tiny: calc(1.2 * var(--unit));
--font-size-small: calc(1.4 * var(--unit));
--font-size-normal: var(--font-size);
--font-size-big: calc(1.8 * var(--unit));
--font-weight-thin: 300;
--font-weight-normal: 400;
--font-weight-semi-bold: 500;
--font-weight-bold: 700;
--shadow-2p:
0 2px 2px 0 rgba(0, 0, 0, 0.14),
0 3px 1px -2px rgba(0, 0, 0, 0.2),
0 1px 5px 0 rgba(0, 0, 0, 0.12);
--shadow-3p:
0 3px 4px 0 rgba(0, 0, 0, 0.14),
0 3px 3px -2px rgba(0, 0, 0, 0.2),
0 1px 8px 0 rgba(0, 0, 0, 0.12);
--shadow-4p:
0 4px 5px 0 rgba(0, 0, 0, 0.14),
0 1px 10px 0 rgba(0, 0, 0, 0.12),
0 2px 4px -1px rgba(0, 0, 0, 0.2);
--shadow-6p:
0 6px 10px 0 rgba(0, 0, 0, 0.14),
0 1px 18px 0 rgba(0, 0, 0, 0.12),
0 3px 5px -1px rgba(0, 0, 0, 0.2);
--shadow-8p:
0 8px 10px 1px rgba(0, 0, 0, 0.14),
0 3px 14px 2px rgba(0, 0, 0, 0.12),
0 5px 5px -3px rgba(0, 0, 0, 0.2);
--shadow-16p:
0 16px 24px 2px rgba(0, 0, 0, 0.14),
0 6px 30px 5px rgba(0, 0, 0, 0.12),
0 8px 10px -5px rgba(0, 0, 0, 0.2);
--shadow-key-umbra-opacity: 0.2;
--shadow-key-penumbra-opacity: 0.14;
--shadow-ambient-shadow-opacity: 0.12;
--zdepth-shadow-1: 0 1px 6px rgba(0, 0, 0, 0.12), 0 1px 4px rgba(0, 0, 0, 0.24);
--zdepth-shadow-2: 0 3px 10px rgba(0, 0, 0, 0.16), 0 3px 10px rgba(0, 0, 0, 0.23);
--zdepth-shadow-3: 0 10px 30px rgba(0, 0, 0, 0.19), 0 6px 10px rgba(0, 0, 0, 0.23);
--zdepth-shadow-4: 0 14px 45px rgba(0, 0, 0, 0.25), 0 10px 18px rgba(0, 0, 0, 0.22);
--zdepth-shadow-5: 0 19px 60px rgba(0, 0, 0, 0.3), 0 15px 20px rgba(0, 0, 0, 0.22);
--animation-duration: 0.35s;
--animation-delay: calc(var(--animation-duration) / 5);
--animation-curve-fast-out-slow-in: cubic-bezier(0.4, 0, 0.2, 1);
--animation-curve-linear-out-slow-in: cubic-bezier(0, 0, 0.2, 1);
--animation-curve-fast-out-linear-in: cubic-bezier(0.4, 0, 1, 1);
--animation-curve-default: var(--animation-curve-fast-out-slow-in);
--z-index-highest: 300;
--z-index-higher: 200;
--z-index-high: 100;
--z-index-normal: 1;
--z-index-low: -100;
--z-index-lower: -200;
}
:root --reset: {
box-sizing: border-box;
font-family: var(--preferred-font);
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-size-adjust: 100%;
}
:root --reset: *,
:root --reset: *::after,
:root --reset: *::before {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-size-adjust: 100%;
-webkit-touch-callout: none;
}
/* Orientation */
@custom-media --portrait (orientation: portrait);
@custom-media --landscape (orientation: landscape);
/* Devices (defined by max width) */
@custom-media --xxs-viewport (max-width: 480px);
@custom-media --xs-viewport (max-width: 600px);
@custom-media --sm-tablet-viewport (max-width: 720px);
@custom-media --sm-viewport (max-width: 840px);
@custom-media --md-viewport (max-width: 960px);
@custom-media --lg-tablet-viewport (max-width: 1024px);
@custom-media --lg-viewport (max-width: 1280px);
@custom-media --xl-viewport (max-width: 1440px);
@custom-media --xxl-viewport (max-width: 1600px);
@custom-media --xxxl-viewport (max-width: 1920px);
/* Devices (defined by min-width) */
@custom-media --larger-than-xxs-viewport (min-width: 480px);
@custom-media --larger-than-xs-viewport (min-width: 600px);
@custom-media --larger-than-sm-tablet-viewport (min-width: 720px);
@custom-media --larger-than-sm-viewport (min-width: 840px);
@custom-media --larger-than-md-viewport (min-width: 960px);
@custom-media --larger-than-lg-tablet-viewport (min-width: 1024px);
@custom-media --larger-than-lg-viewport (min-width: 1280px);
@custom-media --larger-than-xl-viewport (min-width: 1440px);
@custom-media --larger-than-xxl-viewport (min-width: 1600px);
@custom-media --larger-than-xxxl-viewport (min-width: 1920px);
:root {
--standard-increment-mobile: calc(5.6 * var(--unit));
--standard-increment-desktop: calc(6.4 * var(--unit));
}
:root {
--dialog-border-radius: calc(0.2 * var(--unit));
--dialog-color-title: var(--color-black);
--dialog-color-white: var(--color-white);
--dialog-content-padding: calc(2.4 * var(--unit));
--dialog-navigation-padding: calc(0.8 * var(--unit));
--dialog-translate-y: calc(4 * var(--unit));
--overflow: hidden;
}
.wrapper {
align-items: center;
display: flex;
height: 100vh;
justify-content: center;
position: fixed;
top: 0;
width: 100vw;
z-index: var(--z-index-higher);
@apply --reset;
}
.dialog {
background-color: var(--dialog-color-white);
border-radius: var(--dialog-border-radius);
box-shadow: var(--zdepth-shadow-5);
display: flex;
flex-direction: column;
max-height: 96vh;
max-width: 96vw;
opacity: 0;
overflow: var(--overflow);
transform: translateY(calc(-1 * var(--dialog-translate-y)));
transition:
opacity var(--animation-duration) var(--animation-curve-default),
transform var(--animation-duration) var(--animation-curve-default);
transition-delay: var(--animation-delay);
}
.dialog.active {
opacity: 1;
transform: translateY(0%);
}
.small {
width: 30vw;
}
@media screen and (--sm-tablet-viewport) {
.small {
width: 50vw
}
}
@media screen and (--xs-viewport) {
.small {
width: 75vw
}
}
.normal {
width: 50vw;
}
@media screen and (--xs-viewport) {
.normal {
width: 96vw
}
}
.large {
width: 96vw;
}
.fullscreen {
width: 96vw;
}
@media screen and (--xs-viewport) {
.fullscreen {
border-radius: 0;
max-height: 100vh;
max-width: 100vw;
min-height: 100vh;
width: 100vw
}
}
.title {
color: var(--dialog-color-title);
flex-grow: 0;
font-size: calc(2 * var(--unit));
font-weight: 500;
letter-spacing: 0.02em;
line-height: 1;
margin: 0 0 calc(1.6 * var(--unit));
}
.body {
color: var(--color-text-secondary);
flex-grow: 2;
padding: var(--dialog-content-padding);
}
.body p {
font-size: calc(1.4 * var(--unit));
font-weight: 400;
letter-spacing: 0;
line-height: calc(2.4 * var(--unit));
margin: 0;
}
.navigation {
flex-grow: 0;
padding: var(--dialog-navigation-padding);
text-align: right;
}
.button {
margin-left: var(--dialog-navigation-padding);
min-width: 0;
padding-left: var(--dialog-navigation-padding);
padding-right: var(--dialog-navigation-padding);
}
| cdnjs/cdnjs | ajax/libs/react-toolbox/2.0.0-beta.10/dialog/theme.css | CSS | mit | 18,132 | [
30522,
1024,
7117,
1063,
1011,
1011,
27396,
1011,
2417,
1011,
2753,
1024,
1054,
18259,
1006,
20637,
1010,
17825,
1010,
22030,
1007,
1025,
1011,
1011,
27396,
1011,
2417,
1011,
2531,
1024,
1054,
18259,
1006,
20637,
1010,
16327,
1010,
12875,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Android Raspberry Pi display over USB - Joshua Woehlke
Sometimes you really want to play with a Raspberry Pi, but don’t have a display, keyboard, or mouse handy, and the wifi isn’t configured correctly to just be able to SSH in. Invariably you spend an hour digging around for a keyboard or refreshing a wireless clients list, but this doesn’t have to be the case. After a quick one-time setup, everything you need to use a Raspberry Pi will already be in your pocket.
## The idea
Once configured, if you have an Android phone with USB tethering and a cable, you should be well-equipped to use your Pi. Bonus points if you have a bluetooth mouse and keyboard. We’ll be setting up a USB network interface on the Pi and installing a VNC server to pass a session over that interface, thus making your phone a Raspberry Pi display. By the end you should be able to just power up your Pi, plug in your phone, turn on USB tethering, and open up a full desktop.
## Setting up the network
Log into your Pi via SSH or open up a terminal in its GUI and pull up your network interfaces.
```
sudo nano /etc/network/interfaces
```
Paste the following onto the bottom of the file, then save and exit (ctrl-X, Y):
On your next restart, you should have a new interface when you type `ifconfig`. We’ve set this interface to have a static IP address, always `192.168.42.42`, which you will later use to start your VNC session or connect via SSH on your phone.
## Configuring VNC
VNC, or Virtual Network Computing, is a way of sharing a graphical desktop environment over a network, which in this case happens to be your phone’s USB cable. First, we need to install a VNC server onto the Raspberry Pi. We’ll be using TightVNC since raspberrypi.org has a tutorial for it and it’s easy to find help on forums.
```
sudo apt-get install tightvncserver
```
Next, use the command `tightvncserver` to configure VNC for your Pi. It should ask you for a password–be aware that TightVNC will truncate your password to eight characters. It does tell you this in the terminal, but it can be easy to miss and lead to many failed login attempts.
Lastly, we need the VNC server to start up every time the Pi starts so that you really do only need your phone. First, change into your /etc/init.d directory.
```
cd /etc/init.d
```
Create a new file called vncboot. You’ll need root privileges to change anything in this directory.
```
sudo nano vncboot
```
Paste the following into the file (change export USER=’pi’ to your username if not pi, and edit the screen resolution in the start) block if necessary):
```
#! /bin/sh
### BEGIN INIT INFO
# Provides: vncboot
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Run tightvnc on boot
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin
export USER='pi'
eval cd ~$USER
. /lib/init/vars.sh
. /lib/lsb/init-functions
case "$1" in
start)
log_begin_msg "Starting VNC server"
su $USER -c '/usr/bin/vncserver :1 -geometry 1680x1050 -depth 24'
log_end_msg $?
exit 0
;;
stop)
pkill Xtightvnc
log_begin_msg "Stopping VNC server"
log_end_msg $?
exit 0
;;
*)
echo "Usage: /etc/init.d/vncboot {start|stop}"
exit 1
;;
esac
```
Save this file, then update its permissions:
```
sudo chmod 755 vncboot
```
Finally, run the following command to add it to your startup:
```
sudo update-rc.d vncboot defaults
```
Reboot your Pi and it should be ready to rock.
## Getting connected
Now that one side of your setup is complete, you’ll need a VNC client on your phone. VNC Viewer seems plenty quick for this purpose and you can’t argue with the price. Optionally, you may also download an SSH client like JuiceSSH for those times when a GUI just isn’t necessary.
With your app downloaded, power up your Pi and connect your phone via a data USB cable. As your Pi boots up, you should get a notification that the phone is now connected as a media device. Go into your phone’s settings and turn on USB tethering.
Assuming you’ve given the Pi enough time to boot, you should now be ready to pull up your desktop. Open your VNC viewer app, connect to `192.168.42.42:1` (the `:1` is important here), and provide your password. If you just need to SSH, open up your SSH app and connect to `192.168.42.42`.
Congratulations! You now have a Raspberry Pi display, keyboard, and mouse even when you don’t physically have those items available.
| KaliNuska/Personal | Use Raspberry Pi on an Android device.md | Markdown | gpl-2.0 | 4,598 | [
30522,
1001,
11924,
20710,
2361,
9766,
14255,
4653,
2058,
18833,
1011,
9122,
30524,
15536,
8873,
3475,
1521,
1056,
26928,
11178,
2000,
2074,
2022,
2583,
2000,
7020,
2232,
1999,
1012,
26597,
2017,
5247,
2019,
3178,
10443,
2105,
2005,
1037,
9... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
Derby - Class org.apache.derby.impl.jdbc.UTF8ReaderTest
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.derby.impl.jdbc;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.Test;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.types.StringDataValue;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
/**
* Tests {@code UTF8Reader} using package-private classes/methods.
*/
public class UTF8ReaderTest
extends BaseJDBCTestCase {
public UTF8ReaderTest(String name) {
super(name);
}
/**
* Tests simple repositioning.
*/
public void testRepositioningSimple()
throws IOException, SQLException, StandardException {
setAutoCommit(false);
Statement stmt = createStatement();
ResultSet rs = stmt.executeQuery(
"select * from Utf8ReaderTest where id = 101");
rs.next();
final int size = rs.getInt(2);
StringDataValue dvd = (StringDataValue)
((EmbedResultSet)rs).getColumn(3);
StoreStreamClob ssClob = new StoreStreamClob(
dvd.getStreamWithDescriptor(), (EmbedResultSet)rs);
Reader reader = ssClob.getInternalReader(1);
assertEquals('a', reader.read());
// Get internal readers and do stuff.
checkInternalStream(1, ssClob); // Get first character.
checkInternalStream(26, ssClob); // Skip forwards inside buffer.
checkInternalStream(17003, ssClob); // Skip forwards, refill buffer.
checkInternalStream(size, ssClob); // Skip until end.
assertEquals(-1, reader.read());
checkInternalStream(10, ssClob); // Rewind and refill buffer.
try {
checkInternalStream(size*2, ssClob); // Should fail, invalid pos.
fail("Should have failed due to invalid position");
} catch (EOFException eofe) {
// As expected, do nothing.
}
}
/**
* Tests repositioning withing the buffer.
*/
public void testRepositioningWithinBuffer()
throws IOException, SQLException, StandardException {
setAutoCommit(false);
Statement stmt = createStatement();
ResultSet rs = stmt.executeQuery(
"select * from Utf8ReaderTest where id = 100");
rs.next();
StringDataValue dvd = (StringDataValue)
((EmbedResultSet)rs).getColumn(3);
StoreStreamClob ssClob = new StoreStreamClob(
dvd.getStreamWithDescriptor(), (EmbedResultSet)rs);
Reader reader = ssClob.getInternalReader(1);
assertEquals('a', reader.read());
int bufSize = 26000;
char[] buf = new char[bufSize];
int count = 0;
while (count < bufSize) {
count += reader.read(buf, count, bufSize - count);
}
// We have now read 26001 chars. Next char should be 'b'.
// Internal buffer size after the singel read below should be:
// 26002 % 8192 = 1426
assertEquals('b', reader.read());
reader.close();
// Get internal readers and do stuff.
checkInternalStream(26002, ssClob);
checkInternalStream(26001, ssClob);
checkInternalStream(26002-1426+1, ssClob); // First char in buffer
checkInternalStream(26001+(8192-1426+1), ssClob); // Last char in buffer
checkInternalStream(26002-1426, ssClob); // Requires reset
checkInternalStream(26002-1426+1, ssClob); // Requires refilling buffer
checkInternalStream(26002, ssClob);
checkInternalStream(1, ssClob);
}
/**
* Tests repositioning withing buffer with a "real text" to make sure the
* correct values are returned.
*/
public void testRepositioningWithinBufferRealText()
throws IOException, SQLException, StandardException {
setAutoCommit(false);
Statement stmt = createStatement();
ResultSet rs = stmt.executeQuery(
// See insertTestData
"select * from Utf8ReaderTest where id = 1");
rs.next();
StringDataValue dvd = (StringDataValue)
((EmbedResultSet)rs).getColumn(3);
StoreStreamClob ssClob = new StoreStreamClob(
dvd.getStreamWithDescriptor(), (EmbedResultSet)rs);
Reader reader = ssClob.getInternalReader(1);
assertEquals('B', reader.read());
reader = ssClob.getInternalReader(24);
assertEquals('\'', reader.read());
reader = ssClob.getInternalReader(42);
assertEquals('H', reader.read());
reader = ssClob.getInternalReader(70);
assertEquals('M', reader.read());
reader = ssClob.getInternalReader(102);
assertEquals('M', reader.read());
reader = ssClob.getInternalReader(128);
assertEquals('B', reader.read());
reader = ssClob.getInternalReader(155);
assertEquals('A', reader.read());
reader = ssClob.getInternalReader(184);
assertEquals('S', reader.read());
reader = ssClob.getInternalReader(207);
assertEquals('H', reader.read());
reader = ssClob.getInternalReader(224);
assertEquals('O', reader.read());
reader = ssClob.getInternalReader(128);
char[] buf = new char[4];
assertEquals(4, reader.read(buf));
assertEquals("But ", new String(buf));
reader = ssClob.getInternalReader(70);
buf = new char[32];
assertEquals(32, reader.read(buf));
assertEquals("Men the grocer and butcher sent\n", new String(buf));
}
/**
* Makes sure the data returned from the internal Clob matches the data
* returned by a fresh looping alphabet stream.
*
* @param pos 1-based Clob position
* @param clob internal store stream Clob representation
*/
private static void checkInternalStream(long pos, StoreStreamClob clob)
throws IOException, SQLException {
Reader canonStream = new LoopingAlphabetReader(pos + 100);
long toSkip = pos -1; // Convert to 0-based index.
while (toSkip > 0) {
long skipped = canonStream.skip(toSkip);
if (skipped > 0) {
toSkip -= skipped;
}
}
Reader clobStream = clob.getInternalReader(pos);
assertEquals("Data mismatch", canonStream.read(), clobStream.read());
clobStream.close();
}
/**
* Returns a simple test suite, using the embedded driver only.
*
* @return A test suite.
*/
public static Test suite() {
BaseTestSuite suite = new BaseTestSuite(UTF8ReaderTest.class);
return new CleanDatabaseTestSetup(suite) {
public void decorateSQL(Statement stmt)
throws SQLException {
insertTestData(stmt);
}
};
}
/**
* Inserts data used by the tests.
* <p>
* Use the id to select a Clob with specific contents.
*/
private static void insertTestData(Statement stmt)
throws SQLException {
int[][] sizes = new int[][] {
{100, 1*1024*1024}, // 1M chars
{101, 32*1024}, // 32K chars
};
stmt.executeUpdate(
"create table Utf8ReaderTest" +
"(id int primary key, size int, dClob clob)");
PreparedStatement ps = stmt.getConnection().prepareStatement(
"insert into Utf8ReaderTest values (?,?,?)");
for (int i=0; i < sizes.length; i++) {
ps.setInt(1, sizes[i][0]);
int size = sizes[i][1];
ps.setInt(2, size);
ps.setCharacterStream(3, new LoopingAlphabetReader(size), size);
ps.executeUpdate();
}
// Insert some special pieces of text, repeat to get it represented as
// a stream.
ps.setInt(1, 1);
int size = aintWeGotFun.length();
ps.setInt(2, size);
StringBuffer str = new StringBuffer(32*1024 + aintWeGotFun.length());
while (str.length() < 32*1024) {
str.append(aintWeGotFun);
}
ps.setString(3, str.toString());
ps.executeUpdate();
}
/**
* Test data, first part of "Ain't We Got Fun?" (public domain).
* See http://en.wikipedia.org/wiki/Ain%27t_We_Got_Fun%3F
*/
public static final String aintWeGotFun =
// 1-based positions for the first and the last character on line.
"Bill collectors gather\n" + // 1
"'Round and rather\n" + // 24
"Haunt the cottage next door\n" + // 42
"Men the grocer and butcher sent\n" + // 70
"Men who call for the rent\n" + // 102
"But with in a happy chappy\n" + // 128
"And his bride of only a year\n" + // 155
"Seem to be so cheerful\n" + // 184
"Here's an earful\n" + // 207
"Of the chatter you hear\n"; // 224
/*
// Code that can be used to check the positions in the text.
String[] firstWords = new String[] {"Bill", "'Round", "Haunt", "Men th",
"Men wh", "But", "And", "Seem", "Here's", "Of"};
for (int i=0; i < firstWords.length; i++) {
System.out.println("> " + firstWords[i]);
int clobPos = (int)clob.position(firstWords[i], 1);
int strPos = aintWeGotFun.indexOf(firstWords[i]);
System.out.println("\tClob: " + clobPos);
System.out.println("\tString: " + strPos);
assertTrue(clobPos == strPos +1);
}
*/
}
| trejkaz/derby | java/testing/org/apache/derby/impl/jdbc/UTF8ReaderTest.java | Java | apache-2.0 | 10,873 | [
30522,
1013,
1008,
7350,
1011,
2465,
8917,
1012,
15895,
1012,
7350,
1012,
17727,
2140,
1012,
26219,
9818,
1012,
21183,
2546,
2620,
16416,
4063,
22199,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
1213... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/********************************************\
*
* Sire - Molecular Simulation Framework
*
* Copyright (C) 2017 Christopher Woods
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For full details of the license please see the COPYING file
* that should have come with this distribution.
*
* You can contact the authors via the developer's mailing list
* at http://siremol.org
*
\*********************************************/
#include "range.h"
#include "ranges.h"
#include "SireStream/datastream.h"
using namespace SireBase;
using namespace SireStream;
static const RegisterMetaType<Range> r_range( MAGIC_ONLY, "SireBase::Range" );
QDataStream SIREBASE_EXPORT &operator<<(QDataStream &ds, const Range &range)
{
writeHeader(ds, r_range, 1);
ds << static_cast<const Property&>(range);
return ds;
}
QDataStream SIREBASE_EXPORT &operator>>(QDataStream &ds, Range &range)
{
VersionID v = readHeader(ds, r_range);
if (v == 1)
{
ds >> static_cast<Property&>(range);
}
else
throw version_error(v, "1", r_range, CODELOC);
return ds;
}
/** Constructor */
Range::Range() : Property()
{}
/** Copy constructor */
Range::Range(const Range &other) : Property(other)
{}
/** Destructor */
Range::~Range()
{}
/** Copy assignment */
Range& Range::operator=(const Range &other)
{
Property::operator=(other);
return *this;
}
/** Return a null simple range for null */
const Range& Range::null()
{
return *(create_shared_null<SimpleRange>());;
}
/** Return the range that represents the single value 'i' */
RangePtr Range::create(qint64 i)
{
return SimpleRange(i);
}
/** Return the range that represents the range from [start,end) */
RangePtr Range::create(qint64 start, qint64 end)
{
return SimpleRange(start,end);
}
/** Return the range that represents the range from [start,end,increment) */
RangePtr Range::create(qint64 start, qint64 end, qint64 increment)
{
return SimpleRange(start,end,increment);
}
| chryswoods/Sire | corelib/src/libs/SireBase/range.cpp | C++ | gpl-2.0 | 2,721 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Don't need this for our purposes
module = function(){};
if(typeof equal != 'undefined') {
equals = equal;
}
ok = function(actual, message) {
equal(actual, true, message);
}
raises = function(fn, expected, message) {
raisesError(fn, message);
};
asyncTest = function(name, delay, fn) {
test(name, fn);
}
start = function() {
// Just pass through...
}
notStrictEqual = function(a, b, message) {
equal(a === b, false, message);
}
var ensureArray = function(obj) {
if(obj === null) {
return [];
} else if(Object.isArray(obj) && (!obj.indexOf || !obj.lastIndexOf)) {
return obj.concat();
} else if(!Object.isArray(obj) && typeof obj == 'object') {
return Array.prototype.slice.call(obj);
} else {
return obj;
}
}
var CompatibleMethods = [
{
module: Array.prototype,
methods: [
{
name: 'first',
method: function(arr, n, guard){
if(guard) {
return arr[0];
}
return ensureArray(arr).first(n);
}
},
{
name: 'last',
method: function(arr, n, third){
// This is the same check that Underscore makes to hack
// _.last to work with _.map
if(third) n = 1;
return ensureArray(arr).last(n);
}
},
{
name: 'rest',
method: function(arr, n, guard){
if(n === undefined) n = 1;
if(guard) {
return arr.slice(1);
}
return ensureArray(arr).from(n);
}
},
{
name: 'compact',
method: function(arr){
return ensureArray(arr).compact(true);
}
},
/* Object.extend is no longer compatible as it has conflict resolution now.
{
name: 'extend',
method: function(){
return Object.SugarMethods['merge'].method.apply(this, arguments);
}
},
*/
/* Array#flatten is no longer compatible as it has levels of flattening (not just deep/shallow)
{
name: 'flatten',
method: function(arr){
return ensureArray(arr).flatten();
}
},
*/
{
name: 'uniq',
method: function(arr){
return ensureArray(arr).unique();
}
},
{
name: 'intersection',
method: function(arr){
arr = ensureArray(arr);
var args = Array.prototype.slice.call(arguments, 1);
return Array.prototype.intersect.apply(arr, args);
}
},
{
name: 'union',
method: function(arr, a){
arr = ensureArray(arr);
var args = Array.prototype.slice.call(arguments, 1);
return Array.prototype.union.apply(arr, args);
}
},
/*
{
name: 'difference',
method: function(arr, a){
arr = ensureArray(arr);
var args = Array.prototype.slice.call(arguments, 1);
return Array.prototype.subtract.apply(arr, args);
}
},
*/
{
name: 'indexOf',
method: function(arr, a){
return ensureArray(arr).indexOf(a);
}
},
{
name: 'lastIndexOf',
method: function(arr, a){
return ensureArray(arr).lastIndexOf(a);
}
},
{
name: 'range',
method: function(start, stop, step){
if(arguments.length == 1){
stop = arguments[0];
start = 0;
}
var shift = step < 0 ? 1 : -1;
return start.upto(stop + shift, null, step);
}
},
// Collections
// _.each -> Array#forEach OR Object.each
// _.map -> Array#map
// _.reduce -> Array#reduce
// _.reduceRight -> Array#reduceRight
// _.invoke is doing some strange tapdancing for passing methods directly...
// _.sortedIndex ... no direct equivalent
// _.toArray ... no direct equivalent for arguments... Array.create?
// _.size ... no direct equivalent for objects... obj.keys().length?
{
name: 'detect',
method: function(arr, fn, context){
return Array.SugarMethods['find'].method.call(arr, fn.bind(context));
}
},
{
name: 'select',
method: function(arr, fn, context){
return Array.SugarMethods['findAll'].method.call(arr, fn.bind(context));
}
},
{
name: 'reject',
method: function(arr, fn, context){
return Array.SugarMethods['exclude'].method.call(arr, fn.bind(context));
}
},
{
name: 'all',
method: function(arr, fn, context){
return Array.SugarMethods['all'].method.call(arr, fn.bind(context));
}
},
{
name: 'any',
method: function(arr, fn, context){
if(!fn) fn = function(a){ return a; };
return Array.SugarMethods['some'].method.call(arr, fn.bind(context));
}
},
/*
{
name: 'include',
method: function(arr, val){
return Array.SugarMethods['has'].method.call(arr, val);
}
},
*/
{
name: 'pluck',
method: function(arr, prop){
return Array.SugarMethods['map'].method.call(arr, prop);
}
},
{
name: 'max',
method: function(arr, fn, context){
if(!fn) fn = function(a){ return a; };
return Array.SugarMethods['max'].method.call(arr, fn.bind(context))[0];
}
},
{
name: 'min',
method: function(arr, fn, context){
if(!fn) fn = function(a){ return a; };
return Array.SugarMethods['min'].method.call(arr, fn.bind(context))[0];
}
},
{
name: 'sortBy',
method: function(arr, fn, context){
return Array.SugarMethods['sortBy'].method.call(arr, fn.bind(context));
}
},
{
name: 'groupBy',
method: function(arr, fn){
return Array.SugarMethods['groupBy'].method.call(arr, fn);
}
},
// Objects
// _.functions ... no direct equivalent
// _.defaults ... no direct equivalent
// _.tap ... no direct equivalent
// _.isElement ... no direct equivalent
// _.isArguments ... no direct equivalent
// _.isNaN ... no direct equivalent
// _.isNull ... no direct equivalent
// _.isUndefined ... no direct equivalent
{
name: 'keys',
method: function(){
return Object.SugarMethods['keys'].method.apply(this, arguments);
}
},
{
name: 'values',
method: function(){
return Object.SugarMethods['values'].method.apply(this, arguments);
}
},
{
name: 'clone',
method: function(){
return Object.SugarMethods['clone'].method.apply(this, arguments);
}
},
{
name: 'isEqual',
method: function(a, b){
if (a && a._chain) a = a._wrapped;
if (b && b._chain) b = b._wrapped;
if (a && a.isEqual) return a.isEqual(b);
if (b && b.isEqual) return b.isEqual(a);
return Object.SugarMethods['equal'].method.apply(this, arguments);
}
},
{
name: 'isEmpty',
method: function(){
return Object.SugarMethods['isEmpty'].method.apply(this, arguments);
}
},
{
name: 'isArray',
method: function(arr){
return Array.isArray(arr);
}
},
{
name: 'isFunction',
method: function(){
return Object.SugarMethods['isFunction'].method.apply(this, arguments);
}
},
{
name: 'isString',
method: function(){
return Object.SugarMethods['isString'].method.apply(this, arguments);
}
},
{
name: 'isNumber',
method: function(){
if(isNaN(arguments[0])) {
// Sugar differs here as it's trying to stay aligned with Javascript and is
// checking types only.
return false;
}
return Object.SugarMethods['isNumber'].method.apply(this, arguments);
}
},
{
name: 'isBoolean',
method: function(){
return Object.SugarMethods['isBoolean'].method.apply(this, arguments);
}
},
{
name: 'isDate',
method: function(){
return Object.SugarMethods['isDate'].method.apply(this, arguments);
}
},
{
name: 'isRegExp',
method: function(){
return Object.SugarMethods['isRegExp'].method.apply(this, arguments);
}
},
// Functions
// _.bindAll ... no direct equivalent (similar to bindAsEventListener??)
// _.memoize ... no direct equivalent
// _.debounce ... no direct equivalent
// _.once ... no direct equivalent.. is this not similar to memoize?
// _.wrap ... no direct equivalent..
// _.compose ... no direct equivalent.. math stuff
{
name: 'bind',
method: function(fn){
var args = Array.prototype.slice.call(arguments, 1);
return Function.prototype.bind.apply(fn, args);
}
},
{
name: 'after',
method: function(num, fn){
return Function.prototype.after.apply(fn, [num]);
}
},
{
name: 'delay',
method: function(fn){
var args = Array.prototype.slice.call(arguments, 1);
return Function.prototype.delay.apply(fn, args);
}
},
{
name: 'defer',
method: function(fn){
var args = Array.prototype.slice.call(arguments, 1);
return Function.prototype.delay.apply(fn, [1].concat(args));
}
},
{
name: 'throttle',
method: function(fn, wait){
return Function.prototype.lazy.apply(fn, [wait]);
}
},
// Utility
// _.noConflict ... no direct equivalent
// _.identity ... no direct equivalent
// _.mixin ... no direct equivalent
// _.uniqueId ... no direct equivalent
// _.template ... no direct equivalent
// _.chain ... no direct equivalent
// _.value ... no direct equivalent
{
name: 'times',
method: function(n, fn){
return n.times(fn);
}
}
]
}
];
var mapMethods = function() {
var proto;
CompatibleMethods.forEach(function(cm) {
cm.methods.forEach(function(m) {
_[m.name] = m.method;
});
});
}
mapMethods();
| D1plo1d/Sugar | unit_tests/environments/underscore/adapter.js | JavaScript | mit | 10,615 | [
30522,
1013,
1013,
2123,
1005,
1056,
2342,
2023,
2005,
2256,
5682,
11336,
1027,
3853,
1006,
1007,
1063,
1065,
1025,
2065,
1006,
2828,
11253,
5020,
999,
1027,
1005,
6151,
28344,
1005,
1007,
1063,
19635,
1027,
5020,
1025,
1065,
7929,
1027,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
*/
package io.jenetics.prog.op;
import static java.lang.Math.abs;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.cbrt;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.cosh;
import static java.lang.Math.exp;
import static java.lang.Math.floor;
import static java.lang.Math.hypot;
import static java.lang.Math.log;
import static java.lang.Math.log10;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.pow;
import static java.lang.Math.rint;
import static java.lang.Math.signum;
import static java.lang.Math.sin;
import static java.lang.Math.sinh;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static java.lang.Math.tanh;
import static java.util.Objects.requireNonNull;
import static io.jenetics.prog.op.Numbers.box;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.jenetics.ext.util.Tree;
import io.jenetics.ext.util.TreeNode;
/**
* This class contains operations for performing basic numeric operations.
*
* @see Math
*
* @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
* @version 5.0
* @since 3.9
*/
public enum MathOp implements Op<Double> {
/* *************************************************************************
* Arithmetic operations
* ************************************************************************/
/**
* Return the absolute value of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#abs(double)
*/
ABS("abs", 1, v -> abs(v[0])),
/**
* Return the negation value of a double value.
* <em>This operation has arity 1.</em>
*/
NEG("neg", 1, v -> -v[0]),
/**
* The identity function.
*/
ID("id", 1, v -> v[0]),
/**
* Return the minimum of two values.
* <em>This operation has arity 2.</em>
*
* @see Math#min(double, double)
*/
MIN("min", 2, v -> min(v[0], v[1])),
/**
* Return the maximum of two values
* <em>This operation has arity 2.</em>
*
* @see Math#max(double, double)
*/
MAX("max", 2, v -> max(v[0], v[1])),
/**
* Returns the smallest (closest to negative infinity) double value that is
* greater than or equal to the argument and is equal to a mathematical
* integer.
* <em>This operation has arity 1.</em>
*
* @see Math#ceil(double)
*/
CEIL("ceil", 1, v -> ceil(v[0])),
/**
* Returns the largest (closest to positive infinity) double value that is
* less than or equal to the argument and is equal to a mathematical integer.
* <em>This operation has arity 1.</em>
*
* @see Math#floor(double)
*/
FLOOR("floor", 1, v -> floor(v[0])),
/**
* Returns the signum function of the argument; zero if the argument is
* zero, 1.0 if the argument is greater than zero, -1.0 if the argument is
* less than zero.
* <em>This operation has arity 1.</em>
*
* @see Math#signum(double)
*/
SIGNUM("signum", 1, v -> signum(v[0])),
/**
* Returns the double value that is closest in value to the argument and is
* equal to a mathematical integer.
* <em>This operation has arity 1.</em>
*
* @see Math#rint(double)
*/
RINT("rint", 1, v -> rint(v[0])),
/**
* Returns the sum of its arguments.
* <em>This operation has arity 2.</em>
*/
ADD("add", 2, v -> v[0] + v[1]),
/**
* Return the diff of its arguments.
* <em>This operation has arity 2.</em>
*/
SUB("sub", 2, v -> v[0] - v[1]),
/**
* Returns the product of its arguments.
* <em>This operation has arity 2.</em>
*/
MUL("mul", 2, v -> v[0]*v[1]),
/**
* Returns the quotient of its arguments.
* <em>This operation has arity 2.</em>
*/
DIV("div", 2, v -> v[0]/v[1]),
/**
* Returns the modulo of its arguments.
* <em>This operation has arity 2.</em>
*/
MOD("mod", 2, v -> v[0]%v[1]),
/**
* Returns the value of the first argument raised to the power of the second
* argument.
* <em>This operation has arity 2.</em>
*
* @see Math#pow(double, double)
*/
POW("pow", 2, v -> pow(v[0], v[1])),
/**
* Returns the square value of a given double value.
* <em>This operation has arity 1.</em>
*/
SQR("sqr", 1, v -> v[0]*v[0]),
/**
* Returns the correctly rounded positive square root of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#sqrt(double)
*/
SQRT("sqrt", 1, v -> sqrt(v[0])),
/**
* Returns the cube root of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#cbrt(double)
*/
CBRT("cbrt", 1, v -> cbrt(v[0])),
/**
* Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) without
* intermediate overflow or underflow.
* <em>This operation has arity 2.</em>
*
* @see Math#hypot(double, double)
*/
HYPOT("hypot", 2, v -> hypot(v[0], v[1])),
/* *************************************************************************
* Exponential/logarithmic operations
* ************************************************************************/
/**
* Returns Euler's number e raised to the power of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#exp(double)
*/
EXP("exp", 1, v -> exp(v[0])),
/**
* Returns the natural logarithm (base e) of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#log(double)
*/
LOG("log", 1, v -> log(v[0])),
/**
* Returns the base 10 logarithm of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#log10(double)
*/
LOG10("log10", 1, v -> log10(v[0])),
/* *************************************************************************
* Trigonometric operations
* ************************************************************************/
/**
* Returns the trigonometric sine of an angle.
* <em>This operation has arity 1.</em>
*
* @see Math#sin(double)
*/
SIN("sin", 1, v -> sin(v[0])),
/**
* Returns the trigonometric cosine of an angle.
* <em>This operation has arity 1.</em>
*
* @see Math#cos(double)
*/
COS("cos", 1, v -> cos(v[0])),
/**
* Returns the trigonometric tangent of an angle.
* <em>This operation has arity 1.</em>
*
* @see Math#tan(double)
*/
TAN("tan", 1, v -> tan(v[0])),
/**
* Returns the arc cosine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#acos(double)
*/
ACOS("acos", 1, v -> acos(v[0])),
/**
* Returns the arc sine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#asin(double)
*/
ASIN("asin", 1, v -> asin(v[0])),
/**
* Returns the arc tangent of a value.
* <em>This operation has arity 1.</em>
*
* @see Math#atan(double)
*/
ATAN("atan", 1, v -> atan(v[0])),
/**
* Returns the hyperbolic cosine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#cosh(double)
*/
COSH("cosh", 1, v -> cosh(v[0])),
/**
* Returns the hyperbolic sine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#sinh(double)
*/
SINH("sinh", 1, v -> sinh(v[0])),
/**
* Returns the hyperbolic tangent of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#tanh(double)
*/
TANH("tanh", 1, v -> tanh(v[0])),
/* *************************************************************************
* Conditional functions
* ************************************************************************/
/**
* Returns +1.0 if its first argument is greater than its second argument
* and returns -1.0 otherwise.
*
* @since 5.0
*/
GT("gt", 2, v -> v[0] > v[1] ? 1.0 : -1.0);
/* *************************************************************************
* Additional mathematical constants.
* ************************************************************************/
/**
* The double value that is closer than any other to pi, the ratio of the
* circumference of a circle to its diameter. <em>This is a terminal
* operation.</em>
*
* @see Math#PI
*/
public static final Const<Double> PI = Const.of("π", Math.PI);
/**
* The double value that is closer than any other to e, the base of the
* natural logarithms. <em>This is a terminal operation.</em>
*
* @see Math#E
*/
public static final Const<Double> E = Const.of("e", Math.E);
/**
* The names of all defined operation names.
*
* @since 7.0
*/
public static final Set<String> NAMES = Stream.of(MathOp.values())
.map(MathOp::toString)
.collect(Collectors.toUnmodifiableSet());
private final String _name;
private final int _arity;
private final Function<Double[], Double> _function;
MathOp(
final String name,
final int arity,
final Function<Double[], Double> function
) {
assert name != null;
assert arity >= 0;
assert function != null;
_name = name;
_function = function;
_arity = arity;
}
@Override
public int arity() {
return _arity;
}
@Override
public Double apply(final Double[] args) {
return _function.apply(args);
}
/**
* Evaluates the operation with the given arguments.
*
* @since 5.0
*
* @see #apply(Double[])
*
* @param args the operation arguments
* @return the evaluated operation
*/
public double eval(final double... args) {
return apply(box(args));
}
@Override
public String toString() {
return _name;
}
/**
* Converts the string representation of an operation to the operation
* object. It is used for converting the string representation of a tree to
* an operation tree. <b>If you use it that way, you should not forget to
* re-index the tree variables.</b>
*
* <pre>{@code
* final TreeNode<Op<Double>> tree = TreeNode.parse(
* "add(mul(x,y),sub(y,x))",
* MathOp::toMathOp
* );
*
* assert Program.eval(tree, 10.0, 5.0) == 100.0;
* Var.reindex(tree);
* assert Program.eval(tree, 10.0, 5.0) == 45.0;
* }</pre>
*
* @since 5.0
*
* @see Var#reindex(TreeNode)
* @see Program#eval(Tree, Object[])
*
* @param string the string representation of an operation which should be
* converted
* @return the operation, converted from the given string
* @throws IllegalArgumentException if the given {@code value} doesn't
* represent a mathematical expression
* @throws NullPointerException if the given string {@code value} is
* {@code null}
*/
public static Op<Double> toMathOp(final String string) {
requireNonNull(string);
final Op<Double> result;
final Optional<Const<Double>> cop = toConst(string);
if (cop.isPresent()) {
result = cop.orElseThrow(AssertionError::new);
} else {
final Optional<Op<Double>> mop = toOp(string);
result = mop.isPresent()
? mop.orElseThrow(AssertionError::new)
: Var.parse(string);
}
return result;
}
static Optional<Const<Double>> toConst(final String string) {
return Numbers.toDoubleOptional(string)
.map(Const::of);
}
private static Optional<Op<Double>> toOp(final String string) {
return Stream.of(values())
.filter(op -> Objects.equals(op._name, string))
.map(op -> (Op<Double>)op)
.findFirst();
}
}
| jenetics/jenetics | jenetics.prog/src/main/java/io/jenetics/prog/op/MathOp.java | Java | apache-2.0 | 11,985 | [
30522,
1013,
1008,
1008,
9262,
7403,
9896,
3075,
1006,
1030,
1035,
1035,
8909,
4765,
18095,
1035,
1035,
1030,
1007,
1012,
1008,
9385,
1006,
1039,
1007,
1030,
1035,
1035,
2095,
1035,
1035,
1030,
8965,
9070,
16033,
12079,
1008,
1008,
7000,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace Smartling\DbAl\Migrations;
use Smartling\Settings\ConfigurationProfileEntity;
/**
* Class Migration160603
* @package Smartling\DbAl\Migrations
*/
class Migration160603 implements SmartlingDbMigrationInterface
{
public function getVersion()
{
return 160603;
}
public function getQueries($tablePrefix = '')
{
return [
vsprintf(
'ALTER TABLE `%ssmartling_submissions` ADD COLUMN `last_error` %s',
[
$tablePrefix,
ConfigurationProfileEntity::DB_TYPE_STRING_TEXT
]
),
];
}
} | Smartling/wordpress-localization-plugin | inc/Smartling/DbAl/Migrations/Migration160603.php | PHP | gpl-3.0 | 650 | [
30522,
1026,
1029,
25718,
3415,
15327,
6047,
2989,
1032,
16962,
2389,
1032,
9230,
2015,
1025,
2224,
6047,
2989,
1032,
10906,
1032,
9563,
21572,
8873,
24129,
3775,
3723,
1025,
1013,
1008,
1008,
30524,
18939,
4328,
29397,
18447,
2121,
12172,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/bin/sh -e
usage()
{
echo "Usage: ${0} [--structure-only] DATABASE_NAME"
}
STRUCTURE_ONLY=false
if [ "${1}" = --structure-only ]; then
STRUCTURE_ONLY=true
shift
fi
DATABASE_NAME="${1}"
if [ "${DATABASE_NAME}" = "" ]; then
usage
exit 1
fi
if [ "${STRUCTURE_ONLY}" = true ]; then
FILE="${DATABASE_NAME}-structure.sql"
else
FILE="${DATABASE_NAME}-full.sql"
fi
if [ -f "${FILE}" ]; then
echo "File exists: ${FILE}"
exit 1
fi
if [ "${STRUCTURE_ONLY}" = true ]; then
mysqldump --user=root --password --protocol=tcp --no-data --databases "${DATABASE_NAME}" > "${FILE}"
else
mysqldump --user=root --password --protocol=tcp --databases "${DATABASE_NAME}" > "${FILE}"
fi
| FunTimeCoding/mysql-tools | bin/backup-database.sh | Shell | mit | 717 | [
30522,
1001,
999,
1013,
8026,
1013,
14021,
1011,
1041,
8192,
1006,
1007,
1063,
9052,
1000,
8192,
1024,
1002,
1063,
1014,
1065,
1031,
1011,
1011,
3252,
1011,
2069,
1033,
7809,
1035,
2171,
1000,
1065,
3252,
1035,
2069,
1027,
6270,
2065,
103... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* \file
*
* Copyright (c) 2012-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef _SAM4SD32C_PIO_
#define _SAM4SD32C_PIO_
#define PIO_PA0 (1u << 0) /**< \brief Pin Controlled by PA0 */
#define PIO_PA1 (1u << 1) /**< \brief Pin Controlled by PA1 */
#define PIO_PA2 (1u << 2) /**< \brief Pin Controlled by PA2 */
#define PIO_PA3 (1u << 3) /**< \brief Pin Controlled by PA3 */
#define PIO_PA4 (1u << 4) /**< \brief Pin Controlled by PA4 */
#define PIO_PA5 (1u << 5) /**< \brief Pin Controlled by PA5 */
#define PIO_PA6 (1u << 6) /**< \brief Pin Controlled by PA6 */
#define PIO_PA7 (1u << 7) /**< \brief Pin Controlled by PA7 */
#define PIO_PA8 (1u << 8) /**< \brief Pin Controlled by PA8 */
#define PIO_PA9 (1u << 9) /**< \brief Pin Controlled by PA9 */
#define PIO_PA10 (1u << 10) /**< \brief Pin Controlled by PA10 */
#define PIO_PA11 (1u << 11) /**< \brief Pin Controlled by PA11 */
#define PIO_PA12 (1u << 12) /**< \brief Pin Controlled by PA12 */
#define PIO_PA13 (1u << 13) /**< \brief Pin Controlled by PA13 */
#define PIO_PA14 (1u << 14) /**< \brief Pin Controlled by PA14 */
#define PIO_PA15 (1u << 15) /**< \brief Pin Controlled by PA15 */
#define PIO_PA16 (1u << 16) /**< \brief Pin Controlled by PA16 */
#define PIO_PA17 (1u << 17) /**< \brief Pin Controlled by PA17 */
#define PIO_PA18 (1u << 18) /**< \brief Pin Controlled by PA18 */
#define PIO_PA19 (1u << 19) /**< \brief Pin Controlled by PA19 */
#define PIO_PA20 (1u << 20) /**< \brief Pin Controlled by PA20 */
#define PIO_PA21 (1u << 21) /**< \brief Pin Controlled by PA21 */
#define PIO_PA22 (1u << 22) /**< \brief Pin Controlled by PA22 */
#define PIO_PA23 (1u << 23) /**< \brief Pin Controlled by PA23 */
#define PIO_PA24 (1u << 24) /**< \brief Pin Controlled by PA24 */
#define PIO_PA25 (1u << 25) /**< \brief Pin Controlled by PA25 */
#define PIO_PA26 (1u << 26) /**< \brief Pin Controlled by PA26 */
#define PIO_PA27 (1u << 27) /**< \brief Pin Controlled by PA27 */
#define PIO_PA28 (1u << 28) /**< \brief Pin Controlled by PA28 */
#define PIO_PA29 (1u << 29) /**< \brief Pin Controlled by PA29 */
#define PIO_PA30 (1u << 30) /**< \brief Pin Controlled by PA30 */
#define PIO_PA31 (1u << 31) /**< \brief Pin Controlled by PA31 */
#define PIO_PB0 (1u << 0) /**< \brief Pin Controlled by PB0 */
#define PIO_PB1 (1u << 1) /**< \brief Pin Controlled by PB1 */
#define PIO_PB2 (1u << 2) /**< \brief Pin Controlled by PB2 */
#define PIO_PB3 (1u << 3) /**< \brief Pin Controlled by PB3 */
#define PIO_PB4 (1u << 4) /**< \brief Pin Controlled by PB4 */
#define PIO_PB5 (1u << 5) /**< \brief Pin Controlled by PB5 */
#define PIO_PB6 (1u << 6) /**< \brief Pin Controlled by PB6 */
#define PIO_PB7 (1u << 7) /**< \brief Pin Controlled by PB7 */
#define PIO_PB8 (1u << 8) /**< \brief Pin Controlled by PB8 */
#define PIO_PB9 (1u << 9) /**< \brief Pin Controlled by PB9 */
#define PIO_PB10 (1u << 10) /**< \brief Pin Controlled by PB10 */
#define PIO_PB11 (1u << 11) /**< \brief Pin Controlled by PB11 */
#define PIO_PB12 (1u << 12) /**< \brief Pin Controlled by PB12 */
#define PIO_PB13 (1u << 13) /**< \brief Pin Controlled by PB13 */
#define PIO_PB14 (1u << 14) /**< \brief Pin Controlled by PB14 */
#define PIO_PC0 (1u << 0) /**< \brief Pin Controlled by PC0 */
#define PIO_PC1 (1u << 1) /**< \brief Pin Controlled by PC1 */
#define PIO_PC2 (1u << 2) /**< \brief Pin Controlled by PC2 */
#define PIO_PC3 (1u << 3) /**< \brief Pin Controlled by PC3 */
#define PIO_PC4 (1u << 4) /**< \brief Pin Controlled by PC4 */
#define PIO_PC5 (1u << 5) /**< \brief Pin Controlled by PC5 */
#define PIO_PC6 (1u << 6) /**< \brief Pin Controlled by PC6 */
#define PIO_PC7 (1u << 7) /**< \brief Pin Controlled by PC7 */
#define PIO_PC8 (1u << 8) /**< \brief Pin Controlled by PC8 */
#define PIO_PC9 (1u << 9) /**< \brief Pin Controlled by PC9 */
#define PIO_PC10 (1u << 10) /**< \brief Pin Controlled by PC10 */
#define PIO_PC11 (1u << 11) /**< \brief Pin Controlled by PC11 */
#define PIO_PC12 (1u << 12) /**< \brief Pin Controlled by PC12 */
#define PIO_PC13 (1u << 13) /**< \brief Pin Controlled by PC13 */
#define PIO_PC14 (1u << 14) /**< \brief Pin Controlled by PC14 */
#define PIO_PC15 (1u << 15) /**< \brief Pin Controlled by PC15 */
#define PIO_PC16 (1u << 16) /**< \brief Pin Controlled by PC16 */
#define PIO_PC17 (1u << 17) /**< \brief Pin Controlled by PC17 */
#define PIO_PC18 (1u << 18) /**< \brief Pin Controlled by PC18 */
#define PIO_PC19 (1u << 19) /**< \brief Pin Controlled by PC19 */
#define PIO_PC20 (1u << 20) /**< \brief Pin Controlled by PC20 */
#define PIO_PC21 (1u << 21) /**< \brief Pin Controlled by PC21 */
#define PIO_PC22 (1u << 22) /**< \brief Pin Controlled by PC22 */
#define PIO_PC23 (1u << 23) /**< \brief Pin Controlled by PC23 */
#define PIO_PC24 (1u << 24) /**< \brief Pin Controlled by PC24 */
#define PIO_PC25 (1u << 25) /**< \brief Pin Controlled by PC25 */
#define PIO_PC26 (1u << 26) /**< \brief Pin Controlled by PC26 */
#define PIO_PC27 (1u << 27) /**< \brief Pin Controlled by PC27 */
#define PIO_PC28 (1u << 28) /**< \brief Pin Controlled by PC28 */
#define PIO_PC29 (1u << 29) /**< \brief Pin Controlled by PC29 */
#define PIO_PC30 (1u << 30) /**< \brief Pin Controlled by PC30 */
#define PIO_PC31 (1u << 31) /**< \brief Pin Controlled by PC31 */
/* ========== Pio definition for ADC peripheral ========== */
#define PIO_PA17X1_AD0 (1u << 17) /**< \brief Adc signal: AD0 */
#define PIO_PA18X1_AD1 (1u << 18) /**< \brief Adc signal: AD1 */
#define PIO_PC13X1_AD10 (1u << 13) /**< \brief Adc signal: AD10 */
#define PIO_PC15X1_AD11 (1u << 15) /**< \brief Adc signal: AD11 */
#define PIO_PC12X1_AD12 (1u << 12) /**< \brief Adc signal: AD12 */
#define PIO_PC29X1_AD13 (1u << 29) /**< \brief Adc signal: AD13 */
#define PIO_PC30X1_AD14 (1u << 30) /**< \brief Adc signal: AD14 */
#define PIO_PA19X1_AD2 (1u << 19) /**< \brief Adc signal: AD2/WKUP9 */
#define PIO_PA19X1_WKUP9 (1u << 19) /**< \brief Adc signal: AD2/WKUP9 */
#define PIO_PA20X1_AD3 (1u << 20) /**< \brief Adc signal: AD3/WKUP10 */
#define PIO_PA20X1_WKUP10 (1u << 20) /**< \brief Adc signal: AD3/WKUP10 */
#define PIO_PB0X1_AD4 (1u << 0) /**< \brief Adc signal: AD4/RTCOUT0 */
#define PIO_PB0X1_RTCOUT0 (1u << 0) /**< \brief Adc signal: AD4/RTCOUT0 */
#define PIO_PB1X1_AD5 (1u << 1) /**< \brief Adc signal: AD5/RTCOUT1 */
#define PIO_PB1X1_RTCOUT1 (1u << 1) /**< \brief Adc signal: AD5/RTCOUT1 */
#define PIO_PB2X1_AD6 (1u << 2) /**< \brief Adc signal: AD6/WKUP12 */
#define PIO_PB2X1_WKUP12 (1u << 2) /**< \brief Adc signal: AD6/WKUP12 */
#define PIO_PB3X1_AD7 (1u << 3) /**< \brief Adc signal: AD7 */
#define PIO_PA21X1_AD8 (1u << 21) /**< \brief Adc signal: AD8 */
#define PIO_PA22X1_AD9 (1u << 22) /**< \brief Adc signal: AD9 */
#define PIO_PA8B_ADTRG (1u << 8) /**< \brief Adc signal: ADTRG */
/* ========== Pio definition for DACC peripheral ========== */
#define PIO_PB13X1_DAC0 (1u << 13) /**< \brief Dacc signal: DAC0 */
#define PIO_PB14X1_DAC1 (1u << 14) /**< \brief Dacc signal: DAC1 */
#define PIO_PA2C_DATRG (1u << 2) /**< \brief Dacc signal: DATRG */
/* ========== Pio definition for EBI peripheral ========== */
#define PIO_PC18A_A0 (1u << 18) /**< \brief Ebi signal: A0 */
#define PIO_PC19A_A1 (1u << 19) /**< \brief Ebi signal: A1 */
#define PIO_PC28A_A10 (1u << 28) /**< \brief Ebi signal: A10 */
#define PIO_PC29A_A11 (1u << 29) /**< \brief Ebi signal: A11 */
#define PIO_PC30A_A12 (1u << 30) /**< \brief Ebi signal: A12 */
#define PIO_PC31A_A13 (1u << 31) /**< \brief Ebi signal: A13 */
#define PIO_PA18C_A14 (1u << 18) /**< \brief Ebi signal: A14 */
#define PIO_PA19C_A15 (1u << 19) /**< \brief Ebi signal: A15 */
#define PIO_PA20C_A16 (1u << 20) /**< \brief Ebi signal: A16 */
#define PIO_PA0C_A17 (1u << 0) /**< \brief Ebi signal: A17 */
#define PIO_PA1C_A18 (1u << 1) /**< \brief Ebi signal: A18 */
#define PIO_PA23C_A19 (1u << 23) /**< \brief Ebi signal: A19 */
#define PIO_PC20A_A2 (1u << 20) /**< \brief Ebi signal: A2 */
#define PIO_PA24C_A20 (1u << 24) /**< \brief Ebi signal: A20 */
#define PIO_PC16A_A21 (1u << 16) /**< \brief Ebi signal: A21/NANDALE */
#define PIO_PC16A_NANDALE (1u << 16) /**< \brief Ebi signal: A21/NANDALE */
#define PIO_PC17A_A22 (1u << 17) /**< \brief Ebi signal: A22/NANDCLE */
#define PIO_PC17A_NANDCLE (1u << 17) /**< \brief Ebi signal: A22/NANDCLE */
#define PIO_PA25C_A23 (1u << 25) /**< \brief Ebi signal: A23 */
#define PIO_PC21A_A3 (1u << 21) /**< \brief Ebi signal: A3 */
#define PIO_PC22A_A4 (1u << 22) /**< \brief Ebi signal: A4 */
#define PIO_PC23A_A5 (1u << 23) /**< \brief Ebi signal: A5 */
#define PIO_PC24A_A6 (1u << 24) /**< \brief Ebi signal: A6 */
#define PIO_PC25A_A7 (1u << 25) /**< \brief Ebi signal: A7 */
#define PIO_PC26A_A8 (1u << 26) /**< \brief Ebi signal: A8 */
#define PIO_PC27A_A9 (1u << 27) /**< \brief Ebi signal: A9 */
#define PIO_PC0A_D0 (1u << 0) /**< \brief Ebi signal: D0 */
#define PIO_PC1A_D1 (1u << 1) /**< \brief Ebi signal: D1 */
#define PIO_PC2A_D2 (1u << 2) /**< \brief Ebi signal: D2 */
#define PIO_PC3A_D3 (1u << 3) /**< \brief Ebi signal: D3 */
#define PIO_PC4A_D4 (1u << 4) /**< \brief Ebi signal: D4 */
#define PIO_PC5A_D5 (1u << 5) /**< \brief Ebi signal: D5 */
#define PIO_PC6A_D6 (1u << 6) /**< \brief Ebi signal: D6 */
#define PIO_PC7A_D7 (1u << 7) /**< \brief Ebi signal: D7 */
#define PIO_PC9A_NANDOE (1u << 9) /**< \brief Ebi signal: NANDOE */
#define PIO_PC10A_NANDWE (1u << 10) /**< \brief Ebi signal: NANDWE */
#define PIO_PC14A_NCS0 (1u << 14) /**< \brief Ebi signal: NCS0 */
#define PIO_PC15A_NCS1 (1u << 15) /**< \brief Ebi signal: NCS1 */
#define PIO_PA22C_NCS2 (1u << 22) /**< \brief Ebi signal: NCS2 */
#define PIO_PC12A_NCS3 (1u << 12) /**< \brief Ebi signal: NCS3 */
#define PIO_PC11A_NRD (1u << 11) /**< \brief Ebi signal: NRD */
#define PIO_PC13A_NWAIT (1u << 13) /**< \brief Ebi signal: NWAIT */
#define PIO_PC8A_NWE (1u << 8) /**< \brief Ebi signal: NWE */
/* ========== Pio definition for HSMCI peripheral ========== */
#define PIO_PA28C_MCCDA (1u << 28) /**< \brief Hsmci signal: MCCDA */
#define PIO_PA29C_MCCK (1u << 29) /**< \brief Hsmci signal: MCCK */
#define PIO_PA30C_MCDA0 (1u << 30) /**< \brief Hsmci signal: MCDA0 */
#define PIO_PA31C_MCDA1 (1u << 31) /**< \brief Hsmci signal: MCDA1 */
#define PIO_PA26C_MCDA2 (1u << 26) /**< \brief Hsmci signal: MCDA2 */
#define PIO_PA27C_MCDA3 (1u << 27) /**< \brief Hsmci signal: MCDA3 */
/* ========== Pio definition for PIOA peripheral ========== */
#define PIO_PA24D_PIODC0 (1u << 24) /**< \brief Pioa signal: PIODC0 */
#define PIO_PA25D_PIODC1 (1u << 25) /**< \brief Pioa signal: PIODC1 */
#define PIO_PA26D_PIODC2 (1u << 26) /**< \brief Pioa signal: PIODC2 */
#define PIO_PA27D_PIODC3 (1u << 27) /**< \brief Pioa signal: PIODC3 */
#define PIO_PA28D_PIODC4 (1u << 28) /**< \brief Pioa signal: PIODC4 */
#define PIO_PA29D_PIODC5 (1u << 29) /**< \brief Pioa signal: PIODC5 */
#define PIO_PA30D_PIODC6 (1u << 30) /**< \brief Pioa signal: PIODC6 */
#define PIO_PA31D_PIODC7 (1u << 31) /**< \brief Pioa signal: PIODC7 */
#define PIO_PA23D_PIODCCLK (1u << 23) /**< \brief Pioa signal: PIODCCLK */
#define PIO_PA15D_PIODCEN1 (1u << 15) /**< \brief Pioa signal: PIODCEN1 */
#define PIO_PA16D_PIODCEN2 (1u << 16) /**< \brief Pioa signal: PIODCEN2 */
/* ========== Pio definition for PMC peripheral ========== */
#define PIO_PA6B_PCK0 (1u << 6) /**< \brief Pmc signal: PCK0 */
#define PIO_PB13B_PCK0 (1u << 13) /**< \brief Pmc signal: PCK0 */
#define PIO_PA17B_PCK1 (1u << 17) /**< \brief Pmc signal: PCK1 */
#define PIO_PA21B_PCK1 (1u << 21) /**< \brief Pmc signal: PCK1 */
#define PIO_PA18B_PCK2 (1u << 18) /**< \brief Pmc signal: PCK2 */
#define PIO_PA31B_PCK2 (1u << 31) /**< \brief Pmc signal: PCK2 */
#define PIO_PB3B_PCK2 (1u << 3) /**< \brief Pmc signal: PCK2 */
/* ========== Pio definition for PWM peripheral ========== */
#define PIO_PA9C_PWMFI0 (1u << 9) /**< \brief Pwm signal: PWMFI0 */
#define PIO_PA10C_PWMFI1 (1u << 10) /**< \brief Pwm signal: PWMFI1 */
#define PIO_PA18D_PWMFI2 (1u << 18) /**< \brief Pwm signal: PWMFI2 */
#define PIO_PA0A_PWMH0 (1u << 0) /**< \brief Pwm signal: PWMH0 */
#define PIO_PA11B_PWMH0 (1u << 11) /**< \brief Pwm signal: PWMH0 */
#define PIO_PA23B_PWMH0 (1u << 23) /**< \brief Pwm signal: PWMH0 */
#define PIO_PB0A_PWMH0 (1u << 0) /**< \brief Pwm signal: PWMH0 */
#define PIO_PC18B_PWMH0 (1u << 18) /**< \brief Pwm signal: PWMH0 */
#define PIO_PA1A_PWMH1 (1u << 1) /**< \brief Pwm signal: PWMH1 */
#define PIO_PA12B_PWMH1 (1u << 12) /**< \brief Pwm signal: PWMH1 */
#define PIO_PA24B_PWMH1 (1u << 24) /**< \brief Pwm signal: PWMH1 */
#define PIO_PB1A_PWMH1 (1u << 1) /**< \brief Pwm signal: PWMH1 */
#define PIO_PC19B_PWMH1 (1u << 19) /**< \brief Pwm signal: PWMH1 */
#define PIO_PA2A_PWMH2 (1u << 2) /**< \brief Pwm signal: PWMH2 */
#define PIO_PA13B_PWMH2 (1u << 13) /**< \brief Pwm signal: PWMH2 */
#define PIO_PA25B_PWMH2 (1u << 25) /**< \brief Pwm signal: PWMH2 */
#define PIO_PB4B_PWMH2 (1u << 4) /**< \brief Pwm signal: PWMH2 */
#define PIO_PC20B_PWMH2 (1u << 20) /**< \brief Pwm signal: PWMH2 */
#define PIO_PA7B_PWMH3 (1u << 7) /**< \brief Pwm signal: PWMH3 */
#define PIO_PA14B_PWMH3 (1u << 14) /**< \brief Pwm signal: PWMH3 */
#define PIO_PA17C_PWMH3 (1u << 17) /**< \brief Pwm signal: PWMH3 */
#define PIO_PB14B_PWMH3 (1u << 14) /**< \brief Pwm signal: PWMH3 */
#define PIO_PC21B_PWMH3 (1u << 21) /**< \brief Pwm signal: PWMH3 */
#define PIO_PA19B_PWML0 (1u << 19) /**< \brief Pwm signal: PWML0 */
#define PIO_PB5B_PWML0 (1u << 5) /**< \brief Pwm signal: PWML0 */
#define PIO_PC0B_PWML0 (1u << 0) /**< \brief Pwm signal: PWML0 */
#define PIO_PC13B_PWML0 (1u << 13) /**< \brief Pwm signal: PWML0 */
#define PIO_PA20B_PWML1 (1u << 20) /**< \brief Pwm signal: PWML1 */
#define PIO_PB12A_PWML1 (1u << 12) /**< \brief Pwm signal: PWML1 */
#define PIO_PC1B_PWML1 (1u << 1) /**< \brief Pwm signal: PWML1 */
#define PIO_PC15B_PWML1 (1u << 15) /**< \brief Pwm signal: PWML1 */
#define PIO_PA16C_PWML2 (1u << 16) /**< \brief Pwm signal: PWML2 */
#define PIO_PA30A_PWML2 (1u << 30) /**< \brief Pwm signal: PWML2 */
#define PIO_PB13A_PWML2 (1u << 13) /**< \brief Pwm signal: PWML2 */
#define PIO_PC2B_PWML2 (1u << 2) /**< \brief Pwm signal: PWML2 */
#define PIO_PA15C_PWML3 (1u << 15) /**< \brief Pwm signal: PWML3 */
#define PIO_PC3B_PWML3 (1u << 3) /**< \brief Pwm signal: PWML3 */
#define PIO_PC22B_PWML3 (1u << 22) /**< \brief Pwm signal: PWML3 */
/* ========== Pio definition for SPI peripheral ========== */
#define PIO_PA12A_MISO (1u << 12) /**< \brief Spi signal: MISO */
#define PIO_PA13A_MOSI (1u << 13) /**< \brief Spi signal: MOSI */
#define PIO_PA11A_NPCS0 (1u << 11) /**< \brief Spi signal: NPCS0 */
#define PIO_PA9B_NPCS1 (1u << 9) /**< \brief Spi signal: NPCS1 */
#define PIO_PA31A_NPCS1 (1u << 31) /**< \brief Spi signal: NPCS1 */
#define PIO_PB14A_NPCS1 (1u << 14) /**< \brief Spi signal: NPCS1 */
#define PIO_PC4B_NPCS1 (1u << 4) /**< \brief Spi signal: NPCS1 */
#define PIO_PA10B_NPCS2 (1u << 10) /**< \brief Spi signal: NPCS2 */
#define PIO_PA30B_NPCS2 (1u << 30) /**< \brief Spi signal: NPCS2 */
#define PIO_PB2B_NPCS2 (1u << 2) /**< \brief Spi signal: NPCS2 */
#define PIO_PA3B_NPCS3 (1u << 3) /**< \brief Spi signal: NPCS3 */
#define PIO_PA5B_NPCS3 (1u << 5) /**< \brief Spi signal: NPCS3 */
#define PIO_PA22B_NPCS3 (1u << 22) /**< \brief Spi signal: NPCS3 */
#define PIO_PA14A_SPCK (1u << 14) /**< \brief Spi signal: SPCK */
/* ========== Pio definition for SSC peripheral ========== */
#define PIO_PA18A_RD (1u << 18) /**< \brief Ssc signal: RD */
#define PIO_PA20A_RF (1u << 20) /**< \brief Ssc signal: RF */
#define PIO_PA19A_RK (1u << 19) /**< \brief Ssc signal: RK */
#define PIO_PA17A_TD (1u << 17) /**< \brief Ssc signal: TD */
#define PIO_PA15A_TF (1u << 15) /**< \brief Ssc signal: TF */
#define PIO_PA16A_TK (1u << 16) /**< \brief Ssc signal: TK */
/* ========== Pio definition for TC0 peripheral ========== */
#define PIO_PA4B_TCLK0 (1u << 4) /**< \brief Tc0 signal: TCLK0 */
#define PIO_PA28B_TCLK1 (1u << 28) /**< \brief Tc0 signal: TCLK1 */
#define PIO_PA29B_TCLK2 (1u << 29) /**< \brief Tc0 signal: TCLK2 */
#define PIO_PA0B_TIOA0 (1u << 0) /**< \brief Tc0 signal: TIOA0 */
#define PIO_PA15B_TIOA1 (1u << 15) /**< \brief Tc0 signal: TIOA1 */
#define PIO_PA26B_TIOA2 (1u << 26) /**< \brief Tc0 signal: TIOA2 */
#define PIO_PA1B_TIOB0 (1u << 1) /**< \brief Tc0 signal: TIOB0 */
#define PIO_PA16B_TIOB1 (1u << 16) /**< \brief Tc0 signal: TIOB1 */
#define PIO_PA27B_TIOB2 (1u << 27) /**< \brief Tc0 signal: TIOB2 */
/* ========== Pio definition for TC1 peripheral ========== */
#define PIO_PC25B_TCLK3 (1u << 25) /**< \brief Tc1 signal: TCLK3 */
#define PIO_PC28B_TCLK4 (1u << 28) /**< \brief Tc1 signal: TCLK4 */
#define PIO_PC31B_TCLK5 (1u << 31) /**< \brief Tc1 signal: TCLK5 */
#define PIO_PC23B_TIOA3 (1u << 23) /**< \brief Tc1 signal: TIOA3 */
#define PIO_PC26B_TIOA4 (1u << 26) /**< \brief Tc1 signal: TIOA4 */
#define PIO_PC29B_TIOA5 (1u << 29) /**< \brief Tc1 signal: TIOA5 */
#define PIO_PC24B_TIOB3 (1u << 24) /**< \brief Tc1 signal: TIOB3 */
#define PIO_PC27B_TIOB4 (1u << 27) /**< \brief Tc1 signal: TIOB4 */
#define PIO_PC30B_TIOB5 (1u << 30) /**< \brief Tc1 signal: TIOB5 */
/* ========== Pio definition for TWI0 peripheral ========== */
#define PIO_PA4A_TWCK0 (1u << 4) /**< \brief Twi0 signal: TWCK0 */
#define PIO_PA3A_TWD0 (1u << 3) /**< \brief Twi0 signal: TWD0 */
/* ========== Pio definition for TWI1 peripheral ========== */
#define PIO_PB5A_TWCK1 (1u << 5) /**< \brief Twi1 signal: TWCK1 */
#define PIO_PB4A_TWD1 (1u << 4) /**< \brief Twi1 signal: TWD1 */
/* ========== Pio definition for UART0 peripheral ========== */
#define PIO_PA9A_URXD0 (1u << 9) /**< \brief Uart0 signal: URXD0 */
#define PIO_PA10A_UTXD0 (1u << 10) /**< \brief Uart0 signal: UTXD0 */
/* ========== Pio definition for UART1 peripheral ========== */
#define PIO_PB2A_URXD1 (1u << 2) /**< \brief Uart1 signal: URXD1 */
#define PIO_PB3A_UTXD1 (1u << 3) /**< \brief Uart1 signal: UTXD1 */
/* ========== Pio definition for USART0 peripheral ========== */
#define PIO_PA8A_CTS0 (1u << 8) /**< \brief Usart0 signal: CTS0 */
#define PIO_PA7A_RTS0 (1u << 7) /**< \brief Usart0 signal: RTS0 */
#define PIO_PA5A_RXD0 (1u << 5) /**< \brief Usart0 signal: RXD0 */
#define PIO_PA2B_SCK0 (1u << 2) /**< \brief Usart0 signal: SCK0 */
#define PIO_PA6A_TXD0 (1u << 6) /**< \brief Usart0 signal: TXD0 */
/* ========== Pio definition for USART1 peripheral ========== */
#define PIO_PA25A_CTS1 (1u << 25) /**< \brief Usart1 signal: CTS1 */
#define PIO_PA26A_DCD1 (1u << 26) /**< \brief Usart1 signal: DCD1 */
#define PIO_PA28A_DSR1 (1u << 28) /**< \brief Usart1 signal: DSR1 */
#define PIO_PA27A_DTR1 (1u << 27) /**< \brief Usart1 signal: DTR1 */
#define PIO_PA29A_RI1 (1u << 29) /**< \brief Usart1 signal: RI1 */
#define PIO_PA24A_RTS1 (1u << 24) /**< \brief Usart1 signal: RTS1 */
#define PIO_PA21A_RXD1 (1u << 21) /**< \brief Usart1 signal: RXD1 */
#define PIO_PA23A_SCK1 (1u << 23) /**< \brief Usart1 signal: SCK1 */
#define PIO_PA22A_TXD1 (1u << 22) /**< \brief Usart1 signal: TXD1 */
/* ========== Pio indexes ========== */
#define PIO_PA0_IDX 0
#define PIO_PA1_IDX 1
#define PIO_PA2_IDX 2
#define PIO_PA3_IDX 3
#define PIO_PA4_IDX 4
#define PIO_PA5_IDX 5
#define PIO_PA6_IDX 6
#define PIO_PA7_IDX 7
#define PIO_PA8_IDX 8
#define PIO_PA9_IDX 9
#define PIO_PA10_IDX 10
#define PIO_PA11_IDX 11
#define PIO_PA12_IDX 12
#define PIO_PA13_IDX 13
#define PIO_PA14_IDX 14
#define PIO_PA15_IDX 15
#define PIO_PA16_IDX 16
#define PIO_PA17_IDX 17
#define PIO_PA18_IDX 18
#define PIO_PA19_IDX 19
#define PIO_PA20_IDX 20
#define PIO_PA21_IDX 21
#define PIO_PA22_IDX 22
#define PIO_PA23_IDX 23
#define PIO_PA24_IDX 24
#define PIO_PA25_IDX 25
#define PIO_PA26_IDX 26
#define PIO_PA27_IDX 27
#define PIO_PA28_IDX 28
#define PIO_PA29_IDX 29
#define PIO_PA30_IDX 30
#define PIO_PA31_IDX 31
#define PIO_PB0_IDX 32
#define PIO_PB1_IDX 33
#define PIO_PB2_IDX 34
#define PIO_PB3_IDX 35
#define PIO_PB4_IDX 36
#define PIO_PB5_IDX 37
#define PIO_PB6_IDX 38
#define PIO_PB7_IDX 39
#define PIO_PB8_IDX 40
#define PIO_PB9_IDX 41
#define PIO_PB10_IDX 42
#define PIO_PB11_IDX 43
#define PIO_PB12_IDX 44
#define PIO_PB13_IDX 45
#define PIO_PB14_IDX 46
#define PIO_PC0_IDX 64
#define PIO_PC1_IDX 65
#define PIO_PC2_IDX 66
#define PIO_PC3_IDX 67
#define PIO_PC4_IDX 68
#define PIO_PC5_IDX 69
#define PIO_PC6_IDX 70
#define PIO_PC7_IDX 71
#define PIO_PC8_IDX 72
#define PIO_PC9_IDX 73
#define PIO_PC10_IDX 74
#define PIO_PC11_IDX 75
#define PIO_PC12_IDX 76
#define PIO_PC13_IDX 77
#define PIO_PC14_IDX 78
#define PIO_PC15_IDX 79
#define PIO_PC16_IDX 80
#define PIO_PC17_IDX 81
#define PIO_PC18_IDX 82
#define PIO_PC19_IDX 83
#define PIO_PC20_IDX 84
#define PIO_PC21_IDX 85
#define PIO_PC22_IDX 86
#define PIO_PC23_IDX 87
#define PIO_PC24_IDX 88
#define PIO_PC25_IDX 89
#define PIO_PC26_IDX 90
#define PIO_PC27_IDX 91
#define PIO_PC28_IDX 92
#define PIO_PC29_IDX 93
#define PIO_PC30_IDX 94
#define PIO_PC31_IDX 95
#endif /* _SAM4SD32C_PIO_ */
| lazytech-org/RIOT | cpu/sam_common/include/vendor/sam4s/include/pio/pio_sam4sd32c.h | C | lgpl-2.1 | 24,785 | [
30522,
1013,
1008,
1008,
1008,
1032,
5371,
1008,
1008,
9385,
1006,
1039,
1007,
2262,
1011,
2325,
27218,
2884,
3840,
1012,
2035,
2916,
9235,
1012,
1008,
1008,
1032,
2004,
2546,
1035,
6105,
1035,
2707,
1008,
1008,
1032,
3931,
6105,
1008,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';exports.__esModule = true;var _stringify = require('babel-runtime/core-js/json/stringify');var _stringify2 = _interopRequireDefault(_stringify);var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);var _inherits2 = require('babel-runtime/helpers/inherits');var _inherits3 = _interopRequireDefault(_inherits2);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _class = function (_think$controller$bas) {(0, _inherits3.default)(_class, _think$controller$bas);function _class() {(0, _classCallCheck3.default)(this, _class);return (0, _possibleConstructorReturn3.default)(this, _think$controller$bas.apply(this, arguments));}
/**
* some base method in here
*/_class.prototype.
get = function get(key) {
if (key == undefined) {
return this.http._get;
}
return this.http._get[key];
};_class.prototype.
post = function post(key) {
if (key == undefined) {
return this.http._post;
}
return this.http._post[key];
};_class.prototype.
getCookie = function getCookie(key) {
if (key == undefined) {
return '';
}
return this.http._cookie;
};_class.prototype.
setCookie = function setCookie(key, val) {
if (typeof val !== 'string') {
val = (0, _stringify2.default)(val);
}
return this.http._cookie[key] = val;
};_class.prototype.
apiErrorHandle = function apiErrorHandle(errno) {
var API_ERROR_MSG_TABLE = {
// user
'101': '用户未登录',
'102': '用户密码错误',
'111': '密码不一致',
// category
'3000': 'Category name is empty' };
var msg = API_ERROR_MSG_TABLE[errno] || 'system error';
console.log(msg);
this.fail(errno, msg);
};return _class;}(think.controller.base);exports.default = _class; | JackPu/albums | App/user/controller/base.js | JavaScript | mit | 4,099 | [
30522,
1005,
2224,
9384,
1005,
1025,
14338,
1012,
1035,
1035,
9686,
5302,
8566,
2571,
1027,
2995,
1025,
13075,
1035,
5164,
8757,
1027,
5478,
1006,
1005,
11561,
2140,
1011,
2448,
7292,
1013,
4563,
1011,
1046,
2015,
1013,
1046,
3385,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
using Ko.Navigation.ChromiumFx.Tests.Infra;
using Tests.Universal.NavigationTests;
using Xunit;
using Xunit.Abstractions;
namespace Ko.Navigation.ChromiumFx.Tests
{
[Collection("Cfx Window Integrated")]
public class DoubleNavigation_Ko_Cfx_Tests : DoubleNavigationTests
{
public DoubleNavigation_Ko_Cfx_Tests(CfxKoContext context, ITestOutputHelper testOutputHelper)
: base(context, testOutputHelper)
{
}
}
}
| David-Desmaisons/MVVM.CEF.Glue | Tests/JavascriptFramework/Knockout/Ko.Navigation.ChromiumFx.Tests/DoubleNavigation_Ko_Cfx_Tests.cs | C# | lgpl-3.0 | 466 | [
30522,
2478,
12849,
1012,
9163,
1012,
10381,
21716,
5007,
2546,
2595,
1012,
5852,
1012,
1999,
27843,
1025,
2478,
5852,
1012,
5415,
1012,
9163,
22199,
2015,
1025,
2478,
15990,
3490,
2102,
1025,
2478,
15990,
3490,
2102,
1012,
24504,
2015,
102... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.mail;
import java.util.List;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.jvnet.mock_javamail.Mailbox;
public class MailCollectionHeaderTest extends CamelTestSupport {
@Test
public void testMailHeaderWithCollection() throws Exception {
Mailbox.clearAll();
String[] foo = new String[] {"Carlsberg", "Heineken"};
template.sendBodyAndHeader("direct:a", "Hello World", "beers", foo);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived("Hello World");
mock.message(0).header("beers").isNotNull();
mock.assertIsSatisfied();
Object beers = mock.getReceivedExchanges().get(0).getIn().getHeader("beers");
assertNotNull(beers);
List<?> list = assertIsInstanceOf(List.class, beers);
assertEquals("Carlsberg", list.get(0));
assertEquals("Heineken", list.get(1));
}
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("direct:a").to("smtp://localhost?username=james@localhost");
from("pop3://localhost?username=james&password=secret&consumer.initialDelay=100&consumer.delay=100").to("mock:result");
}
};
}
}
| kevinearls/camel | components/camel-mail/src/test/java/org/apache/camel/component/mail/MailCollectionHeaderTest.java | Java | apache-2.0 | 2,329 | [
30522,
1013,
1008,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
2030,
2062,
1008,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
5500,
2007,
1008,
2023,
2147,
2005,
3176,
2592,
4953,
9385,
6095,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# extension imports
from _NetworKit import PageRankNibble, GCE | fmaschler/networkit | networkit/scd.py | Python | mit | 62 | [
30522,
1001,
5331,
17589,
2013,
1035,
2897,
4183,
12324,
3931,
26763,
3490,
11362,
1010,
1043,
3401,
102,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Copyright 2019 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=invalid-name
# pylint: disable=missing-docstring
"""EfficientNet models for Keras.
Reference:
- [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](
https://arxiv.org/abs/1905.11946) (ICML 2019)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import math
from tensorflow.python.keras import backend
from tensorflow.python.keras.applications import imagenet_utils
from tensorflow.python.keras.engine import training
from tensorflow.python.keras.layers import VersionAwareLayers
from tensorflow.python.keras.utils import data_utils
from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.lib.io import file_io
from tensorflow.python.util.tf_export import keras_export
BASE_WEIGHTS_PATH = 'https://storage.googleapis.com/keras-applications/'
WEIGHTS_HASHES = {
'b0': ('902e53a9f72be733fc0bcb005b3ebbac',
'50bc09e76180e00e4465e1a485ddc09d'),
'b1': ('1d254153d4ab51201f1646940f018540',
'74c4e6b3e1f6a1eea24c589628592432'),
'b2': ('b15cce36ff4dcbd00b6dd88e7857a6ad',
'111f8e2ac8aa800a7a99e3239f7bfb39'),
'b3': ('ffd1fdc53d0ce67064dc6a9c7960ede0',
'af6d107764bb5b1abb91932881670226'),
'b4': ('18c95ad55216b8f92d7e70b3a046e2fc',
'ebc24e6d6c33eaebbd558eafbeedf1ba'),
'b5': ('ace28f2a6363774853a83a0b21b9421a',
'38879255a25d3c92d5e44e04ae6cec6f'),
'b6': ('165f6e37dce68623721b423839de8be5',
'9ecce42647a20130c1f39a5d4cb75743'),
'b7': ('8c03f828fec3ef71311cd463b6759d99',
'cbcfe4450ddf6f3ad90b1b398090fe4a'),
}
DEFAULT_BLOCKS_ARGS = [{
'kernel_size': 3,
'repeats': 1,
'filters_in': 32,
'filters_out': 16,
'expand_ratio': 1,
'id_skip': True,
'strides': 1,
'se_ratio': 0.25
}, {
'kernel_size': 3,
'repeats': 2,
'filters_in': 16,
'filters_out': 24,
'expand_ratio': 6,
'id_skip': True,
'strides': 2,
'se_ratio': 0.25
}, {
'kernel_size': 5,
'repeats': 2,
'filters_in': 24,
'filters_out': 40,
'expand_ratio': 6,
'id_skip': True,
'strides': 2,
'se_ratio': 0.25
}, {
'kernel_size': 3,
'repeats': 3,
'filters_in': 40,
'filters_out': 80,
'expand_ratio': 6,
'id_skip': True,
'strides': 2,
'se_ratio': 0.25
}, {
'kernel_size': 5,
'repeats': 3,
'filters_in': 80,
'filters_out': 112,
'expand_ratio': 6,
'id_skip': True,
'strides': 1,
'se_ratio': 0.25
}, {
'kernel_size': 5,
'repeats': 4,
'filters_in': 112,
'filters_out': 192,
'expand_ratio': 6,
'id_skip': True,
'strides': 2,
'se_ratio': 0.25
}, {
'kernel_size': 3,
'repeats': 1,
'filters_in': 192,
'filters_out': 320,
'expand_ratio': 6,
'id_skip': True,
'strides': 1,
'se_ratio': 0.25
}]
CONV_KERNEL_INITIALIZER = {
'class_name': 'VarianceScaling',
'config': {
'scale': 2.0,
'mode': 'fan_out',
'distribution': 'truncated_normal'
}
}
DENSE_KERNEL_INITIALIZER = {
'class_name': 'VarianceScaling',
'config': {
'scale': 1. / 3.,
'mode': 'fan_out',
'distribution': 'uniform'
}
}
layers = VersionAwareLayers()
BASE_DOCSTRING = """Instantiates the {name} architecture.
Reference:
- [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](
https://arxiv.org/abs/1905.11946) (ICML 2019)
Optionally loads weights pre-trained on ImageNet.
Note that the data format convention used by the model is
the one specified in your Keras config at `~/.keras/keras.json`.
If you have never configured it, it defaults to `"channels_last"`.
Arguments:
include_top: Whether to include the fully-connected
layer at the top of the network. Defaults to True.
weights: One of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor: Optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: Optional shape tuple, only to be specified
if `include_top` is False.
It should have exactly 3 inputs channels.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`. Defaults to None.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional layer.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: Optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified. Defaults to 1000 (number of
ImageNet classes).
classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
Defaults to 'softmax'.
Returns:
A `keras.Model` instance.
"""
def EfficientNet(
width_coefficient,
depth_coefficient,
default_size,
dropout_rate=0.2,
drop_connect_rate=0.2,
depth_divisor=8,
activation='swish',
blocks_args='default',
model_name='efficientnet',
include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax'):
"""Instantiates the EfficientNet architecture using given scaling coefficients.
Reference:
- [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](
https://arxiv.org/abs/1905.11946) (ICML 2019)
Optionally loads weights pre-trained on ImageNet.
Note that the data format convention used by the model is
the one specified in your Keras config at `~/.keras/keras.json`.
Arguments:
width_coefficient: float, scaling coefficient for network width.
depth_coefficient: float, scaling coefficient for network depth.
default_size: integer, default input image size.
dropout_rate: float, dropout rate before final classifier layer.
drop_connect_rate: float, dropout rate at skip connections.
depth_divisor: integer, a unit of network width.
activation: activation function.
blocks_args: list of dicts, parameters to construct block modules.
model_name: string, model name.
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False.
It should have exactly 3 inputs channels.
pooling: optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional layer.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
Returns:
A `keras.Model` instance.
Raises:
ValueError: in case of invalid argument for `weights`,
or invalid input shape.
ValueError: if `classifier_activation` is not `softmax` or `None` when
using a pretrained top layer.
"""
if blocks_args == 'default':
blocks_args = DEFAULT_BLOCKS_ARGS
if not (weights in {'imagenet', None} or file_io.file_exists_v2(weights)):
raise ValueError('The `weights` argument should be either '
'`None` (random initialization), `imagenet` '
'(pre-training on ImageNet), '
'or the path to the weights file to be loaded.')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as `"imagenet"` with `include_top`'
' as true, `classes` should be 1000')
# Determine proper input shape
input_shape = imagenet_utils.obtain_input_shape(
input_shape,
default_size=default_size,
min_size=32,
data_format=backend.image_data_format(),
require_flatten=include_top,
weights=weights)
if input_tensor is None:
img_input = layers.Input(shape=input_shape)
else:
if not backend.is_keras_tensor(input_tensor):
img_input = layers.Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1
def round_filters(filters, divisor=depth_divisor):
"""Round number of filters based on depth multiplier."""
filters *= width_coefficient
new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_filters < 0.9 * filters:
new_filters += divisor
return int(new_filters)
def round_repeats(repeats):
"""Round number of repeats based on depth multiplier."""
return int(math.ceil(depth_coefficient * repeats))
# Build stem
x = img_input
x = layers.Rescaling(1. / 255.)(x)
x = layers.Normalization(axis=bn_axis)(x)
x = layers.ZeroPadding2D(
padding=imagenet_utils.correct_pad(x, 3),
name='stem_conv_pad')(x)
x = layers.Conv2D(
round_filters(32),
3,
strides=2,
padding='valid',
use_bias=False,
kernel_initializer=CONV_KERNEL_INITIALIZER,
name='stem_conv')(x)
x = layers.BatchNormalization(axis=bn_axis, name='stem_bn')(x)
x = layers.Activation(activation, name='stem_activation')(x)
# Build blocks
blocks_args = copy.deepcopy(blocks_args)
b = 0
blocks = float(sum(round_repeats(args['repeats']) for args in blocks_args))
for (i, args) in enumerate(blocks_args):
assert args['repeats'] > 0
# Update block input and output filters based on depth multiplier.
args['filters_in'] = round_filters(args['filters_in'])
args['filters_out'] = round_filters(args['filters_out'])
for j in range(round_repeats(args.pop('repeats'))):
# The first block needs to take care of stride and filter size increase.
if j > 0:
args['strides'] = 1
args['filters_in'] = args['filters_out']
x = block(
x,
activation,
drop_connect_rate * b / blocks,
name='block{}{}_'.format(i + 1, chr(j + 97)),
**args)
b += 1
# Build top
x = layers.Conv2D(
round_filters(1280),
1,
padding='same',
use_bias=False,
kernel_initializer=CONV_KERNEL_INITIALIZER,
name='top_conv')(x)
x = layers.BatchNormalization(axis=bn_axis, name='top_bn')(x)
x = layers.Activation(activation, name='top_activation')(x)
if include_top:
x = layers.GlobalAveragePooling2D(name='avg_pool')(x)
if dropout_rate > 0:
x = layers.Dropout(dropout_rate, name='top_dropout')(x)
imagenet_utils.validate_activation(classifier_activation, weights)
x = layers.Dense(
classes,
activation=classifier_activation,
kernel_initializer=DENSE_KERNEL_INITIALIZER,
name='predictions')(x)
else:
if pooling == 'avg':
x = layers.GlobalAveragePooling2D(name='avg_pool')(x)
elif pooling == 'max':
x = layers.GlobalMaxPooling2D(name='max_pool')(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = layer_utils.get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = training.Model(inputs, x, name=model_name)
# Load weights.
if weights == 'imagenet':
if include_top:
file_suffix = '.h5'
file_hash = WEIGHTS_HASHES[model_name[-2:]][0]
else:
file_suffix = '_notop.h5'
file_hash = WEIGHTS_HASHES[model_name[-2:]][1]
file_name = model_name + file_suffix
weights_path = data_utils.get_file(
file_name,
BASE_WEIGHTS_PATH + file_name,
cache_subdir='models',
file_hash=file_hash)
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
return model
def block(inputs,
activation='swish',
drop_rate=0.,
name='',
filters_in=32,
filters_out=16,
kernel_size=3,
strides=1,
expand_ratio=1,
se_ratio=0.,
id_skip=True):
"""An inverted residual block.
Arguments:
inputs: input tensor.
activation: activation function.
drop_rate: float between 0 and 1, fraction of the input units to drop.
name: string, block label.
filters_in: integer, the number of input filters.
filters_out: integer, the number of output filters.
kernel_size: integer, the dimension of the convolution window.
strides: integer, the stride of the convolution.
expand_ratio: integer, scaling coefficient for the input filters.
se_ratio: float between 0 and 1, fraction to squeeze the input filters.
id_skip: boolean.
Returns:
output tensor for the block.
"""
bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1
# Expansion phase
filters = filters_in * expand_ratio
if expand_ratio != 1:
x = layers.Conv2D(
filters,
1,
padding='same',
use_bias=False,
kernel_initializer=CONV_KERNEL_INITIALIZER,
name=name + 'expand_conv')(
inputs)
x = layers.BatchNormalization(axis=bn_axis, name=name + 'expand_bn')(x)
x = layers.Activation(activation, name=name + 'expand_activation')(x)
else:
x = inputs
# Depthwise Convolution
if strides == 2:
x = layers.ZeroPadding2D(
padding=imagenet_utils.correct_pad(x, kernel_size),
name=name + 'dwconv_pad')(x)
conv_pad = 'valid'
else:
conv_pad = 'same'
x = layers.DepthwiseConv2D(
kernel_size,
strides=strides,
padding=conv_pad,
use_bias=False,
depthwise_initializer=CONV_KERNEL_INITIALIZER,
name=name + 'dwconv')(x)
x = layers.BatchNormalization(axis=bn_axis, name=name + 'bn')(x)
x = layers.Activation(activation, name=name + 'activation')(x)
# Squeeze and Excitation phase
if 0 < se_ratio <= 1:
filters_se = max(1, int(filters_in * se_ratio))
se = layers.GlobalAveragePooling2D(name=name + 'se_squeeze')(x)
se = layers.Reshape((1, 1, filters), name=name + 'se_reshape')(se)
se = layers.Conv2D(
filters_se,
1,
padding='same',
activation=activation,
kernel_initializer=CONV_KERNEL_INITIALIZER,
name=name + 'se_reduce')(
se)
se = layers.Conv2D(
filters,
1,
padding='same',
activation='sigmoid',
kernel_initializer=CONV_KERNEL_INITIALIZER,
name=name + 'se_expand')(se)
x = layers.multiply([x, se], name=name + 'se_excite')
# Output phase
x = layers.Conv2D(
filters_out,
1,
padding='same',
use_bias=False,
kernel_initializer=CONV_KERNEL_INITIALIZER,
name=name + 'project_conv')(x)
x = layers.BatchNormalization(axis=bn_axis, name=name + 'project_bn')(x)
if id_skip and strides == 1 and filters_in == filters_out:
if drop_rate > 0:
x = layers.Dropout(
drop_rate, noise_shape=(None, 1, 1, 1), name=name + 'drop')(x)
x = layers.add([x, inputs], name=name + 'add')
return x
@keras_export('keras.applications.efficientnet.EfficientNetB0',
'keras.applications.EfficientNetB0')
def EfficientNetB0(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.0,
1.0,
224,
0.2,
model_name='efficientnetb0',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB1',
'keras.applications.EfficientNetB1')
def EfficientNetB1(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.0,
1.1,
240,
0.2,
model_name='efficientnetb1',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB2',
'keras.applications.EfficientNetB2')
def EfficientNetB2(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.1,
1.2,
260,
0.3,
model_name='efficientnetb2',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB3',
'keras.applications.EfficientNetB3')
def EfficientNetB3(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.2,
1.4,
300,
0.3,
model_name='efficientnetb3',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB4',
'keras.applications.EfficientNetB4')
def EfficientNetB4(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.4,
1.8,
380,
0.4,
model_name='efficientnetb4',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB5',
'keras.applications.EfficientNetB5')
def EfficientNetB5(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.6,
2.2,
456,
0.4,
model_name='efficientnetb5',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB6',
'keras.applications.EfficientNetB6')
def EfficientNetB6(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
1.8,
2.6,
528,
0.5,
model_name='efficientnetb6',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
@keras_export('keras.applications.efficientnet.EfficientNetB7',
'keras.applications.EfficientNetB7')
def EfficientNetB7(include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation='softmax',
**kwargs):
return EfficientNet(
2.0,
3.1,
600,
0.5,
model_name='efficientnetb7',
include_top=include_top,
weights=weights,
input_tensor=input_tensor,
input_shape=input_shape,
pooling=pooling,
classes=classes,
classifier_activation=classifier_activation,
**kwargs)
EfficientNetB0.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB0')
EfficientNetB1.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB1')
EfficientNetB2.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB2')
EfficientNetB3.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB3')
EfficientNetB4.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB4')
EfficientNetB5.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB5')
EfficientNetB6.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB6')
EfficientNetB7.__doc__ = BASE_DOCSTRING.format(name='EfficientNetB7')
@keras_export('keras.applications.efficientnet.preprocess_input')
def preprocess_input(x, data_format=None): # pylint: disable=unused-argument
return x
@keras_export('keras.applications.efficientnet.decode_predictions')
def decode_predictions(preds, top=5):
return imagenet_utils.decode_predictions(preds, top=top)
decode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__
| karllessard/tensorflow | tensorflow/python/keras/applications/efficientnet.py | Python | apache-2.0 | 24,166 | [
30522,
1001,
9385,
10476,
1996,
23435,
12314,
6048,
1012,
2035,
2916,
9235,
1012,
1001,
1001,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
1012,
1014,
1006,
1996,
1000,
6105,
1000,
1007,
1025,
1001,
2017,
2089,
2025,
2224,
2023,
5371,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#ifndef AUTOBOOST_MPL_LIST_LIST40_C_HPP_INCLUDED
#define AUTOBOOST_MPL_LIST_LIST40_C_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#if !defined(AUTOBOOST_MPL_PREPROCESSING_MODE)
# include <autoboost/mpl/list/list30_c.hpp>
#endif
#include <autoboost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(AUTOBOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(AUTOBOOST_MPL_PREPROCESSING_MODE)
# define AUTOBOOST_MPL_PREPROCESSED_HEADER list40_c.hpp
# include <autoboost/mpl/list/aux_/include_preprocessed.hpp>
#else
# include <autoboost/preprocessor/iterate.hpp>
namespace autoboost { namespace mpl {
# define AUTOBOOST_PP_ITERATION_PARAMS_1 \
(3,(31, 40, <autoboost/mpl/list/aux_/numbered_c.hpp>))
# include AUTOBOOST_PP_ITERATE()
}}
#endif // AUTOBOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // AUTOBOOST_MPL_LIST_LIST40_C_HPP_INCLUDED
| codemercenary/autowiring | contrib/autoboost/autoboost/mpl/list/list40_c.hpp | C++ | apache-2.0 | 1,124 | [
30522,
1001,
2065,
13629,
2546,
8285,
5092,
14122,
1035,
6131,
2140,
1035,
2862,
1035,
2862,
12740,
1035,
1039,
1035,
6522,
2361,
1035,
2443,
1001,
9375,
8285,
5092,
14122,
1035,
6131,
2140,
1035,
2862,
1035,
2862,
12740,
1035,
1039,
1035,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# truffle-flattener
[](https://www.npmjs.com/package/truffle-flattener)
Truffle Flattener concats solidity files developed under Truffle with all of
their dependencies.
This tool helps you to verify contracts developed with Truffle on
[Etherscan](https://etherscan.io), or debugging them on
[Remix](https://remix.ethereum.org), by merging your files and their
dependencies in the right order.
Check out [Buidler](https://github.com/nomiclabs/buidler), our alternative to
Truffle. It's got flattening built-in, it's faster, and much more flexible.
# Installation
`npm install truffle-flattener -g`
# Usage
Just intall it with npm in your truffle project and run
`truffle-flattener <solidity-files>`.
# Why not [Solidity Flattener](https://github.com/BlockCatIO/solidity-flattener)?
This project is a [Truffle](https://github.com/trufflesuite/truffle) specific
reimplementation of Solidity Flattener. By being closely coupled to Truffle it
can take advantage of its dependencies resolution logic making `--solc-paths` a
thing of the past. It also supports flattening more than one file at once,
concatenating everything in the right order, whithout duplicating any file.
# Limitations
If you deploy your contracts with truffle's migrations the output of
`truffle-flattener` may not match while verifying it in Etherscan. You
can use [Solidity Flattener](https://github.com/BlockCatIO/solidity-flattener)
in that case, or deploy your contracts from [Remix](https://remix.ethereum.org).
Aliased imports (eg: `import {symbol1 as alias, symbol2} from "filename";`) are
not supported by `truffle-flattener`.
| alcuadrado/truffle-flattener | README.md | Markdown | mit | 1,673 | [
30522,
1001,
19817,
16093,
21031,
1011,
4257,
6528,
2121,
1031,
999,
1031,
27937,
2213,
1033,
1006,
16770,
1024,
1013,
1013,
10047,
2290,
1012,
11824,
1012,
22834,
1013,
27937,
2213,
1013,
1058,
1013,
19817,
16093,
21031,
1011,
4257,
6528,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2014 Vincent Sanders <vince@netsurf-browser.org>
*
* This file is part of NetSurf, http://www.netsurf-browser.org/
*
* NetSurf 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; version 2 of the License.
*
* NetSurf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
*
* Interface to core interface table.
*
* \note must not be used by frontends directly.
*/
#ifndef _NETSURF_DESKTOP_GUI_INTERNAL_H_
#define _NETSURF_DESKTOP_GUI_INTERNAL_H_
#include "desktop/gui_table.h"
/**
* The global operation table.
*/
extern struct netsurf_table *guit;
#endif
| ashmew2/nskolibrios | netsurf/desktop/gui_internal.h | C | gpl-2.0 | 1,036 | [
30522,
1013,
1008,
1008,
9385,
2297,
6320,
12055,
1026,
12159,
1030,
16996,
3126,
2546,
1011,
16602,
1012,
8917,
1028,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
16996,
3126,
2546,
1010,
8299,
1024,
1013,
1013,
7479,
1012,
16996,
3126,
2546,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.gradle.test.performance.mediummonolithicjavaproject.p428;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test8570 {
Production8570 objectUnderTest = new Production8570();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p428/Test8570.java | Java | apache-2.0 | 2,111 | [
30522,
7427,
8917,
1012,
24665,
4215,
2571,
1012,
3231,
1012,
2836,
1012,
5396,
8202,
10893,
23048,
3900,
3567,
21572,
20614,
1012,
1052,
20958,
2620,
1025,
12324,
8917,
1012,
12022,
4183,
1012,
3231,
1025,
12324,
10763,
8917,
1012,
12022,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.apache.maven.plugin.assembly.archive.task;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import junit.framework.TestCase;
import org.apache.maven.plugin.assembly.archive.ArchiveCreationException;
import org.apache.maven.plugin.assembly.testutils.TestFileManager;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.FileSet;
import org.easymock.classextension.EasyMockSupport;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.expect;
public class AddDirectoryTaskTest
extends TestCase
{
private EasyMockSupport mockManager;
private TestFileManager fileManager;
private Archiver archiver;
public void setUp()
{
fileManager = new TestFileManager( "ArchiveAssemblyUtils.test.", "" );
mockManager = new EasyMockSupport();
archiver = mockManager.createMock(Archiver.class);
}
public void tearDown()
throws IOException
{
fileManager.cleanUp();
}
public void testAddDirectory_ShouldNotAddDirectoryIfNonExistent()
throws ArchiveCreationException
{
File dir = new File( System.getProperty( "java.io.tmpdir" ), "non-existent." + System.currentTimeMillis() );
configureModeExpectations( -1, -1, -1, -1, false );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.execute( archiver );
mockManager.verifyAll();
}
public void testAddDirectory_ShouldAddDirectory()
throws ArchiveCreationException
{
File dir = fileManager.createTempDir();
try
{
archiver.addFileSet( (FileSet) anyObject() );
}
catch ( ArchiverException e )
{
fail( "Should never happen." );
}
configureModeExpectations( -1, -1, -1, -1, false );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.setOutputDirectory( "dir" );
task.execute( archiver );
mockManager.verifyAll();
}
public void testAddDirectory_ShouldAddDirectoryWithDirMode()
throws ArchiveCreationException
{
File dir = fileManager.createTempDir();
try
{
archiver.addFileSet( (FileSet) anyObject() );
}
catch ( ArchiverException e )
{
fail( "Should never happen." );
}
int dirMode = Integer.parseInt( "777", 8 );
int fileMode = Integer.parseInt( "777", 8 );
configureModeExpectations( -1, -1, dirMode, fileMode, true );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.setDirectoryMode( dirMode );
task.setFileMode( fileMode );
task.setOutputDirectory( "dir" );
task.execute( archiver );
mockManager.verifyAll();
}
public void testAddDirectory_ShouldAddDirectoryWithIncludesAndExcludes()
throws ArchiveCreationException
{
File dir = fileManager.createTempDir();
try
{
archiver.addFileSet( (FileSet) anyObject() );
}
catch ( ArchiverException e )
{
fail( "Should never happen." );
}
configureModeExpectations( -1, -1, -1, -1, false );
mockManager.replayAll();
AddDirectoryTask task = new AddDirectoryTask( dir );
task.setIncludes( Collections.singletonList( "**/*.txt" ) );
task.setExcludes( Collections.singletonList( "**/README.txt" ) );
task.setOutputDirectory( "dir" );
task.execute( archiver );
mockManager.verifyAll();
}
private void configureModeExpectations( int defaultDirMode, int defaultFileMode, int dirMode, int fileMode,
boolean expectTwoSets )
{
expect(archiver.getOverrideDirectoryMode()).andReturn( defaultDirMode );
expect(archiver.getOverrideFileMode()).andReturn( defaultFileMode );
if ( expectTwoSets )
{
if ( dirMode > -1 )
{
archiver.setDirectoryMode( dirMode );
}
if ( fileMode > -1 )
{
archiver.setFileMode( fileMode );
}
}
if ( dirMode > -1 )
{
archiver.setDirectoryMode( defaultDirMode );
}
if ( fileMode > -1 )
{
archiver.setFileMode( defaultFileMode );
}
}
}
| kikinteractive/maven-plugins | maven-assembly-plugin/src/test/java/org/apache/maven/plugin/assembly/archive/task/AddDirectoryTaskTest.java | Java | apache-2.0 | 5,455 | [
30522,
7427,
8917,
1012,
15895,
1012,
5003,
8159,
1012,
13354,
2378,
1012,
3320,
1012,
8756,
1012,
4708,
1025,
1013,
1008,
1008,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
1008,
2030,
2062,
12130,
6105,
10540,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* @file
* CSS for Cesium Cartesian3.
*/
div.form-item table .form-type-textfield,
div.form-item table .form-type-textfield * {
display: inline-block;
}
| maikuru/cesium-drupal | cesium_cartesian3/cesium_cartesian3.css | CSS | apache-2.0 | 163 | [
30522,
1013,
1008,
1008,
1008,
1030,
5371,
1008,
20116,
2015,
2005,
8292,
5332,
2819,
11122,
25253,
2509,
1012,
1008,
1013,
4487,
2615,
1012,
2433,
1011,
8875,
2795,
1012,
2433,
1011,
2828,
1011,
3793,
3790,
1010,
4487,
2615,
1012,
2433,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!--- Licensed to the Apache Software Foundation (ASF) under one -->
<!--- or more contributor license agreements. See the NOTICE file -->
<!--- distributed with this work for additional information -->
<!--- regarding copyright ownership. The ASF licenses this file -->
<!--- to you under the Apache License, Version 2.0 (the -->
<!--- "License"); you may not use this file except in compliance -->
<!--- with the License. You may obtain a copy of the License at -->
<!--- http://www.apache.org/licenses/LICENSE-2.0 -->
<!--- Unless required by applicable law or agreed to in writing, -->
<!--- software distributed under the License is distributed on an -->
<!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->
<!--- KIND, either express or implied. See the License for the -->
<!--- specific language governing permissions and limitations -->
<!--- under the License. -->
# Running inference on MXNet/Gluon from an ONNX model
[Open Neural Network Exchange (ONNX)](https://github.com/onnx/onnx) provides an open source format for AI models. It defines an extensible computation graph model, as well as definitions of built-in operators and standard data types.
In this tutorial we will:
- learn how to load a pre-trained .onnx model file into MXNet/Gluon
- learn how to test this model using the sample input/output
- learn how to test the model on custom images
## Pre-requisite
To run the tutorial you will need to have installed the following python modules:
- [MXNet > 1.1.0](https://mxnet.apache.org/get_started)
- [onnx](https://github.com/onnx/onnx) (follow the install guide)
- matplotlib
```{.python .input}
import numpy as np
import mxnet as mx
from mxnet.contrib import onnx as onnx_mxnet
from mxnet import gluon, nd
%matplotlib inline
import matplotlib.pyplot as plt
import tarfile, os
import json
import logging
logging.basicConfig(level=logging.INFO)
```
### Downloading supporting files
These are images and a vizualisation script
```{.python .input}
image_folder = "images"
utils_file = "utils.py" # contain utils function to plot nice visualization
image_net_labels_file = "image_net_labels.json"
images = ['apron.jpg', 'hammerheadshark.jpg', 'dog.jpg', 'wrench.jpg', 'dolphin.jpg', 'lotus.jpg']
base_url = "https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/doc/tutorials/onnx/{}?raw=true"
for image in images:
mx.test_utils.download(base_url.format("{}/{}".format(image_folder, image)), fname=image,dirname=image_folder)
mx.test_utils.download(base_url.format(utils_file), fname=utils_file)
mx.test_utils.download(base_url.format(image_net_labels_file), fname=image_net_labels_file)
from utils import *
```
## Downloading a model from the ONNX model zoo
We download a pre-trained model, in our case the [GoogleNet](https://arxiv.org/abs/1409.4842) model, trained on [ImageNet](http://www.image-net.org/) from the [ONNX model zoo](https://github.com/onnx/models). The model comes packaged in an archive `tar.gz` file containing an `model.onnx` model file.
```{.python .input}
base_url = "https://s3.amazonaws.com/download.onnx/models/opset_3/"
current_model = "bvlc_googlenet"
model_folder = "model"
archive = "{}.tar.gz".format(current_model)
archive_file = os.path.join(model_folder, archive)
url = "{}{}".format(base_url, archive)
```
Download and extract pre-trained model
```{.python .input}
mx.test_utils.download(url, dirname = model_folder)
if not os.path.isdir(os.path.join(model_folder, current_model)):
print('Extracting model...')
tar = tarfile.open(archive_file, "r:gz")
tar.extractall(model_folder)
tar.close()
print('Extracted')
```
The models have been pre-trained on ImageNet, let's load the label mapping of the 1000 classes.
```{.python .input}
categories = json.load(open(image_net_labels_file, 'r'))
```
## Loading the model into MXNet Gluon
```{.python .input}
onnx_path = os.path.join(model_folder, current_model, "model.onnx")
```
We get the symbol and parameter objects
```{.python .input}
sym, arg_params, aux_params = onnx_mxnet.import_model(onnx_path)
```
We pick a device, CPU is fine for inference, switch to mx.gpu() if you want to use your GPU.
```{.python .input}
device = mx.cpu()
```
We obtain the data names of the inputs to the model by using the model metadata API:
```{.python .input}
model_metadata = onnx_mxnet.get_model_metadata(onnx_path)
print(model_metadata)
```
```
{'output_tensor_data': [(u'gpu_0/softmax_1', (1L, 1000L))],
'input_tensor_data': [(u'gpu_0/data_0', (1L, 3L, 224L, 224L))]}
```
```{.python .input}
data_names = [inputs[0] for inputs in model_metadata.get('input_tensor_data')]
print(data_names)
```
And load them into a MXNet Gluon symbol block.
```{.python .input}
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
net = gluon.nn.SymbolBlock(outputs=sym, inputs=mx.sym.var('data_0'))
net_params = net.collect_params()
for param in arg_params:
if param in net_params:
net_params[param]._load_init(arg_params[param], device=device)
for param in aux_params:
if param in net_params:
net_params[param]._load_init(aux_params[param], device=device)
```
We can now cache the computational graph through [hybridization](https://mxnet.apache.org/versions/master/api/python/docs/tutorials/packages/gluon/blocks/hybridize.html) to gain some performance
```{.python .input}
net.hybridize()
```
We can visualize the network (requires graphviz installed)
```{.python .input}
mx.visualization.plot_network(sym, node_attrs={"shape":"oval","fixedsize":"false"})
```
<!--notebook-skip-line-->
This is a helper function to run M batches of data of batch-size N through the net and collate the outputs into an array of shape (K, 1000) where K=MxN is the total number of examples (mumber of batches x batch-size) run through the network.
```{.python .input}
def run_batch(net, data):
results = []
for batch in data:
outputs = net(batch)
results.extend([o for o in outputs.asnumpy()])
return np.array(results)
```
## Test using real images
```{.python .input}
TOP_P = 3 # How many top guesses we show in the visualization
```
Transform function to set the data into the format the network expects, (N, 3, 224, 224) where N is the batch size.
```{.python .input}
def transform(img):
return np.expand_dims(np.transpose(img, (2,0,1)),axis=0).astype(np.float32)
```
We load two sets of images in memory
```{.python .input}
image_net_images = [plt.imread('{}/{}.jpg'.format(image_folder, path)) for path in ['apron', 'hammerheadshark','dog']]
caltech101_images = [plt.imread('{}/{}.jpg'.format(image_folder, path)) for path in ['wrench', 'dolphin','lotus']]
images = image_net_images + caltech101_images
```
And run them as a batch through the network to get the predictions
```{.python .input}
batch = nd.array(np.concatenate([transform(img) for img in images], axis=0), device=device)
result = run_batch(net, [batch])
```
```{.python .input}
plot_predictions(image_net_images, result[:3], categories, TOP_P)
```
<!--notebook-skip-line-->
**Well done!** Looks like it is doing a pretty good job at classifying pictures when the category is a ImageNet label
Let's now see the results on the 3 other images
```{.python .input}
plot_predictions(caltech101_images, result[3:7], categories, TOP_P)
```
<!--notebook-skip-line-->
**Hmm, not so good...** Even though predictions are close, they are not accurate, which is due to the fact that the ImageNet dataset does not contain `wrench`, `dolphin`, or `lotus` categories and our network has been trained on ImageNet.
Lucky for us, the [Caltech101 dataset](http://www.vision.caltech.edu/Image_Datasets/Caltech101/) has them, let's see how we can fine-tune our network to classify these categories correctly.
We show that in our next tutorial:
- [Fine-tuning an ONNX Model using the modern imperative MXNet/Gluon](https://mxnet.apache.org/versions/master/api/python/docs/tutorials/packages/onnx/fine_tuning_gluon.html)
<!-- INSERT SOURCE DOWNLOAD BUTTONS -->
| szha/mxnet | docs/python_docs/python/tutorials/packages/onnx/inference_on_onnx_model.md | Markdown | apache-2.0 | 8,432 | [
30522,
1026,
999,
1011,
1011,
1011,
7000,
2000,
1996,
15895,
4007,
3192,
1006,
2004,
2546,
1007,
2104,
2028,
1011,
1011,
1028,
1026,
999,
1011,
1011,
1011,
2030,
2062,
12130,
6105,
10540,
1012,
2156,
1996,
5060,
5371,
1011,
1011,
1028,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Background sketch
* Author: Uriel Sade
* Date: Feb. 22, 2017
*/
var canvas;
var time_x, time_y, time_z, time_inc;
var field = [];
var particles = [];
var rows, cols;
var scl = 20;
function setup() {
canvas = createCanvas(windowWidth, windowHeight);
canvas.position(0,0);
canvas.style('z-value', '-1');
canvas.style('opacity', '0.99');
background(0,0,0,0);
rows = 25;
scl = floor(height/rows);
cols = floor(width/scl);
time_inc = 0.2;
time_x = time_y = time_z = 0;
for(var i = 0; i < 20; i++){
particles[i] = new Particle();
}
}
function draw(){
background(0,0,0,10);
fill(255);
// text("by Uriel Sade", width/40, height- height/40);
noFill();
field = [];
time_y = 0;
for(var y = 0; y < rows; y++){
time_x = 0;
for(var x = 0; x < cols; x++){
push();
translate(x*scl + scl/2, y*scl + scl/2);
var direction_vector = p5.Vector.fromAngle(noise(time_x, time_y, time_z)*2*PI + PI);
rotate(direction_vector.heading());
stroke(0,255,0, 7);
strokeWeight(1);
line(-scl/6,0,scl/6,0);
pop();
field[y* cols + x] = direction_vector;
time_x += time_inc;
}
time_y += time_inc;
time_z += 0.0002;
}
updateParticles();
}
function updateParticles(){
for(var i = 0; i < particles.length; i++){
particles[i].accelerate(field);
}
}
function windowResized(){
setup();
}
| urielsade/urielsade.github.io | flowfield.js | JavaScript | mit | 1,411 | [
30522,
1013,
1008,
1008,
4281,
11080,
1008,
3166,
1024,
24471,
9257,
6517,
2063,
1008,
3058,
1024,
13114,
1012,
2570,
1010,
2418,
1008,
1013,
13075,
10683,
1025,
13075,
2051,
1035,
1060,
1010,
2051,
1035,
1061,
1010,
2051,
1035,
1062,
1010,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.compiere.model.MAttachment;
import org.compiere.model.MImage;
import org.compiere.print.MPrintFormatItem;
import org.compiere.print.PrintDataElement;
import org.compiere.util.CCache;
import org.compiere.util.Env;
/**
* Image Element
*
* @author Jorg Janke
* @version $Id: ImageElement.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class ImageElement extends PrintElement
{
/**
* Create Image from URL
* @param imageURLString image url
* @return image element
*/
public static ImageElement get (String imageURLString)
{
Object key = imageURLString;
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
image = new ImageElement(imageURLString);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/**
* Create Image from URL
* @param imageURL image url
* @return image element
*/
public static ImageElement get (URL imageURL)
{
Object key = imageURL;
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
image = new ImageElement(imageURL);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/**
* Create Image from Attachment
* @param AD_PrintFormatItem_ID record id
* @return image element
*/
public static ImageElement get (int AD_PrintFormatItem_ID)
{
Object key = new Integer(AD_PrintFormatItem_ID);
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
image = new ImageElement(AD_PrintFormatItem_ID);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/**
* Create Image from database column
* @param data the printdataelement, containing the reference
* @param imageURLString image url - containing just the AD_Image_ID reference
* @return image element
*/
public static ImageElement get(PrintDataElement data, String imageURLString)
{
Object key = (BigDecimal) data.getValue();
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
BigDecimal imkeybd = (BigDecimal) data.getValue();
int imkeyint = 0;
if (imkeybd != null)
imkeyint = imkeybd.intValue();
image = new ImageElement(imkeyint, false);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/** 60 minute Cache */
private static CCache<Object,ImageElement> s_cache
= new CCache<Object,ImageElement>("ImageElement", 10, 60);
/**************************************************************************
* Create from existing Image
* @param image image
*/
public ImageElement(Image image)
{
m_image = image;
if (m_image != null)
log.debug("Image=" + image);
else
log.warn("Image is NULL");
} // ImageElement
/**
* Create Image from URL
* @param imageURLstring image url
*/
private ImageElement(String imageURLstring)
{
URL imageURL = getURL(imageURLstring);
if (imageURL != null)
{
m_image = Toolkit.getDefaultToolkit().createImage(imageURL);
if (m_image != null)
log.debug("URL=" + imageURL);
else
log.warn("Not loaded - URL=" + imageURL);
}
else
log.warn("Invalid URL=" + imageURLstring);
} // ImageElement
/**
* Create Image from URL
* @param imageURL image url
*/
private ImageElement(URL imageURL)
{
if (imageURL != null)
{
m_image = Toolkit.getDefaultToolkit().createImage(imageURL);
if (m_image != null)
log.debug("URL=" + imageURL);
else
log.warn("Not loaded - URL=" + imageURL);
}
else
log.error("ImageURL is NULL");
} // ImageElement
/**
* Create Image from Attachment
* @param AD_PrintFormatItem_ID record id
*/
private ImageElement(int AD_PrintFormatItem_ID)
{
loadAttachment(AD_PrintFormatItem_ID);
} // ImageElement
/**
* Create Image from Attachment or Column
* @param record_ID_ID record id from printformat or column
* @param isAttachment flag to indicate if is attachment or is a column from DB
*/
public ImageElement(int record_ID, boolean isAttachment)
{
if (isAttachment)
loadAttachment(record_ID);
else
loadFromDB(record_ID);
} // ImageElement
/** The Image */
private Image m_image = null;
/** Scale */
private double m_scaleFactor = 1;
/**************************************************************************
* Get URL from String
* @param urlString url or resource
* @return URL or null
*/
private URL getURL (String urlString)
{
URL url = null;
// not a URL - may be a resource
if (urlString.indexOf("://") == -1)
{
ClassLoader cl = getClass().getClassLoader();
url = cl.getResource(urlString);
if (url != null)
return url;
log.warn("Not found - " + urlString);
return null;
}
// load URL
try
{
url = new URL (urlString);
}
catch (MalformedURLException ex)
{
log.warn(urlString, ex);
}
return url;
} // getURL;
/**
* Load from DB
* @param record_ID record id
*/
private void loadFromDB(int record_ID)
{
MImage mimage = MImage.get(Env.getCtx(), record_ID);
if (mimage == null)
{
log.warn("No Image - record_ID=" + record_ID);
return;
}
byte[] imageData = mimage.getData();
if (imageData != null)
m_image = Toolkit.getDefaultToolkit().createImage(imageData);
if (m_image != null)
log.debug(mimage.toString()
+ " - Size=" + imageData.length);
else
log.warn(mimage.toString()
+ " - not loaded (must be gif or jpg) - record_ID=" + record_ID);
} // loadFromDB
/**
* Load Attachment
* @param AD_PrintFormatItem_ID record id
*/
private void loadAttachment(int AD_PrintFormatItem_ID)
{
MAttachment attachment = MAttachment.get(Env.getCtx(),
MPrintFormatItem.Table_ID, AD_PrintFormatItem_ID);
if (attachment == null)
{
log.warn("No Attachment - AD_PrintFormatItem_ID=" + AD_PrintFormatItem_ID);
return;
}
if (attachment.getEntryCount() != 1)
{
log.warn("Need just 1 Attachment Entry = " + attachment.getEntryCount());
return;
}
byte[] imageData = attachment.getEntryData(0);
if (imageData != null)
m_image = Toolkit.getDefaultToolkit().createImage(imageData);
if (m_image != null)
log.debug(attachment.getEntryName(0)
+ " - Size=" + imageData.length);
else
log.warn(attachment.getEntryName(0)
+ " - not loaded (must be gif or jpg) - AD_PrintFormatItem_ID=" + AD_PrintFormatItem_ID);
} // loadAttachment
/**************************************************************************
* Calculate Image Size.
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize()
{
p_width = 0;
p_height = 0;
if (m_image == null)
return true;
// we have an image
// if the image was not loaded, consider that there is no image - teo_sarca [ 1674706 ]
if (waitForLoad(m_image) && m_image != null)
{
p_width = m_image.getWidth(this);
p_height = m_image.getHeight(this);
if (p_width * p_height == 0)
return true; // don't bother scaling and prevent div by 0
// 0 = unlimited so scale to fit restricted dimension
/* teo_sarca, [ 1673548 ] Image is not scaled in a report table cell
if (p_maxWidth * p_maxHeight != 0) // scale to maintain aspect ratio
{
if (p_width/p_height > p_maxWidth/p_maxHeight)
// image "fatter" than available area
m_scaleFactor = p_maxWidth/p_width;
else
m_scaleFactor = p_maxHeight/p_height;
}
*/
m_scaleFactor = 1;
if (p_maxWidth != 0 && p_width > p_maxWidth)
m_scaleFactor = p_maxWidth / p_width;
if (p_maxHeight != 0 && p_height > p_maxHeight && p_maxHeight/p_height < m_scaleFactor)
m_scaleFactor = p_maxHeight / p_height;
p_width = (float) m_scaleFactor * p_width;
p_height = (float) m_scaleFactor * p_height;
}
// If the image is not loaded set it to null.
// This prevents SecurityException when invoking getWidth() or getHeight(). - teo_sarca [ 1674706 ]
else {
m_image = null;
}
return true;
} // calculateSize
/**
* Get the Image
* @return image
*/
public Image getImage()
{
return m_image;
} // getImage
/**
* Get image scale factor.
*
* @author teo_sarca - [ 1673548 ] Image is not scaled in a report table cell
* @return scale factor
*/
public double getScaleFactor() {
if (!p_sizeCalculated)
p_sizeCalculated = calculateSize();
return m_scaleFactor;
}
/**
* Paint Image
* @param g2D Graphics
* @param pageStart top left Location of page
* @param pageNo page number for multi page support (0 = header/footer) - ignored
* @param ctx print context
* @param isView true if online view (IDs are links)
*/
public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
if (m_image == null)
return;
// Position
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType))
x += p_maxWidth - p_width;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
x += (p_maxWidth - p_width) / 2;
int y = (int)location.y;
// map a scaled and shifted version of the image to device space
AffineTransform transform = new AffineTransform();
transform.translate(x,y);
transform.scale(m_scaleFactor, m_scaleFactor);
g2D.drawImage(m_image, transform, this);
} // paint
} // ImageElement
| klst-com/metasfresh | de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/print/layout/ImageElement.java | Java | gpl-2.0 | 11,006 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
define([],function(){
var config = {};
config.title="Domain Totals Report";
var backColor = '#ffffff';
var axisColor = '#3e3e3e';
var gridlinesColor = '#000000';
var axisTitleColor = '#333333';
var color1 = '#4BACC6';
var color2 = '#8064A2';
var color3 = '#eda637';
var color4 = '#a7a737';
var color5 = '#86aa65';
var color6 = '#8aabaf';
var color7 = '#69c8ff';
var color8 = '#3e3e3e';
var color9 = '#4bb3d3';
config.height=550,
config.width= '100%';
config.title="Domain Totals Report";
config.vAxis= {maxValue: 100};
config.backgroundColor= backColor;
config.chartArea={left: 165, width:"100%",height:"75%"};
config.hAxis= {title: 'Domain', textStyle: {color: axisTitleColor}};
config.vAxis= {title: '# of Visits', gridlines: {count: 5, color: gridlinesColor},format:0, baselineColor:axisColor, textStyle:{color: axisTitleColor}};
config.colors= [ color1, color2, color3, color4, color5, color6, color7, color8];
config.visType="PieChart";
return config;
}); | uoForms/quickforms3 | QF3 Apps/rpp/reports/js/totalDomain.js | JavaScript | mit | 1,016 | [
30522,
9375,
1006,
1031,
1033,
1010,
3853,
1006,
1007,
1063,
13075,
9530,
8873,
2290,
1027,
1063,
1065,
1025,
9530,
8873,
2290,
1012,
2516,
1027,
1000,
5884,
21948,
3189,
1000,
1025,
13075,
2067,
18717,
1027,
1005,
1001,
21461,
4246,
4246,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright 2006-2016 Edward Smith
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.lang.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import root.util.Root;
import sun.misc.Unsafe;
/**
*
* @author Edward Smith
* @version 0.5
* @since 0.5
*
* @param <C>
* The class type of the {@link Object}
*/
public final class StaticPrimitiveField<C> {
// <><><><><><><><><><><><><><><> Constants <><><><><><><><><><><><><><><>
private static final Unsafe unsafe = Root.getUnsafe();
// <><><><><><><><><><><><><><><> Attributes <><><><><><><><><><><><><><><>
private final long fieldOffset;
private final Object objectBase;
// <><><><><><><><><><><><><><>< Constructors ><><><><><><><><><><><><><><>
public StaticPrimitiveField(final Class<C> clazz, final String fieldName) {
try {
final Field f = clazz.getDeclaredField(fieldName);
if (!Modifier.isStatic(f.getModifiers())) {
throw new RuntimeException("StaticPrimitiveField does not support instance fields");
}
this.fieldOffset = unsafe.staticFieldOffset(f);
this.objectBase = unsafe.staticFieldBase(f);
} catch (NoSuchFieldException | SecurityException e) {
throw new RuntimeException(e);
}
}
// <><><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><><>
public final boolean getBoolean() {
return unsafe.getBoolean(this.objectBase, this.fieldOffset);
}
public final byte getByte() {
return unsafe.getByte(this.objectBase, this.fieldOffset);
}
public final char getChar() {
return unsafe.getChar(this.objectBase, this.fieldOffset);
}
public final double getDouble() {
return unsafe.getDouble(this.objectBase, this.fieldOffset);
}
public final float getFloat() {
return unsafe.getFloat(this.objectBase, this.fieldOffset);
}
public final int getInt() {
return unsafe.getInt(this.objectBase, this.fieldOffset);
}
public final long getLong() {
return unsafe.getLong(this.objectBase, this.fieldOffset);
}
public final short getShort() {
return unsafe.getShort(this.objectBase, this.fieldOffset);
}
public final void setBoolean(final boolean value) {
unsafe.putBoolean(this.objectBase, this.fieldOffset, value);
}
public final void setByte(final byte value) {
unsafe.putByte(this.objectBase, this.fieldOffset, value);
}
public final void setChar(final char value) {
unsafe.putChar(this.objectBase, this.fieldOffset, value);
}
public final void setDouble(final double value) {
unsafe.putDouble(this.objectBase, this.fieldOffset, value);
}
public final void setFloat(final float value) {
unsafe.putFloat(this.objectBase, this.fieldOffset, value);
}
public final void setInt(final int value) {
unsafe.putInt(this.objectBase, this.fieldOffset, value);
}
public final void setLong(final long value) {
unsafe.putLong(this.objectBase, this.fieldOffset, value);
}
public final void setShort(final short value) {
unsafe.putShort(this.objectBase, this.fieldOffset, value);
}
} // End StaticPrimitiveField
| macvelli/RootFramework | src/root/lang/reflect/StaticPrimitiveField.java | Java | apache-2.0 | 3,554 | [
30522,
1013,
1008,
1008,
9385,
2294,
1011,
2355,
3487,
3044,
1008,
1008,
7000,
2104,
1996,
15895,
6105,
1010,
2544,
1016,
30524,
1013,
1013,
7479,
1012,
15895,
1012,
8917,
1013,
15943,
1013,
6105,
1011,
1016,
1012,
1014,
1008,
1008,
4983,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* iOS and Android apis should match.
* It doesn't matter if you export `.ios` or `.android`, either one but only one.
*/
// export * from './mip';
// export * from './mip-finder';
// export * from './ble-utils';
// export * from './bluetooth.scanner."
// export * from './codes"
// export * from './mip-controller"
// export * from './mip-device"
// export * from './mip-status-reader"
// export * from './mip-types"
// export * from './mip.android';
// export * from './mip-finder.android';
// export * from './ble-utils.android';
// Export any shared classes, constants, etc.
//export * from './mip.common'; | sebawita/nativescript-mip-ble | index.d.ts | TypeScript | mit | 619 | [
30522,
1013,
1008,
1008,
1008,
16380,
1998,
11924,
17928,
2015,
2323,
2674,
1012,
1008,
2009,
2987,
1005,
1056,
3043,
2065,
2017,
9167,
1036,
1012,
16380,
1036,
2030,
1036,
1012,
11924,
1036,
1010,
2593,
2028,
2021,
2069,
2028,
1012,
1008,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
/**
* @package jCart
* @copyright Copyright (C) 2009 - 2012 softPHP,http://www.soft-php.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
// Text
$_['text_title'] = 'Bank Transfer';
$_['text_instruction'] = 'Bank Transfer Instructions';
$_['text_description'] = 'Please transfer the total amount to the following bank account.';
$_['text_payment'] = 'Your order will not ship until we receive payment.';
?> | jiangfanglu/grart | components/com_opencart/catalog/language/english/payment/bank_transfer.php | PHP | gpl-2.0 | 512 | [
30522,
1026,
1029,
25718,
1013,
1008,
1008,
1008,
1030,
7427,
29175,
8445,
1008,
1030,
9385,
9385,
1006,
1039,
1007,
2268,
1011,
2262,
3730,
8458,
2361,
1010,
8299,
1024,
1013,
1013,
7479,
1012,
3730,
1011,
30524,
1013,
14246,
2140,
1012,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
-- start_ignore
SET gp_create_table_random_default_distribution=off;
-- end_ignore
--
-- SYNC2 HEAP TABLE 1
--
CREATE TABLE sync2_heap_alter_part_rn1 (id int, rank int, year date, gender
char(1)) DISTRIBUTED BY (id, gender, year)
partition by list (gender)
subpartition by range (year)
subpartition template (
start (date '2001-01-01'))
(
values ('M'),
values ('F')
);
--
-- Insert few records into the table
--
insert into sync2_heap_alter_part_rn1 values (generate_series(1,20),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from sync2_heap_alter_part_rn1;
--
-- SYNC2 HEAP TABLE 2
--
CREATE TABLE sync2_heap_alter_part_rn2 (id int, rank int, year date, gender
char(1)) DISTRIBUTED BY (id, gender, year)
partition by list (gender)
subpartition by range (year)
subpartition template (
start (date '2001-01-01'))
(
values ('M'),
values ('F')
);
--
-- Insert few records into the table
--
insert into sync2_heap_alter_part_rn2 values (generate_series(1,20),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from sync2_heap_alter_part_rn2;
--
-- ALTER SYNC1 HEAP
--
--
-- Add default Partition
--
alter table sync1_heap_alter_part_rn7 add default partition default_part;
--
-- Rename Default Partition
--
alter table sync1_heap_alter_part_rn7 rename default partition to new_default_part;
--
-- Insert few records into the table
--
insert into sync1_heap_alter_part_rn7 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from sync1_heap_alter_part_rn7;
--
-- Rename Table
--
alter table sync1_heap_alter_part_rn7 rename to sync1_heap_alter_part_rn7_0;
--
-- Insert few records into the table
--
insert into sync1_heap_alter_part_rn7_0 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from sync1_heap_alter_part_rn7_0;
--
-- ALTER CK_SYNC1 HEAP
--
--
-- Add default Partition
--
alter table ck_sync1_heap_alter_part_rn6 add default partition default_part;
--
-- Rename Default Partition
--
alter table ck_sync1_heap_alter_part_rn6 rename default partition to new_default_part;
--
-- Insert few records into the table
--
insert into ck_sync1_heap_alter_part_rn6 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from ck_sync1_heap_alter_part_rn6;
--
-- Rename Table
--
alter table ck_sync1_heap_alter_part_rn6 rename to ck_sync1_heap_alter_part_rn6_0;
--
-- Insert few records into the table
--
insert into ck_sync1_heap_alter_part_rn6_0 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from ck_sync1_heap_alter_part_rn6_0;
--
-- ALTER CT HEAP
--
--
-- Add default Partition
--
alter table ct_heap_alter_part_rn4 add default partition default_part;
--
-- Rename Default Partition
--
alter table ct_heap_alter_part_rn4 rename default partition to new_default_part;
--
-- Insert few records into the table
--
insert into ct_heap_alter_part_rn4 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from ct_heap_alter_part_rn4;
--
-- Rename Table
--
alter table ct_heap_alter_part_rn4 rename to ct_heap_alter_part_rn4_0;
--
-- Insert few records into the table
--
insert into ct_heap_alter_part_rn4_0 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from ct_heap_alter_part_rn4_0;
--
-- ALTER RESYNC HEAP
--
--
-- Add default Partition
--
alter table resync_heap_alter_part_rn2 add default partition default_part;
--
-- Rename Default Partition
--
alter table resync_heap_alter_part_rn2 rename default partition to new_default_part;
--
-- Insert few records into the table
--
insert into resync_heap_alter_part_rn2 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from resync_heap_alter_part_rn2;
--
-- Rename Table
--
alter table resync_heap_alter_part_rn2 rename to resync_heap_alter_part_rn2_0;
--
-- Insert few records into the table
--
insert into resync_heap_alter_part_rn2_0 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from resync_heap_alter_part_rn2_0;
--
-- ALTER SYNC2 HEAP
--
--
-- Add default Partition
--
alter table sync2_heap_alter_part_rn1 add default partition default_part;
--
-- Rename Default Partition
--
alter table sync2_heap_alter_part_rn1 rename default partition to new_default_part;
--
-- Insert few records into the table
--
insert into sync2_heap_alter_part_rn1 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from sync2_heap_alter_part_rn1;
--
-- Rename Table
--
alter table sync2_heap_alter_part_rn1 rename to sync2_heap_alter_part_rn1_0;
--
-- Insert few records into the table
--
insert into sync2_heap_alter_part_rn1_0 values (generate_series(1,10),1,'2001-01-01','F');
--
-- select from the Table
--
select count(*) from sync2_heap_alter_part_rn1_0;
| edespino/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/filerep_end_to_end/sync2/sql/sync2_heap_alter_part_rename.sql | SQL | apache-2.0 | 5,002 | [
30522,
1011,
1011,
2707,
1035,
8568,
2275,
14246,
1035,
3443,
1035,
2795,
1035,
6721,
1035,
12398,
1035,
4353,
1027,
2125,
1025,
1011,
1011,
2203,
1035,
8568,
1011,
1011,
1011,
1011,
26351,
2475,
16721,
2795,
1015,
1011,
1011,
3443,
2795,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* rcmuserAdminUsersApp.rcmuserAdminUsers
*/
angular.module('rcmuserAdminUsersApp').controller(
'rcmuserAdminUsers',
[
'$window',
'$scope',
'$log',
'$uibModal',
'RcmUserResult',
'RcmResults',
'rcmUserUserService',
function (
$window,
$scope,
$log,
$uibModal,
RcmUserResult,
RcmResults,
rcmUserUserService
) {
var self = this;
var userServiceEventManager = rcmUserUserService.getEventManager();
$scope.loading = true;
userServiceEventManager.on(
'RcmUserHttp.loading',
function (loading) {
$scope.loading = loading;
}
);
$scope.userQuery = '';
$scope.availableStates = [
'enabled',
'disabled'
];
// User
$scope.showMessages = false;
var onError = function (data) {
$window.alert('An error occurred');
console.error(data);
};
var onGetUsersSuccess = function (data) {
$scope.users = data.data;
$scope.messages = data.messages;
};
rcmUserUserService.getUsers(
onGetUsersSuccess,
onError
);
var onGetRolesSuccess = function (data) {
$scope.roles = data.data;
$scope.messages = data.messages;
};
// User Roles
rcmUserUserService.getRoles(
onGetRolesSuccess,
onError
);
var onValidUserStatesSuccess = function (data, status) {
$scope.availableStates = data.data;
};
// valid user states
rcmUserUserService.getValidUserStates(
onValidUserStatesSuccess
);
$scope.rolePropertyId = rcmUserUserService.getPropertyRoleId();
$scope.oneAtATime = false;
$scope.addUser = function () {
var user = {
username: '',
password: null,
state: 'disabled',
email: '',
name: '',
properties: {},
isNew: true
};
user.properties[$scope.rolePropertyId] = [];
$scope.users.unshift(user);
// clear filter
$scope.userQuery = '';
}
}
]
);
| rodmcnew/Rcm | user-ui/public/admin-users-app/rcmuser-admin-users-controller.js | JavaScript | isc | 2,694 | [
30522,
1013,
1008,
1008,
1008,
22110,
7606,
6906,
22117,
13429,
2545,
29098,
1012,
22110,
7606,
6906,
22117,
13429,
2545,
1008,
1013,
16108,
1012,
11336,
1006,
1005,
22110,
7606,
6906,
22117,
13429,
2545,
29098,
1005,
1007,
1012,
11486,
1006,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#!/usr/bin/env python
#
# This file is part of pacman-mirrors.
#
# pacman-mirrors 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.
#
# pacman-mirrors is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pacman-mirrors. If not, see <http://www.gnu.org/licenses/>.
#
# from https://wiki.maemo.org/Internationalize_a_Python_application
"""Pacman-Mirrors Translation Module"""
import os
import sys
import locale
import gettext
# The translation files will be under
# @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo
APP_NAME = "pacman_mirrors"
APP_DIR = os.path.join(sys.prefix, "share")
LOCALE_DIR = os.path.join(APP_DIR, "locale")
CODESET = "utf-8"
# Now we need to choose the language. We will provide a list, and gettext
# will use the first translation available in the list
LANGUAGES = []
try:
user_locale = locale.getdefaultlocale()[0]
if user_locale:
LANGUAGES += user_locale
except ValueError:
pass
LANGUAGES += os.environ.get("LANGUAGE", "").split(":")
LANGUAGES += ["en_US"]
# Lets tell those details to gettext
# (nothing to change here for you)
gettext.install(True)
gettext.bindtextdomain(APP_NAME, LOCALE_DIR)
gettext.bind_textdomain_codeset(APP_NAME, codeset=CODESET)
gettext.textdomain(APP_NAME)
language = gettext.translation(APP_NAME, LOCALE_DIR, LANGUAGES, fallback=True)
# Add this to every module:
#
# import i18n
# _ = i18n.language.gettext
| fhdk/pacman-mirrors | pacman_mirrors/translation/i18n.py | Python | gpl-3.0 | 1,832 | [
30522,
1001,
999,
1013,
2149,
2099,
1013,
8026,
1013,
4372,
2615,
18750,
1001,
1001,
2023,
5371,
2003,
2112,
1997,
14397,
2386,
1011,
13536,
1012,
1001,
1001,
14397,
2386,
1011,
13536,
2003,
2489,
4007,
1024,
2017,
2064,
2417,
2923,
3089,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
require_relative "../lib/stressfactor"
require "pry"
file = GPX::GPXFile.new(:gpx_file => "examples/data/sample.gpx")
pc = Stressfactor::PaceCalculator.new(file)
pace = pc.calculate
puts pace
binding.pry
| andrewhao/stressfactor | scripts/analyze_sample_gpx.rb | Ruby | mit | 204 | [
30522,
5478,
1035,
5816,
1000,
1012,
1012,
1013,
5622,
2497,
1013,
6911,
7011,
16761,
1000,
5478,
1000,
29198,
1000,
5371,
1027,
14246,
2595,
1024,
1024,
14246,
2595,
8873,
2571,
1012,
2047,
1006,
1024,
14246,
2595,
1035,
5371,
1027,
1028,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package com.wisobi.leanbean.restlet.resource;
import com.wisobi.leanbean.Hashids;
import com.wisobi.leanbean.LeanBeanDao;
import com.wisobi.leanbean.LeanBeanUtil;
import com.wisobi.leanbean.dto.DAO2DTOMapper;
import com.wisobi.leanbean.dto.DTO2DAOMapper;
import com.wisobi.leanbean.dto.MeetingTO;
import com.wisobi.leanbean.dto.MeetingViewTO;
import com.wisobi.leanbean.jpa.LeanBeanJpaDao;
import com.wisobi.leanbean.jpa.entity.Meeting;
import org.restlet.data.Status;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by bjork on 25/08/14.
*/
public class MeetingResource extends ServerResource {
final private static Logger logger = LoggerFactory.getLogger(MeetingResource.class);
final private LeanBeanDao dao = new LeanBeanJpaDao();
@Get("json")
public MeetingViewTO findMeetingById() {
String hash = getRequestAttributes().get("meeting-id").toString();
long meetingId = LeanBeanUtil.idDecode(hash);
return findMeetingById(meetingId);
}
public MeetingViewTO findMeetingById(long meetingId) {
if(meetingId < 0) {
// If the hash cannot be decoded to an integer, no need to check the database
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
Meeting meeting = dao.findByMeetingId(meetingId);
try {
dao.close();
} catch (Exception e) {
logger.debug(e.getMessage());
}
if (meeting == null) {
// No meeting with decoded id found in the database
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
}
MeetingViewTO meetingViewTO = DAO2DTOMapper.mapMeeting(meeting);
return meetingViewTO;
}
@Post("json")
public MeetingViewTO addMeeting(MeetingTO meetingTO) {
Meeting meeting = DTO2DAOMapper.mapMeeting(meetingTO);
logger.info("Meeting: " + meeting.getTitle() + ", Device: " + meeting.getDevice().getId());
try {
dao.addMeeting(meeting);
getResponse().setStatus(Status.SUCCESS_CREATED);
} catch (Exception e) {
logger.debug(e.getMessage());
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage(), e);
} finally {
try {
dao.close();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return DAO2DTOMapper.mapMeeting(meeting);
}
}
| wisobi/leanbean | leanbean-api/src/main/java/com/wisobi/leanbean/restlet/resource/MeetingResource.java | Java | apache-2.0 | 2,584 | [
30522,
7427,
4012,
1012,
15536,
6499,
5638,
1012,
8155,
4783,
2319,
1012,
2717,
7485,
1012,
7692,
1025,
12324,
4012,
1012,
15536,
6499,
5638,
1012,
8155,
4783,
2319,
1012,
23325,
9821,
1025,
12324,
4012,
1012,
15536,
6499,
5638,
1012,
8155,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import numpy as np
import pandas as pd
import pytest
from dask.dataframe.hashing import hash_pandas_object
from dask.dataframe.utils import assert_eq
@pytest.mark.parametrize('obj', [
pd.Series([1, 2, 3]),
pd.Series([1.0, 1.5, 3.2]),
pd.Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]),
pd.Series(['a', 'b', 'c']),
pd.Series([True, False, True]),
pd.Index([1, 2, 3]),
pd.Index([True, False, True]),
pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3]}),
pd.util.testing.makeMissingDataframe(),
pd.util.testing.makeMixedDataFrame(),
pd.util.testing.makeTimeDataFrame(),
pd.util.testing.makeTimeSeries(),
pd.util.testing.makeTimedeltaIndex()])
def test_hash_pandas_object(obj):
a = hash_pandas_object(obj)
b = hash_pandas_object(obj)
if isinstance(a, np.ndarray):
np.testing.assert_equal(a, b)
else:
assert_eq(a, b)
| chrisbarber/dask | dask/dataframe/tests/test_hashing.py | Python | bsd-3-clause | 899 | [
30522,
12324,
16371,
8737,
2100,
2004,
27937,
12324,
25462,
2015,
2004,
22851,
12324,
1052,
17250,
3367,
2013,
8695,
2243,
1012,
2951,
15643,
1012,
23325,
2075,
12324,
23325,
1035,
25462,
2015,
1035,
4874,
2013,
8695,
2243,
1012,
2951,
15643,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
define(['backbone', 'underscore'], function (Backbone, _) {
return Backbone.Model.extend({
idAttribute: 'username',
defaults: {
persona: {
personaPnombre: '',
personaSnombre: '',
personaApaterno: '',
personaAmaterno: '',
dni: ''
}
},
validate: function (attrs, options) {
console.log('persona', attrs.persona);
if (_.isUndefined(attrs.persona)) {
return {
field: 'persona',
error: 'Debe definir una persona'
};
}
if (_.isUndefined(attrs.persona.personaDni) || _.isEmpty(attrs.persona.personaDni.trim()) || attrs.persona.personaDni.trim().length != 8) {
return {
field: 'persona-personaDni',
error: 'El dni es un campo obligatorio y debe tener 8 caracteres.'
};
}
if (_.isUndefined(attrs.persona.personaPnombre) || _.isEmpty(attrs.persona.personaPnombre.trim())) {
return {
field: 'persona-personaPnombre',
error: 'El primer nombre es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) {
return {
field: 'persona-personaApaterno',
error: 'El apellido paterno es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) {
return {
field: 'persona-personaAmaterno',
error: 'El apellido materno es un campo obligatorio.'
};
}
}
});
}); | jaxkodex/edu-stat | src/main/webapp/resources/js/app/models/docente-model.js | JavaScript | gpl-3.0 | 1,442 | [
30522,
9375,
1006,
1031,
1005,
21505,
1005,
1010,
1005,
2104,
9363,
2890,
1005,
1033,
1010,
3853,
1006,
21505,
1010,
1035,
1007,
1063,
2709,
21505,
1012,
2944,
1012,
7949,
1006,
1063,
16096,
4779,
3089,
8569,
2618,
1024,
1005,
5310,
18442,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_processing/audio_buffer.h"
#include "webrtc/common_audio/include/audio_util.h"
#include "webrtc/common_audio/resampler/push_sinc_resampler.h"
#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
namespace webrtc {
namespace {
enum {
kSamplesPer8kHzChannel = 80,
kSamplesPer16kHzChannel = 160,
kSamplesPer32kHzChannel = 320
};
bool HasKeyboardChannel(AudioProcessing::ChannelLayout layout) {
switch (layout) {
case AudioProcessing::kMono:
case AudioProcessing::kStereo:
return false;
case AudioProcessing::kMonoAndKeyboard:
case AudioProcessing::kStereoAndKeyboard:
return true;
}
assert(false);
return false;
}
int KeyboardChannelIndex(AudioProcessing::ChannelLayout layout) {
switch (layout) {
case AudioProcessing::kMono:
case AudioProcessing::kStereo:
assert(false);
return -1;
case AudioProcessing::kMonoAndKeyboard:
return 1;
case AudioProcessing::kStereoAndKeyboard:
return 2;
}
assert(false);
return -1;
}
void StereoToMono(const float* left, const float* right, float* out,
int samples_per_channel) {
for (int i = 0; i < samples_per_channel; ++i) {
out[i] = (left[i] + right[i]) / 2;
}
}
void StereoToMono(const int16_t* left, const int16_t* right, int16_t* out,
int samples_per_channel) {
for (int i = 0; i < samples_per_channel; ++i) {
out[i] = (left[i] + right[i]) >> 1;
}
}
} // namespace
// One int16_t and one float ChannelBuffer that are kept in sync. The sync is
// broken when someone requests write access to either ChannelBuffer, and
// reestablished when someone requests the outdated ChannelBuffer. It is
// therefore safe to use the return value of ibuf_const() and fbuf_const()
// until the next call to ibuf() or fbuf(), and the return value of ibuf() and
// fbuf() until the next call to any of the other functions.
class IFChannelBuffer {
public:
IFChannelBuffer(int samples_per_channel, int num_channels)
: ivalid_(true),
ibuf_(samples_per_channel, num_channels),
fvalid_(true),
fbuf_(samples_per_channel, num_channels) {}
ChannelBuffer<int16_t>* ibuf() { return ibuf(false); }
ChannelBuffer<float>* fbuf() { return fbuf(false); }
const ChannelBuffer<int16_t>* ibuf_const() { return ibuf(true); }
const ChannelBuffer<float>* fbuf_const() { return fbuf(true); }
private:
ChannelBuffer<int16_t>* ibuf(bool readonly) {
RefreshI();
fvalid_ = readonly;
return &ibuf_;
}
ChannelBuffer<float>* fbuf(bool readonly) {
RefreshF();
ivalid_ = readonly;
return &fbuf_;
}
void RefreshF() {
if (!fvalid_) {
assert(ivalid_);
const int16_t* const int_data = ibuf_.data();
float* const float_data = fbuf_.data();
const int length = fbuf_.length();
for (int i = 0; i < length; ++i)
float_data[i] = int_data[i];
fvalid_ = true;
}
}
void RefreshI() {
if (!ivalid_) {
assert(fvalid_);
const float* const float_data = fbuf_.data();
int16_t* const int_data = ibuf_.data();
const int length = ibuf_.length();
for (int i = 0; i < length; ++i)
int_data[i] = WEBRTC_SPL_SAT(std::numeric_limits<int16_t>::max(),
float_data[i],
std::numeric_limits<int16_t>::min());
ivalid_ = true;
}
}
bool ivalid_;
ChannelBuffer<int16_t> ibuf_;
bool fvalid_;
ChannelBuffer<float> fbuf_;
};
AudioBuffer::AudioBuffer(int input_samples_per_channel,
int num_input_channels,
int process_samples_per_channel,
int num_process_channels,
int output_samples_per_channel)
: input_samples_per_channel_(input_samples_per_channel),
num_input_channels_(num_input_channels),
proc_samples_per_channel_(process_samples_per_channel),
num_proc_channels_(num_process_channels),
output_samples_per_channel_(output_samples_per_channel),
samples_per_split_channel_(proc_samples_per_channel_),
mixed_low_pass_valid_(false),
reference_copied_(false),
activity_(AudioFrame::kVadUnknown),
keyboard_data_(NULL),
channels_(new IFChannelBuffer(proc_samples_per_channel_,
num_proc_channels_)) {
assert(input_samples_per_channel_ > 0);
assert(proc_samples_per_channel_ > 0);
assert(output_samples_per_channel_ > 0);
assert(num_input_channels_ > 0 && num_input_channels_ <= 2);
assert(num_proc_channels_ <= num_input_channels);
if (num_input_channels_ == 2 && num_proc_channels_ == 1) {
input_buffer_.reset(new ChannelBuffer<float>(input_samples_per_channel_,
num_proc_channels_));
}
if (input_samples_per_channel_ != proc_samples_per_channel_ ||
output_samples_per_channel_ != proc_samples_per_channel_) {
// Create an intermediate buffer for resampling.
process_buffer_.reset(new ChannelBuffer<float>(proc_samples_per_channel_,
num_proc_channels_));
}
if (input_samples_per_channel_ != proc_samples_per_channel_) {
input_resamplers_.reserve(num_proc_channels_);
for (int i = 0; i < num_proc_channels_; ++i) {
input_resamplers_.push_back(
new PushSincResampler(input_samples_per_channel_,
proc_samples_per_channel_));
}
}
if (output_samples_per_channel_ != proc_samples_per_channel_) {
output_resamplers_.reserve(num_proc_channels_);
for (int i = 0; i < num_proc_channels_; ++i) {
output_resamplers_.push_back(
new PushSincResampler(proc_samples_per_channel_,
output_samples_per_channel_));
}
}
if (proc_samples_per_channel_ == kSamplesPer32kHzChannel) {
samples_per_split_channel_ = kSamplesPer16kHzChannel;
split_channels_low_.reset(new IFChannelBuffer(samples_per_split_channel_,
num_proc_channels_));
split_channels_high_.reset(new IFChannelBuffer(samples_per_split_channel_,
num_proc_channels_));
filter_states_.reset(new SplitFilterStates[num_proc_channels_]);
}
}
AudioBuffer::~AudioBuffer() {}
void AudioBuffer::CopyFrom(const float* const* data,
int samples_per_channel,
AudioProcessing::ChannelLayout layout) {
assert(samples_per_channel == input_samples_per_channel_);
assert(ChannelsFromLayout(layout) == num_input_channels_);
InitForNewData();
if (HasKeyboardChannel(layout)) {
keyboard_data_ = data[KeyboardChannelIndex(layout)];
}
// Downmix.
const float* const* data_ptr = data;
if (num_input_channels_ == 2 && num_proc_channels_ == 1) {
StereoToMono(data[0],
data[1],
input_buffer_->channel(0),
input_samples_per_channel_);
data_ptr = input_buffer_->channels();
}
// Resample.
if (input_samples_per_channel_ != proc_samples_per_channel_) {
for (int i = 0; i < num_proc_channels_; ++i) {
input_resamplers_[i]->Resample(data_ptr[i],
input_samples_per_channel_,
process_buffer_->channel(i),
proc_samples_per_channel_);
}
data_ptr = process_buffer_->channels();
}
// Convert to int16.
for (int i = 0; i < num_proc_channels_; ++i) {
ScaleAndRoundToInt16(data_ptr[i], proc_samples_per_channel_,
channels_->ibuf()->channel(i));
}
}
void AudioBuffer::CopyTo(int samples_per_channel,
AudioProcessing::ChannelLayout layout,
float* const* data) {
assert(samples_per_channel == output_samples_per_channel_);
assert(ChannelsFromLayout(layout) == num_proc_channels_);
// Convert to float.
float* const* data_ptr = data;
if (output_samples_per_channel_ != proc_samples_per_channel_) {
// Convert to an intermediate buffer for subsequent resampling.
data_ptr = process_buffer_->channels();
}
for (int i = 0; i < num_proc_channels_; ++i) {
ScaleToFloat(channels_->ibuf()->channel(i),
proc_samples_per_channel_,
data_ptr[i]);
}
// Resample.
if (output_samples_per_channel_ != proc_samples_per_channel_) {
for (int i = 0; i < num_proc_channels_; ++i) {
output_resamplers_[i]->Resample(data_ptr[i],
proc_samples_per_channel_,
data[i],
output_samples_per_channel_);
}
}
}
void AudioBuffer::InitForNewData() {
keyboard_data_ = NULL;
mixed_low_pass_valid_ = false;
reference_copied_ = false;
activity_ = AudioFrame::kVadUnknown;
}
const int16_t* AudioBuffer::data(int channel) const {
return channels_->ibuf_const()->channel(channel);
}
int16_t* AudioBuffer::data(int channel) {
mixed_low_pass_valid_ = false;
return channels_->ibuf()->channel(channel);
}
const float* AudioBuffer::data_f(int channel) const {
return channels_->fbuf_const()->channel(channel);
}
float* AudioBuffer::data_f(int channel) {
mixed_low_pass_valid_ = false;
return channels_->fbuf()->channel(channel);
}
const int16_t* AudioBuffer::low_pass_split_data(int channel) const {
return split_channels_low_.get()
? split_channels_low_->ibuf_const()->channel(channel)
: data(channel);
}
int16_t* AudioBuffer::low_pass_split_data(int channel) {
mixed_low_pass_valid_ = false;
return split_channels_low_.get()
? split_channels_low_->ibuf()->channel(channel)
: data(channel);
}
const float* AudioBuffer::low_pass_split_data_f(int channel) const {
return split_channels_low_.get()
? split_channels_low_->fbuf_const()->channel(channel)
: data_f(channel);
}
float* AudioBuffer::low_pass_split_data_f(int channel) {
mixed_low_pass_valid_ = false;
return split_channels_low_.get()
? split_channels_low_->fbuf()->channel(channel)
: data_f(channel);
}
const int16_t* AudioBuffer::high_pass_split_data(int channel) const {
return split_channels_high_.get()
? split_channels_high_->ibuf_const()->channel(channel)
: NULL;
}
int16_t* AudioBuffer::high_pass_split_data(int channel) {
return split_channels_high_.get()
? split_channels_high_->ibuf()->channel(channel)
: NULL;
}
const float* AudioBuffer::high_pass_split_data_f(int channel) const {
return split_channels_high_.get()
? split_channels_high_->fbuf_const()->channel(channel)
: NULL;
}
float* AudioBuffer::high_pass_split_data_f(int channel) {
return split_channels_high_.get()
? split_channels_high_->fbuf()->channel(channel)
: NULL;
}
const int16_t* AudioBuffer::mixed_low_pass_data() {
// Currently only mixing stereo to mono is supported.
assert(num_proc_channels_ == 1 || num_proc_channels_ == 2);
if (num_proc_channels_ == 1) {
return low_pass_split_data(0);
}
if (!mixed_low_pass_valid_) {
if (!mixed_low_pass_channels_.get()) {
mixed_low_pass_channels_.reset(
new ChannelBuffer<int16_t>(samples_per_split_channel_, 1));
}
StereoToMono(low_pass_split_data(0),
low_pass_split_data(1),
mixed_low_pass_channels_->data(),
samples_per_split_channel_);
mixed_low_pass_valid_ = true;
}
return mixed_low_pass_channels_->data();
}
const int16_t* AudioBuffer::low_pass_reference(int channel) const {
if (!reference_copied_) {
return NULL;
}
return low_pass_reference_channels_->channel(channel);
}
const float* AudioBuffer::keyboard_data() const {
return keyboard_data_;
}
SplitFilterStates* AudioBuffer::filter_states(int channel) {
assert(channel >= 0 && channel < num_proc_channels_);
return &filter_states_[channel];
}
void AudioBuffer::set_activity(AudioFrame::VADActivity activity) {
activity_ = activity;
}
AudioFrame::VADActivity AudioBuffer::activity() const {
return activity_;
}
int AudioBuffer::num_channels() const {
return num_proc_channels_;
}
int AudioBuffer::samples_per_channel() const {
return proc_samples_per_channel_;
}
int AudioBuffer::samples_per_split_channel() const {
return samples_per_split_channel_;
}
int AudioBuffer::samples_per_keyboard_channel() const {
// We don't resample the keyboard channel.
return input_samples_per_channel_;
}
// TODO(andrew): Do deinterleaving and mixing in one step?
void AudioBuffer::DeinterleaveFrom(AudioFrame* frame) {
assert(proc_samples_per_channel_ == input_samples_per_channel_);
assert(num_proc_channels_ == num_input_channels_);
assert(frame->num_channels_ == num_proc_channels_);
assert(frame->samples_per_channel_ == proc_samples_per_channel_);
InitForNewData();
activity_ = frame->vad_activity_;
int16_t* interleaved = frame->data_;
for (int i = 0; i < num_proc_channels_; i++) {
int16_t* deinterleaved = channels_->ibuf()->channel(i);
int interleaved_idx = i;
for (int j = 0; j < proc_samples_per_channel_; j++) {
deinterleaved[j] = interleaved[interleaved_idx];
interleaved_idx += num_proc_channels_;
}
}
}
void AudioBuffer::InterleaveTo(AudioFrame* frame, bool data_changed) const {
assert(proc_samples_per_channel_ == output_samples_per_channel_);
assert(num_proc_channels_ == num_input_channels_);
assert(frame->num_channels_ == num_proc_channels_);
assert(frame->samples_per_channel_ == proc_samples_per_channel_);
frame->vad_activity_ = activity_;
if (!data_changed) {
return;
}
int16_t* interleaved = frame->data_;
for (int i = 0; i < num_proc_channels_; i++) {
int16_t* deinterleaved = channels_->ibuf()->channel(i);
int interleaved_idx = i;
for (int j = 0; j < proc_samples_per_channel_; j++) {
interleaved[interleaved_idx] = deinterleaved[j];
interleaved_idx += num_proc_channels_;
}
}
}
void AudioBuffer::CopyLowPassToReference() {
reference_copied_ = true;
if (!low_pass_reference_channels_.get()) {
low_pass_reference_channels_.reset(
new ChannelBuffer<int16_t>(samples_per_split_channel_,
num_proc_channels_));
}
for (int i = 0; i < num_proc_channels_; i++) {
low_pass_reference_channels_->CopyFrom(low_pass_split_data(i), i);
}
}
} // namespace webrtc
| xin3liang/platform_external_chromium_org_third_party_webrtc | modules/audio_processing/audio_buffer.cc | C++ | bsd-3-clause | 14,986 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2262,
1996,
30524,
2806,
6105,
1008,
2008,
2064,
2022,
2179,
1999,
1996,
6105,
5371,
1999,
1996,
7117,
1997,
1996,
3120,
1008,
3392,
1012,
2019,
3176,
7789,
3200,
2916,
3946,
2064,
2022,
21... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Tue Apr 26 20:40:34 CST 2011 -->
<TITLE>
com.numericalmethod.suanshu.stats.timeseries.linear.multivariate.stationaryprocess.arima (SuanShu 1.3.1 API Documentation)
</TITLE>
<META NAME="date" CONTENT="2011-04-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../../../../com/numericalmethod/suanshu/stats/timeseries/linear/multivariate/stationaryprocess/arima/package-summary.html" target="classFrame">com.numericalmethod.suanshu.stats.timeseries.linear.multivariate.stationaryprocess.arima</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="ArimaModel.html" title="class in com.numericalmethod.suanshu.stats.timeseries.linear.multivariate.stationaryprocess.arima" target="classFrame">ArimaModel</A>
<BR>
<A HREF="ArimaSim.html" title="class in com.numericalmethod.suanshu.stats.timeseries.linear.multivariate.stationaryprocess.arima" target="classFrame">ArimaSim</A>
<BR>
<A HREF="ArimaxModel.html" title="class in com.numericalmethod.suanshu.stats.timeseries.linear.multivariate.stationaryprocess.arima" target="classFrame">ArimaxModel</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| Aliced3645/DataCenterMarketing | suanshu-javadoc-1.3.1/com/numericalmethod/suanshu/stats/timeseries/linear/multivariate/stationaryprocess/arima/package-frame.html | HTML | apache-2.0 | 1,584 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
30524,
1028,
1026,
999,
1011,
1011,
7013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
include 'init.php';
$output = '';
$setup = new ON_Settings();
$setup->load();
$setup->registerForm('setup');
// fill form with elements
$setup->fillForm();
// process forms if posted
if ($setup->form->isSubmitted() && $setup->form->validate()) {
$values =& $setup->form->exportValues();
$setup->setValues($values);
if($setup->globalid > 0) {
$res = $setup->update();
if ($res) {
ON_Say::add(fmtSuccess(_('Settings updated successfuly')));
$defaults = $setup->defaults();
$setup->form->resetDefaults($defaults);
} else {
ON_Say::add(fmtError(_('Database error: settings update failed')));
}
} else {
$res = $setup->insert();
if ($res) {
ON_Say::add(fmtSuccess(_('Settings inserted successfuly')));
} else {
ON_Say::add(fmtError(_('Database error: settings insert failed')));
}
}
}
$output .= $setup->form->toHtml();
include 'theme.php';
?> | uzaytek/orion | admin/settings-store.php | PHP | gpl-2.0 | 935 | [
30522,
1026,
1029,
25718,
2421,
1005,
1999,
4183,
1012,
25718,
1005,
1025,
1002,
6434,
1027,
1005,
1005,
1025,
1002,
16437,
1027,
2047,
2006,
1035,
10906,
1006,
1007,
1025,
1002,
16437,
1011,
1028,
7170,
1006,
1007,
1025,
1002,
16437,
1011,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
fileedit.cpp
Редактирование файла - надстройка над editor.cpp
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "fileedit.hpp"
// Internal:
#include "keyboard.hpp"
#include "encoding.hpp"
#include "macroopcode.hpp"
#include "keys.hpp"
#include "ctrlobj.hpp"
#include "poscache.hpp"
#include "filepanels.hpp"
#include "panel.hpp"
#include "dialog.hpp"
#include "FarDlgBuilder.hpp"
#include "fileview.hpp"
#include "help.hpp"
#include "manager.hpp"
#include "namelist.hpp"
#include "history.hpp"
#include "cmdline.hpp"
#include "scrbuf.hpp"
#include "savescr.hpp"
#include "filestr.hpp"
#include "TPreRedrawFunc.hpp"
#include "syslog.hpp"
#include "taskbar.hpp"
#include "interf.hpp"
#include "message.hpp"
#include "config.hpp"
#include "delete.hpp"
#include "datetime.hpp"
#include "pathmix.hpp"
#include "dirmix.hpp"
#include "strmix.hpp"
#include "exitcode.hpp"
#include "constitle.hpp"
#include "wakeful.hpp"
#include "uuids.far.dialogs.hpp"
#include "stddlg.hpp"
#include "plugins.hpp"
#include "lang.hpp"
#include "keybar.hpp"
#include "string_utils.hpp"
#include "cvtname.hpp"
#include "global.hpp"
#include "file_io.hpp"
// Platform:
#include "platform.env.hpp"
#include "platform.fs.hpp"
// Common:
#include "common/view/enumerate.hpp"
// External:
#include "format.hpp"
//----------------------------------------------------------------------------
enum enumOpenEditor
{
ID_OE_TITLE,
ID_OE_OPENFILETITLE,
ID_OE_FILENAME,
ID_OE_SEPARATOR1,
ID_OE_CODEPAGETITLE,
ID_OE_CODEPAGE,
ID_OE_SEPARATOR2,
ID_OE_OK,
ID_OE_CANCEL,
ID_OE_COUNT
};
static intptr_t hndOpenEditor(Dialog* Dlg, intptr_t msg, intptr_t param1, void* param2)
{
if (msg == DN_INITDIALOG)
{
const auto codepage = *static_cast<uintptr_t*>(param2);
codepages::instance().FillCodePagesList(Dlg, ID_OE_CODEPAGE, codepage, true, false, true, false, false);
}
if (msg == DN_CLOSE)
{
if (param1 == ID_OE_OK)
{
const auto param = reinterpret_cast<uintptr_t*>(Dlg->SendMessage(DM_GETDLGDATA, 0, nullptr));
FarListPos pos={sizeof(FarListPos)};
Dlg->SendMessage(DM_LISTGETCURPOS, ID_OE_CODEPAGE, &pos);
*param = Dlg->GetListItemSimpleUserData(ID_OE_CODEPAGE, pos.SelectPos);
return TRUE;
}
}
return Dlg->DefProc(msg, param1, param2);
}
bool dlgOpenEditor(string &strFileName, uintptr_t &codepage)
{
auto EditDlg = MakeDialogItems<ID_OE_COUNT>(
{
{ DI_DOUBLEBOX, {{3, 1}, {72, 8}}, DIF_NONE, msg(lng::MEditTitle), },
{ DI_TEXT, {{5, 2}, {0 , 2}}, DIF_NONE, msg(lng::MEditOpenCreateLabel), },
{ DI_EDIT, {{5, 3}, {70, 3}}, DIF_FOCUS | DIF_HISTORY | DIF_USELASTHISTORY | DIF_EDITEXPAND | DIF_EDITPATH, },
{ DI_TEXT, {{-1, 4}, {0, 4}}, DIF_SEPARATOR, {} },
{ DI_TEXT, {{5, 5}, {0, 5}}, DIF_NONE, msg(lng::MEditCodePage), },
{ DI_COMBOBOX, {{25, 5}, {70, 5}}, DIF_DROPDOWNLIST | DIF_LISTWRAPMODE | DIF_LISTAUTOHIGHLIGHT, },
{ DI_TEXT, {{-1, 6}, {0, 6}}, DIF_SEPARATOR, {} },
{ DI_BUTTON, {{0, 7}, {0, 7}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MOk), },
{ DI_BUTTON, {{0, 7}, {0, 7}}, DIF_CENTERGROUP, msg(lng::MCancel), },
});
EditDlg[ID_OE_FILENAME].strHistory = L"NewEdit"sv;
const auto Dlg = Dialog::create(EditDlg, hndOpenEditor, &codepage);
Dlg->SetPosition({ -1, -1, 76, 10 });
Dlg->SetHelp(L"FileOpenCreate"sv);
Dlg->SetId(FileOpenCreateId);
Dlg->Process();
if (Dlg->GetExitCode() == ID_OE_OK)
{
strFileName = EditDlg[ID_OE_FILENAME].strData;
return true;
}
return false;
}
static bool dlgBadEditorCodepage(uintptr_t& codepage)
{
DialogBuilder Builder(lng::MWarning);
Builder.AddText(lng::MEditorLoadCPWarn1)->Flags = DIF_CENTERTEXT;
Builder.AddText(lng::MEditorLoadCPWarn2)->Flags = DIF_CENTERTEXT;
Builder.AddText(lng::MEditorSaveNotRecommended)->Flags = DIF_CENTERTEXT;
Builder.AddSeparator();
IntOption cp_val;
cp_val = codepage;
std::vector<DialogBuilderListItem> Items;
codepages::instance().FillCodePagesList(Items, true, false, true, false, false);
Builder.AddComboBox(cp_val, 46, Items);
Builder.AddOKCancel();
Builder.SetDialogMode(DMODE_WARNINGSTYLE);
Builder.SetId(BadEditorCodePageId);
if (!Builder.ShowDialog())
return false;
codepage = cp_val;
return true;
}
enum enumSaveFileAs
{
ID_SF_TITLE,
ID_SF_SAVEASFILETITLE,
ID_SF_FILENAME,
ID_SF_SEPARATOR1,
ID_SF_CODEPAGETITLE,
ID_SF_CODEPAGE,
ID_SF_SIGNATURE,
ID_SF_SEPARATOR2,
ID_SF_SAVEASFORMATTITLE,
ID_SF_DONOTCHANGE,
ID_SF_WINDOWS,
ID_SF_UNIX,
ID_SF_MAC,
ID_SF_SEPARATOR3,
ID_SF_OK,
ID_SF_CANCEL,
ID_SF_COUNT
};
static intptr_t hndSaveFileAs(Dialog* Dlg, intptr_t msg, intptr_t param1, void* param2)
{
static uintptr_t CurrentCodepage = 0;
switch (msg)
{
case DN_INITDIALOG:
{
CurrentCodepage = *reinterpret_cast<uintptr_t*>(Dlg->SendMessage(DM_GETDLGDATA, 0, nullptr));
codepages::instance().FillCodePagesList(Dlg, ID_SF_CODEPAGE, CurrentCodepage, false, false, false, false, false);
break;
}
case DN_CLOSE:
{
if (param1 == ID_SF_OK)
{
const auto CodepagePtr = reinterpret_cast<uintptr_t*>(Dlg->SendMessage(DM_GETDLGDATA, 0, nullptr));
FarListPos pos={sizeof(FarListPos)};
Dlg->SendMessage(DM_LISTGETCURPOS, ID_SF_CODEPAGE, &pos);
*CodepagePtr = Dlg->GetListItemSimpleUserData(ID_SF_CODEPAGE, pos.SelectPos);
return TRUE;
}
break;
}
case DN_EDITCHANGE:
{
if (param1==ID_SF_CODEPAGE)
{
FarListPos pos={sizeof(FarListPos)};
Dlg->SendMessage(DM_LISTGETCURPOS,ID_SF_CODEPAGE,&pos);
const uintptr_t cp = Dlg->GetListItemSimpleUserData(ID_SF_CODEPAGE, pos.SelectPos);
if (cp != CurrentCodepage)
{
if (IsUnicodeOrUtfCodePage(cp))
{
if (!IsUnicodeOrUtfCodePage(CurrentCodepage))
Dlg->SendMessage(DM_SETCHECK,ID_SF_SIGNATURE,ToPtr(Global->Opt->EdOpt.AddUnicodeBOM));
Dlg->SendMessage(DM_ENABLE,ID_SF_SIGNATURE,ToPtr(TRUE));
}
else
{
Dlg->SendMessage(DM_SETCHECK,ID_SF_SIGNATURE,ToPtr(BSTATE_UNCHECKED));
Dlg->SendMessage(DM_ENABLE, ID_SF_SIGNATURE, ToPtr(FALSE));
}
CurrentCodepage = cp;
return TRUE;
}
}
break;
}
default:
break;
}
return Dlg->DefProc(msg, param1, param2);
}
static bool dlgSaveFileAs(string &strFileName, eol& Eol, uintptr_t &codepage, bool &AddSignature)
{
const auto ucp = IsUnicodeOrUtfCodePage(codepage);
auto EditDlg = MakeDialogItems<ID_SF_COUNT>(
{
{ DI_DOUBLEBOX, {{3, 1 }, {72, 15}}, DIF_NONE, msg(lng::MEditTitle), },
{ DI_TEXT, {{5, 2 }, {0, 2 }}, DIF_NONE, msg(lng::MEditSaveAs), },
{ DI_EDIT, {{5, 3 }, {70, 3 }}, DIF_FOCUS | DIF_HISTORY | DIF_EDITEXPAND | DIF_EDITPATH, },
{ DI_TEXT, {{-1, 4 }, {0, 4 }}, DIF_SEPARATOR, },
{ DI_TEXT, {{5, 5 }, {0, 5 }}, DIF_NONE, msg(lng::MEditCodePage), },
{ DI_COMBOBOX, {{25, 5 }, {70, 5 }}, DIF_DROPDOWNLIST | DIF_LISTWRAPMODE | DIF_LISTAUTOHIGHLIGHT, },
{ DI_CHECKBOX, {{5, 6 }, {0, 6 }}, ucp ? DIF_NONE : DIF_DISABLE,msg(lng::MEditAddSignature), },
{ DI_TEXT, {{-1, 7 }, {0, 7 }}, DIF_SEPARATOR, },
{ DI_TEXT, {{5, 8 }, {0, 8 }}, DIF_NONE, msg(lng::MEditSaveAsFormatTitle), },
{ DI_RADIOBUTTON, {{5, 9 }, {0, 9 }}, DIF_GROUP, msg(lng::MEditSaveOriginal), },
{ DI_RADIOBUTTON, {{5, 10}, {0, 10}}, DIF_NONE, msg(lng::MEditSaveDOS), },
{ DI_RADIOBUTTON, {{5, 11}, {0, 11}}, DIF_NONE, msg(lng::MEditSaveUnix), },
{ DI_RADIOBUTTON, {{5, 12}, {0, 12}}, DIF_NONE, msg(lng::MEditSaveMac), },
{ DI_TEXT, {{-1, 13}, {0, 13}}, DIF_SEPARATOR, },
{ DI_BUTTON, {{0, 14}, {0, 14}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MEditorSave), },
{ DI_BUTTON, {{0, 14}, {0, 14}}, DIF_CENTERGROUP, msg(lng::MCancel), },
});
EditDlg[ID_SF_FILENAME].strHistory = L"NewEdit"sv;
EditDlg[ID_SF_FILENAME].strData = (/*Flags.Check(FFILEEDIT_SAVETOSAVEAS)?strFullFileName:strFileName*/strFileName);
EditDlg[ID_SF_SIGNATURE].Selected = AddSignature;
if (const auto pos = EditDlg[ID_SF_FILENAME].strData.find(msg(lng::MNewFileName)); pos != string::npos)
EditDlg[ID_SF_FILENAME].strData.resize(pos);
const auto EolToIndex = [&]()
{
if (Eol == eol::win)
return 1;
if (Eol == eol::unix)
return 2;
if (Eol == eol::mac)
return 3;
return 0;
};
EditDlg[ID_SF_DONOTCHANGE + EolToIndex()].Selected = TRUE;
const auto Dlg = Dialog::create(EditDlg, hndSaveFileAs, &codepage);
Dlg->SetPosition({ -1, -1, 76, 17 });
Dlg->SetHelp(L"FileSaveAs"sv);
Dlg->SetId(FileSaveAsId);
Dlg->Process();
if ((Dlg->GetExitCode() == ID_SF_OK) && !EditDlg[ID_SF_FILENAME].strData.empty())
{
strFileName = EditDlg[ID_SF_FILENAME].strData;
AddSignature=EditDlg[ID_SF_SIGNATURE].Selected!=0;
if (EditDlg[ID_SF_DONOTCHANGE].Selected)
Eol = eol::none;
else if (EditDlg[ID_SF_WINDOWS].Selected)
Eol = eol::win;
else if (EditDlg[ID_SF_UNIX].Selected)
Eol = eol::unix;
else if (EditDlg[ID_SF_MAC].Selected)
Eol = eol::mac;
return true;
}
return false;
}
fileeditor_ptr FileEditor::create(const string_view Name, uintptr_t codepage, DWORD InitFlags, int StartLine, int StartChar, const string* PluginData, EDITOR_FLAGS OpenModeExstFile)
{
auto FileEditorPtr = std::make_shared<FileEditor>(private_tag());
FileEditorPtr->ScreenObjectWithShadow::SetPosition({ 0, 0, ScrX, ScrY });
FileEditorPtr->m_Flags.Set(InitFlags);
FileEditorPtr->m_Flags.Set(FFILEEDIT_FULLSCREEN);
FileEditorPtr->Init(Name, codepage, nullptr, StartLine, StartChar, PluginData, FALSE, nullptr, OpenModeExstFile);
return FileEditorPtr;
}
fileeditor_ptr FileEditor::create(const string_view Name, uintptr_t codepage, DWORD InitFlags, int StartLine, int StartChar, const string* Title, rectangle Position, int DeleteOnClose, const window_ptr& Update, EDITOR_FLAGS OpenModeExstFile)
{
auto FileEditorPtr = std::make_shared<FileEditor>(private_tag());
FileEditorPtr->m_Flags.Set(InitFlags);
// BUGBUG WHY ALL THIS?
if (Position.left < 0)
Position.left = 0;
if (Position.right < 0 || Position.right > ScrX)
Position.right = ScrX;
if (Position.top < 0)
Position.top = 0;
if (Position.bottom < 0 || Position.bottom > ScrY)
Position.bottom = ScrY;
if (Position.left > Position.right)
{
Position.left = 0;
Position.right = ScrX;
}
if (Position.top > Position.bottom)
{
Position.top = 0;
Position.bottom = ScrY;
}
FileEditorPtr->SetPosition(Position);
FileEditorPtr->m_Flags.Change(FFILEEDIT_FULLSCREEN, (!Position.left && !Position.top && Position.right == ScrX && Position.bottom == ScrY));
string EmptyTitle;
FileEditorPtr->Init(Name, codepage, Title, StartLine, StartChar, &EmptyTitle, DeleteOnClose, Update, OpenModeExstFile);
return FileEditorPtr;
}
/* $ 07.05.2001 DJ
в деструкторе грохаем EditNamesList, если он был создан, а в SetNamesList()
создаем EditNamesList и копируем туда значения
*/
/*
Вызов деструкторов идет так:
FileEditor::~FileEditor()
Editor::~Editor()
...
*/
FileEditor::~FileEditor()
{
if (!m_Flags.Check(FFILEEDIT_OPENFAILED))
{
/* $ 11.10.2001 IS
Удалим файл вместе с каталогом, если это просится и файла с таким же
именем не открыто в других окнах.
*/
/* $ 14.06.2001 IS
Если установлен FEDITOR_DELETEONLYFILEONCLOSE и сброшен
FEDITOR_DELETEONCLOSE, то удаляем только файл.
*/
if (m_Flags.Check(FFILEEDIT_DELETEONCLOSE|FFILEEDIT_DELETEONLYFILEONCLOSE) &&
!Global->WindowManager->CountWindowsWithName(strFullFileName))
{
if (m_Flags.Check(FFILEEDIT_DELETEONCLOSE))
DeleteFileWithFolder(strFullFileName);
else
{
(void)os::fs::set_file_attributes(strFullFileName,FILE_ATTRIBUTE_NORMAL); // BUGBUG
(void)os::fs::delete_file(strFullFileName); //BUGBUG
}
}
}
}
void FileEditor::Init(
const string_view Name,
uintptr_t codepage,
const string* Title,
int StartLine,
int StartChar,
const string* PluginData,
int DeleteOnClose,
const window_ptr& Update,
EDITOR_FLAGS OpenModeExstFile
)
{
m_windowKeyBar = std::make_unique<KeyBar>(shared_from_this());
const auto BlankFileName = Name == msg(lng::MNewFileName) || Name.empty();
bEE_READ_Sent = false;
bLoaded = false;
m_bAddSignature = false;
m_editor = std::make_unique<Editor>(shared_from_this(), codepage);
m_codepage = codepage;
*AttrStr=0;
m_FileAttributes=INVALID_FILE_ATTRIBUTES;
SetTitle(Title);
// $ 17.08.2001 KM - Добавлено для поиска по AltF7. При редактировании найденного файла из архива для клавиши F2 сделать вызов ShiftF2.
m_Flags.Change(FFILEEDIT_SAVETOSAVEAS, BlankFileName);
if (BlankFileName && !m_Flags.Check(FFILEEDIT_CANNEWFILE))
{
SetExitCode(XC_OPEN_ERROR);
return;
}
SetPluginData(PluginData);
m_editor->SetHostFileEditor(this);
SetCanLoseFocus(m_Flags.Check(FFILEEDIT_ENABLEF6));
strStartDir = os::fs::GetCurrentDirectory();
if (!SetFileName(Name))
{
SetExitCode(XC_OPEN_ERROR);
return;
}
{
if (auto EditorWindow = Global->WindowManager->FindWindowByFile(windowtype_editor, strFullFileName))
{
int SwitchTo=FALSE;
if (!EditorWindow->GetCanLoseFocus(true) || Global->Opt->Confirm.AllowReedit)
{
int Result = XC_EXISTS;
if (OpenModeExstFile == EF_OPENMODE_QUERY)
{
int MsgCode;
if (m_Flags.Check(FFILEEDIT_ENABLEF6))
{
MsgCode = Message(0,
msg(lng::MEditTitle),
{
strFullFileName,
msg(lng::MAskReload)
},
{ lng::MCurrent, lng::MNewOpen, lng::MReload, lng::MCancel },
L"EditorReload"sv, &EditorReloadId);
}
else
{
MsgCode = Message(0,
msg(lng::MEditTitle),
{
strFullFileName,
msg(lng::MAskReload)
},
{ lng::MNewOpen, lng::MCancel },
L"EditorReload"sv, &EditorReloadModalId);
if (MsgCode == Message::first_button)
MsgCode = Message::second_button;
}
switch (MsgCode)
{
case Message::first_button:
Result = XC_EXISTS;
break;
case Message::second_button:
Result = XC_OPEN_NEWINSTANCE;
break;
case Message::third_button:
Result = XC_RELOAD;
break;
default:
SetExitCode(XC_LOADING_INTERRUPTED);
return;
}
}
else
{
if (m_Flags.Check(FFILEEDIT_ENABLEF6))
{
switch (OpenModeExstFile)
{
case EF_OPENMODE_USEEXISTING:
Result = XC_EXISTS;
break;
case EF_OPENMODE_NEWIFOPEN:
Result = XC_OPEN_NEWINSTANCE;
break;
case EF_OPENMODE_RELOADIFOPEN:
Result = XC_RELOAD;
break;
default:
SetExitCode(XC_EXISTS);
return;
}
}
else
{
switch (OpenModeExstFile)
{
case EF_OPENMODE_NEWIFOPEN:
Result = XC_OPEN_NEWINSTANCE;
break;
}
}
}
switch (Result)
{
case XC_EXISTS:
SwitchTo=TRUE;
SetExitCode(Result); // ???
break;
case XC_OPEN_NEWINSTANCE:
SetExitCode(Result); // ???
break;
case XC_RELOAD:
{
//файл могли уже закрыть. например макросом в диалоговой процедуре предыдущего Message.
EditorWindow = Global->WindowManager->FindWindowByFile(windowtype_editor, strFullFileName);
if (EditorWindow)
{
EditorWindow->SetFlags(FFILEEDIT_DISABLESAVEPOS);
Global->WindowManager->DeleteWindow(EditorWindow);
}
SetExitCode(Result); // -2 ???
}
break;
}
}
else
{
SwitchTo=TRUE;
SetExitCode((OpenModeExstFile != EF_OPENMODE_QUERY) ? XC_EXISTS : XC_MODIFIED); // TRUE???
}
if (SwitchTo)
{
//файл могли уже закрыть. например макросом в диалоговой процедуре предыдущего Message.
EditorWindow = Global->WindowManager->FindWindowByFile(windowtype_editor, strFullFileName);
if (EditorWindow)
{
Global->WindowManager->ActivateWindow(EditorWindow);
}
return ;
}
}
}
/* $ 29.11.2000 SVS
Если файл имеет атрибут ReadOnly или System или Hidden,
И параметр на запрос выставлен, то сначала спросим.
*/
/* $ 03.12.2000 SVS
System или Hidden - задаются отдельно
*/
/* $ 15.12.2000 SVS
- Shift-F4, новый файл. Выдает сообщение :-(
*/
const os::fs::file_status FileStatus(Name);
/* $ 05.06.2001 IS
+ посылаем подальше всех, кто пытается отредактировать каталог
*/
if (os::fs::is_directory(FileStatus))
{
Message(MSG_WARNING,
msg(lng::MEditTitle),
{
msg(lng::MEditCanNotEditDirectory)
},
{ lng::MOk },
{}, &EditorCanNotEditDirectoryId);
SetExitCode(XC_OPEN_ERROR);
return;
}
if (m_editor->EdOpt.ReadOnlyLock & 1_bit &&
FileStatus.check(FILE_ATTRIBUTE_READONLY |
/* Hidden=0x2 System=0x4 - располагаются во 2-м полубайте,
поэтому применяем маску 0110.0000 и
сдвигаем на свое место => 0000.0110 и получаем
те самые нужные атрибуты */
((m_editor->EdOpt.ReadOnlyLock & 0b0110'0000) >> 4)
)
)
{
if (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
string(Name),
msg(lng::MEditRSH),
msg(lng::MEditROOpen)
},
{ lng::MYes, lng::MNo },
{}, &EditorOpenRSHId) != Message::first_button)
{
SetExitCode(XC_OPEN_ERROR);
return;
}
}
m_editor->SetPosition({ m_Where.left, m_Where.top + (IsTitleBarVisible()? 1 : 0), m_Where.right, m_Where.bottom - (IsKeyBarVisible()? 1 : 0) });
m_editor->SetStartPos(StartLine,StartChar);
SetDeleteOnClose(DeleteOnClose);
int UserBreak;
/* $ 06.07.2001 IS
При создании файла с нуля так же посылаем плагинам событие EE_READ, дабы
не нарушать однообразие.
*/
if (!os::fs::exists(FileStatus))
m_Flags.Set(FFILEEDIT_NEW);
if (BlankFileName && m_Flags.Check(FFILEEDIT_CANNEWFILE))
m_Flags.Set(FFILEEDIT_NEW);
if (m_Flags.Check(FFILEEDIT_NEW))
m_bAddSignature = Global->Opt->EdOpt.AddUnicodeBOM;
if (m_Flags.Check(FFILEEDIT_LOCKED))
m_editor->m_Flags.Set(Editor::FEDITOR_LOCKMODE);
error_state_ex ErrorState;
while (!LoadFile(strFullFileName,UserBreak, ErrorState))
{
if (BlankFileName)
{
m_Flags.Clear(FFILEEDIT_OPENFAILED); //AY: ну так как редактор мы открываем то видимо надо и сбросить ошибку открытия
UserBreak=0;
}
if (!m_Flags.Check(FFILEEDIT_NEW) || UserBreak)
{
if (UserBreak!=1)
{
if(OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotOpen), false) == operation::retry)
continue;
else
SetExitCode(XC_OPEN_ERROR);
}
else
{
SetExitCode(XC_LOADING_INTERRUPTED);
}
// Ахтунг. Ниже комментарии оставлены в назидании потомкам (до тех пор, пока не измениться манагер)
//WindowManager->DeleteWindow(this); // BugZ#546 - Editor валит фар!
//Global->CtrlObject->Cp()->Redraw(); //AY: вроде как не надо, делает проблемы с прорисовкой если в редакторе из истории попытаться выбрать несуществующий файл
// если прервали загрузку, то фреймы нужно проапдейтить, чтобы предыдущие месаги не оставались на экране
if (!Global->Opt->Confirm.Esc && UserBreak && GetExitCode() == XC_LOADING_INTERRUPTED)
Global->WindowManager->RefreshWindow();
return;
}
if (m_codepage==CP_DEFAULT || m_codepage == CP_REDETECT)
m_codepage = GetDefaultCodePage();
m_editor->SetCodePage(m_codepage, nullptr, false);
break;
}
if (GetExitCode() == XC_LOADING_INTERRUPTED || GetExitCode() == XC_OPEN_ERROR)
return;
InitKeyBar();
// Note: bottom - bottom
m_windowKeyBar->SetPosition({ m_Where.left, m_Where.bottom, m_Where.right, m_Where.bottom });
if (IsKeyBarVisible())
{
m_windowKeyBar->Show();
}
else
{
m_windowKeyBar->Hide();
}
SetMacroMode(MACROAREA_EDITOR);
F4KeyOnly=true;
bLoaded = true;
if (m_Flags.Check(FFILEEDIT_ENABLEF6))
{
if (Update) Global->WindowManager->ReplaceWindow(Update, shared_from_this());
else Global->WindowManager->InsertWindow(shared_from_this());
}
else
{
if (Update) Global->WindowManager->DeleteWindow(Update);
Global->WindowManager->ExecuteWindow(shared_from_this());
}
Global->WindowManager->CallbackWindow([this](){ ReadEvent(); });
}
void FileEditor::ReadEvent()
{
Global->CtrlObject->Plugins->ProcessEditorEvent(EE_READ, nullptr, m_editor.get());
bEE_READ_Sent = true;
Global->WindowManager->RefreshWindow(); //в EE_READ поменялась позиция курсора или размер табуляции.
}
void FileEditor::InitKeyBar()
{
auto& Keybar = *m_windowKeyBar;
Keybar.SetLabels(lng::MEditF1);
if (Global->OnlyEditorViewerUsed)
{
Keybar[KBL_SHIFT][F4].clear();
Keybar[KBL_CTRL][F10].clear();
}
if (!GetCanLoseFocus())
{
Keybar[KBL_MAIN][F12].clear();
Keybar[KBL_ALT][F11].clear();
Keybar[KBL_SHIFT][F4].clear();
}
if (m_Flags.Check(FFILEEDIT_SAVETOSAVEAS))
Keybar[KBL_MAIN][F2] = msg(lng::MEditShiftF2);
if (!m_Flags.Check(FFILEEDIT_ENABLEF6))
Keybar[KBL_MAIN][F6].clear();
Keybar[KBL_MAIN][F8] = f8cps.NextCPname(m_codepage);
Keybar.SetCustomLabels(KBA_EDITOR);
}
void FileEditor::SetNamesList(NamesList& Names)
{
EditNamesList = std::move(Names);
}
void FileEditor::Show()
{
if (m_Flags.Check(FFILEEDIT_FULLSCREEN))
{
if (IsKeyBarVisible())
{
m_windowKeyBar->SetPosition({ 0, ScrY, ScrX, ScrY });
}
ScreenObjectWithShadow::SetPosition({ 0, 0, ScrX, ScrY });
}
if (IsKeyBarVisible())
{
m_windowKeyBar->Redraw();
}
m_editor->SetPosition({ m_Where.left, m_Where.top + (IsTitleBarVisible()? 1 : 0), m_Where.right, m_Where.bottom - (IsKeyBarVisible()? 1 : 0) });
ScreenObjectWithShadow::Show();
}
void FileEditor::DisplayObject()
{
if (!m_bClosing)
{
m_editor->Show();
}
}
long long FileEditor::VMProcess(int OpCode, void* vParam, long long iParam)
{
if (OpCode == MCODE_V_EDITORSTATE)
{
DWORD MacroEditState = 0;
MacroEditState |= m_Flags.Check(FFILEEDIT_NEW)? 0_bit : 0;
MacroEditState |= m_Flags.Check(FFILEEDIT_ENABLEF6)? 1_bit : 0;
MacroEditState |= m_Flags.Check(FFILEEDIT_DELETEONCLOSE)? 2_bit : 0;
MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)? 3_bit : 0;
MacroEditState |= m_editor->IsStreamSelection()? 4_bit : 0;
MacroEditState |= m_editor->IsVerticalSelection()? 5_bit : 0;
MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_WASCHANGED)? 6_bit : 0;
MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_OVERTYPE)? 7_bit : 0;
MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_CURPOSCHANGEDBYPLUGIN)? 8_bit : 0;
MacroEditState |= m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE)? 9_bit : 0;
MacroEditState |= m_editor->EdOpt.PersistentBlocks? 10_bit : 0;
MacroEditState |= !GetCanLoseFocus()? 11_bit : 0;
MacroEditState |= Global->OnlyEditorViewerUsed ? 27_bit | 11_bit : 0;
return MacroEditState;
}
if (OpCode == MCODE_V_EDITORCURPOS)
return m_editor->m_it_CurLine->GetTabCurPos()+1;
if (OpCode == MCODE_V_EDITORCURLINE)
return m_editor->m_it_CurLine.Number() + 1;
if (OpCode == MCODE_V_ITEMCOUNT || OpCode == MCODE_V_EDITORLINES)
return m_editor->Lines.size();
if (OpCode == MCODE_F_KEYBAR_SHOW)
{
int PrevMode=IsKeyBarVisible()?2:1;
switch (iParam)
{
case 0:
break;
case 1:
Global->Opt->EdOpt.ShowKeyBar = true;
m_windowKeyBar->Show();
Show();
break;
case 2:
Global->Opt->EdOpt.ShowKeyBar = false;
m_windowKeyBar->Hide();
Show();
break;
case 3:
ProcessKey(Manager::Key(KEY_CTRLB));
break;
default:
PrevMode=0;
break;
}
return PrevMode;
}
return m_editor->VMProcess(OpCode,vParam,iParam);
}
bool FileEditor::ProcessKey(const Manager::Key& Key)
{
return ReProcessKey(Key, false);
}
bool FileEditor::ReProcessKey(const Manager::Key& Key, bool CalledFromControl)
{
const auto LocalKey = Key();
if (none_of(LocalKey, KEY_F4, KEY_IDLE))
F4KeyOnly=false;
if (m_Flags.Check(FFILEEDIT_REDRAWTITLE) && ((LocalKey & 0x00ffffff) < KEY_END_FKEY || IsInternalKeyReal(LocalKey & 0x00ffffff)))
ShowConsoleTitle();
// Все остальные необработанные клавиши пустим далее
/* $ 28.04.2001 DJ
не передаем KEY_MACRO* плагину - поскольку ReadRec в этом случае
никак не соответствует обрабатываемой клавише, возникают разномастные
глюки
*/
if (in_closed_range(KEY_MACRO_BASE, LocalKey, KEY_MACRO_ENDBASE) || in_closed_range(KEY_OP_BASE, LocalKey, KEY_OP_ENDBASE)) // исключаем MACRO
{
// ; //
}
switch (LocalKey)
{
case KEY_F6:
{
if (m_Flags.Check(FFILEEDIT_ENABLEF6))
{
int FirstSave=1;
auto cp = m_codepage;
// проверка на "а может это говно удалили уже?"
// возможно здесь она и не нужна!
// хотя, раз уж были изменения, то
if (m_editor->IsFileChanged() && // в текущем сеансе были изменения?
!os::fs::exists(strFullFileName))
{
switch (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
msg(lng::MEditSavedChangedNonFile),
msg(lng::MEditSavedChangedNonFile2)
},
{ lng::MHYes, lng::MHNo },
{}, &EditorSaveF6DeletedId))
{
case 0:
if (ProcessKey(Manager::Key(KEY_F2)))
{
FirstSave=0;
break;
}
[[fallthrough]];
default:
return false;
}
}
if (!FirstSave || m_editor->IsFileChanged() || os::fs::exists(strFullFileName))
{
const auto FilePos = m_editor->GetCurPos(true, m_bAddSignature);
/* $ 01.02.2001 IS
! Открываем viewer с указанием длинного имени файла, а не короткого
*/
bool NeedQuestion = true;
if (ProcessQuitKey(FirstSave,NeedQuestion,false))
{
int delete_on_close = 0;
if (m_Flags.Check(FFILEEDIT_DELETEONCLOSE))
delete_on_close = 1;
else if (m_Flags.Check(FFILEEDIT_DELETEONLYFILEONCLOSE))
delete_on_close = 2;
SetDeleteOnClose(0);
FileViewer::create(
strFullFileName,
GetCanLoseFocus(),
m_Flags.Check(FFILEEDIT_DISABLEHISTORY),
false,
FilePos,
{},
&EditNamesList,
m_Flags.Check(FFILEEDIT_SAVETOSAVEAS),
cp,
strTitle,
delete_on_close,
shared_from_this());
}
}
return true;
}
break; // отдадим F6 плагинам, если есть запрет на переключение
}
/* $ 10.05.2001 DJ
Alt-F11 - показать view/edit history
*/
case KEY_ALTF11:
case KEY_RALTF11:
{
if (GetCanLoseFocus())
{
Global->CtrlObject->CmdLine()->ShowViewEditHistory();
return true;
}
break; // отдадим Alt-F11 на растерзание плагинам, если редактор модальный
}
}
bool ProcessedNext = true;
_SVS(if (LocalKey=='n' || LocalKey=='m'))
_SVS(SysLog(L"%d Key='%c'",__LINE__,LocalKey));
const auto MacroState = Global->CtrlObject->Macro.GetState();
if (!CalledFromControl && (MacroState == MACROSTATE_RECORDING_COMMON || MacroState == MACROSTATE_EXECUTING_COMMON || MacroState == MACROSTATE_NOMACRO))
{
assert(Key.IsEvent());
if (Key.IsReal())
{
ProcessedNext=!ProcessEditorInput(Key.Event());
}
}
if (ProcessedNext)
{
switch (LocalKey)
{
case KEY_F1:
{
help::show(L"Editor"sv);
return true;
}
/* $ 25.04.2001 IS
ctrl+f - вставить в строку полное имя редактируемого файла
*/
case KEY_CTRLF:
case KEY_RCTRLF:
{
if (!m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE))
{
m_editor->Pasting++;
m_editor->TextChanged(true);
if (!m_editor->EdOpt.PersistentBlocks && m_editor->IsAnySelection())
{
m_editor->TurnOffMarkingBlock();
m_editor->DeleteBlock();
}
m_editor->Paste(strFullFileName); //???
//if (!EdOpt.PersistentBlocks)
m_editor->UnmarkBlock();
m_editor->Pasting--;
m_editor->Show(); //???
}
return true;
}
/* $ 24.08.2000 SVS
+ Добавляем реакцию показа бакграунда на клавишу CtrlAltShift
*/
case KEY_CTRLO:
case KEY_RCTRLO:
{
m_editor->Hide(); // $ 27.09.2000 skv - To prevent redraw in macro with Ctrl-O
if (Global->WindowManager->ShowBackground())
{
SetCursorType(false, 0);
WaitKey();
}
Global->WindowManager->RefreshAll();
return true;
}
case KEY_F2:
case KEY_SHIFTF2:
{
auto Done = false;
while (!Done) // бьемся до упора
{
// проверим путь к файлу, может его уже снесли...
// BUGBUG, похоже, не работает
const auto pos = FindLastSlash(strFullFileName);
if (pos != string::npos)
{
const auto Path = string_view(strFullFileName).substr(pos);
// В корне?
if(IsRootPath(Path))
{
// а дальше? каталог существует?
if (!os::fs::is_directory(Path)
//|| LocalStricmp(OldCurDir,FullFileName) // <- это видимо лишнее.
)
m_Flags.Set(FFILEEDIT_SAVETOSAVEAS);
}
}
if (LocalKey == KEY_F2 && os::fs::is_file(strFullFileName))
{
m_Flags.Clear(FFILEEDIT_SAVETOSAVEAS);
}
static eol SavedEol = eol::none; // none here means "do not change"
uintptr_t codepage = m_codepage;
const auto SaveAs = LocalKey==KEY_SHIFTF2 || m_Flags.Check(FFILEEDIT_SAVETOSAVEAS);
string strFullSaveAsName = strFullFileName;
if (SaveAs)
{
string strSaveAsName = m_Flags.Check(FFILEEDIT_SAVETOSAVEAS)?strFullFileName:strFileName;
if (!dlgSaveFileAs(strSaveAsName, SavedEol, codepage, m_bAddSignature))
return false;
strSaveAsName = unquote(os::env::expand(strSaveAsName));
const auto NameChanged = !equal_icase(strSaveAsName, m_Flags.Check(FFILEEDIT_SAVETOSAVEAS)? strFullFileName : strFileName);
if (NameChanged)
{
if (!AskOverwrite(strSaveAsName))
{
return true;
}
}
strFullSaveAsName = ConvertNameToFull(strSaveAsName); //BUGBUG, не проверяем имя на правильность
}
error_state_ex ErrorState;
int SaveResult=SaveFile(strFullSaveAsName, 0, SaveAs, ErrorState, SavedEol, codepage, m_bAddSignature);
if (SaveResult==SAVEFILE_ERROR)
{
if (OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotSave), false) != operation::retry)
{
Done = true;
break;
}
}
else if (SaveResult==SAVEFILE_SUCCESS)
{
//здесь идет полная жопа, проверка на ошибки вообще пока отсутствует
{
bool bInPlace = /*(!IsUnicodeOrUtfCodePage(m_codepage) && !IsUnicodeOrUtfCodePage(codepage)) || */(m_codepage == codepage);
if (!bInPlace)
{
m_editor->FreeAllocatedData();
m_editor->PushString({});
m_codepage = codepage;
}
SetFileName(strFullSaveAsName);
if (!bInPlace)
{
//Message(MSG_WARNING, 1, L"WARNING!", L"Editor will be reopened with new file!", msg(lng::MOk));
int UserBreak;
error_state_ex LoadErrorState;
LoadFile(strFullSaveAsName, UserBreak, LoadErrorState); // BUGBUG check result
// TODO: возможно подобный ниже код здесь нужен (copy/paste из FileEditor::Init()). оформить его нужно по иному
//if(!Global->Opt->Confirm.Esc && UserBreak && GetExitCode()==XC_LOADING_INTERRUPTED && WindowManager)
// WindowManager->RefreshWindow();
}
// перерисовывать надо как минимум когда изменилась кодировка или имя файла
ShowConsoleTitle();
Show();//!!! BUGBUG
}
Done = true;
}
else
{
Done = true;
break;
}
}
return true;
}
// $ 30.05.2003 SVS - Shift-F4 в редакторе/вьювере позволяет открывать другой редактор/вьювер (пока только редактор)
case KEY_SHIFTF4:
{
if (!Global->OnlyEditorViewerUsed && GetCanLoseFocus())
{
if (!m_Flags.Check(FFILEEDIT_DISABLESAVEPOS) && (m_editor->EdOpt.SavePos || m_editor->EdOpt.SaveShortPos)) // save position/codepage before reload
SaveToCache();
Global->CtrlObject->Cp()->ActivePanel()->ProcessKey(Key);
}
return true;
}
// $ 21.07.2000 SKV + выход с позиционированием на редактируемом файле по CTRLF10
case KEY_CTRLF10:
case KEY_RCTRLF10:
{
if (Global->WindowManager->InModal())
{
return true;
}
string strFullFileNameTemp = strFullFileName;
if (!os::fs::exists(strFullFileName)) // а сам файл то еще на месте?
{
if (!CheckShortcutFolder(strFullFileNameTemp, true, false))
return false;
path::append(strFullFileNameTemp, L'.'); // для вваливания внутрь :-)
}
const auto ActivePanel = Global->CtrlObject->Cp()->ActivePanel();
if (m_Flags.Check(FFILEEDIT_NEW) || (ActivePanel && ActivePanel->FindFile(strFileName) == -1)) // Mantis#279
{
UpdateFileList();
m_Flags.Clear(FFILEEDIT_NEW);
}
{
SCOPED_ACTION(SaveScreen);
Global->CtrlObject->Cp()->GoToFile(strFullFileNameTemp);
m_Flags.Set(FFILEEDIT_REDRAWTITLE);
}
return true;
}
case KEY_CTRLB:
case KEY_RCTRLB:
{
Global->Opt->EdOpt.ShowKeyBar=!Global->Opt->EdOpt.ShowKeyBar;
if (IsKeyBarVisible())
m_windowKeyBar->Show();
else
m_windowKeyBar->Hide();
Show();
return true;
}
case KEY_CTRLSHIFTB:
case KEY_RCTRLSHIFTB:
{
Global->Opt->EdOpt.ShowTitleBar=!Global->Opt->EdOpt.ShowTitleBar;
Show();
return true;
}
case KEY_SHIFTF10:
if (!ProcessKey(Manager::Key(KEY_F2))) // учтем факт того, что могли отказаться от сохранения
return false;
[[fallthrough]];
case KEY_F4:
if (F4KeyOnly)
return true;
[[fallthrough]];
case KEY_ESC:
case KEY_F10:
{
bool FirstSave = true, NeedQuestion = true;
if (LocalKey != KEY_SHIFTF10) // KEY_SHIFTF10 не учитываем!
{
const auto FilePlaced = !os::fs::exists(strFullFileName) && !m_Flags.Check(FFILEEDIT_NEW);
if (m_editor->IsFileChanged() || // в текущем сеансе были изменения?
FilePlaced) // а сам файл то еще на месте?
{
auto MsgLine1 = lng::MNewFileName;
if (m_editor->IsFileChanged() && FilePlaced)
MsgLine1 = lng::MEditSavedChangedNonFile;
else if (!m_editor->IsFileChanged() && FilePlaced)
MsgLine1 = lng::MEditSavedChangedNonFile1;
if (MsgLine1 != lng::MNewFileName)
{
switch (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
msg(MsgLine1),
msg(lng::MEditSavedChangedNonFile2)
},
{ lng::MHYes, lng::MHNo, lng::MHCancel },
{}, &EditorSaveExitDeletedId))
{
case Message::first_button:
if (!ProcessKey(Manager::Key(KEY_F2))) // попытка сначала сохранить
NeedQuestion = false;
FirstSave = false;
break;
case Message::second_button:
NeedQuestion = false;
FirstSave = false;
break;
default:
return false;
}
}
}
else if (!m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)) //????
NeedQuestion = false;
}
return ProcessQuitKey(FirstSave, NeedQuestion);
}
case KEY_F8:
{
SetCodePageEx(f8cps.NextCP(m_codepage));
return true;
}
case KEY_SHIFTF8:
{
uintptr_t codepage = m_codepage;
if (codepages::instance().SelectCodePage(codepage, false, true))
SetCodePageEx(codepage == CP_DEFAULT? CP_REDETECT : codepage);
return true;
}
case KEY_ALTSHIFTF9:
case KEY_RALTSHIFTF9:
{
// Работа с локальной копией EditorOptions
Options::EditorOptions EdOpt;
GetEditorOptions(EdOpt);
Global->Opt->LocalEditorConfig(EdOpt); // $ 27.11.2001 DJ - Local в EditorConfig
m_windowKeyBar->Show(); //???? Нужно ли????
SetEditorOptions(EdOpt);
if (IsKeyBarVisible())
m_windowKeyBar->Show();
m_editor->Show();
return true;
}
default:
{
if (m_Flags.Check(FFILEEDIT_FULLSCREEN) && !Global->CtrlObject->Macro.IsExecuting())
if (IsKeyBarVisible())
m_windowKeyBar->Show();
if (!m_windowKeyBar->ProcessKey(Key))
return m_editor->ProcessKey(Key);
}
}
}
return true;
}
bool FileEditor::SetCodePageEx(uintptr_t cp)
{
if (cp == CP_DEFAULT)
{
EditorPosCache epc;
if (!LoadFromCache(epc) || epc.CodePage <= 0 || epc.CodePage > 0xffff)
return false;
cp = epc.CodePage;
}
else if (cp == CP_REDETECT)
{
const os::fs::file EditFile(strFileName, FILE_READ_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING);
const auto DefaultCodepage = GetDefaultCodePage();
cp = EditFile? GetFileCodepage(EditFile, DefaultCodepage) : DefaultCodepage;
}
if (cp == CP_DEFAULT || !codepages::IsCodePageSupported(cp))
{
Message(MSG_WARNING,
msg(lng::MEditTitle),
{
format(msg(lng::MEditorCPNotSupported), cp)
},
{ lng::MOk });
return false;
}
if (cp == m_codepage)
return true;
const auto CurrentCodepage = m_codepage;
const auto need_reload = !m_Flags.Check(FFILEEDIT_NEW) // we can't reload non-existing file
&& (BadConversion
|| IsUnicodeCodePage(m_codepage)
|| IsUnicodeCodePage(cp));
if (need_reload)
{
if (IsFileModified())
{
if (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
msg(lng::MEditorReloadCPWarnLost1),
msg(lng::MEditorReloadCPWarnLost2)
},
{ lng::MOk, lng::MCancel }) != Message::first_button)
{
return false;
}
}
// BUGBUG result check???
ReloadFile(cp);
}
else
{
SetCodePage(cp);
}
if (m_codepage == CurrentCodepage)
return false;
InitKeyBar();
return true;
}
bool FileEditor::ProcessQuitKey(int FirstSave, bool NeedQuestion, bool DeleteWindow)
{
for (;;)
{
int SaveCode=SAVEFILE_SUCCESS;
error_state_ex ErrorState;
if (NeedQuestion)
{
SaveCode=SaveFile(strFullFileName, FirstSave, false, ErrorState);
}
if (SaveCode==SAVEFILE_CANCEL)
break;
if (SaveCode==SAVEFILE_SUCCESS)
{
/* $ 09.02.2002 VVM
+ Обновить панели, если писали в текущий каталог */
if (NeedQuestion)
{
if (os::fs::exists(strFullFileName))
{
UpdateFileList();
}
}
if (DeleteWindow)
{
Global->WindowManager->DeleteWindow();
}
SetExitCode(XC_QUIT);
break;
}
if (strFileName == msg(lng::MNewFileName))
{
if (!ProcessKey(Manager::Key(KEY_SHIFTF2)))
{
return FALSE;
}
else
break;
}
if (OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotSave), false) != operation::retry)
break;
FirstSave=0;
}
return GetExitCode() == XC_QUIT;
}
bool FileEditor::LoadFile(const string& Name,int &UserBreak, error_state_ex& ErrorState)
{
try
{
// TODO: indentation
SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<Editor::EditorPreRedrawItem>());
SCOPED_ACTION(taskbar::indeterminate);
SCOPED_ACTION(wakeful);
EditorPosCache pc;
UserBreak = 0;
os::fs::file EditFile(Name, FILE_READ_DATA, FILE_SHARE_READ | (Global->Opt->EdOpt.EditOpenedForWrite? (FILE_SHARE_WRITE | FILE_SHARE_DELETE) : 0), nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN);
if(!EditFile)
{
ErrorState = error_state::fetch();
if ((ErrorState.Win32Error != ERROR_FILE_NOT_FOUND) && (ErrorState.Win32Error != ERROR_PATH_NOT_FOUND))
{
UserBreak = -1;
m_Flags.Set(FFILEEDIT_OPENFAILED);
}
return false;
}
if (Global->Opt->EdOpt.FileSizeLimit)
{
unsigned long long FileSize = 0;
if (EditFile.GetSize(FileSize))
{
if (FileSize > static_cast<unsigned long long>(Global->Opt->EdOpt.FileSizeLimit))
{
if (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
Name,
// Ширина = 8 - это будет... в Kb и выше...
format(msg(lng::MEditFileLong), trim(FileSizeToStr(FileSize, 8))),
format(msg(lng::MEditFileLong2), trim(FileSizeToStr(Global->Opt->EdOpt.FileSizeLimit, 8))),
msg(lng::MEditROOpen)
},
{ lng::MYes, lng::MNo },
{}, &EditorFileLongId) != Message::first_button)
{
EditFile.Close();
SetLastError(ERROR_OPEN_FAILED); //????
ErrorState = error_state::fetch();
UserBreak=1;
m_Flags.Set(FFILEEDIT_OPENFAILED);
return false;
}
}
}
else
{
if (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
Name, msg(lng::MEditFileGetSizeError),
msg(lng::MEditROOpen)
},
{ lng::MYes, lng::MNo },
{}, &EditorFileGetSizeErrorId) != Message::first_button)
{
EditFile.Close();
SetLastError(ERROR_OPEN_FAILED); //????
ErrorState = error_state::fetch();
UserBreak=1;
m_Flags.Set(FFILEEDIT_OPENFAILED);
return false;
}
}
}
for (BitFlags f0 = m_editor->m_Flags; ; m_editor->m_Flags = f0)
{
m_editor->FreeAllocatedData();
const auto Cached = LoadFromCache(pc);
const os::fs::file_status FileStatus(Name);
if ((m_editor->EdOpt.ReadOnlyLock & 0_bit) && FileStatus.check(FILE_ATTRIBUTE_READONLY | (m_editor->EdOpt.ReadOnlyLock & 0b0110'0000) >> 4))
{
m_editor->m_Flags.Invert(Editor::FEDITOR_LOCKMODE);
}
if (Cached && pc.CodePage && !codepages::IsCodePageSupported(pc.CodePage))
pc.CodePage = 0;
bool testBOM = true;
const auto Redetect = (m_codepage == CP_REDETECT);
if (Redetect)
m_codepage = CP_DEFAULT;
if (m_codepage == CP_DEFAULT)
{
if (!Redetect && Cached && pc.CodePage)
{
m_codepage = pc.CodePage;
}
else
{
const auto Cp = GetFileCodepage(EditFile, GetDefaultCodePage(), &m_bAddSignature, Redetect || Global->Opt->EdOpt.AutoDetectCodePage);
testBOM = false;
if (codepages::IsCodePageSupported(Cp))
m_codepage = Cp;
}
if (m_codepage == CP_DEFAULT)
m_codepage = GetDefaultCodePage();
}
m_editor->SetCodePage(m_codepage, nullptr, false); //BUGBUG
m_editor->GlobalEOL = eol::none;
unsigned long long FileSize = 0;
// BUGBUG check result
(void)EditFile.GetSize(FileSize);
const time_check TimeCheck;
os::fs::filebuf StreamBuffer(EditFile, std::ios::in);
std::istream Stream(&StreamBuffer);
Stream.exceptions(Stream.badbit | Stream.failbit);
enum_lines EnumFileLines(Stream, m_codepage);
for (auto Str: EnumFileLines)
{
if (testBOM && IsUnicodeOrUtfCodePage(m_codepage))
{
if (starts_with(Str.Str, encoding::bom_char))
{
Str.Str.remove_prefix(1);
m_bAddSignature = true;
}
}
testBOM = false;
if (TimeCheck)
{
if (CheckForEscSilent())
{
if (ConfirmAbortOp())
{
UserBreak = 1;
EditFile.Close();
return false;
}
}
SetCursorType(false, 0);
const auto CurPos = EditFile.GetPointer();
auto Percent = CurPos * 100 / FileSize;
// В случае если во время загрузки файл увеличивается размере, то количество
// процентов может быть больше 100. Обрабатываем эту ситуацию.
if (Percent > 100)
{
// BUGBUG check result
(void)EditFile.GetSize(FileSize);
Percent = std::min(CurPos * 100 / FileSize, 100ull);
}
Editor::EditorShowMsg(msg(lng::MEditTitle), msg(lng::MEditReading), Name, Percent);
}
if (m_editor->GlobalEOL == eol::none && Str.Eol != eol::none)
{
m_editor->GlobalEOL = Str.Eol;
}
m_editor->PushString(Str.Str);
m_editor->LastLine()->SetEOL(Str.Eol);
}
BadConversion = EnumFileLines.conversion_error();
if (BadConversion)
{
uintptr_t cp = m_codepage;
if (!dlgBadEditorCodepage(cp)) // cancel
{
EditFile.Close();
SetLastError(ERROR_OPEN_FAILED); //????
ErrorState = error_state::fetch();
UserBreak=1;
m_Flags.Set(FFILEEDIT_OPENFAILED);
return false;
}
else if (cp != m_codepage)
{
m_codepage = cp;
EditFile.SetPointer(0, nullptr, FILE_BEGIN);
continue;
}
// else -- codepage accepted
}
break;
}
if (m_editor->Lines.empty() || m_editor->Lines.back().GetEOL() != eol::none)
m_editor->PushString({});
if (m_editor->GlobalEOL == eol::none)
m_editor->GlobalEOL = Editor::GetDefaultEOL();
EditFile.Close();
m_editor->SetCacheParams(pc, m_bAddSignature);
ErrorState = error_state::fetch();
// BUGBUG check result
(void)os::fs::get_find_data(Name, FileInfo);
EditorGetFileAttributes(Name);
return true;
}
catch (const std::bad_alloc&)
{
// TODO: better diagnostics
m_editor->FreeAllocatedData();
m_Flags.Set(FFILEEDIT_OPENFAILED);
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
ErrorState = error_state::fetch();
return false;
}
catch (const std::exception&)
{
// A portion of file can be locked
// TODO: better diagnostics
m_editor->FreeAllocatedData();
m_Flags.Set(FFILEEDIT_OPENFAILED);
ErrorState = error_state::fetch();
return false;
}
}
bool FileEditor::ReloadFile(uintptr_t codepage)
{
const auto save_codepage(m_codepage);
const auto save_bAddSignature(m_bAddSignature);
const auto save_BadConversiom(BadConversion);
const auto save_Flags(m_Flags), save_Flags1(m_editor->m_Flags);
Editor saved(shared_from_this(), CP_DEFAULT);
saved.fake_editor = true;
m_editor->SwapState(saved);
int user_break = 0;
m_codepage = codepage;
error_state_ex ErrorState;
for (;;)
{
if (LoadFile(strFullFileName, user_break, ErrorState))
{
m_editor->m_Flags.Set(Editor::FEDITOR_WASCHANGED);
m_editor->m_Flags.Clear(Editor::FEDITOR_MODIFIED);
Show();
return true;
}
if (user_break != 1)
{
if (OperationFailed(ErrorState, strFullFileName, lng::MEditTitle, msg(lng::MEditCannotOpen), false) == operation::retry)
continue;
}
m_codepage = save_codepage;
m_bAddSignature = save_bAddSignature;
BadConversion = save_BadConversiom;
m_Flags = save_Flags;
m_editor->m_Flags = save_Flags1;
m_editor->SwapState(saved);
Show();
return false;
}
}
//TextFormat и codepage используются ТОЛЬКО, если bSaveAs = true!
int FileEditor::SaveFile(const string& Name,int Ask, bool bSaveAs, error_state_ex& ErrorState, eol Eol, uintptr_t Codepage, bool AddSignature)
{
if (!bSaveAs)
{
Eol = eol::none;
Codepage=m_editor->GetCodePage();
}
if (m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE) && !m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED) && !bSaveAs)
return SAVEFILE_SUCCESS;
SCOPED_ACTION(taskbar::indeterminate);
SCOPED_ACTION(wakeful);
if (Ask)
{
if (!m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED))
return SAVEFILE_SUCCESS;
std::vector Buttons{ lng::MHYes, lng::MHNo };
if (Global->AllowCancelExit)
{
Buttons.emplace_back(lng::MHCancel);
}
int Code = Message(MSG_WARNING,
msg(lng::MEditTitle),
{
msg(lng::MEditAskSave)
},
Buttons,
{}, &EditAskSaveId);
if(Code < 0 && !Global->AllowCancelExit)
{
Code = Message::second_button; // close == not save
}
switch (Code)
{
case Message::first_button: // Save
break;
case Message::second_button: // Not Save
m_editor->TextChanged(false);
return SAVEFILE_SUCCESS;
default:
return SAVEFILE_CANCEL;
}
}
int NewFile=TRUE;
const auto FileAttr = os::fs::get_file_attributes(Name);
if (FileAttr != INVALID_FILE_ATTRIBUTES)
{
// Проверка времени модификации...
if (!m_Flags.Check(FFILEEDIT_SAVEWQUESTIONS))
{
os::fs::find_data FInfo;
if (os::fs::get_find_data(Name, FInfo) && !FileInfo.FileName.empty())
{
if (FileInfo.LastWriteTime != FInfo.LastWriteTime || FInfo.FileSize != FileInfo.FileSize)
{
switch (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
msg(lng::MEditAskSaveExt)
},
{ lng::MHYes, lng::MEditBtnSaveAs, lng::MHCancel },
L"WarnEditorSavedEx"sv, &EditAskSaveExtId))
{
case Message::first_button: // Save
break;
case Message::second_button: // Save as
return ProcessKey(Manager::Key(KEY_SHIFTF2))?
SAVEFILE_SUCCESS :
SAVEFILE_CANCEL;
default:
return SAVEFILE_CANCEL;
}
}
}
}
m_Flags.Clear(FFILEEDIT_SAVEWQUESTIONS);
NewFile=FALSE;
if (FileAttr & FILE_ATTRIBUTE_READONLY)
{
//BUGBUG
if (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
Name,
msg(lng::MEditRO),
msg(lng::MEditOvr)
},
{ lng::MYes, lng::MNo },
{}, &EditorSavedROId) != Message::first_button)
return SAVEFILE_CANCEL;
(void)os::fs::set_file_attributes(Name, FileAttr & ~FILE_ATTRIBUTE_READONLY); //BUGBUG
}
}
else
{
// проверим путь к файлу, может его уже снесли...
string strCreatedPath = Name;
if (CutToParent(strCreatedPath))
{
if (!os::fs::exists(strCreatedPath))
{
// и попробуем создать.
// Раз уж
CreatePath(strCreatedPath);
if (!os::fs::exists(strCreatedPath))
{
ErrorState = error_state::fetch();
return SAVEFILE_ERROR;
}
}
}
}
if (BadConversion)
{
if(Message(MSG_WARNING,
msg(lng::MWarning),
{
msg(lng::MEditDataLostWarn),
msg(lng::MEditorSaveNotRecommended)
},
{ lng::MEditorSave, lng::MCancel }) == Message::first_button)
{
BadConversion = false;
}
else
{
return SAVEFILE_CANCEL;
}
}
int RetCode=SAVEFILE_SUCCESS;
if (Eol != eol::none)
{
m_editor->m_Flags.Set(Editor::FEDITOR_WASCHANGED);
m_editor->GlobalEOL = Eol;
}
if (!os::fs::exists(Name))
m_Flags.Set(FFILEEDIT_NEW);
//SaveScreen SaveScr;
/* $ 11.10.2001 IS
Если было произведено сохранение с любым результатом, то не удалять файл
*/
m_Flags.Clear(FFILEEDIT_DELETEONCLOSE|FFILEEDIT_DELETEONLYFILEONCLOSE);
//_D(SysLog(L"%08d EE_SAVE",__LINE__));
if (!IsUnicodeOrUtfCodePage(Codepage))
{
int LineNumber=-1;
encoding::error_position ErrorPosition;
for(auto& Line: m_editor->Lines)
{
++LineNumber;
const auto& SaveStr = Line.GetString();
auto LineEol = Line.GetEOL();
(void)encoding::get_bytes_count(Codepage, SaveStr, &ErrorPosition);
const auto ValidStr = !ErrorPosition;
if (ValidStr)
(void)encoding::get_bytes_count(Codepage, LineEol.str(), &ErrorPosition);
if (ErrorPosition)
{
//SetMessageHelp(L"EditorDataLostWarning")
const int Result = Message(MSG_WARNING,
msg(lng::MWarning),
{
msg(lng::MEditorSaveCPWarn1),
msg(lng::MEditorSaveCPWarn2),
msg(lng::MEditorSaveNotRecommended)
},
{ lng::MCancel, lng::MEditorSaveCPWarnShow, lng::MEditorSave });
if (Result == Message::third_button)
break;
if(Result == Message::second_button)
{
m_editor->GoToLine(LineNumber);
if(!ValidStr)
{
Line.SetCurPos(static_cast<int>(*ErrorPosition));
}
else
{
Line.SetCurPos(Line.GetLength());
}
Show();
}
return SAVEFILE_CANCEL;
}
}
}
EditorSaveFile esf = {sizeof(esf), Name.c_str(), m_editor->GlobalEOL.str().data(), Codepage};
Global->CtrlObject->Plugins->ProcessEditorEvent(EE_SAVE, &esf, m_editor.get());
try
{
save_file_with_replace(Name, FileAttr, 0, Global->Opt->EdOpt.CreateBackups, [&](std::ostream& Stream)
{
m_editor->UndoSavePos = m_editor->UndoPos;
m_editor->m_Flags.Clear(Editor::FEDITOR_UNDOSAVEPOSLOST);
SetCursorType(false, 0);
SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<Editor::EditorPreRedrawItem>());
if (!bSaveAs)
AddSignature = m_bAddSignature;
const time_check TimeCheck;
encoding::writer Writer(Stream, Codepage, AddSignature);
size_t LineNumber = -1;
for (auto& Line : m_editor->Lines)
{
++LineNumber;
if (TimeCheck)
{
Editor::EditorShowMsg(msg(lng::MEditTitle), msg(lng::MEditSaving), Name, LineNumber * 100 / m_editor->Lines.size());
}
const auto& SaveStr = Line.GetString();
auto LineEol = Line.GetEOL();
if (Eol != eol::none && LineEol != eol::none)
{
LineEol = m_editor->GlobalEOL;
Line.SetEOL(LineEol);
}
Writer.write(SaveStr);
Writer.write(LineEol.str());
}
});
}
catch (const far_exception& e)
{
RetCode = SAVEFILE_ERROR;
ErrorState = e;
}
// BUGBUG check result
(void)os::fs::get_find_data(Name, FileInfo);
EditorGetFileAttributes(Name);
if (m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED) || NewFile)
m_editor->m_Flags.Set(Editor::FEDITOR_WASCHANGED);
/* Этот кусок раскомметировать в том случае, если народ решит, что
для если файл был залочен и мы его переписали под други именем...
...то "лочка" должна быть снята.
*/
// if(SaveAs)
// Flags.Clear(FEDITOR_LOCKMODE);
/* 28.12.2001 VVM
! Проверить на успешную запись */
if (RetCode==SAVEFILE_SUCCESS)
{
m_editor->TextChanged(false);
m_editor->m_Flags.Set(Editor::FEDITOR_NEWUNDO);
}
Show();
// ************************************
m_Flags.Clear(FFILEEDIT_NEW);
return RetCode;
}
bool FileEditor::ProcessMouse(const MOUSE_EVENT_RECORD *MouseEvent)
{
F4KeyOnly = false;
if (!m_windowKeyBar->ProcessMouse(MouseEvent))
{
INPUT_RECORD mouse = { MOUSE_EVENT };
mouse.Event.MouseEvent=*MouseEvent;
if (!ProcessEditorInput(mouse))
if (!m_editor->ProcessMouse(MouseEvent))
return false;
}
return true;
}
int FileEditor::GetTypeAndName(string &strType, string &strName)
{
strType = msg(lng::MScreensEdit);
strName = strFullFileName;
return windowtype_editor;
}
void FileEditor::ShowConsoleTitle()
{
string strEditorTitleFormat=Global->Opt->strEditorTitleFormat.Get();
replace_icase(strEditorTitleFormat, L"%Lng"sv, msg(lng::MInEditor));
replace_icase(strEditorTitleFormat, L"%File"sv, PointToName(strFileName));
ConsoleTitle::SetFarTitle(strEditorTitleFormat);
m_Flags.Clear(FFILEEDIT_REDRAWTITLE);
}
void FileEditor::SetScreenPosition()
{
if (m_Flags.Check(FFILEEDIT_FULLSCREEN))
{
SetPosition({ 0, 0, ScrX, ScrY });
}
}
void FileEditor::OnDestroy()
{
_OT(SysLog(L"[%p] FileEditor::OnDestroy()",this));
if (Global->CtrlObject && !m_Flags.Check(FFILEEDIT_DISABLEHISTORY) && !equal_icase(strFileName, msg(lng::MNewFileName)))
Global->CtrlObject->ViewHistory->AddToHistory(strFullFileName, m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE) ? HR_EDITOR_RO : HR_EDITOR);
//AY: флаг оповещающий закрытие редактора.
m_bClosing = true;
if (bEE_READ_Sent && Global->CtrlObject)
{
Global->CtrlObject->Plugins->ProcessEditorEvent(EE_CLOSE, nullptr, m_editor.get());
}
if (!m_Flags.Check(FFILEEDIT_OPENFAILED) && !m_Flags.Check(FFILEEDIT_DISABLESAVEPOS) && (m_editor->EdOpt.SavePos || m_editor->EdOpt.SaveShortPos) && Global->CtrlObject)
SaveToCache();
}
bool FileEditor::GetCanLoseFocus(bool DynamicMode) const
{
if (DynamicMode && m_editor->IsFileModified())
{
return false;
}
return window::GetCanLoseFocus();
}
void FileEditor::SetLockEditor(bool LockMode) const
{
if (LockMode)
m_editor->m_Flags.Set(Editor::FEDITOR_LOCKMODE);
else
m_editor->m_Flags.Clear(Editor::FEDITOR_LOCKMODE);
}
bool FileEditor::CanFastHide() const
{
return (Global->Opt->AllCtrlAltShiftRule & CASR_EDITOR) != 0;
}
int FileEditor::ProcessEditorInput(const INPUT_RECORD& Rec)
{
return Global->CtrlObject->Plugins->ProcessEditorInput(&Rec);
}
void FileEditor::SetPluginTitle(const string* PluginTitle)
{
if (!PluginTitle)
strPluginTitle.clear();
else
strPluginTitle = *PluginTitle;
}
bool FileEditor::SetFileName(const string_view NewFileName)
{
// BUGBUG This whole MNewFileName thing is madness.
// TODO: Just support an empty name
strFileName = NewFileName.empty()? msg(lng::MNewFileName) : NewFileName;
if (strFileName != msg(lng::MNewFileName))
{
strFullFileName = ConvertNameToFull(strFileName);
string strFilePath=strFullFileName;
if (CutToParent(strFilePath))
{
if (equal_icase(strFilePath, os::fs::GetCurrentDirectory()))
strFileName = PointToName(strFullFileName);
}
//Дабы избежать бардака, развернём слешики...
ReplaceSlashToBackslash(strFullFileName);
}
else
{
strFullFileName = path::join(strStartDir, strFileName);
}
return true;
}
void FileEditor::SetTitle(const string* Title)
{
if (Title)
strTitle = *Title;
else
strTitle.clear();
}
string FileEditor::GetTitle() const
{
string strLocalTitle;
if (!strPluginTitle.empty())
strLocalTitle = strPluginTitle;
else
{
if (!strTitle.empty())
strLocalTitle = strTitle;
else
strLocalTitle = strFullFileName;
}
return strLocalTitle;
}
static std::pair<string, size_t> char_code(std::optional<wchar_t> const& Char, int const Codebase)
{
const auto process = [&](string_view const Format, string_view const Max)
{
return std::pair{ Char.has_value()? format(Format, unsigned(*Char)) : L""s, Max.size() };
};
switch (Codebase)
{
case 0:
return process(L"0{0:o}"sv, L"0177777"sv);
case 2:
return process(L"{0:X}h"sv, L"FFFFh"sv);
case 1:
default:
return process(L"{0}"sv, L"65535"sv);
}
}
static std::pair<string, size_t> ansi_char_code(std::optional<wchar_t> const& Char, int const Codebase, uintptr_t const Codepage)
{
const auto process = [&](string_view const Format, string_view const Max)
{
std::optional<unsigned> CharCode;
char Buffer;
encoding::error_position ErrorPosition;
if (Char.has_value() && encoding::get_bytes(Codepage, { &*Char, 1 }, { &Buffer, 1 }, &ErrorPosition) == 1 && !ErrorPosition)
{
const unsigned AnsiCode = Buffer;
if (AnsiCode != *Char)
{
CharCode = AnsiCode;
}
}
return std::pair{ CharCode.has_value()? format(Format, *CharCode) : L""s, Max.size() };
};
switch (Codebase)
{
case 0:
return process(L"0{0:<3o}"sv, L"0377"sv);
case 2:
return process(L"{0:02X}h"sv, L"FFh"sv);
case 1:
default:
return process(L"{0:<3}"sv, L"255"sv);
}
}
void FileEditor::ShowStatus() const
{
if (!IsTitleBarVisible())
return;
SetColor(COL_EDITORSTATUS);
GotoXY(m_Where.left, m_Where.top); //??
const auto& Str = m_editor->m_it_CurLine->GetString();
const size_t CurPos = m_editor->m_it_CurLine->GetCurPos();
string CharCode;
{
std::optional<wchar_t> Char;
if (CurPos < Str.size())
Char = Str[CurPos];
auto [UnicodeStr, UnicodeSize] = char_code(Char, m_editor->EdOpt.CharCodeBase);
CharCode = std::move(UnicodeStr);
if (!IsUnicodeOrUtfCodePage(m_codepage))
{
const auto [AnsiStr, AnsiSize] = ansi_char_code(Char, m_editor->EdOpt.CharCodeBase, m_codepage);
if (!CharCode.empty() && !AnsiStr.empty())
{
append(CharCode, L'/', AnsiStr);
}
UnicodeSize += AnsiSize + 1;
}
if (Char.has_value())
inplace::pad_right(CharCode, UnicodeSize);
else
CharCode.assign(UnicodeSize, L' ');
}
//предварительный расчет
const auto LinesFormat = FSTR(L"{0}/{1}");
const auto SizeLineStr = format(LinesFormat, m_editor->Lines.size(), m_editor->Lines.size()).size();
const auto strLineStr = format(LinesFormat, m_editor->m_it_CurLine.Number() + 1, m_editor->Lines.size());
const auto strAttr = *AttrStr? L"│"s + AttrStr : L""s;
auto StatusLine = format(FSTR(L"│{0}{1}│{2:5.5}│{3:.3} {4:>{5}}│{6:.3} {7:<3}│{8:.3} {9:<3}{10}│{11}"),
m_editor->m_Flags.Check(Editor::FEDITOR_MODIFIED)?L'*':L' ',
m_editor->m_Flags.Check(Editor::FEDITOR_LOCKMODE)? L'-' : m_editor->m_Flags.Check(Editor::FEDITOR_PROCESSCTRLQ)? L'"' : L' ',
ShortReadableCodepageName(m_codepage),
msg(lng::MEditStatusLine),
strLineStr,
SizeLineStr,
msg(lng::MEditStatusCol),
m_editor->m_it_CurLine->GetTabCurPos() + 1,
msg(lng::MEditStatusChar),
m_editor->m_it_CurLine->GetCurPos() + 1,
strAttr,
CharCode);
// Explicitly signed types - it's too easy to screw it up on small console sizes otherwise
const int ClockSize = Global->Opt->ViewerEditorClock && m_Flags.Check(FFILEEDIT_FULLSCREEN)? static_cast<int>(Global->CurrentTime.size()) : 0;
const int AvailableSpace = std::max(0, ObjWidth() - ClockSize - (ClockSize? 1 : 0));
inplace::cut_right(StatusLine, AvailableSpace);
const int NameWidth = std::max(0, AvailableSpace - static_cast<int>(StatusLine.size()));
Text(fit_to_left(truncate_path(GetTitle(), NameWidth), NameWidth));
Text(StatusLine);
if (ClockSize)
{
Text(L'│'); // Separator before the clock
ShowTime();
}
}
/* $ 13.02.2001
Узнаем атрибуты файла и заодно сформируем готовую строку атрибутов для
статуса.
*/
os::fs::attributes FileEditor::EditorGetFileAttributes(string_view const Name)
{
m_FileAttributes = os::fs::get_file_attributes(Name);
int ind=0;
if (m_FileAttributes!=INVALID_FILE_ATTRIBUTES)
{
if (m_FileAttributes&FILE_ATTRIBUTE_READONLY) AttrStr[ind++]=L'R';
if (m_FileAttributes&FILE_ATTRIBUTE_SYSTEM) AttrStr[ind++]=L'S';
if (m_FileAttributes&FILE_ATTRIBUTE_HIDDEN) AttrStr[ind++]=L'H';
}
AttrStr[ind]=0;
return m_FileAttributes;
}
/* true - панель обновили
*/
bool FileEditor::UpdateFileList() const
{
const auto ActivePanel = Global->CtrlObject->Cp()->ActivePanel();
const auto FileName = PointToName(strFullFileName);
string strFilePath(strFullFileName), strPanelPath(ActivePanel->GetCurDir());
strFilePath.resize(strFullFileName.size() - FileName.size());
AddEndSlash(strPanelPath);
AddEndSlash(strFilePath);
if (strPanelPath == strFilePath)
{
ActivePanel->Update(UPDATE_KEEP_SELECTION|UPDATE_DRAW_MESSAGE);
return true;
}
return false;
}
void FileEditor::SetPluginData(const string* PluginData)
{
if (PluginData)
strPluginData = *PluginData;
else
strPluginData.clear();
}
/* $ 14.06.2002 IS
DeleteOnClose стал int:
0 - не удалять ничего
1 - удалять файл и каталог
2 - удалять только файл
*/
void FileEditor::SetDeleteOnClose(int NewMode)
{
m_Flags.Clear(FFILEEDIT_DELETEONCLOSE|FFILEEDIT_DELETEONLYFILEONCLOSE);
if (NewMode==1)
m_Flags.Set(FFILEEDIT_DELETEONCLOSE);
else if (NewMode==2)
m_Flags.Set(FFILEEDIT_DELETEONLYFILEONCLOSE);
}
void FileEditor::GetEditorOptions(Options::EditorOptions& EdOpt) const
{
EdOpt = m_editor->EdOpt;
}
void FileEditor::SetEditorOptions(const Options::EditorOptions& EdOpt) const
{
m_editor->SetOptions(EdOpt);
}
void FileEditor::OnChangeFocus(bool focus)
{
window::OnChangeFocus(focus);
if (!m_bClosing)
{
Global->CtrlObject->Plugins->ProcessEditorEvent(focus? EE_GOTFOCUS : EE_KILLFOCUS, nullptr, m_editor.get());
}
}
intptr_t FileEditor::EditorControl(int Command, intptr_t Param1, void *Param2)
{
#if defined(SYSLOG_KEYMACRO)
_KEYMACRO(CleverSysLog SL(L"FileEditor::EditorControl()"));
if (Command == ECTL_READINPUT || Command == ECTL_PROCESSINPUT)
{
_KEYMACRO(SysLog(L"(Command=%s, Param2=[%d/0x%08X]) Macro.IsExecuting()=%d",_ECTL_ToName(Command),(int)((intptr_t)Param2),(int)((intptr_t)Param2),Global->CtrlObject->Macro.IsExecuting()));
}
#else
_ECTLLOG(CleverSysLog SL(L"FileEditor::EditorControl()"));
_ECTLLOG(SysLog(L"(Command=%s, Param2=[%d/0x%08X])",_ECTL_ToName(Command),(int)Param2,Param2));
#endif
if(m_editor->EditorControlLocked()) return FALSE;
if (m_bClosing && (Command != ECTL_GETINFO) && (Command != ECTL_GETBOOKMARKS) && (Command!=ECTL_GETFILENAME))
return FALSE;
switch (Command)
{
case ECTL_GETFILENAME:
{
if (Param2 && static_cast<size_t>(Param1) > strFullFileName.size())
{
*copy_string(strFullFileName, static_cast<wchar_t*>(Param2)) = {};
}
return strFullFileName.size()+1;
}
case ECTL_GETBOOKMARKS:
{
const auto ebm = static_cast<EditorBookmarks*>(Param2);
if (!m_Flags.Check(FFILEEDIT_OPENFAILED) && CheckNullOrStructSize(ebm))
{
size_t size;
if(Editor::InitSessionBookmarksForPlugin(ebm, m_editor->m_SavePos.size(), size))
{
for (const auto& [i, index]: enumerate(m_editor->m_SavePos))
{
if (ebm->Line)
{
ebm->Line[index] = i.Line;
}
if (ebm->Cursor)
{
ebm->Cursor[index] = i.LinePos;
}
if (ebm->ScreenLine)
{
ebm->ScreenLine[index] = i.ScreenLine;
}
if (ebm->LeftPos)
{
ebm->LeftPos[index] = i.LeftPos;
}
}
}
return size;
}
return 0;
}
case ECTL_ADDSESSIONBOOKMARK:
{
m_editor->AddSessionBookmark();
return TRUE;
}
case ECTL_PREVSESSIONBOOKMARK:
{
m_editor->TurnOffMarkingBlock();
return m_editor->PrevSessionBookmark();
}
case ECTL_NEXTSESSIONBOOKMARK:
{
m_editor->TurnOffMarkingBlock();
return m_editor->NextSessionBookmark();
}
case ECTL_CLEARSESSIONBOOKMARKS:
{
m_editor->ClearSessionBookmarks();
return TRUE;
}
case ECTL_DELETESESSIONBOOKMARK:
{
return m_editor->DeleteSessionBookmark(m_editor->PointerToSessionBookmark(static_cast<int>(reinterpret_cast<intptr_t>(Param2))));
}
case ECTL_GETSESSIONBOOKMARKS:
{
return CheckNullOrStructSize(static_cast<const EditorBookmarks*>(Param2))?
m_editor->GetSessionBookmarksForPlugin(static_cast<EditorBookmarks*>(Param2)) : 0;
}
case ECTL_GETTITLE:
{
const auto strLocalTitle = GetTitle();
if (Param2 && static_cast<size_t>(Param1) > strLocalTitle.size())
{
*copy_string(strLocalTitle, static_cast<wchar_t*>(Param2)) = {};
}
return strLocalTitle.size()+1;
}
case ECTL_SETTITLE:
{
strPluginTitle = NullToEmpty(static_cast<const wchar_t*>(Param2));
ShowStatus();
if (!m_editor->m_InEERedraw)
Global->ScrBuf->Flush(); //???
return TRUE;
}
case ECTL_REDRAW:
{
Global->WindowManager->RefreshWindow(shared_from_this());
Global->WindowManager->PluginCommit();
Global->ScrBuf->Flush();
return TRUE;
}
/*
Функция установки Keybar Labels
Param2 = nullptr - восстановить, пред. значение
Param2 = -1 - обновить полосу (перерисовать)
Param2 = KeyBarTitles
*/
case ECTL_SETKEYBAR:
{
const auto Kbt = static_cast<const FarSetKeyBarTitles*>(Param2);
if (!Kbt) //восстановить изначальное
InitKeyBar();
else
{
if (reinterpret_cast<intptr_t>(Param2) != -1) // не только перерисовать?
{
if(CheckStructSize(Kbt))
m_windowKeyBar->Change(Kbt->Titles);
else
return FALSE;
}
m_windowKeyBar->Show();
}
return TRUE;
}
case ECTL_SAVEFILE:
{
string strName = strFullFileName;
auto Eol = eol::none;
uintptr_t codepage=m_codepage;
const auto esf = static_cast<const EditorSaveFile*>(Param2);
if (CheckStructSize(esf))
{
if (esf->FileName)
strName=esf->FileName;
if (esf->FileEOL)
Eol = eol::parse(esf->FileEOL);
if (esf->CodePage != CP_DEFAULT)
codepage=esf->CodePage;
}
{
const auto strOldFullFileName = strFullFileName;
if (SetFileName(strName))
{
if (!equal_icase(strFullFileName, strOldFullFileName))
{
if (!AskOverwrite(strName))
{
SetFileName(strOldFullFileName);
return FALSE;
}
}
m_Flags.Set(FFILEEDIT_SAVEWQUESTIONS);
//всегда записываем в режиме save as - иначе не сменить кодировку и концы линий.
error_state_ex ErrorState;
return SaveFile(strName, FALSE, true, ErrorState, Eol, codepage, m_bAddSignature);
}
}
return FALSE;
}
case ECTL_QUIT:
{
if (!bLoaded) // do not delete not created window
{
SetExitCode(XC_LOADING_INTERRUPTED);
}
else
{
Global->WindowManager->DeleteWindow(shared_from_this());
SetExitCode(XC_OPEN_ERROR); // что-то меня терзают смутные сомнения ...??? SAVEFILE_ERROR ???
Global->WindowManager->PluginCommit();
}
return TRUE;
}
case ECTL_READINPUT:
{
const auto MacroState = Global->CtrlObject->Macro.GetState();
if (MacroState == MACROSTATE_RECORDING || MacroState == MACROSTATE_EXECUTING)
{
//return FALSE;
}
if (Param2)
{
const auto rec = static_cast<INPUT_RECORD*>(Param2);
for (;;)
{
const auto Key = GetInputRecord(rec);
if ((!rec->EventType || rec->EventType == KEY_EVENT) &&
((Key >= KEY_MACRO_BASE && Key <= KEY_MACRO_ENDBASE) || (Key>=KEY_OP_BASE && Key <=KEY_OP_ENDBASE))) // исключаем MACRO
ReProcessKey(Manager::Key(Key, *rec));
else
break;
}
#if defined(SYSLOG_KEYMACRO)
if (rec->EventType == KEY_EVENT)
{
SysLog(L"ECTL_READINPUT={KEY_EVENT,{%d,%d,Vk=0x%04X,0x%08X}}",
rec->Event.KeyEvent.bKeyDown,
rec->Event.KeyEvent.wRepeatCount,
rec->Event.KeyEvent.wVirtualKeyCode,
rec->Event.KeyEvent.dwControlKeyState);
}
#endif
return TRUE;
}
return FALSE;
}
case ECTL_PROCESSINPUT:
{
if (Param2)
{
auto& rec = *static_cast<INPUT_RECORD*>(Param2);
if (ProcessEditorInput(rec))
return TRUE;
if (rec.EventType==MOUSE_EVENT)
ProcessMouse(&rec.Event.MouseEvent);
else
{
#if defined(SYSLOG_KEYMACRO)
if (!rec.EventType || rec.EventType == KEY_EVENT)
{
SysLog(L"ECTL_PROCESSINPUT={%s,{%d,%d,Vk=0x%04X,0x%08X}}",
(rec.EventType == KEY_EVENT?L"KEY_EVENT":L"(internal, macro)_KEY_EVENT"),
rec.Event.KeyEvent.bKeyDown,
rec.Event.KeyEvent.wRepeatCount,
rec.Event.KeyEvent.wVirtualKeyCode,
rec.Event.KeyEvent.dwControlKeyState);
}
#endif
const auto Key = ShieldCalcKeyCode(&rec, false);
ReProcessKey(Manager::Key(Key, rec));
}
return TRUE;
}
return FALSE;
}
case ECTL_SETPARAM:
{
const auto espar = static_cast<const EditorSetParameter*>(Param2);
if (CheckStructSize(espar))
{
if (ESPT_SETBOM==espar->Type)
{
if(IsUnicodeOrUtfCodePage(m_codepage))
{
m_bAddSignature=espar->iParam != 0;
return TRUE;
}
return FALSE;
}
}
break;
}
}
const auto result = m_editor->EditorControl(Command, Param1, Param2);
if (result&&ECTL_GETINFO==Command)
{
const auto Info=static_cast<EditorInfo*>(Param2);
if (m_bAddSignature)
Info->Options|=EOPT_BOM;
if (Global->Opt->EdOpt.ShowTitleBar)
Info->Options|=EOPT_SHOWTITLEBAR;
if (Global->Opt->EdOpt.ShowKeyBar)
Info->Options|=EOPT_SHOWKEYBAR;
}
return result;
}
bool FileEditor::LoadFromCache(EditorPosCache &pc) const
{
string strCacheName;
const auto PluginData = GetPluginData();
if (!PluginData.empty())
{
strCacheName = concat(PluginData, PointToName(strFullFileName));
}
else
{
strCacheName = strFullFileName;
ReplaceSlashToBackslash(strCacheName);
}
pc.Clear();
return FilePositionCache::GetPosition(strCacheName, pc);
}
void FileEditor::SaveToCache() const
{
EditorPosCache pc;
m_editor->GetCacheParams(pc);
if (!m_Flags.Check(FFILEEDIT_OPENFAILED)) //????
{
pc.CodePage = BadConversion ? 0 : m_codepage;
FilePositionCache::AddPosition(strPluginData.empty()? strFullFileName : strPluginData + PointToName(strFullFileName), pc);
}
}
bool FileEditor::SetCodePage(uintptr_t codepage)
{
if (codepage == m_codepage || !m_editor)
return false;
uintptr_t ErrorCodepage;
size_t ErrorLine, ErrorPos;
if (!m_editor->TryCodePage(codepage, ErrorCodepage, ErrorLine, ErrorPos))
{
const auto Info = codepages::GetInfo(ErrorCodepage);
const int Result = Message(MSG_WARNING,
msg(lng::MWarning),
{
msg(lng::MEditorSwitchCPWarn1),
msg(lng::MEditorSwitchCPWarn2),
format(FSTR(L"{0} - {1}"), codepage, Info? Info->Name : str(codepage)),
msg(lng::MEditorSwitchCPConfirm)
},
{ lng::MCancel, lng::MEditorSaveCPWarnShow, lng::MOk });
switch (Result)
{
default:
case Message::first_button:
return false;
case Message::second_button:
m_editor->GoToLine(static_cast<int>(ErrorLine));
m_editor->m_it_CurLine->SetCurPos(static_cast<int>(ErrorPos));
Show();
return false;
case Message::third_button:
break;
}
}
m_codepage = codepage;
BadConversion = !m_editor->SetCodePage(m_codepage, &m_bAddSignature);
return true;
}
bool FileEditor::AskOverwrite(const string& FileName)
{
bool result=true;
if (os::fs::exists(FileName))
{
if (Message(MSG_WARNING,
msg(lng::MEditTitle),
{
FileName,
msg(lng::MEditExists),
msg(lng::MEditOvr)
},
{ lng::MYes, lng::MNo },
{}, &EditorAskOverwriteId) != Message::first_button)
{
result=false;
}
else
{
m_Flags.Set(FFILEEDIT_SAVEWQUESTIONS);
}
}
return result;
}
uintptr_t FileEditor::GetDefaultCodePage()
{
intptr_t cp = Global->Opt->EdOpt.DefaultCodePage;
if (cp < 0 || !codepages::IsCodePageSupported(cp))
cp = encoding::codepage::ansi();
return cp;
}
Editor* FileEditor::GetEditor()
{
return m_editor.get();
}
bool FileEditor::IsKeyBarVisible() const
{
return Global->Opt->EdOpt.ShowKeyBar && ObjHeight() > 2;
}
bool FileEditor::IsTitleBarVisible() const
{
return Global->Opt->EdOpt.ShowTitleBar && ObjHeight() > 1;
}
| data-man/FarAS | far/fileedit.cpp | C++ | bsd-3-clause | 76,603 | [
30522,
1013,
1008,
5371,
2098,
4183,
1012,
18133,
2361,
1195,
15290,
29742,
10260,
23925,
22919,
10325,
16856,
19259,
28995,
10325,
15290,
30524,
1998,
2224,
1999,
3120,
1998,
12441,
3596,
1010,
2007,
2030,
2302,
14080,
1010,
2024,
7936,
3024... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2012, assimp team
All rights reserved.
Redistribution and use of this software 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 list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef OBJ_FILE_IMPORTER_H_INC
#define OBJ_FILE_IMPORTER_H_INC
#include "BaseImporter.h"
#include <vector>
struct aiMesh;
struct aiNode;
namespace Assimp
{
namespace ObjFile
{
struct Object;
struct Model;
}
// ------------------------------------------------------------------------------------------------
/// \class ObjFileImporter
/// \brief Imports a waveform obj file
// ------------------------------------------------------------------------------------------------
class ObjFileImporter : public BaseImporter
{
public:
/// \brief Default constructor
ObjFileImporter();
/// \brief Destructor
~ObjFileImporter();
public:
/// \brief Returns whether the class can handle the format of the given file.
/// \remark See BaseImporter::CanRead() for details.
bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const;
private:
//! \brief Appends the supported extention.
const aiImporterDesc* GetInfo () const;
//! \brief File import implementation.
void InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler);
//! \brief Create the data from imported content.
void CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene);
//! \brief Creates all nodes stored in imported content.
aiNode *createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pData, unsigned int uiMeshIndex,
aiNode *pParent, aiScene* pScene, std::vector<aiMesh*> &MeshArray);
//! \brief Creates topology data like faces and meshes for the geometry.
void createTopology(const ObjFile::Model* pModel, const ObjFile::Object* pData,
unsigned int uiMeshIndex, aiMesh* pMesh);
//! \brief Creates vertices from model.
void createVertexArray(const ObjFile::Model* pModel, const ObjFile::Object* pCurrentObject,
unsigned int uiMeshIndex, aiMesh* pMesh,unsigned int uiIdxCount);
//! \brief Object counter helper method.
void countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes);
//! \brief Material creation.
void createMaterials(const ObjFile::Model* pModel, aiScene* pScene);
//! \brief Appends a child node to a parentnode and updates the datastructures.
void appendChildToParentNode(aiNode *pParent, aiNode *pChild);
//! \brief TODO!
void createAnimations();
private:
//! Data buffer
std::vector<char> m_Buffer;
//! Pointer to root object instance
ObjFile::Object *m_pRootObject;
//! Absolute pathname of model in filesystem
std::string m_strAbsPath;
};
// ------------------------------------------------------------------------------------------------
} // Namespace Assimp
#endif
| alexa-infra/negine | thirdparty/assimp-3.0.1270/code/ObjFileImporter.h | C | mit | 4,461 | [
30522,
1013,
1008,
2330,
11412,
12324,
3075,
1006,
4632,
5714,
2361,
1007,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1011,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0) on Thu Jan 05 01:03:29 EST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.owasp.appsensor.integration.jmx (appsensor-parent 2.3.1 API)</title>
<meta name="date" content="2017-01-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.owasp.appsensor.integration.jmx (appsensor-parent 2.3.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="header">
<h1 title="Package" class="title">Package org.owasp.appsensor.integration.jmx</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/integration/jmx/JmxEmitter.JmxAppSensorMBean.html" title="interface in org.owasp.appsensor.integration.jmx">JmxEmitter.JmxAppSensorMBean</a></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/integration/jmx/JmxEmitter.JmxAttackMBean.html" title="interface in org.owasp.appsensor.integration.jmx">JmxEmitter.JmxAttackMBean</a></td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/integration/jmx/JmxEmitter.JmxEventMBean.html" title="interface in org.owasp.appsensor.integration.jmx">JmxEmitter.JmxEventMBean</a></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/integration/jmx/JmxEmitter.JmxResponseMBean.html" title="interface in org.owasp.appsensor.integration.jmx">JmxEmitter.JmxResponseMBean</a></td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/owasp/appsensor/integration/jmx/JmxEmitter.html" title="class in org.owasp.appsensor.integration.jmx">JmxEmitter</a></td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.owasp.org">The Open Web Application Security Project (OWASP)</a>. All rights reserved.</small></p>
</body>
</html>
| jtmelton/appsensor | appsensor-dot-org/site-contents/docs/v2.3.1/javadoc/org/owasp/appsensor/integration/jmx/package-summary.html | HTML | mit | 3,196 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
1059,
2509,
2278,
1013,
1013,
26718,
2094,
16129,
1018,
1012,
5890,
17459,
1013,
1013,
4372,
1000,
1000,
8299,
1024,
1013,
1013,
7479,
1012,
1059,
2509,
1012,
8917,
1013,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../js/resources/js-test-pre.js"></script>
</head>
<body>
<script src="script-tests/permission-denied-stops-watches.js"></script>
<script src="../../js/resources/js-test-post.js"></script>
</body>
</html>
| youfoh/webkit-efl | LayoutTests/fast/dom/Geolocation/permission-denied-stops-watches.html | HTML | lgpl-2.1 | 281 | [
30522,
1026,
999,
9986,
13874,
16129,
2270,
1000,
1011,
1013,
1013,
29464,
24475,
1013,
1013,
26718,
2094,
16129,
1013,
1013,
4372,
1000,
1028,
1026,
16129,
1028,
1026,
2132,
1028,
1026,
5896,
5034,
2278,
1027,
1000,
1012,
1012,
1013,
1012,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (c) 2010 Nolan Lum <nol888@gmail.com>
* Copyright (c) 2009 Loren Merritt <lorenm@u.washignton.edu>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* gradfun debanding filter, ported from MPlayer
* libmpcodecs/vf_gradfun.c
*
* Apply a boxblur debanding algorithm (based on the gradfun2db
* Avisynth filter by prunedtree).
* Foreach pixel, if it's within threshold of the blurred value, make it closer.
* So now we have a smoothed and higher bitdepth version of all the shallow
* gradients, while leaving detailed areas untouched.
* Dither it back to 8bit.
*/
#include "libavutil/imgutils.h"
#include "libavutil/cpu.h"
#include "libavutil/pixdesc.h"
#include "avfilter.h"
#include "gradfun.h"
DECLARE_ALIGNED(16, static const uint16_t, dither)[8][8] = {
{0x00,0x60,0x18,0x78,0x06,0x66,0x1E,0x7E},
{0x40,0x20,0x58,0x38,0x46,0x26,0x5E,0x3E},
{0x10,0x70,0x08,0x68,0x16,0x76,0x0E,0x6E},
{0x50,0x30,0x48,0x28,0x56,0x36,0x4E,0x2E},
{0x04,0x64,0x1C,0x7C,0x02,0x62,0x1A,0x7A},
{0x44,0x24,0x5C,0x3C,0x42,0x22,0x5A,0x3A},
{0x14,0x74,0x0C,0x6C,0x12,0x72,0x0A,0x6A},
{0x54,0x34,0x4C,0x2C,0x52,0x32,0x4A,0x2A},
};
void ff_gradfun_filter_line_c(uint8_t *dst, const uint8_t *src, const uint16_t *dc, int width, int thresh, const uint16_t *dithers)
{
int x;
for (x = 0; x < width; x++, dc += x & 1) {
int pix = src[x] << 7;
int delta = dc[0] - pix;
int m = abs(delta) * thresh >> 16;
m = FFMAX(0, 127 - m);
m = m * m * delta >> 14;
pix += m + dithers[x & 7];
dst[x] = av_clip_uint8(pix >> 7);
}
}
void ff_gradfun_blur_line_c(uint16_t *dc, uint16_t *buf, const uint16_t *buf1, const uint8_t *src, int src_linesize, int width)
{
int x, v, old;
for (x = 0; x < width; x++) {
v = buf1[x] + src[2 * x] + src[2 * x + 1] + src[2 * x + src_linesize] + src[2 * x + 1 + src_linesize];
old = buf[x];
buf[x] = v;
dc[x] = v - old;
}
}
static void filter(GradFunContext *ctx, uint8_t *dst, const uint8_t *src, int width, int height, int dst_linesize, int src_linesize, int r)
{
int bstride = FFALIGN(width, 16) / 2;
int y;
uint32_t dc_factor = (1 << 21) / (r * r);
uint16_t *dc = ctx->buf + 16;
uint16_t *buf = ctx->buf + bstride + 32;
int thresh = ctx->thresh;
memset(dc, 0, (bstride + 16) * sizeof(*buf));
for (y = 0; y < r; y++)
ctx->blur_line(dc, buf + y * bstride, buf + (y - 1) * bstride, src + 2 * y * src_linesize, src_linesize, width / 2);
for (;;) {
if (y < height - r) {
int mod = ((y + r) / 2) % r;
uint16_t *buf0 = buf + mod * bstride;
uint16_t *buf1 = buf + (mod ? mod - 1 : r - 1) * bstride;
int x, v;
ctx->blur_line(dc, buf0, buf1, src + (y + r) * src_linesize, src_linesize, width / 2);
for (x = v = 0; x < r; x++)
v += dc[x];
for (; x < width / 2; x++) {
v += dc[x] - dc[x-r];
dc[x-r] = v * dc_factor >> 16;
}
for (; x < (width + r + 1) / 2; x++)
dc[x-r] = v * dc_factor >> 16;
for (x = -r / 2; x < 0; x++)
dc[x] = dc[0];
}
if (y == r) {
for (y = 0; y < r; y++)
ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]);
}
ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]);
if (++y >= height) break;
ctx->filter_line(dst + y * dst_linesize, src + y * src_linesize, dc - r / 2, width, thresh, dither[y & 7]);
if (++y >= height) break;
}
}
static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
{
GradFunContext *gf = ctx->priv;
float thresh = 1.2;
int radius = 16;
int cpu_flags = av_get_cpu_flags();
if (args)
sscanf(args, "%f:%d", &thresh, &radius);
thresh = av_clipf(thresh, 0.51, 255);
gf->thresh = (1 << 15) / thresh;
gf->radius = av_clip((radius + 1) & ~1, 4, 32);
gf->blur_line = ff_gradfun_blur_line_c;
gf->filter_line = ff_gradfun_filter_line_c;
if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX2)
gf->filter_line = ff_gradfun_filter_line_mmx2;
if (HAVE_SSSE3 && cpu_flags & AV_CPU_FLAG_SSSE3)
gf->filter_line = ff_gradfun_filter_line_ssse3;
if (HAVE_SSE && cpu_flags & AV_CPU_FLAG_SSE2)
gf->blur_line = ff_gradfun_blur_line_sse2;
av_log(ctx, AV_LOG_INFO, "threshold:%.2f radius:%d\n", thresh, gf->radius);
return 0;
}
static av_cold void uninit(AVFilterContext *ctx)
{
GradFunContext *gf = ctx->priv;
av_freep(&gf->buf);
}
static int query_formats(AVFilterContext *ctx)
{
static const enum PixelFormat pix_fmts[] = {
PIX_FMT_YUV410P, PIX_FMT_YUV420P,
PIX_FMT_GRAY8, PIX_FMT_NV12,
PIX_FMT_NV21, PIX_FMT_YUV444P,
PIX_FMT_YUV422P, PIX_FMT_YUV411P,
PIX_FMT_NONE
};
avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
return 0;
}
static int config_input(AVFilterLink *inlink)
{
GradFunContext *gf = inlink->dst->priv;
int hsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
int vsub = av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
gf->buf = av_mallocz((FFALIGN(inlink->w, 16) * (gf->radius + 1) / 2 + 32) * sizeof(uint16_t));
if (!gf->buf)
return AVERROR(ENOMEM);
gf->chroma_w = -((-inlink->w) >> hsub);
gf->chroma_h = -((-inlink->h) >> vsub);
gf->chroma_r = av_clip(((((gf->radius >> hsub) + (gf->radius >> vsub)) / 2 ) + 1) & ~1, 4, 32);
return 0;
}
static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
{
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFilterBufferRef *outpicref;
if (inpicref->perms & AV_PERM_PRESERVE) {
outpicref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
avfilter_copy_buffer_ref_props(outpicref, inpicref);
outpicref->video->w = outlink->w;
outpicref->video->h = outlink->h;
} else
outpicref = inpicref;
outlink->out_buf = outpicref;
avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
}
static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
static void end_frame(AVFilterLink *inlink)
{
GradFunContext *gf = inlink->dst->priv;
AVFilterBufferRef *inpic = inlink->cur_buf;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFilterBufferRef *outpic = outlink->out_buf;
int p;
for (p = 0; p < 4 && inpic->data[p]; p++) {
int w = inlink->w;
int h = inlink->h;
int r = gf->radius;
if (p) {
w = gf->chroma_w;
h = gf->chroma_h;
r = gf->chroma_r;
}
if (FFMIN(w, h) > 2 * r)
filter(gf, outpic->data[p], inpic->data[p], w, h, outpic->linesize[p], inpic->linesize[p], r);
else if (outpic->data[p] != inpic->data[p])
av_image_copy_plane(outpic->data[p], outpic->linesize[p], inpic->data[p], inpic->linesize[p], w, h);
}
avfilter_draw_slice(outlink, 0, inlink->h, 1);
avfilter_end_frame(outlink);
avfilter_unref_buffer(inpic);
if (outpic != inpic)
avfilter_unref_buffer(outpic);
}
AVFilter avfilter_vf_gradfun = {
.name = "gradfun",
.description = NULL_IF_CONFIG_SMALL("Debands video quickly using gradients."),
.priv_size = sizeof(GradFunContext),
.init = init,
.uninit = uninit,
.query_formats = query_formats,
.inputs = (const AVFilterPad[]) {{ .name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.config_props = config_input,
.start_frame = start_frame,
.draw_slice = null_draw_slice,
.end_frame = end_frame,
.min_perms = AV_PERM_READ, },
{ .name = NULL}},
.outputs = (const AVFilterPad[]) {{ .name = "default",
.type = AVMEDIA_TYPE_VIDEO, },
{ .name = NULL}},
};
| SuperrSonic/WiiMC-SSLC | source/mplayer/ffmpeg/libavfilter/vf_gradfun.c | C | gpl-3.0 | 9,235 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2230,
13401,
11320,
2213,
1026,
2053,
2140,
2620,
2620,
2620,
1030,
20917,
4014,
1012,
4012,
1028,
1008,
9385,
1006,
1039,
1007,
2268,
28779,
26701,
1026,
28779,
2213,
1030,
1057,
1012,
9378,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* This file is part of the Artenus 2D Framework.
* Copyright (C) 2015 Hessan Feghhi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package com.annahid.libs.artenus;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import com.annahid.libs.artenus.graphics.TextureManager;
import com.annahid.libs.artenus.graphics.rendering.ShaderManager;
import com.annahid.libs.artenus.internal.core.StageImpl;
import com.annahid.libs.artenus.sound.SoundManager;
import com.annahid.libs.artenus.core.Stage;
import com.annahid.libs.artenus.unified.Stores;
import com.annahid.libs.artenus.unified.UnifiedServices;
import com.annahid.libs.artenus.unified.AdLayout;
import java.lang.ref.WeakReference;
/**
* The abstract superclass of a typical Artenus SDK activity. This class should be
* extended by the game application and the {@code init()} method must be implemented
* to handle basic initializations and retrieving the stage.
*
* @author Hessan Feghhi
*/
public abstract class Artenus extends Activity {
/**
* Holds the Artenus instance. Only one instance should exist per application.
* This instance is assigned not in the constructor, but when its context is ready.
*/
private static WeakReference<Artenus> instance = null;
/**
* Indicates whether the default splash screen will be displayed. This value can be set by
* calling the protected constructor.
*/
private static boolean hideIntro;
/**
* Holds the app-store as specified in the Android manifest file.
*/
private static Stores manifestStore;
/**
* Holds a reference to the default stage.
*/
private WeakReference<StageImpl> stage;
/**
* Holds the audio manager used for mapping volume keys to media volume.
*/
private AudioManager audio;
/**
* Indicates whether the app is out-focused.
*/
private boolean hasOutFocused = false;
/**
* Creates a new instance of Artenus activity.
*
* @param hideIntro A value indicating whether to hide the initial splash screen
*/
protected Artenus(boolean hideIntro) {
Artenus.hideIntro = hideIntro;
}
/**
* Creates a new instance of Artenus activity.
*/
protected Artenus() {
this(false);
}
/**
* Gets the currently running instance of {@code Artenus}.
*
* @return The running instance
*/
public static Artenus getInstance() {
if (instance == null) {
throw new IllegalStateException("Artenus instance does not exist!");
}
return instance.get();
}
/**
* Determines whether an intro screen should be displayed before the game.
*
* @return true if there should be an intro, false otherwise
*/
public static boolean shouldHideIntro() {
return hideIntro;
}
/**
* Gets the store preference specified in the application manifest for unified services.
*
* @return Store identifier
*
* @see com.annahid.libs.artenus.unified.UnifiedServices
*/
public static Stores getManifestAppStore() {
return manifestStore;
}
/**
* Gets the game stage. Each game has only one stage, where its different scenes are displayed.
*
* @return The stage
*/
public Stage getStage() {
return stage.get();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = new WeakReference<>(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
try {
ApplicationInfo ai = getPackageManager().getApplicationInfo(
getPackageName(),
PackageManager.GET_META_DATA
);
final String store = ai.metaData.getString("com.annahid.libs.artenus.APP_STORE");
manifestStore = Stores.NONE;
if (store != null) {
switch (store) {
case "google":
manifestStore = Stores.GOOGLE;
break;
case "amazon":
manifestStore = Stores.AMAZON;
break;
case "bazaar":
manifestStore = Stores.BAZAAR;
break;
case "cando":
manifestStore = Stores.CANDO;
break;
case "samsung":
manifestStore = Stores.SAMSUNG;
break;
}
}
} catch (PackageManager.NameNotFoundException | NullPointerException e) {
manifestStore = Stores.NONE;
}
if (!SoundManager.isContextInitialized()) {
SoundManager.initContext(this);
}
setContentView(R.layout.game_layout);
stage = new WeakReference<>((StageImpl) findViewById(R.id.gameStage));
ShaderManager.register(TextureManager.getShaderProgram());
init(stage.get());
UnifiedServices unified = UnifiedServices.getInstance();
if (unified == null) {
unified = UnifiedServices.getInstance(0);
}
if (unified.hasServices(UnifiedServices.SERVICE_ADS)) {
unified.getAdManager().setAdLayout((AdLayout) stage.get().getParent());
}
unified.onCreate(this);
}
@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (stage != null && stage.get() != null && stage.get().onBackButton()) {
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
hasOutFocused = true;
} else if (hasOutFocused) {
SoundManager.resumeMusic();
hasOutFocused = false;
}
}
/**
* Exits the game or application. This is the recommended method to exit within the framework.
*/
@SuppressWarnings("UnusedDeclaration")
public final void exit() {
System.exit(0);
}
@Override
protected void onPause() {
super.onPause();
stage.get().onPause();
SoundManager.pauseMusic();
UnifiedServices.getInstance().onPause();
}
@Override
protected void onResume() {
super.onResume();
if (!hasOutFocused) {
SoundManager.resumeMusic();
}
stage.get().onResume();
UnifiedServices.getInstance().onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
UnifiedServices.getInstance().onDestroy(this);
TextureManager.unloadAll();
SoundManager.unloadAll();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UnifiedServices.getInstance().onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onStop() {
super.onStop();
UnifiedServices.getInstance().onStop();
}
@Override
protected void onStart() {
super.onStart();
UnifiedServices.getInstance().onStart();
}
/**
* Initializes the game. Subclasses should implement this method and use it as an entry point to
* load textures and other resources into the framework.
*
* @param stage The stage for the game
*/
protected abstract void init(Stage stage);
}
| hessan/artenus | src/main/java/com/annahid/libs/artenus/Artenus.java | Java | gpl-3.0 | 9,599 | [
30522,
1013,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
1996,
16185,
10182,
14134,
7705,
1012,
1008,
9385,
1006,
1039,
1007,
2325,
23484,
2319,
10768,
5603,
4048,
1008,
1008,
2023,
2565,
2003,
2489,
4007,
1024,
2017,
2064,
2417,
2923,
3089,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import sbt._
import sbt.Keys._
object LiftProjectBuild extends Build {
import Dependencies._
import BuildSettings._
lazy val root = Project("lift-poly-example", file("."))
.settings(liftAppSettings: _*)
.settings(libraryDependencies ++=
compile(
liftWebkit,
liftMongodb,
liftExtras,
liftMongoauth,
logback,
rogueField,
rogueCore,
rogueLift,
rogueIndex
) ++
test(scalatest) ++
container(jettyWebapp)
)
}
| eltimn/lift-poly-example | project/Build.scala | Scala | apache-2.0 | 520 | [
30522,
12324,
24829,
2102,
1012,
1035,
12324,
24829,
2102,
1012,
6309,
1012,
1035,
4874,
6336,
21572,
20614,
8569,
4014,
2094,
8908,
3857,
1063,
12324,
12530,
15266,
1012,
1035,
12324,
16473,
18319,
3070,
2015,
1012,
1035,
13971,
11748,
7117,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.totalboumboum.ai.v201112.ais.kayukataskin.v3.criterion;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCriterionString;
import org.totalboumboum.ai.v201112.adapter.communication.StopRequestException;
import org.totalboumboum.ai.v201112.adapter.data.AiTile;
import org.totalboumboum.ai.v201112.ais.kayukataskin.v3.KayukaTaskin;
/**
* Cette classe est un simple exemple de
* critère chaîne de caractères. Copiez-la, renommez-la, modifiez-la
* pour l'adapter à vos besoin. Notez que le domaine
* de définition est spécifiés dans l'appel au constructeur
* ({@code super(nom,inf,sup)}).
*
* @author Pol Kayuka
* @author Ayça Taşkın
*/
@SuppressWarnings("deprecation")
public class CriterionThird extends AiUtilityCriterionString
{ /** Nom de ce critère */
public static final String NAME = "THIRD";
/** Valeurs du domaine de définition */
public static final String VALUE1 = "une valeur";
/** */
public static final String VALUE2 = "une autre valeur";
/** */
public static final String VALUE3 = "encore une autre";
/** */
public static final String VALUE4 = "et puis une autre";
/** */
public static final String VALUE5 = "et enfin une dernière";
/** Domaine de définition */
public static final Set<String> DOMAIN = new TreeSet<String>(Arrays.asList
( VALUE1,
VALUE2,
VALUE3,
VALUE4,
VALUE5
));
/**
* Crée un nouveau critère entier.
* @param ai
* ?
* @throws StopRequestException
* Au cas où le moteur demande la terminaison de l'agent.
*/
public CriterionThird(KayukaTaskin ai) throws StopRequestException
{ // init nom + bornes du domaine de définition
super(NAME,DOMAIN);
ai.checkInterruption();
// init agent
this.ai = ai;
}
/////////////////////////////////////////////////////////////////
// ARTIFICIAL INTELLIGENCE /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** */
protected KayukaTaskin ai;
/////////////////////////////////////////////////////////////////
// PROCESS /////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
public String processValue(AiTile tile) throws StopRequestException
{ ai.checkInterruption();
String result = VALUE3;
// à compléter par le traitement approprié
return result;
}
}
| vlabatut/totalboumboum | resources/ai/org/totalboumboum/ai/v201112/ais/kayukataskin/v3/criterion/CriterionThird.java | Java | gpl-2.0 | 2,534 | [
30522,
7427,
8917,
1012,
2561,
5092,
25438,
24778,
1012,
9932,
1012,
1058,
11387,
14526,
12521,
1012,
9932,
2015,
1012,
10905,
15750,
10230,
4939,
1012,
1058,
2509,
1012,
19229,
1025,
12324,
9262,
1012,
21183,
4014,
1012,
27448,
1025,
12324,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
from contextlib import contextmanager
from functools import wraps
from werkzeug.local import LocalProxy, LocalStack
_additional_ctx_stack = LocalStack()
__all__ = ("current_additions", "Additional", "AdditionalManager")
@LocalProxy
def current_additions():
"""
Proxy to the currently added requirements
"""
rv = _additional_ctx_stack.top
if rv is None:
return None
return rv[1]
def _isinstance(f):
@wraps(f)
def check(self, other):
if not isinstance(other, Additional):
return NotImplemented
return f(self, other)
return check
class Additional(object):
"""
Container object that allows to run extra requirements on checks. These
additional requirements will be run at most once per check and will
occur in no guarenteed order.
Requirements can be added by passing them into the constructor or
by calling the ``add`` method. They can be removed from this object
by calling the ``remove`` method. To check if a requirement has been added
to the current conext, you may call ``is_added`` or use ``in``::
some_req in additional
additional.is_added(some)req)
Additional objects can be iterated and length checked::
additional = Additional(some_req)
assert len(additional) == 1
assert list(additional) == [some_req]
Additional objects may be combined and compared to each other with the following
operators:
``+`` creates a new additional object by combining two others, the new
additional supplies all requirements that both parents did.
``+=`` similar to ``+`` except it is an inplace update.
``-`` creates a new additional instance by removing any requirements from
the first instance that are contained in the second instance.
``-=`` similar to ``-`` except it is an inplace update.
``==`` compares two additional instances and returns true if both have
the same added requirements.
``!=`` similar to ``!=`` except returns true if both have different
requirements contained in them.
"""
def __init__(self, *requirements):
self._requirements = set(requirements)
def add(self, requirement, *requirements):
self._requirements.update((requirement,) + requirements)
def remove(self, requirement, *requirements):
self._requirements.difference_update((requirement,) + requirements)
@_isinstance
def __add__(self, other):
requirements = self._requirements | other._requirements
return Additional(*requirements)
@_isinstance
def __iadd__(self, other):
if len(other._requirements) > 0:
self._requirements.add(*other._requirements)
return self
@_isinstance
def __sub__(self, other):
requirements = self._requirements - other._requirements
return Additional(*requirements)
@_isinstance
def __isub__(self, other):
if len(other._requirements) > 0:
self.remove(*other._requirements)
return self
@_isinstance
def __eq__(self, other):
return self._requirements == other._requirements
@_isinstance
def __ne__(self, other):
return not self == other
def __iter__(self):
return iter(self._requirements)
def is_added(self, requirement):
return requirement in self._requirements
def __contains__(self, requirement):
return self.is_added(requirement)
def __len__(self):
return len(self._requirements)
def __bool__(self):
return len(self) != 0
__nonzero__ = __bool__
def __repr__(self):
return "Additional({!r})".format(self._requirements)
class AdditionalManager(object):
"""
Used to manage the process of adding and removing additional requirements
to be run. This class shouldn't be used directly, instead use
``allows.additional`` to access these controls.
"""
def push(self, additional, use_parent=False):
"""
Binds an additional to the current context, optionally use the
current additionals in conjunction with this additional
If ``use_parent`` is true, a new additional is created from the
parent and child additionals rather than manipulating either
directly.
"""
current = self.current
if use_parent and current:
additional = current + additional
_additional_ctx_stack.push((self, additional))
def pop(self):
"""
Pops the latest additional context.
If the additional context was pushed by a different additional manager,
a ``RuntimeError`` is raised.
"""
rv = _additional_ctx_stack.pop()
if rv is None or rv[0] is not self:
raise RuntimeError(
"popped wrong additional context ({} instead of {})".format(rv, self)
)
@property
def current(self):
"""
Returns the current additional context if set otherwise None
"""
try:
return _additional_ctx_stack.top[1]
except TypeError:
return None
@contextmanager
def additional(self, additional, use_parent=False):
"""
Allows temporarily pushing an additional context, yields the new context
into the following block.
"""
self.push(additional, use_parent)
yield self.current
self.pop()
| justanr/flask-allows | src/flask_allows/additional.py | Python | mit | 5,469 | [
30522,
2013,
6123,
29521,
12324,
6123,
24805,
4590,
2013,
4569,
6593,
13669,
2015,
12324,
19735,
2013,
2057,
8024,
4371,
15916,
1012,
2334,
12324,
2334,
21572,
18037,
1010,
10575,
2696,
3600,
1035,
3176,
1035,
14931,
2595,
1035,
9991,
1027,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (C) 2019 by Sukchan Lee <acetcom@gmail.com>
*
* This file is part of Open5GS.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef OGS_IPFW_H
#define OGS_IPFW_H
#ifdef __cplusplus
extern "C" {
#endif
#include "ogs-core.h"
typedef struct ogs_ipfw_rule_s {
uint8_t proto;
uint8_t ipv4_src;
uint8_t ipv4_dst;
uint8_t ipv6_src;
uint8_t ipv6_dst;
struct {
struct {
uint32_t addr[4];
uint32_t mask[4];
} src;
struct {
uint32_t addr[4];
uint32_t mask[4];
} dst;
} ip;
struct {
struct {
uint16_t low;
uint16_t high;
} src;
struct {
uint16_t low;
uint16_t high;
} dst;
} port;
uint16_t tos_traffic_class;
uint32_t security_parameter_index;
uint32_t flow_label; /* 24bit */
uint32_t sdf_filter_id;
} ogs_ipfw_rule_t;
int ogs_ipfw_compile_rule(ogs_ipfw_rule_t *ipfw_rule, char *flow_description);
char *ogs_ipfw_encode_flow_description(ogs_ipfw_rule_t *ipfw_rule);
/*
* Refer to lib/ipfw/ogs-ipfw.h
* Issue #338
*
* <DOWNLINK>
* RX : permit out from <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT> to <UE_IP> <UE_PORT>
* GX : permit out from <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT> to <UE_IP> <UE_PORT>
* PFCP : permit out from <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT> to <UE_IP> <UE_PORT>
* RULE : Source <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT> Destination <UE_IP> <UE_PORT>
* TFT : Local <UE_IP> <UE_PORT> REMOTE <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT>
*
* <UPLINK>
* RX : permit in from <UE_IP> <UE_PORT> to <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT>
* GX : permit out from <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT> to <UE_IP> <UE_PORT>
* PFCP : permit out from <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT> to <UE_IP> <UE_PORT>
* RULE : Source <UE_IP> <UE_PORT> Destination <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT>
* TFT : Local <UE_IP> <UE_PORT> REMOTE <P-CSCF_RTP_IP> <P-CSCF_RTP_PORT>
*/
ogs_ipfw_rule_t *ogs_ipfw_copy_and_swap(
ogs_ipfw_rule_t *dst, ogs_ipfw_rule_t *src);
void ogs_ipfw_rule_swap(ogs_ipfw_rule_t *ipfw_rule);
#define OGS_MAX_NUM_OF_PACKET_FILTER_COMPONENT 16
typedef struct ogs_pf_content_s {
uint8_t length;
#define OGS_PACKET_FILTER_MATCH_ALL 1
#define OGS_PACKET_FILTER_PROTOCOL_IDENTIFIER_NEXT_HEADER_TYPE 48
#define OGS_PACKET_FILTER_IPV4_REMOTE_ADDRESS_TYPE 16
#define OGS_PACKET_FILTER_IPV4_LOCAL_ADDRESS_TYPE 17
#define OGS_PACKET_FILTER_IPV6_REMOTE_ADDRESS_TYPE 32
#define OGS_PACKET_FILTER_IPV6_REMOTE_ADDRESS_PREFIX_LENGTH_TYPE 33
#define OGS_PACKET_FILTER_IPV6_LOCAL_ADDRESS_TYPE 34
#define OGS_PACKET_FILTER_IPV6_LOCAL_ADDRESS_PREFIX_LENGTH_TYPE 35
#define OGS_PACKET_FILTER_SINGLE_LOCAL_PORT_TYPE 64
#define OGS_PACKET_FILTER_LOCAL_PORT_RANGE_TYPE 65
#define OGS_PACKET_FILTER_SINGLE_REMOTE_PORT_TYPE 80
#define OGS_PACKET_FILTER_REMOTE_PORT_RANGE_TYPE 81
#define OGS_PACKET_FILTER_SECURITY_PARAMETER_INDEX_TYPE 96
#define OGS_PACKET_FILTER_TOS_TRAFFIC_CLASS_TYPE 112
#define OGS_PACKET_FILTER_FLOW_LABEL_TYPE 128
struct {
uint8_t type;
union {
uint8_t proto;
struct {
uint32_t addr;
uint32_t mask;
} ipv4;
struct {
uint32_t addr[4];
uint8_t prefixlen;
} ipv6;
struct {
uint32_t addr[4];
uint32_t mask[4];
} ipv6_mask;
struct {
uint16_t low;
uint16_t high;
} port;
};
} component[OGS_MAX_NUM_OF_PACKET_FILTER_COMPONENT];
uint8_t num_of_component;
} ogs_pf_content_t;
void ogs_pf_content_from_ipfw_rule(
uint8_t direction, ogs_pf_content_t *content, ogs_ipfw_rule_t *rule);
#ifdef __cplusplus
}
#endif
#endif /* OGS_IPFW_H */
| acetcom/nextepc | lib/ipfw/ogs-ipfw.h | C | agpl-3.0 | 4,446 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
10476,
2011,
10514,
2243,
14856,
3389,
1026,
9078,
13535,
5358,
1030,
20917,
4014,
1012,
4012,
1028,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
2330,
2629,
5620,
1012,
1008,
1008,
2023,
2565,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/**
* WebCLGLVertexFragmentProgram Object
* @class
* @constructor
*/
WebCLGLVertexFragmentProgram = function(gl, vertexSource, vertexHeader, fragmentSource, fragmentHeader) {
this.gl = gl;
var highPrecisionSupport = this.gl.getShaderPrecisionFormat(this.gl.FRAGMENT_SHADER, this.gl.HIGH_FLOAT);
this.precision = (highPrecisionSupport.precision != 0) ? 'precision highp float;\n\nprecision highp int;\n\n' : 'precision lowp float;\n\nprecision lowp int;\n\n';
this.utils = new WebCLGLUtils();
this.vertexSource;
this.fragmentSource;
this.in_vertex_values = [];
this.in_fragment_values = [];
this.vertexAttributes = []; // {location,value}
this.vertexUniforms = []; // {location,value}
this.fragmentSamplers = []; // {location,value}
this.fragmentUniforms = []; // {location,value}
if(vertexSource != undefined) this.setVertexSource(vertexSource, vertexHeader);
if(fragmentSource != undefined) this.setFragmentSource(fragmentSource, fragmentHeader);
};
/**
* Update the vertex source
* @type Void
* @param {String} vertexSource
* @param {String} vertexHeader
*/
WebCLGLVertexFragmentProgram.prototype.setVertexSource = function(vertexSource, vertexHeader) {
this.vertexHead =(vertexHeader!=undefined)?vertexHeader:'';
this.in_vertex_values = [];//{value,type,name,idPointer}
// value: argument value
// type: 'buffer_float4_fromKernel'(4 packet pointer4), 'buffer_float_fromKernel'(1 packet pointer4), 'buffer_float4'(1 pointer4), 'buffer_float'(1 pointer1)
// name: argument name
// idPointer to: this.vertexAttributes or this.vertexUniforms (according to type)
var argumentsSource = vertexSource.split(')')[0].split('(')[1].split(','); // "float* A", "float* B", "float C", "float4* D"
//console.log(argumentsSource);
for(var n = 0, f = argumentsSource.length; n < f; n++) {
if(argumentsSource[n].match(/\*kernel/gm) != null) {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float4_fromKernel',
name:argumentsSource[n].split('*kernel')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float_fromKernel',
name:argumentsSource[n].split('*kernel')[1].trim()};
}
} else if(argumentsSource[n].match(/\*/gm) != null) {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float4',
name:argumentsSource[n].split('*')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'buffer_float',
name:argumentsSource[n].split('*')[1].trim()};
}
} else {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'float4',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'float',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/mat4/gm) != null) {
this.in_vertex_values[n] = {value:undefined,
type:'mat4',
name:argumentsSource[n].split(' ')[1].trim()};
}
}
}
//console.log(this.in_vertex_values);
//console.log('original source: '+vertexSource);
this.vertexSource = vertexSource.replace(/\r\n/gi, '').replace(/\r/gi, '').replace(/\n/gi, '');
this.vertexSource = this.vertexSource.replace(/^\w* \w*\([\w\s\*,]*\) {/gi, '').replace(/}(\s|\t)*$/gi, '');
//console.log('minified source: '+this.vertexSource);
this.vertexSource = this.parseVertexSource(this.vertexSource);
if(this.fragmentSource != undefined) this.compileVertexFragmentSource();
};
/** @private **/
WebCLGLVertexFragmentProgram.prototype.parseVertexSource = function(source) {
//console.log(source);
for(var n = 0, f = this.in_vertex_values.length; n < f; n++) { // for each in_vertex_values (in argument)
var regexp = new RegExp(this.in_vertex_values[n].name+'\\[\\w*\\]',"gm");
var varMatches = source.match(regexp);// "Search current "in_vertex_values.name[xxx]" in source and store in array varMatches
//console.log(varMatches);
if(varMatches != null) {
for(var nB = 0, fB = varMatches.length; nB < fB; nB++) { // for each varMatches ("A[x]", "A[x]")
var regexpNativeGL = new RegExp('```(\s|\t)*gl.*'+varMatches[nB]+'.*```[^```(\s|\t)*gl]',"gm");
var regexpNativeGLMatches = source.match(regexpNativeGL);
if(regexpNativeGLMatches == null) {
var name = varMatches[nB].split('[')[0];
var vari = varMatches[nB].split('[')[1].split(']')[0];
var regexp = new RegExp(name+'\\['+vari.trim()+'\\]',"gm");
if(this.in_vertex_values[n].type == 'buffer_float4_fromKernel')
source = source.replace(regexp, 'buffer_float4_fromKernel_data('+name+'0,'+name+'1,'+name+'2,'+name+'3)');
if(this.in_vertex_values[n].type == 'buffer_float_fromKernel')
source = source.replace(regexp, 'buffer_float_fromKernel_data('+name+'0)');
if(this.in_vertex_values[n].type == 'buffer_float4')
source = source.replace(regexp, name);
if(this.in_vertex_values[n].type == 'buffer_float')
source = source.replace(regexp, name);
}
}
}
}
source = source.replace(/```(\s|\t)*gl/gi, "").replace(/```/gi, "");
//console.log('%c translated source:'+source, "background-color:#000;color:#FFF");
return source;
};
/**
* Update the fragment source
* @type Void
* @param {String} fragmentSource
* @param {String} fragmentHeader
*/
WebCLGLVertexFragmentProgram.prototype.setFragmentSource = function(fragmentSource, fragmentHeader) {
this.fragmentHead =(fragmentHeader!=undefined)?fragmentHeader:'';
this.in_fragment_values = [];//{value,type,name,idPointer}
// value: argument value
// type: 'buffer_float4'(RGBA channels), 'buffer_float'(Red channel)
// name: argument name
// idPointer to: this.fragmentSamplers or this.fragmentUniforms (according to type)
var argumentsSource = fragmentSource.split(')')[0].split('(')[1].split(','); // "float* A", "float* B", "float C", "float4* D"
//console.log(argumentsSource);
for(var n = 0, f = argumentsSource.length; n < f; n++) {
if(argumentsSource[n].match(/\*/gm) != null) {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'buffer_float4',
name:argumentsSource[n].split('*')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'buffer_float',
name:argumentsSource[n].split('*')[1].trim()};
}
} else {
if(argumentsSource[n].match(/float4/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'float4',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/float/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'float',
name:argumentsSource[n].split(' ')[1].trim()};
} else if(argumentsSource[n].match(/mat4/gm) != null) {
this.in_fragment_values[n] = {value:undefined,
type:'mat4',
name:argumentsSource[n].split(' ')[1].trim()};
}
}
}
//console.log(this.in_fragment_values);
//console.log('original source: '+source);
this.fragmentSource = fragmentSource.replace(/\r\n/gi, '').replace(/\r/gi, '').replace(/\n/gi, '');
this.fragmentSource = this.fragmentSource.replace(/^\w* \w*\([\w\s\*,]*\) {/gi, '').replace(/}(\s|\t)*$/gi, '');
//console.log('minified source: '+this.fragmentSource);
this.fragmentSource = this.parseFragmentSource(this.fragmentSource);
if(this.vertexSource != undefined) this.compileVertexFragmentSource();
};
/** @private **/
WebCLGLVertexFragmentProgram.prototype.parseFragmentSource = function(source) {
//console.log(source);
for(var n = 0, f = this.in_fragment_values.length; n < f; n++) { // for each in_fragment_values (in argument)
var regexp = new RegExp(this.in_fragment_values[n].name+'\\[\\w*\\]',"gm");
var varMatches = source.match(regexp);// "Search current "in_fragment_values.name[xxx]" in source and store in array varMatches
//console.log(varMatches);
if(varMatches != null) {
for(var nB = 0, fB = varMatches.length; nB < fB; nB++) { // for each varMatches ("A[x]", "A[x]")
var regexpNativeGL = new RegExp('```(\s|\t)*gl.*'+varMatches[nB]+'.*```[^```(\s|\t)*gl]',"gm");
var regexpNativeGLMatches = source.match(regexpNativeGL);
if(regexpNativeGLMatches == null) {
var name = varMatches[nB].split('[')[0];
var vari = varMatches[nB].split('[')[1].split(']')[0];
var regexp = new RegExp(name+'\\['+vari.trim()+'\\]',"gm");
if(this.in_fragment_values[n].type == 'buffer_float4')
source = source.replace(regexp, 'buffer_float4_data('+name+','+vari+')');
if(this.in_fragment_values[n].type == 'buffer_float')
source = source.replace(regexp, 'buffer_float_data('+name+','+vari+')');
}
}
}
}
source = source.replace(/```(\s|\t)*gl/gi, "").replace(/```/gi, "");
//console.log('%c translated source:'+source, "background-color:#000;color:#FFF");
return source;
};
/** @private **/
WebCLGLVertexFragmentProgram.prototype.compileVertexFragmentSource = function() {
lines_vertex_attrs = (function() {
str = '';
for(var n = 0, f = this.in_vertex_values.length; n < f; n++) {
if(this.in_vertex_values[n].type == 'buffer_float4_fromKernel') {
str += 'attribute vec4 '+this.in_vertex_values[n].name+'0;\n';
str += 'attribute vec4 '+this.in_vertex_values[n].name+'1;\n';
str += 'attribute vec4 '+this.in_vertex_values[n].name+'2;\n';
str += 'attribute vec4 '+this.in_vertex_values[n].name+'3;\n';
} else if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') {
str += 'attribute vec4 '+this.in_vertex_values[n].name+'0;\n';
} else if(this.in_vertex_values[n].type == 'buffer_float4') {
str += 'attribute vec4 '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'buffer_float') {
str += 'attribute float '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'float') {
str += 'uniform float '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'float4') {
str += 'uniform vec4 '+this.in_vertex_values[n].name+';\n';
} else if(this.in_vertex_values[n].type == 'mat4') {
str += 'uniform mat4 '+this.in_vertex_values[n].name+';\n';
}
}
return str;
}).bind(this);
lines_fragment_attrs = (function() {
str = '';
for(var n = 0, f = this.in_fragment_values.length; n < f; n++) {
if(this.in_fragment_values[n].type == 'buffer_float4' || this.in_fragment_values[n].type == 'buffer_float') {
str += 'uniform sampler2D '+this.in_fragment_values[n].name+';\n';
} else if(this.in_fragment_values[n].type == 'float') {
str += 'uniform float '+this.in_fragment_values[n].name+';\n';
} else if(this.in_fragment_values[n].type == 'float4') {
str += 'uniform vec4 '+this.in_fragment_values[n].name+';\n';
} else if(this.in_fragment_values[n].type == 'mat4') {
str += 'uniform mat4 '+this.in_fragment_values[n].name+';\n';
}
}
return str;
}).bind(this);
var sourceVertex = this.precision+
'uniform float uOffset;\n'+
lines_vertex_attrs()+
this.utils.unpackGLSLFunctionString()+
'vec4 buffer_float4_fromKernel_data(vec4 arg0, vec4 arg1, vec4 arg2, vec4 arg3) {\n'+
'float argX = (unpack(arg0)*(uOffset*2.0))-uOffset;\n'+
'float argY = (unpack(arg1)*(uOffset*2.0))-uOffset;\n'+
'float argZ = (unpack(arg2)*(uOffset*2.0))-uOffset;\n'+
'float argW = (unpack(arg3)*(uOffset*2.0))-uOffset;\n'+
'return vec4(argX, argY, argZ, argW);\n'+
'}\n'+
'float buffer_float_fromKernel_data(vec4 arg0) {\n'+
'float argX = (unpack(arg0)*(uOffset*2.0))-uOffset;\n'+
'return argX;\n'+
'}\n'+
'vec2 get_global_id() {\n'+
'return vec2(0.0, 0.0);\n'+
'}\n'+
this.vertexHead+
'void main(void) {\n'+
this.vertexSource+
'}\n';
//console.log(sourceVertex);
var sourceFragment = this.precision+
lines_fragment_attrs()+
'vec4 buffer_float4_data(sampler2D arg, vec2 coord) {\n'+
'vec4 textureColor = texture2D(arg, coord);\n'+
'return textureColor;\n'+
'}\n'+
'float buffer_float_data(sampler2D arg, vec2 coord) {\n'+
'vec4 textureColor = texture2D(arg, coord);\n'+
'return textureColor.x;\n'+
'}\n'+
'vec2 get_global_id() {\n'+
'return vec2(0.0, 0.0);\n'+
'}\n'+
this.fragmentHead+
'void main(void) {\n'+
this.fragmentSource+
'}\n';
//console.log(sourceFragment);
this.vertexFragmentProgram = this.gl.createProgram();
this.utils.createShader(this.gl, "WEBCLGL VERTEX FRAGMENT PROGRAM", sourceVertex, sourceFragment, this.vertexFragmentProgram);
this.vertexAttributes = []; // {location,value}
this.vertexUniforms = []; // {location,value}
this.fragmentSamplers = []; // {location,value}
this.fragmentUniforms = []; // {location,value}
this.uOffset = this.gl.getUniformLocation(this.vertexFragmentProgram, "uOffset");
// vertexAttributes & vertexUniforms
for(var n = 0, f = this.in_vertex_values.length; n < f; n++) {
if( this.in_vertex_values[n].type == 'buffer_float4_fromKernel') {
this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"0"),
this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"1"),
this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"2"),
this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"3")],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1;
} else if(this.in_vertex_values[n].type == 'buffer_float_fromKernel') {
this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name+"0")],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1;
} else if(this.in_vertex_values[n].type == 'buffer_float4' || this.in_vertex_values[n].type == 'buffer_float') {
this.vertexAttributes.push({location:[this.gl.getAttribLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name)],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexAttributes.length-1;
} else if(this.in_vertex_values[n].type == 'float' || this.in_vertex_values[n].type == 'float4' || this.in_vertex_values[n].type == 'mat4') {
this.vertexUniforms.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_vertex_values[n].name)],
value:this.in_vertex_values[n].value,
type: this.in_vertex_values[n].type});
this.in_vertex_values[n].idPointer = this.vertexUniforms.length-1;
}
}
// fragmentSamplers & fragmentUniforms
for(var n = 0, f = this.in_fragment_values.length; n < f; n++) {
if(this.in_fragment_values[n].type == 'buffer_float4' || this.in_fragment_values[n].type == 'buffer_float') {
this.fragmentSamplers.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_fragment_values[n].name)],
value:this.in_fragment_values[n].value,
type: this.in_fragment_values[n].type});
this.in_fragment_values[n].idPointer = this.fragmentSamplers.length-1;
} else if(this.in_fragment_values[n].type == 'float' || this.in_fragment_values[n].type == 'float4' || this.in_fragment_values[n].type == 'mat4') {
this.fragmentUniforms.push({location:[this.gl.getUniformLocation(this.vertexFragmentProgram, this.in_fragment_values[n].name)],
value:this.in_fragment_values[n].value,
type: this.in_fragment_values[n].type});
this.in_fragment_values[n].idPointer = this.fragmentUniforms.length-1;
}
}
return true;
};
/**
* Bind float, mat4 or a WebCLGLBuffer to a vertex argument
* @type Void
* @param {Int|String} argument Id of argument or name of this
* @param {Float|Int|WebCLGLBuffer} data
*/
WebCLGLVertexFragmentProgram.prototype.setVertexArg = function(argument, data) {
if(data == undefined) alert("Error: setVertexArg("+argument+", undefined)");
var numArg;
if(typeof argument != "string") {
numArg = argument;
} else {
for(var n=0, fn = this.in_vertex_values.length; n < fn; n++) {
if(this.in_vertex_values[n].name == argument) {
numArg = n;
break;
}
}
}
if(this.in_vertex_values[numArg] == undefined) {
console.log("argument "+argument+" not exist in this vertex program");
return;
}
this.in_vertex_values[numArg].value = data;
if( this.in_vertex_values[numArg].type == 'buffer_float4_fromKernel' ||
this.in_vertex_values[numArg].type == 'buffer_float_fromKernel' ||
this.in_vertex_values[numArg].type == 'buffer_float4' ||
this.in_vertex_values[numArg].type == 'buffer_float') {
this.vertexAttributes[this.in_vertex_values[numArg].idPointer].value = this.in_vertex_values[numArg].value;
} else if(this.in_vertex_values[numArg].type == 'float' || this.in_vertex_values[numArg].type == 'float4' || this.in_vertex_values[numArg].type == 'mat4') {
this.vertexUniforms[this.in_vertex_values[numArg].idPointer].value = this.in_vertex_values[numArg].value;
}
};
/**
* Bind float or a WebCLGLBuffer to a fragment argument
* @type Void
* @param {Int|String} argument Id of argument or name of this
* @param {Float|Int|WebCLGLBuffer} data
*/
WebCLGLVertexFragmentProgram.prototype.setFragmentArg = function(argument, data) {
if(data == undefined) alert("Error: setFragmentArg("+argument+", undefined)");
var numArg;
if(typeof argument != "string") {
numArg = argument;
} else {
for(var n=0, fn = this.in_fragment_values.length; n < fn; n++) {
if(this.in_fragment_values[n].name == argument) {
numArg = n;
break;
}
}
}
if(this.in_fragment_values[numArg] == undefined) {
console.log("argument "+argument+" not exist in this fragment program");
return;
}
this.in_fragment_values[numArg].value = data;
if(this.in_fragment_values[numArg].type == 'buffer_float4' || this.in_fragment_values[numArg].type == 'buffer_float') {
this.fragmentSamplers[this.in_fragment_values[numArg].idPointer].value = this.in_fragment_values[numArg].value;
} else if(this.in_fragment_values[numArg].type == 'float' || this.in_fragment_values[numArg].type == 'float4' || this.in_fragment_values[numArg].type == 'mat4') {
this.fragmentUniforms[this.in_fragment_values[numArg].idPointer].value = this.in_fragment_values[numArg].value;
}
};
| stormcolor/stormenginec | StormEngineC/WebCLGLVertexFragmentProgram.class.js | JavaScript | mit | 19,084 | [
30522,
1013,
1008,
1008,
1008,
4773,
20464,
23296,
16874,
10288,
27843,
21693,
4765,
21572,
13113,
4874,
1008,
1030,
2465,
1008,
1030,
9570,
2953,
1008,
1013,
4773,
20464,
23296,
16874,
10288,
27843,
21693,
4765,
21572,
13113,
1027,
3853,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickrepeater_p.h"
#include "qquickrepeater_p_p.h"
#include <private/qqmlglobal_p.h>
#include <private/qqmllistaccessor_p.h>
#include <private/qqmlchangeset_p.h>
#include <private/qqmldelegatemodel_p.h>
#include <QtQml/QQmlInfo>
QT_BEGIN_NAMESPACE
QQuickRepeaterPrivate::QQuickRepeaterPrivate()
: model(0), ownModel(false), inRequest(false), dataSourceIsObject(false), delegateValidated(false), itemCount(0), createFrom(-1)
{
}
QQuickRepeaterPrivate::~QQuickRepeaterPrivate()
{
if (ownModel)
delete model;
}
/*!
\qmltype Repeater
\instantiates QQuickRepeater
\inqmlmodule QtQuick
\ingroup qtquick-models
\ingroup qtquick-positioning
\inherits Item
\brief Instantiates a number of Item-based components using a provided model
The Repeater type is used to create a large number of
similar items. Like other view types, a Repeater has a \l model and a \l delegate:
for each entry in the model, the delegate is instantiated
in a context seeded with data from the model. A Repeater item is usually
enclosed in a positioner type such as \l Row or \l Column to visually
position the multiple delegate items created by the Repeater.
The following Repeater creates three instances of a \l Rectangle item within
a \l Row:
\snippet qml/repeaters/repeater.qml import
\codeline
\snippet qml/repeaters/repeater.qml simple
\image repeater-simple.png
A Repeater's \l model can be any of the supported \l {qml-data-models}{data models}.
Additionally, like delegates for other views, a Repeater delegate can access
its index within the repeater, as well as the model data relevant to the
delegate. See the \l delegate property documentation for details.
Items instantiated by the Repeater are inserted, in order, as
children of the Repeater's parent. The insertion starts immediately after
the repeater's position in its parent stacking list. This allows
a Repeater to be used inside a layout. For example, the following Repeater's
items are stacked between a red rectangle and a blue rectangle:
\snippet qml/repeaters/repeater.qml layout
\image repeater.png
\note A Repeater item owns all items it instantiates. Removing or dynamically destroying
an item created by a Repeater results in unpredictable behavior.
\section2 Considerations when using Repeater
The Repeater type creates all of its delegate items when the repeater is first
created. This can be inefficient if there are a large number of delegate items and
not all of the items are required to be visible at the same time. If this is the case,
consider using other view types like ListView (which only creates delegate items
when they are scrolled into view) or use the \l {Dynamic Object Creation} methods to
create items as they are required.
Also, note that Repeater is \l {Item}-based, and can only repeat \l {Item}-derived objects.
For example, it cannot be used to repeat QtObjects:
\code
//bad code
Item {
Can't repeat QtObject as it doesn't derive from Item.
Repeater {
model: 10
QtObject {}
}
}
\endcode
*/
/*!
\qmlsignal QtQuick::Repeater::itemAdded(int index, Item item)
This signal is emitted when an item is added to the repeater. The \a index
parameter holds the index at which the item has been inserted within the
repeater, and the \a item parameter holds the \l Item that has been added.
The corresponding handler is \c onItemAdded.
*/
/*!
\qmlsignal QtQuick::Repeater::itemRemoved(int index, Item item)
This signal is emitted when an item is removed from the repeater. The \a index
parameter holds the index at which the item was removed from the repeater,
and the \a item parameter holds the \l Item that was removed.
Do not keep a reference to \a item if it was created by this repeater, as
in these cases it will be deleted shortly after the signal is handled.
The corresponding handler is \c onItemRemoved.
*/
QQuickRepeater::QQuickRepeater(QQuickItem *parent)
: QQuickItem(*(new QQuickRepeaterPrivate), parent)
{
}
QQuickRepeater::~QQuickRepeater()
{
}
/*!
\qmlproperty any QtQuick::Repeater::model
The model providing data for the repeater.
This property can be set to any of the supported \l {qml-data-models}{data models}:
\list
\li A number that indicates the number of delegates to be created by the repeater
\li A model (e.g. a ListModel item, or a QAbstractItemModel subclass)
\li A string list
\li An object list
\endlist
The type of model affects the properties that are exposed to the \l delegate.
\sa {qml-data-models}{Data Models}
*/
QVariant QQuickRepeater::model() const
{
Q_D(const QQuickRepeater);
if (d->dataSourceIsObject) {
QObject *o = d->dataSourceAsObject;
return QVariant::fromValue(o);
}
return d->dataSource;
}
void QQuickRepeater::setModel(const QVariant &m)
{
Q_D(QQuickRepeater);
QVariant model = m;
if (model.userType() == qMetaTypeId<QJSValue>())
model = model.value<QJSValue>().toVariant();
if (d->dataSource == model)
return;
clear();
if (d->model) {
disconnect(d->model, SIGNAL(modelUpdated(QQmlChangeSet,bool)),
this, SLOT(modelUpdated(QQmlChangeSet,bool)));
disconnect(d->model, SIGNAL(createdItem(int,QObject*)), this, SLOT(createdItem(int,QObject*)));
disconnect(d->model, SIGNAL(initItem(int,QObject*)), this, SLOT(initItem(int,QObject*)));
// disconnect(d->model, SIGNAL(destroyingItem(QObject*)), this, SLOT(destroyingItem(QObject*)));
}
d->dataSource = model;
QObject *object = qvariant_cast<QObject*>(model);
d->dataSourceAsObject = object;
d->dataSourceIsObject = object != 0;
QQmlInstanceModel *vim = 0;
if (object && (vim = qobject_cast<QQmlInstanceModel *>(object))) {
if (d->ownModel) {
delete d->model;
d->ownModel = false;
}
d->model = vim;
} else {
if (!d->ownModel) {
d->model = new QQmlDelegateModel(qmlContext(this));
d->ownModel = true;
if (isComponentComplete())
static_cast<QQmlDelegateModel *>(d->model.data())->componentComplete();
}
if (QQmlDelegateModel *dataModel = qobject_cast<QQmlDelegateModel*>(d->model))
dataModel->setModel(model);
}
if (d->model) {
connect(d->model, SIGNAL(modelUpdated(QQmlChangeSet,bool)),
this, SLOT(modelUpdated(QQmlChangeSet,bool)));
connect(d->model, SIGNAL(createdItem(int,QObject*)), this, SLOT(createdItem(int,QObject*)));
connect(d->model, SIGNAL(initItem(int,QObject*)), this, SLOT(initItem(int,QObject*)));
// connect(d->model, SIGNAL(destroyingItem(QObject*)), this, SLOT(destroyingItem(QObject*)));
regenerate();
}
emit modelChanged();
emit countChanged();
}
/*!
\qmlproperty Component QtQuick::Repeater::delegate
\default
The delegate provides a template defining each item instantiated by the repeater.
Delegates are exposed to a read-only \c index property that indicates the index
of the delegate within the repeater. For example, the following \l Text delegate
displays the index of each repeated item:
\table
\row
\li \snippet qml/repeaters/repeater.qml index
\li \image repeater-index.png
\endtable
If the \l model is a \l{QStringList-based model}{string list} or
\l{QObjectList-based model}{object list}, the delegate is also exposed to
a read-only \c modelData property that holds the string or object data. For
example:
\table
\row
\li \snippet qml/repeaters/repeater.qml modeldata
\li \image repeater-modeldata.png
\endtable
If the \l model is a model object (such as a \l ListModel) the delegate
can access all model roles as named properties, in the same way that delegates
do for view classes like ListView.
\sa {QML Data Models}
*/
QQmlComponent *QQuickRepeater::delegate() const
{
Q_D(const QQuickRepeater);
if (d->model) {
if (QQmlDelegateModel *dataModel = qobject_cast<QQmlDelegateModel*>(d->model))
return dataModel->delegate();
}
return 0;
}
void QQuickRepeater::setDelegate(QQmlComponent *delegate)
{
Q_D(QQuickRepeater);
if (QQmlDelegateModel *dataModel = qobject_cast<QQmlDelegateModel*>(d->model))
if (delegate == dataModel->delegate())
return;
if (!d->ownModel) {
d->model = new QQmlDelegateModel(qmlContext(this));
d->ownModel = true;
}
if (QQmlDelegateModel *dataModel = qobject_cast<QQmlDelegateModel*>(d->model)) {
dataModel->setDelegate(delegate);
regenerate();
emit delegateChanged();
d->delegateValidated = false;
}
}
/*!
\qmlproperty int QtQuick::Repeater::count
This property holds the number of items in the repeater.
*/
int QQuickRepeater::count() const
{
Q_D(const QQuickRepeater);
if (d->model)
return d->model->count();
return 0;
}
/*!
\qmlmethod Item QtQuick::Repeater::itemAt(index)
Returns the \l Item that has been created at the given \a index, or \c null
if no item exists at \a index.
*/
QQuickItem *QQuickRepeater::itemAt(int index) const
{
Q_D(const QQuickRepeater);
if (index >= 0 && index < d->deletables.count())
return d->deletables[index];
return 0;
}
void QQuickRepeater::componentComplete()
{
Q_D(QQuickRepeater);
if (d->model && d->ownModel)
static_cast<QQmlDelegateModel *>(d->model.data())->componentComplete();
QQuickItem::componentComplete();
regenerate();
if (d->model && d->model->count())
emit countChanged();
}
void QQuickRepeater::itemChange(ItemChange change, const ItemChangeData &value)
{
QQuickItem::itemChange(change, value);
if (change == ItemParentHasChanged) {
regenerate();
}
}
void QQuickRepeater::clear()
{
Q_D(QQuickRepeater);
bool complete = isComponentComplete();
if (d->model) {
for (int i = 0; i < d->deletables.count(); ++i) {
if (QQuickItem *item = d->deletables.at(i)) {
if (complete)
emit itemRemoved(i, item);
item->setParentItem(0);
d->model->release(item);
}
}
}
d->deletables.clear();
d->itemCount = 0;
}
void QQuickRepeater::regenerate()
{
Q_D(QQuickRepeater);
if (!isComponentComplete())
return;
clear();
if (!d->model || !d->model->count() || !d->model->isValid() || !parentItem() || !isComponentComplete())
return;
d->itemCount = count();
d->deletables.resize(d->itemCount);
d->createFrom = 0;
d->createItems();
}
void QQuickRepeaterPrivate::createItems()
{
Q_Q(QQuickRepeater);
if (createFrom == -1)
return;
inRequest = true;
for (int ii = createFrom; ii < itemCount; ++ii) {
if (!deletables.at(ii)) {
QObject *object = model->object(ii, false);
QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
if (!item) {
if (object) {
model->release(object);
if (!delegateValidated) {
delegateValidated = true;
QObject* delegate = q->delegate();
qmlInfo(delegate ? delegate : q) << QQuickRepeater::tr("Delegate must be of Item type");
}
}
createFrom = ii;
break;
}
deletables[ii] = item;
item->setParentItem(q->parentItem());
if (ii > 0 && deletables.at(ii-1)) {
item->stackAfter(deletables.at(ii-1));
} else {
QQuickItem *after = q;
for (int si = ii+1; si < itemCount; ++si) {
if (deletables.at(si)) {
after = deletables.at(si);
break;
}
}
item->stackBefore(after);
}
emit q->itemAdded(ii, item);
}
}
inRequest = false;
}
void QQuickRepeater::createdItem(int, QObject *)
{
Q_D(QQuickRepeater);
if (!d->inRequest)
d->createItems();
}
void QQuickRepeater::initItem(int, QObject *object)
{
QQuickItem *item = qmlobject_cast<QQuickItem*>(object);
if (item)
item->setParentItem(parentItem());
}
void QQuickRepeater::modelUpdated(const QQmlChangeSet &changeSet, bool reset)
{
Q_D(QQuickRepeater);
if (!isComponentComplete())
return;
if (reset) {
regenerate();
if (changeSet.difference() != 0)
emit countChanged();
return;
}
int difference = 0;
QHash<int, QVector<QPointer<QQuickItem> > > moved;
foreach (const QQmlChangeSet::Change &remove, changeSet.removes()) {
int index = qMin(remove.index, d->deletables.count());
int count = qMin(remove.index + remove.count, d->deletables.count()) - index;
if (remove.isMove()) {
moved.insert(remove.moveId, d->deletables.mid(index, count));
d->deletables.erase(
d->deletables.begin() + index,
d->deletables.begin() + index + count);
} else while (count--) {
QQuickItem *item = d->deletables.at(index);
d->deletables.remove(index);
emit itemRemoved(index, item);
if (item) {
item->setParentItem(0);
d->model->release(item);
}
--d->itemCount;
}
difference -= remove.count;
}
d->createFrom = -1;
foreach (const QQmlChangeSet::Change &insert, changeSet.inserts()) {
int index = qMin(insert.index, d->deletables.count());
if (insert.isMove()) {
QVector<QPointer<QQuickItem> > items = moved.value(insert.moveId);
d->deletables = d->deletables.mid(0, index) + items + d->deletables.mid(index);
QQuickItem *stackBefore = index + items.count() < d->deletables.count()
? d->deletables.at(index + items.count())
: this;
for (int i = index; i < index + items.count(); ++i)
d->deletables.at(i)->stackBefore(stackBefore);
} else for (int i = 0; i < insert.count; ++i) {
int modelIndex = index + i;
++d->itemCount;
d->deletables.insert(modelIndex, 0);
if (d->createFrom == -1)
d->createFrom = modelIndex;
}
difference += insert.count;
}
d->createItems();
if (difference != 0)
emit countChanged();
}
QT_END_NAMESPACE
| Distrotech/qtdeclarative | src/quick/items/qquickrepeater.cpp | C++ | lgpl-3.0 | 16,594 | [
30522,
1013,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
30524,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
1008,
10... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
module("tinymce.EnterKey", {
setupModule: function() {
QUnit.stop();
tinymce.init({
selector: "textarea",
plugins: wpPlugins,
add_unload_trigger: false,
disable_nodechange: true,
indent: false,
skin: false,
entities: 'raw',
schema: 'html5',
extended_valid_elements: 'div[id|style|contenteditable],span[id|style|contenteditable],#dt,#dd',
valid_styles: {
'*' : 'color,font-size,font-family,background-color,font-weight,font-style,text-decoration,float,margin,margin-top,margin-right,margin-bottom,margin-left,display,position,top,left'
},
init_instance_callback: function(ed) {
window.editor = ed;
QUnit.start();
}
});
},
teardown: function() {
editor.settings.forced_root_block = 'p';
editor.settings.forced_root_block_attrs = null;
editor.settings.end_container_on_empty_block = false;
editor.settings.br_in_pre = true;
editor.settings.keep_styles = true;
delete editor.settings.force_p_newlines;
}
});
test('Enter at end of H1', function() {
editor.setContent('<h1>abc</h1>');
Utils.setSelection('h1', 3);
Utils.pressEnter();
equal(editor.getContent(), '<h1>abc</h1><p>\u00a0</p>');
equal(editor.selection.getRng(true).startContainer.nodeName, 'P');
});
test('Enter in midde of H1', function() {
editor.setContent('<h1>abcd</h1>');
Utils.setSelection('h1', 2);
Utils.pressEnter();
equal(editor.getContent(), '<h1>ab</h1><h1>cd</h1>');
equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'H1');
});
test('Enter before text after EM', function() {
editor.setContent('<p><em>a</em>b</p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 1);
Utils.pressEnter();
equal(editor.getContent(), '<p><em>a</em></p><p>b</p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeValue, 'b');
});
test('Enter before first IMG in P', function() {
editor.setContent('<p><img alt="" src="about:blank" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><p><img src="about:blank" alt="" /></p>');
});
test('Enter before last IMG in P with text', function() {
editor.setContent('<p>abc<img alt="" src="about:blank" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 1);
Utils.pressEnter();
equal(editor.getContent(), '<p>abc</p><p><img src="about:blank" alt="" /></p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeName, 'P');
equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'IMG');
});
test('Enter before last IMG in P with IMG sibling', function() {
editor.setContent('<p><img src="about:blank" alt="" /><img src="about:blank" alt="" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 1);
Utils.pressEnter();
equal(editor.getContent(), '<p><img src="about:blank" alt="" /></p><p><img src="about:blank" alt="" /></p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeName, 'P');
equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'IMG');
});
test('Enter after last IMG in P', function() {
editor.setContent('<p>abc<img alt="" src="about:blank" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 2);
Utils.pressEnter();
equal(editor.getContent(), '<p>abc<img src="about:blank" alt="" /></p><p>\u00a0</p>');
});
test('Enter before last INPUT in P with text', function() {
editor.setContent('<p>abc<input type="text" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 1);
Utils.pressEnter();
equal(editor.getContent(), '<p>abc</p><p><input type="text" /></p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeName, 'P');
equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'INPUT');
});
test('Enter before last INPUT in P with IMG sibling', function() {
editor.setContent('<p><input type="text" /><input type="text" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 1);
Utils.pressEnter();
equal(editor.getContent(), '<p><input type="text" /></p><p><input type="text" /></p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeName, 'P');
equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'INPUT');
});
test('Enter after last INPUT in P', function() {
editor.setContent('<p>abc<input type="text" /></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 2);
Utils.pressEnter();
equal(editor.getContent(), '<p>abc<input type="text" /></p><p>\u00a0</p>');
});
test('Enter at end of P', function() {
editor.setContent('<p>abc</p>');
Utils.setSelection('p', 3);
Utils.pressEnter();
equal(editor.getContent(), '<p>abc</p><p>\u00a0</p>');
equal(editor.selection.getRng(true).startContainer.nodeName, 'P');
});
test('Enter at end of EM inside P', function() {
editor.setContent('<p><em>abc</em></p>');
Utils.setSelection('em', 3);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>| /g, ''), '<p><em>abc</em></p><p><em></em></p>');
equal(editor.selection.getRng(true).startContainer.nodeName, 'EM');
});
test('Enter at middle of EM inside P', function() {
editor.setContent('<p><em>abcd</em></p>');
Utils.setSelection('em', 2);
Utils.pressEnter();
equal(editor.getContent(), '<p><em>ab</em></p><p><em>cd</em></p>');
equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'EM');
});
test('Enter at beginning EM inside P', function() {
editor.setContent('<p><em>abc</em></p>');
Utils.setSelection('em', 0);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>| /g, ''), '<p><em></em></p><p><em>abc</em></p>');
equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc');
});
test('Enter at end of STRONG in EM inside P', function() {
editor.setContent('<p><em><strong>abc</strong></em></p>');
Utils.setSelection('strong', 3);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>| /g, ''), '<p><em><strong>abc</strong></em></p><p><em><strong></strong></em></p>');
equal(editor.selection.getRng(true).startContainer.nodeName, 'STRONG');
});
test('Enter at middle of STRONG in EM inside P', function() {
editor.setContent('<p><em><strong>abcd</strong></em></p>');
Utils.setSelection('strong', 2);
Utils.pressEnter();
equal(editor.getContent(), '<p><em><strong>ab</strong></em></p><p><em><strong>cd</strong></em></p>');
equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'STRONG');
});
test('Enter at beginning STRONG in EM inside P', function() {
editor.setContent('<p><em><strong>abc</strong></em></p>');
Utils.setSelection('strong', 0);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>| /g, ''), '<p><em><strong></strong></em></p><p><em><strong>abc</strong></em></p>');
equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc');
});
test('Enter at beginning of P', function() {
editor.setContent('<p>abc</p>');
Utils.setSelection('p', 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><p>abc</p>');
equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc');
});
test('Enter at middle of P with style, id and class attributes', function() {
editor.setContent('<p id="a" class="b" style="color:#000">abcd</p>');
Utils.setSelection('p', 2);
Utils.pressEnter();
equal(editor.getContent(), '<p id="a" class="b" style="color: #000;">ab</p><p class="b" style="color: #000;">cd</p>');
equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'P');
});
test('Enter at a range between H1 and P', function() {
editor.setContent('<h1>abcd</h1><p>efgh</p>');
Utils.setSelection('h1', 2, 'p', 2);
Utils.pressEnter();
equal(editor.getContent(), '<h1>abgh</h1>');
equal(editor.selection.getNode().nodeName, 'H1');
});
test('Enter at end of H1 in HGROUP', function() {
editor.setContent('<hgroup><h1>abc</h1></hgroup>');
Utils.setSelection('h1', 3);
Utils.pressEnter();
equal(editor.getContent(), '<hgroup><h1>abc</h1><h1>\u00a0</h1></hgroup>');
equal(editor.selection.getRng(true).startContainer.nodeName, 'H1');
});
test('Enter inside empty TD', function() {
editor.getBody().innerHTML = '<table><tr><td></td></tr></table>';
Utils.setSelection('td', 0);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>| /g, ''), '<table><tbody><tr><td><p></p><p></p></td></tr></tbody></table>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Shift+Enter inside STRONG inside TD with BR', function() {
editor.getBody().innerHTML = '<table><tr><td>d <strong>e</strong><br></td></tr></table>';
Utils.setSelection('strong', 1);
Utils.pressEnter({shiftKey: true});
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<table><tbody><tr><td>d <strong>e<br></strong><br></td></tr></tbody></table>');
equal(editor.selection.getNode().nodeName, 'STRONG');
});
test('Enter inside middle of text node in body', function() {
editor.getBody().innerHTML = 'abcd';
Utils.setSelection('body', 2);
Utils.pressEnter();
equal(editor.getContent(), '<p>ab</p><p>cd</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside at beginning of text node in body', function() {
editor.getBody().innerHTML = 'abcd';
Utils.setSelection('body', 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><p>abcd</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside at end of text node in body', function() {
editor.getBody().innerHTML = 'abcd';
Utils.setSelection('body', 4);
Utils.pressEnter();
equal(editor.getContent(), '<p>abcd</p><p>\u00a0</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside empty body', function() {
editor.getBody().innerHTML = '';
Utils.setSelection('body', 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside empty li in beginning of ol', function() {
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>';
Utils.setSelection('li', 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><ol><li>a</li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside empty li at the end of ol', function() {
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>';
Utils.setSelection('li:last', 0);
Utils.pressEnter();
equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Shift+Enter inside empty li in the middle of ol', function() {
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>';
Utils.setSelection('li:nth-child(2)', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p><ol><li>b</li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Shift+Enter inside empty li in beginning of ol', function() {
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>';
Utils.setSelection('li', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p>\u00a0</p><ol><li>a</li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Shift+Enter inside empty li at the end of ol', function() {
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>';
Utils.setSelection('li:last', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside empty li in the middle of ol with forced_root_block: false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>';
Utils.setSelection('li:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<ol><li>a</li></ol><br /><ol><li>b</li></ol>');
equal(editor.selection.getNode().nodeName, 'BODY');
});
test('Enter inside empty li in beginning of ol with forced_root_block: false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>';
Utils.setSelection('li', 0);
Utils.pressEnter();
equal(editor.getContent(), '<br /><ol><li>a</li></ol>');
equal(editor.selection.getNode().nodeName, 'BODY');
});
test('Enter inside empty li at the end of ol with forced_root_block: false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>';
Utils.setSelection('li:last', 0);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<ol><li>a</li></ol><br>');
equal(editor.selection.getNode().nodeName, 'BODY');
});
test('Enter inside empty li in the middle of ol', function() {
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>';
Utils.setSelection('li:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p><ol><li>b</li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
// Nested lists in LI elements
test('Enter inside empty LI in beginning of OL in LI', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a' +
'<ol>' +
'<li><br></li>' +
'<li>a</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
Utils.setSelection('li li', 0);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>' +
'<ol>' +
'<li>a</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Enter inside empty LI in middle of OL in LI', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>a</li>' +
'<li><br></li>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
Utils.setSelection('li li:nth-child(2)', 0);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>a</li>' +
'</ol>' +
'</li>' +
'<li>\u00a0' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
// Ignore on IE 7, 8 this is a known bug not worth fixing
if (!tinymce.Env.ie || tinymce.Env.ie > 8) {
equal(editor.selection.getNode().nodeName, 'LI');
}
});
test('Enter inside empty LI in end of OL in LI', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>a</li>' +
'<li><br></li>' +
'</ol>' +
'</li>' +
'</ol>'
);
Utils.setSelection('li li:last', 0);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>a</li>' +
'</ol>' +
'</li>' +
'<li></li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
// Nested lists in OL elements
// Ignore on IE 7, 8 this is a known bug not worth fixing
if (!tinymce.Env.ie || tinymce.Env.ie > 8) {
test('Enter before nested list', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ol>'
);
Utils.setSelection('ol > li', 1);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>\u00a0' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
}
test('Enter inside empty LI in beginning of OL in OL', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li><br></li>' +
'<li>a</li>' +
'</ol>' +
'</ol>'
);
Utils.setSelection('ol ol li', 0);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li></li>' +
'<ol>' +
'<li>a</li>' +
'</ol>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Enter inside empty LI in middle of OL in OL', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>a</li>' +
'<li><br></li>' +
'<li>b</li>' +
'</ol>' +
'</ol>'
);
Utils.setSelection('ol ol li:nth-child(2)', 0);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<li></li>' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Enter inside empty LI in end of OL in OL', function() {
editor.getBody().innerHTML = Utils.trimBrsOnIE(
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>a</li>' +
'<li><br></li>' +
'</ol>' +
'</ol>'
);
Utils.setSelection('ol ol li:last', 0);
editor.focus();
Utils.pressEnter();
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<li></li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Enter at beginning of first DT inside DL', function() {
editor.getBody().innerHTML = '<dl><dt>a</dt></dl>';
Utils.setSelection('dt', 0);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dt>\u00a0</dt><dt>a</dt></dl>');
equal(editor.selection.getNode().nodeName, 'DT');
});
test('Enter at beginning of first DD inside DL', function() {
editor.getBody().innerHTML = '<dl><dd>a</dd></dl>';
Utils.setSelection('dd', 0);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dd>\u00a0</dd><dd>a</dd></dl>');
equal(editor.selection.getNode().nodeName, 'DD');
});
test('Enter at beginning of middle DT inside DL', function() {
editor.getBody().innerHTML = '<dl><dt>a</dt><dt>b</dt><dt>c</dt></dl>';
Utils.setSelection('dt:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dt>a</dt><dt>\u00a0</dt><dt>b</dt><dt>c</dt></dl>');
equal(editor.selection.getNode().nodeName, 'DT');
});
test('Enter at beginning of middle DD inside DL', function() {
editor.getBody().innerHTML = '<dl><dd>a</dd><dd>b</dd><dd>c</dd></dl>';
Utils.setSelection('dd:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dd>a</dd><dd>\u00a0</dd><dd>b</dd><dd>c</dd></dl>');
equal(editor.selection.getNode().nodeName, 'DD');
});
test('Enter at end of last DT inside DL', function() {
editor.getBody().innerHTML = '<dl><dt>a</dt></dl>';
Utils.setSelection('dt', 1);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dt>a</dt><dt>\u00a0</dt></dl>');
equal(editor.selection.getNode().nodeName, 'DT');
});
test('Enter at end of last DD inside DL', function() {
editor.getBody().innerHTML = '<dl><dd>a</dd></dl>';
Utils.setSelection('dd', 1);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dd>a</dd><dd>\u00a0</dd></dl>');
equal(editor.selection.getNode().nodeName, 'DD');
});
test('Enter at end of last empty DT inside DL', function() {
editor.getBody().innerHTML = '<dl><dt>a</dt><dt></dt></dl>';
Utils.setSelection('dt:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dt>a</dt></dl><p>\u00a0</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter at end of last empty DD inside DL', function() {
editor.getBody().innerHTML = '<dl><dd>a</dd><dd></dd></dl>';
Utils.setSelection('dd:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<dl><dd>a</dd></dl><p>\u00a0</p>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter at beginning of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 0);
Utils.pressEnter();
equal(editor.getContent(), '<ol><li></li><li><p>abcd</p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter inside middle of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 2);
Utils.pressEnter();
equal(editor.getContent(), '<ol><li><p>ab</p></li><li><p>cd</p></li></ol>');
// Ignore on IE 7, 8 this is a known bug not worth fixing
if (!tinymce.Env.ie || tinymce.Env.ie > 8) {
equal(editor.selection.getNode().nodeName, 'P');
}
});
test('Enter at end of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 4);
Utils.pressEnter();
equal(editor.getContent(), '<ol><li><p>abcd</p></li><li></li></ol>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Shift+Enter at beginning of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<ol><li><p><br />abcd</p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Shift+Enter inside middle of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 2);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<ol><li><p>ab<br />cd</p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Shift+Enter at end of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 4);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li><p>abcd</p></li></ol>' : '<ol><li><p>abcd<br /><br /></p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Ctrl+Enter at beginning of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 0);
Utils.pressEnter({ctrlKey: true});
equal(editor.getContent(), '<ol><li><p>\u00a0</p><p>abcd</p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Ctrl+Enter inside middle of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 2);
Utils.pressEnter({ctrlKey: true});
equal(editor.getContent(), '<ol><li><p>ab</p><p>cd</p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Ctrl+Enter at end of P inside LI', function() {
editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>';
Utils.setSelection('p', 4);
Utils.pressEnter({ctrlKey: true});
equal(editor.getContent(), '<ol><li><p>abcd</p><p>\u00a0</p></li></ol>');
equal(editor.selection.getNode().nodeName, 'P');
});
test('Enter in the middle of text in P with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<p>abc</p>';
Utils.setSelection('p', 2);
Utils.pressEnter();
equal(editor.getContent(), '<p>ab<br />c</p>');
});
test('Enter at the end of text in P with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<p>abc</p>';
Utils.setSelection('p', 3);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), (tinymce.isIE && tinymce.Env.ie < 11) ? '<p>abc<br></p>' : '<p>abc<br><br></p>');
});
test('Enter at the middle of text in BODY with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = 'abcd';
Utils.setSelection('body', 2);
editor.focus();
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), 'ab<br>cd');
});
test('Enter at the beginning of text in BODY with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = 'abcd';
Utils.setSelection('body', 0);
editor.focus();
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<br>abcd');
});
test('Enter at the end of text in BODY with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = 'abcd';
Utils.setSelection('body', 4);
editor.focus();
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), (tinymce.isIE && tinymce.Env.ie < 11) ? 'abcd<br>' : 'abcd<br><br>');
});
test('Enter in empty P at the end of a blockquote and end_container_on_empty_block: true', function() {
editor.settings.end_container_on_empty_block = true;
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p>abc</p><p></p></blockquote>' : '<blockquote><p>abc</p><p><br></p></blockquote>';
Utils.setSelection('p:last', 0);
Utils.pressEnter();
equal(editor.getContent(), '<blockquote><p>abc</p></blockquote><p>\u00a0</p>');
});
test('Enter in empty P at the beginning of a blockquote and end_container_on_empty_block: true', function() {
editor.settings.end_container_on_empty_block = true;
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p></p><p>abc</p></blockquote>' : '<blockquote><p><br></p><p>abc</p></blockquote>';
Utils.setSelection('p', 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><blockquote><p>abc</p></blockquote>');
});
test('Enter in empty P at in the middle of a blockquote and end_container_on_empty_block: true', function() {
editor.settings.end_container_on_empty_block = true;
editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p>abc</p><p></p><p>123</p></blockquote>' : '<blockquote><p>abc</p><p><br></p><p>123</p></blockquote>';
Utils.setSelection('p:nth-child(2)', 0);
Utils.pressEnter();
equal(editor.getContent(), '<blockquote><p>abc</p></blockquote><p>\u00a0</p><blockquote><p>123</p></blockquote>');
});
test('Enter inside empty P with empty P siblings', function() {
// Tests that a workaround for an IE bug is working correctly
editor.getBody().innerHTML = '<p></p><p></p><p>X</p>';
Utils.setSelection('p', 0);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p><p>\u00a0</p><p>X</p>');
});
test('Enter at end of H1 with forced_root_block_attrs', function() {
editor.settings.forced_root_block_attrs = {"class": "class1"};
editor.getBody().innerHTML = '<h1>a</h1>';
Utils.setSelection('h1', 1);
Utils.pressEnter();
equal(editor.getContent(), '<h1>a</h1><p class="class1">\u00a0</p>');
});
test('Shift+Enter at beginning of P', function() {
editor.getBody().innerHTML = '<p>abc</p>';
Utils.setSelection('p', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p><br />abc</p>');
});
test('Shift+Enter in the middle of P', function() {
editor.getBody().innerHTML = '<p>abcd</p>';
Utils.setSelection('p', 2);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p>ab<br />cd</p>');
});
test('Shift+Enter at the end of P', function() {
editor.getBody().innerHTML = '<p>abcd</p>';
Utils.setSelection('p', 4);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<p>abcd</p>' : '<p>abcd<br /><br /></p>');
});
test('Shift+Enter in the middle of B with a BR after it', function() {
editor.getBody().innerHTML = '<p><b>abcd</b><br></p>';
Utils.setSelection('b', 2);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p><b>ab<br />cd</b></p>');
});
test('Shift+Enter at the end of B with a BR after it', function() {
editor.getBody().innerHTML = '<p><b>abcd</b><br></p>';
Utils.setSelection('b', 4);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p><b>abcd<br /></b></p>');
});
test('Enter in beginning of PRE', function() {
editor.getBody().innerHTML = '<pre>abc</pre>';
Utils.setSelection('pre', 0);
Utils.pressEnter();
equal(editor.getContent(), '<pre><br />abc</pre>');
});
test('Enter in the middle of PRE', function() {
editor.getBody().innerHTML = '<pre>abcd</pre>';
Utils.setSelection('pre', 2);
Utils.pressEnter();
equal(editor.getContent(), '<pre>ab<br />cd</pre>');
});
test('Enter at the end of PRE', function() {
editor.getBody().innerHTML = '<pre>abcd</pre>';
Utils.setSelection('pre', 4);
Utils.pressEnter();
equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<pre>abcd</pre>' : '<pre>abcd<br /><br /></pre>');
});
test('Enter in beginning of PRE and br_in_pre: false', function() {
editor.settings.br_in_pre = false;
editor.getBody().innerHTML = '<pre>abc</pre>';
Utils.setSelection('pre', 0);
Utils.pressEnter();
equal(editor.getContent(), '<pre>\u00a0</pre><pre>abc</pre>');
});
test('Enter in the middle of PRE and br_in_pre: false', function() {
editor.settings.br_in_pre = false;
editor.getBody().innerHTML = '<pre>abcd</pre>';
Utils.setSelection('pre', 2);
Utils.pressEnter();
equal(editor.getContent(), '<pre>ab</pre><pre>cd</pre>');
});
test('Enter at the end of PRE and br_in_pre: false', function() {
editor.settings.br_in_pre = false;
editor.getBody().innerHTML = '<pre>abcd</pre>';
Utils.setSelection('pre', 4);
Utils.pressEnter();
equal(editor.getContent(), '<pre>abcd</pre><p>\u00a0</p>');
});
test('Shift+Enter in beginning of PRE', function() {
editor.getBody().innerHTML = '<pre>abc</pre>';
Utils.setSelection('pre', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<pre>\u00a0</pre><pre>abc</pre>');
});
test('Shift+Enter in the middle of PRE', function() {
editor.getBody().innerHTML = '<pre>abcd</pre>';
Utils.setSelection('pre', 2);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<pre>ab</pre><pre>cd</pre>');
});
test('Shift+Enter at the end of PRE', function() {
editor.getBody().innerHTML = '<pre>abcd</pre>';
Utils.setSelection('pre', 4);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<pre>abcd</pre><p>\u00a0</p>');
});
test('Shift+Enter in beginning of P with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<p>abc</p>';
Utils.setSelection('p', 0);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p>\u00a0</p><p>abc</p>');
});
test('Shift+Enter in middle of P with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<p>abcd</p>';
Utils.setSelection('p', 2);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p>ab</p><p>cd</p>');
});
test('Shift+Enter at the end of P with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<p>abc</p>';
Utils.setSelection('p', 3);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p>abc</p><p>\u00a0</p>');
});
test('Shift+Enter in body with forced_root_block set to false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = 'abcd';
var rng = editor.dom.createRng();
rng.setStart(editor.getBody().firstChild, 2);
rng.setEnd(editor.getBody().firstChild, 2);
editor.selection.setRng(rng);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<p>ab</p><p>cd</p>');
});
test('Enter at the end of DIV layer', function() {
editor.settings.br_in_pre = false;
editor.setContent('<div style="position: absolute; top: 1px; left: 2px;">abcd</div>');
Utils.setSelection('div', 4);
Utils.pressEnter();
equal(editor.getContent(), '<div style="position: absolute; top: 1px; left: 2px;"><p>abcd</p><p>\u00a0</p></div>');
});
test('Enter in div inside contentEditable:false div', function() {
editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div>abcd</div></div>';
Utils.setSelection('div div', 2);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div>abcd</div></div>');
});
test('Enter in div with contentEditable:true inside contentEditable:false div', function() {
editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true">abcd</div></div>';
Utils.setSelection('div div', 2);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><p>ab</p><p>cd</p></div></div>');
});
test('Enter in span with contentEditable:true inside contentEditable:false div', function() {
editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>';
Utils.setSelection('span', 2);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>');
});
test('Shift+Enter in span with contentEditable:true inside contentEditable:false div', function() {
editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>';
Utils.setSelection('span', 2);
Utils.pressEnter({shiftKey: true});
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">ab<br>cd</span></div>');
});
test('Enter in span with contentEditable:true inside contentEditable:false div and forced_root_block: false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>';
Utils.setSelection('span', 2);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">ab<br>cd</span></div>');
});
test('Enter in em within contentEditable:true div inside contentEditable:false div', function() {
editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><em>abcd</em></div></div>';
Utils.setSelection('em', 2);
Utils.pressEnter();
equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><p><em>ab</em></p><p><em>cd</em></p></div></div>');
});
test('Enter at end of text in a span inside a P and keep_styles: false', function() {
editor.settings.keep_styles = false;
editor.getBody().innerHTML = '<p><em><span style="font-size: 13px;">X</span></em></p>';
Utils.setSelection('span', 1);
Utils.pressEnter();
equal(editor.getContent(), '<p><em><span style="font-size: 13px;">X</span></em></p><p>\u00a0</p>');
});
test('Shift+enter in LI when forced_root_block: false', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = '<ul><li>text</li></ul>';
Utils.setSelection('li', 2);
Utils.pressEnter({shiftKey: true});
equal(editor.getContent(), '<ul><li>te<br />xt</li></ul>');
});
test('Enter when forced_root_block: false and force_p_newlines: true', function() {
editor.settings.forced_root_block = false;
editor.settings.force_p_newlines = true;
editor.getBody().innerHTML = 'text';
Utils.setSelection('body', 2);
Utils.pressEnter();
equal(editor.getContent(), '<p>te</p><p>xt</p>');
});
test('Enter at end of br line', function() {
editor.settings.forced_root_block = false;
editor.settings.force_p_newlines = true;
editor.getBody().innerHTML = '<p>a<br>b</p>';
Utils.setSelection('p', 1);
Utils.pressEnter();
equal(editor.getContent(), '<p>a</p><p><br />b</p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeName, 'P');
equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'BR');
});
// Ignore on IE 7, 8 this is a known bug not worth fixing
if (!tinymce.Env.ie || tinymce.Env.ie > 8) {
test('Enter before BR between DIVs', function() {
editor.getBody().innerHTML = '<div>a<span>b</span>c</div><br /><div>d</div>';
var rng = editor.dom.createRng();
rng.setStartBefore(editor.dom.select('br')[0]);
rng.setEndBefore(editor.dom.select('br')[0]);
editor.selection.setRng(rng);
Utils.pressEnter();
equal(editor.getContent(), '<div>a<span>b</span>c</div><p>\u00a0</p><p>\u00a0</p><div>d</div>');
});
}
// Only test these on modern browsers
if (window.getSelection) {
test('Enter behind table element', function() {
var rng = editor.dom.createRng();
editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table>';
rng.setStartAfter(editor.getBody().lastChild);
rng.setEndAfter(editor.getBody().lastChild);
editor.selection.setRng(rng);
Utils.pressEnter();
equal(editor.getContent(), '<table><tbody><tr><td>x</td></tr></tbody></table><p>\u00a0</p>');
});
test('Enter before table element', function() {
var rng = editor.dom.createRng();
editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table>';
rng.setStartBefore(editor.getBody().lastChild);
rng.setEndBefore(editor.getBody().lastChild);
editor.selection.setRng(rng);
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>');
});
test('Enter behind table followed by a p', function() {
var rng = editor.dom.createRng();
editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table><p>x</p>';
rng.setStartAfter(editor.getBody().firstChild);
rng.setEndAfter(editor.getBody().firstChild);
editor.selection.setRng(rng);
Utils.pressEnter();
equal(editor.getContent(), '<table><tbody><tr><td>x</td></tr></tbody></table><p>\u00a0</p><p>x</p>');
});
test('Enter before table element preceded by a p', function() {
var rng = editor.dom.createRng();
editor.getBody().innerHTML = '<p>x</p><table><tbody><td>x</td></tbody></table>';
rng.setStartBefore(editor.getBody().lastChild);
rng.setStartBefore(editor.getBody().lastChild);
editor.selection.setRng(rng);
Utils.pressEnter();
equal(editor.getContent(), '<p>x</p><p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>');
});
test('Enter twice before table element', function(){
var rng = editor.dom.createRng();
editor.getBody().innerHTML = '<table><tbody><tr><td>x</td></tr></tbody></table>';
rng.setStartBefore(editor.getBody().lastChild);
rng.setEndBefore(editor.getBody().lastChild);
editor.selection.setRng(rng);
Utils.pressEnter();
Utils.pressEnter();
equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>');
});
test('Enter after span with space', function() {
editor.setContent('<p><b>abc </b></p>');
Utils.setSelection('b', 3);
Utils.pressEnter();
equal(editor.getContent(), '<p><b>abc</b></p><p>\u00a0</p>');
var rng = editor.selection.getRng(true);
equal(rng.startContainer.nodeName, 'B');
notEqual(rng.startContainer.data, ' ');
});
}
| chiss22/letusquoteyou | www/wordpress-develop/tests/qunit/editor/tinymce/EnterKey.js | JavaScript | apache-2.0 | 39,319 | [
30522,
11336,
1006,
1000,
4714,
12458,
2063,
1012,
4607,
14839,
1000,
1010,
1063,
16437,
5302,
8566,
2571,
1024,
3853,
1006,
1007,
1063,
24209,
3490,
2102,
1012,
2644,
1006,
1007,
1025,
4714,
12458,
2063,
1012,
1999,
4183,
1006,
1063,
27000... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# encoding: utf-8
module Attestor
# Describes the result, returned by safe validation
class Report
# @private
def initialize(object, error = nil)
@object = object
@error = error
freeze
end
# @!attribute [r] object
# The object being validated
#
# @return [Object]
attr_reader :object
# @!attribute [r] error
# The exception raised by validation
#
# @return [Attestor::InvalidError] if validation fails
# @return [nil] if validation passes
attr_reader :error
# Checks whether validation passes
#
# @return [Boolean]
def valid?
error.blank?
end
# Checks whether validation fails
#
# @return [Boolean]
def invalid?
!valid?
end
# Returns the list of error messages
#
# @return [Array<String>]
def messages
error ? error.messages : []
end
end # class Report
end # module Attestor
| nepalez/attestor | lib/attestor/report.rb | Ruby | mit | 944 | [
30522,
1001,
17181,
1024,
21183,
2546,
1011,
1022,
11336,
2012,
22199,
2953,
1001,
5577,
1996,
2765,
1010,
2513,
2011,
3647,
27354,
2465,
3189,
1001,
1030,
2797,
13366,
3988,
4697,
1006,
4874,
1010,
7561,
1027,
9152,
2140,
1007,
1030,
4874,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace LolApi\Classes\TournamentProvider;
/**
* TournamentCodeParameters
*
* @author Javier
*/
class TournamentCodeParameters {
// ~ maptype ~
const MAPTYPE_SUMMONERS_RIFT='SUMMONERS_RIFT';
const MAPTYPE_TWISTED_TREELINE='TWISTED_TREELINE';
const MAPTYPE_HOWLING_ABYSS='HOWLING_ABYSS';
// ~ pickType ~
const PICKTYPE_BLIND_PICK='BLIND_PICK';
const PICKTYPE_DRAFT_MODE='DRAFT_MODE';
const PICKTYPE_ALL_RANDOM='ALL_RANDOM';
const PICKTYPE_TOURNAMENT_DRAFT='TOURNAMENT_DRAFT';
// ~ SPECTATORTYPE ~
const SPECTATORTYPE_NONE='NONE';
const SPECTATORTYPE_LOBBYONLY='LOBBYONLY';
const SPECTATORTYPE_ALL='';
/**
* Optional list of participants in order to validate the players eligible
* to join the lobby. NOTE: We currently do not enforce participants at the
* team level, but rather the aggregate of teamOne and teamTwo. We may add
* the ability to enforce at the team level in the future.
* @var SummonerIdParams
*/
public $allowedSummonerIds;
/**
* The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, and HOWLING_ABYSS.
* @var string
*/
public $mapType;
/**
* Optional string that may contain any data in any format, if specified at all. Used to denote any custom information about the game.
* @var string
*/
public $metadata;
/**
* The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT.
* @var string
*/
public $pickType;
/**
* The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL.
* @var string
*/
public $spectatorType;
/**
* The team size of the game. Valid values are 1-5.
* @var int
*/
public $teamSize;
function __construct($d) {
$this->allowedSummonerIds = new SummonerIdParams($d->allowedSummonerIds);
$this->mapType = $d->mapType;
$this->metadata = $d->metadata;
$this->pickType = $d->pickType;
$this->spectatorType = $d->spectatorType;
$this->teamSize = $d->teamSize;
}
}
| javierglch/HexaniaBlogSymfony | src/LolApi/Classes/TournamentProvider/TournamentCodeParameters.php | PHP | mit | 2,170 | [
30522,
1026,
1029,
25718,
3415,
15327,
15137,
8197,
1032,
4280,
1032,
2977,
21572,
17258,
2121,
1025,
1013,
1008,
1008,
1008,
2977,
16044,
28689,
22828,
2015,
1008,
1008,
1030,
3166,
13824,
1008,
1013,
2465,
2977,
16044,
28689,
22828,
2015,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
namespace completecontrol;
/*
* This file is part of completecontrol
*
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
*/
require 'file.class.php';
class FileTest extends \PHPUnit_Framework_TestCase
{
public function testConstructAndGetAndSet()
{
$file= new File('/etc/passwd');
$this->assertEquals('root', $file->owner());
}
public function testWrite()
{
$file = new File('/tmp/test');
$this->assertEquals(true, $file->append("test\n"));
$this->assertEquals(true, $file->append("test\n"));
$this->assertEquals(true, $file->copy('/tmp/test2'));
$this->assertEquals(true, $file->delete());
$file = new File('/tmp/test2');
$linecount=0;
foreach ($file->lines() as $line) {
$linecount=$linecount+1;
}
$array=$file->toArray();
$this->assertEquals(2, count($array));
$this->assertEquals(2, $linecount);
$this->assertEquals(true, $file->delete());
$this->assertEquals(false, $file->isFile());
}
}
| seanyainkiranina/completecontrol | library/filetest.class.php | PHP | lgpl-2.1 | 1,225 | [
30522,
1026,
1029,
25718,
3415,
15327,
3143,
8663,
13181,
2140,
1025,
1013,
1008,
1008,
2023,
5371,
2003,
2112,
1997,
3143,
8663,
13181,
2140,
1008,
1008,
1008,
2005,
1996,
2440,
9385,
1998,
6105,
2592,
1010,
3531,
3193,
1996,
6105,
1008,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
package org.jcodec.containers.mp4.boxes;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jcodec.common.tools.ToJSON;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* @author The JCodec project
*
*/
public class EditListBox extends FullBox {
private List<Edit> edits;
public static String fourcc() {
return "elst";
}
public EditListBox(Header atom) {
super(atom);
}
public EditListBox() {
this(new Header(fourcc()));
}
public EditListBox(List<Edit> edits) {
this();
this.edits = edits;
}
public void parse(ByteBuffer input) {
super.parse(input);
edits = new ArrayList<Edit>();
long num = input.getInt();
for (int i = 0; i < num; i++) {
int duration = input.getInt();
int mediaTime = input.getInt();
float rate = input.getInt() / 65536f;
edits.add(new Edit(duration, mediaTime, rate));
}
}
protected void doWrite(ByteBuffer out) {
super.doWrite(out);
out.putInt(edits.size());
for (Edit edit : edits) {
out.putInt((int) edit.getDuration());
out.putInt((int) edit.getMediaTime());
out.putInt((int) (edit.getRate() * 65536));
}
}
public List<Edit> getEdits() {
return edits;
}
public void dump(StringBuilder sb) {
super.dump(sb);
sb.append(": ");
ToJSON.toJSON(this, sb, "edits");
}
}
| OpenSpaceDev/OpenSpaceDVR | src/org/jcodec/containers/mp4/boxes/EditListBox.java | Java | mpl-2.0 | 1,602 | [
30522,
7427,
8917,
1012,
29175,
10244,
2278,
1012,
16143,
1012,
6131,
2549,
1012,
8378,
1025,
12324,
9262,
1012,
9152,
2080,
1012,
24880,
8569,
12494,
1025,
12324,
9262,
1012,
21183,
4014,
1012,
9140,
9863,
1025,
12324,
9262,
1012,
21183,
4... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
import * as clipboardy from 'clipboardy'
const rows = clipboardy.readSync();
const transformed = rows.split('\n')
.map(row => {
const cells = row.split('\t').map(cell => (cell || '').replace(/\n/g, ' ').trim());
return ` /** ${cells[1]} */\n ${cells[0].replace(/^.*\./g, '')}`;
})
.join('\n');
clipboardy.writeSync(transformed);
console.log(transformed); | JasonKleban/Framework7.d.ts | clip-docs-2.ts | TypeScript | mit | 408 | [
30522,
12324,
1008,
2004,
12528,
6277,
2100,
2013,
1005,
12528,
6277,
2100,
1005,
9530,
3367,
10281,
1027,
12528,
6277,
2100,
1012,
9631,
6038,
2278,
1006,
1007,
1025,
9530,
3367,
8590,
1027,
10281,
1012,
3975,
1006,
1005,
1032,
1050,
1005,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
(function () {
'use strict';
angular
.module('app.home')
.config(appRun);
/* @ngInject */
function appRun($stateProvider) {
$stateProvider
.state('root.home', {
url: '/',
templateUrl: 'app/home/home.html',
controller: 'Home',
controllerAs: 'vm',
});
}
})();
| hawkup/github-stars | angularjs/app/home/config.route.js | JavaScript | mit | 326 | [
30522,
1006,
3853,
1006,
1007,
1063,
1005,
2224,
9384,
1005,
1025,
16108,
1012,
11336,
1006,
1005,
10439,
1012,
2188,
1005,
1007,
1012,
9530,
8873,
2290,
1006,
10439,
15532,
1007,
1025,
1013,
1008,
1030,
12835,
2378,
20614,
1008,
1013,
3853... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// bin/sum-mllt.cc
// Copyright 2014 LINSE/UFSC; Augusto Henrique Hentz
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "util/common-utils.h"
#include "transform/mllt.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
typedef kaldi::int32 int32;
const char *usage =
"Sum stats obtained with gmm-acc-mllt.\n"
"Usage: sum-mllt-accs [options] <stats-out> <stats-in1> <stats-in2> "
"...\n";
bool binary = true;
ParseOptions po(usage);
po.Register("binary", &binary, "Write accumulators in binary mode.");
po.Read(argc, argv);
if (po.NumArgs() < 2) {
po.PrintUsage();
exit(1);
}
MlltAccs mllt_accs;
std::string stats_out_filename = po.GetArg(1);
for (int32 i = 2; i <= po.NumArgs(); i++) {
bool binary_in, add = true;
Input ki(po.GetArg(i), &binary_in);
mllt_accs.Read(ki.Stream(), binary_in, add);
}
Output ko(stats_out_filename, binary);
mllt_accs.Write(ko.Stream(), binary);
return 0;
} catch (const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| ypkang/djinn | tonic-suite/asr/src/bin/sum-mllt-accs.cc | C++ | bsd-3-clause | 1,758 | [
30522,
1013,
1013,
8026,
1013,
7680,
1011,
19875,
7096,
1012,
10507,
1013,
1013,
9385,
2297,
11409,
3366,
1013,
1057,
10343,
2278,
1025,
29085,
8863,
4226,
21863,
5753,
1013,
1013,
2156,
1012,
1012,
1013,
1012,
1012,
1013,
24731,
2005,
1885... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
# Matelea congesta (Decne.) Woodson SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Apocynaceae/Matelea/Matelea congesta/README.md | Markdown | apache-2.0 | 183 | [
30522,
1001,
6775,
19738,
26478,
4355,
2050,
1006,
11703,
2638,
1012,
1007,
5249,
2239,
2427,
1001,
1001,
1001,
1001,
3570,
3970,
1001,
1001,
1001,
1001,
2429,
2000,
2248,
3269,
3415,
5950,
1001,
1001,
1001,
1001,
2405,
1999,
19701,
1001,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Tfile Schema
*/
var TfileSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please add a TestFile name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
content: {
type:String,
default: ''
},
tags: {
type:[String],
default: {}
}
});
mongoose.model('Tfile', TfileSchema); | kaseyalusi/tests | app/models/tfile.server.model.js | JavaScript | mit | 557 | [
30522,
1005,
2224,
30524,
1007,
1010,
8040,
28433,
1027,
12256,
3995,
9232,
1012,
8040,
28433,
1025,
1013,
1008,
1008,
1008,
1056,
8873,
2571,
8040,
28433,
1008,
1013,
13075,
1056,
8873,
4244,
5403,
2863,
1027,
2047,
8040,
28433,
1006,
1063... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePointSalesServiceInvoiceServiceTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('point_sales_service_invoice_service', function ($table) {
$table->increments('id');
$table->integer('point_sales_service_invoice_id')->unsigned()->index('ps_service_invoice_id_index');
$table->foreign('point_sales_service_invoice_id', 'ps_service_invoice_id_foreign')
->references('id')->on('point_sales_service_invoice')
->onUpdate('cascade')
->onDelete('cascade');
$table->integer('service_id')->unsigned();
$table->decimal('quantity', 16, 4);
$table->decimal('price', 16, 4);
$table->decimal('discount', 16, 4);
$table->string('service_notes')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('point_sales_service_invoice_service');
}
}
| bgd-point/point-app-test | packages/point/point-sales/src/database/migrations/2017_02_06_230000_create_point_sales_service_invoice_service_table.php | PHP | apache-2.0 | 1,203 | [
30522,
1026,
1029,
25718,
2224,
5665,
12717,
12556,
1032,
7809,
1032,
8040,
28433,
1032,
2630,
16550,
1025,
2224,
5665,
12717,
12556,
1032,
7809,
1032,
9230,
2015,
1032,
9230,
1025,
2465,
3443,
26521,
23266,
8043,
7903,
12377,
6767,
23522,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#pragma once
#include "kernel/kernel_hlemodule.h"
namespace mic
{
class Module : public kernel::HleModuleImpl<Module>
{
public:
virtual void initialise() override;
public:
static void RegisterFunctions();
private:
static void registerCoreFunctions();
};
} // namespace mic
| petmac/decaf-emu | src/libdecaf/src/modules/mic/mic.h | C | gpl-3.0 | 287 | [
30522,
1001,
10975,
8490,
2863,
2320,
1001,
2421,
1000,
16293,
1013,
16293,
1035,
1044,
16930,
7716,
9307,
1012,
1044,
1000,
3415,
15327,
23025,
1063,
2465,
11336,
1024,
2270,
16293,
1024,
1024,
1044,
16930,
7716,
9307,
5714,
24759,
1026,
1... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
#ifndef ethernetclient_h
#define ethernetclient_h
#include "Arduino.h"
#include "Print.h"
#include "Client.h"
#include "IPAddress.h"
class EthernetClient : public Client {
public:
EthernetClient();
EthernetClient(uint8_t sock);
uint8_t status();
virtual int connect(IPAddress ip, uint16_t port);
virtual int connect(const char *host, uint16_t port);
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buf, size_t size);
virtual int available();
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek();
virtual void flush();
virtual void stop();
virtual uint8_t connected();
virtual operator bool();
friend class EthernetServer;
using Print::write;
private:
static uint16_t _srcport;
uint8_t _sock;
};
#endif
| chcbaram/FPGA | zap-2.3.0-windows/papilio-zap-ide/hardware/arduino/sam/libraries/Ethernet/EthernetClient.h | C | mit | 800 | [
30522,
1001,
2065,
13629,
2546,
26110,
20464,
11638,
1035,
1044,
1001,
9375,
26110,
20464,
11638,
1035,
1044,
1001,
2421,
1000,
12098,
8566,
5740,
1012,
1044,
1000,
1001,
2421,
1000,
6140,
1012,
1044,
1000,
1001,
2421,
1000,
7396,
1012,
104... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
/*
* Copyright (c) 2015 - 2016 Memorial Sloan-Kettering Cancer Center.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mskcc.cbio.portal.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.cbioportal.persistence.GenePanelRepository;
import org.cbioportal.model.GenePanel;
import org.mskcc.cbio.portal.model.GeneticAlterationType;
import org.mskcc.cbio.portal.model.GeneticProfile;
/**
* Genetic Profile Util Class.
*
*/
public class GeneticProfileUtil {
/**
* Gets the GeneticProfile with the Specified GeneticProfile ID.
* @param profileId GeneticProfile ID.
* @param profileList List of Genetic Profiles.
* @return GeneticProfile or null.
*/
public static GeneticProfile getProfile(String profileId,
ArrayList<GeneticProfile> profileList) {
for (GeneticProfile profile : profileList) {
if (profile.getStableId().equals(profileId)) {
return profile;
}
}
return null;
}
/**
* Returns true if Any of the Profiles Selected by the User Refer to mRNA Expression
* outlier profiles.
*
* @param geneticProfileIdSet Set of Chosen Profiles IDs.
* @param profileList List of Genetic Profiles.
* @return true or false.
*/
public static boolean outlierExpressionSelected(HashSet<String> geneticProfileIdSet,
ArrayList<GeneticProfile> profileList) {
Iterator<String> geneticProfileIdIterator = geneticProfileIdSet.iterator();
while (geneticProfileIdIterator.hasNext()) {
String geneticProfileId = geneticProfileIdIterator.next();
GeneticProfile geneticProfile = getProfile (geneticProfileId, profileList);
if (geneticProfile != null && geneticProfile.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION) {
String profileName = geneticProfile.getProfileName();
if (profileName != null) {
if (profileName.toLowerCase().contains("outlier")) {
return true;
}
}
}
}
return false;
}
public static int getGenePanelId(String panelId) {
GenePanelRepository genePanelRepository = SpringUtil.getGenePanelRepository();
GenePanel genePanel = genePanelRepository.getGenePanelByStableId(panelId).get(0);
return genePanel.getInternalId();
}
}
| bihealth/cbioportal | core/src/main/java/org/mskcc/cbio/portal/util/GeneticProfileUtil.java | Java | agpl-3.0 | 3,897 | [
30522,
1013,
1008,
1008,
9385,
1006,
1039,
1007,
2325,
1011,
2355,
3986,
19024,
1011,
17710,
19567,
4456,
2415,
1012,
1008,
1008,
2023,
3075,
2003,
5500,
1999,
1996,
3246,
2008,
2009,
2097,
2022,
6179,
1010,
2021,
2302,
1008,
2151,
10943,
... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
local awful = require("awful")
awful.rules = require("awful.rules")
local beautiful = require("beautiful")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
local naughty = require("naughty")
local serialize = require('utils/serialize')
clientbuttons = awful.util.table.join(
awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
awful.button({ modkey }, 1, function(c)
awful.mouse.client.move(c)
c:raise()
end),
awful.button({ modkey }, 3, awful.mouse.client.resize)
)
awful.rules.rules = {
-- All clients will match this rule.
{
rule = { },
properties = {
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
screen = function(c)
local current_screen = awesome.startup and c.screen or awful.screen.focused()
local client_geometry = c:geometry()
-- 防止client在当前屏幕之外
if client_geometry.x > current_screen.geometry.x + current_screen.geometry.width
or client_geometry.x + client_geometry.width < current_screen.geometry.x
then
client_geometry.x = (current_screen.geometry.x + current_screen.geometry.width) / 2 - client_geometry.width / 2
end
if client_geometry.y > current_screen.geometry.y + current_screen.geometry.height
or client_geometry.y + client_geometry.height < current_screen.geometry.y
then
client_geometry.y = current_screen.geometry.y
end
c:geometry(client_geometry)
return current_screen
end,
keys = clientkeys,
buttons = clientbuttons
} ,
},
{
rule = { class = "smplayer" },
properties = {
callback = function(c)
c:connect_signal(
'property::size',
function(tc)
if tc.fullscreen then
tc.no_border = true
tc.border_width = 0
else
tc.no_border = false
tc.border_width = beautiful.border_width
tc.border_color = beautiful.border_normal
end
end
)
end,
}
},
{
rule = { class = "org.remmina.Remmina" },
properties = {
callback = function(c)
c:connect_signal(
'property::size',
function(tc)
if tc.fullscreen then
tc.no_border = true
tc.border_width = 0
else
tc.no_border = false
tc.border_width = beautiful.border_width
tc.border_color = beautiful.border_normal
end
end
)
end,
}
},
{
rule = { class = "Synergy" },
properties = {
size_hints_honor = false,
maximized_vertical = true,
}
},
{
rule = { class = "sourceinsight4.exe" },
properties = {
screen = screen.primary,
}
},
{
rule = { class = "Xfdesktop" },
properties = {
no_border = true,
border_width = 0,
x = screen.primary.geometry.x,
y = screen.primary.geometry.y,
}
},
{
rule = { class = "Plank" },
except = { name = "Plank Clock Calendar" },
properties = {
no_border = true,
border_width = 0,
minimized = false,
dockable = false,
ontop = false, -- set default value
above = false, -- set default value
below = true, -- set default value
callback = function(c)
c:connect_signal('focus', function(tc)
tc.ontop = true
tc.below = false
tc.above = true
end)
c:connect_signal('unfocus', function(tc)
tc.ontop = false
tc.below = true
tc.above = false
end)
c:connect_signal('property::minimized', function(tc)
-- this client can not minized
tc.minimized = false
end)
end,
}
},
{
rule = { class = "Pcmanfm" },
except = {class = ""},
properties = {
border_width = 0,
maximized = true,
sticky = true,
focusable = false,
floating = false,
type = "desktop",
screen = screen.primary,
}
},
{
rule = { class = "Popup" },
properties = { border_width = 0, no_border = true },
},
{
rule = { class = "deepin-voice-recorder" },
properties = { border_width = 0, no_border = true },
},
}
| Hacksign/configs | .config/awesome/configs/rules.lua | Lua | gpl-2.0 | 5,300 | [
30522,
2334,
9643,
1027,
5478,
1006,
1000,
9643,
1000,
1007,
9643,
1012,
3513,
1027,
5478,
1006,
1000,
9643,
1012,
3513,
1000,
1007,
2334,
3376,
1027,
5478,
1006,
1000,
3376,
1000,
1007,
2334,
1060,
6072,
8162,
9623,
1027,
5478,
1006,
100... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
// Copyright (c) 2012-2018 The DigiByte Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DIGIBYTE_BLOOM_H
#define DIGIBYTE_BLOOM_H
#include <serialize.h>
#include <vector>
class COutPoint;
class CTransaction;
class uint256;
//! 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
static const unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes
static const unsigned int MAX_HASH_FUNCS = 50;
/**
* First two bits of nFlags control how much IsRelevantAndUpdate actually updates
* The remaining bits are reserved
*/
enum bloomflags
{
BLOOM_UPDATE_NONE = 0,
BLOOM_UPDATE_ALL = 1,
// Only adds outpoints to the filter if the output is a pay-to-pubkey/pay-to-multisig script
BLOOM_UPDATE_P2PUBKEY_ONLY = 2,
BLOOM_UPDATE_MASK = 3,
};
/**
* BloomFilter is a probabilistic filter which SPV clients provide
* so that we can filter the transactions we send them.
*
* This allows for significantly more efficient transaction and block downloads.
*
* Because bloom filters are probabilistic, a SPV node can increase the false-
* positive rate, making us send it transactions which aren't actually its,
* allowing clients to trade more bandwidth for more privacy by obfuscating which
* keys are controlled by them.
*/
class CBloomFilter
{
private:
std::vector<unsigned char> vData;
bool isFull;
bool isEmpty;
unsigned int nHashFuncs;
unsigned int nTweak;
unsigned char nFlags;
unsigned int Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const;
// Private constructor for CRollingBloomFilter, no restrictions on size
CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweak);
friend class CRollingBloomFilter;
public:
/**
* Creates a new bloom filter which will provide the given fp rate when filled with the given number of elements
* Note that if the given parameters will result in a filter outside the bounds of the protocol limits,
* the filter created will be as close to the given parameters as possible within the protocol limits.
* This will apply if nFPRate is very low or nElements is unreasonably high.
* nTweak is a constant which is added to the seed value passed to the hash function
* It should generally always be a random value (and is largely only exposed for unit testing)
* nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK)
*/
CBloomFilter(const unsigned int nElements, const double nFPRate, const unsigned int nTweak, unsigned char nFlagsIn);
CBloomFilter() : isFull(true), isEmpty(false), nHashFuncs(0), nTweak(0), nFlags(0) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(vData);
READWRITE(nHashFuncs);
READWRITE(nTweak);
READWRITE(nFlags);
}
void insert(const std::vector<unsigned char>& vKey);
void insert(const COutPoint& outpoint);
void insert(const uint256& hash);
bool contains(const std::vector<unsigned char>& vKey) const;
bool contains(const COutPoint& outpoint) const;
bool contains(const uint256& hash) const;
void clear();
void reset(const unsigned int nNewTweak);
//! True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS
//! (catch a filter which was just deserialized which was too big)
bool IsWithinSizeConstraints() const;
//! Also adds any outputs which match the filter to the filter (to match their spending txes)
bool IsRelevantAndUpdate(const CTransaction& tx);
//! Checks for empty and full filters to avoid wasting cpu
void UpdateEmptyFull();
};
/**
* RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
* Construct it with the number of items to keep track of, and a false-positive
* rate. Unlike CBloomFilter, by default nTweak is set to a cryptographically
* secure random value for you. Similarly rather than clear() the method
* reset() is provided, which also changes nTweak to decrease the impact of
* false-positives.
*
* contains(item) will always return true if item was one of the last N to 1.5*N
* insert()'ed ... but may also return true for items that were not inserted.
*
* It needs around 1.8 bytes per element per factor 0.1 of false positive rate.
* (More accurately: 3/(log(256)*log(2)) * log(1/fpRate) * nElements bytes)
*/
class CRollingBloomFilter
{
public:
// A random bloom filter calls GetRand() at creation time.
// Don't create global CRollingBloomFilter objects, as they may be
// constructed before the randomizer is properly initialized.
CRollingBloomFilter(const unsigned int nElements, const double nFPRate);
void insert(const std::vector<unsigned char>& vKey);
void insert(const uint256& hash);
bool contains(const std::vector<unsigned char>& vKey) const;
bool contains(const uint256& hash) const;
void reset();
private:
int nEntriesPerGeneration;
int nEntriesThisGeneration;
int nGeneration;
std::vector<uint64_t> data;
unsigned int nTweak;
int nHashFuncs;
};
#endif // DIGIBYTE_BLOOM_H
| digibyte/digibyte | src/bloom.h | C | mit | 5,355 | [
30522,
1013,
1013,
9385,
1006,
1039,
1007,
2262,
1011,
2760,
1996,
10667,
12322,
17250,
4563,
9797,
1013,
1013,
5500,
2104,
1996,
10210,
4007,
6105,
1010,
2156,
1996,
10860,
1013,
1013,
5371,
24731,
2030,
8299,
1024,
1013,
1013,
7479,
1012,... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1... | [
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.