max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
970 | {"id":14,"description":"Build packages","ref":"master","cron":"0 1 * * 5","cron_timezone":"UTC","next_run_at":"2017-05-26T01:00:00.000Z","active":true,"created_at":"2017-05-19T13:43:08.169Z","updated_at":"2017-05-19T13:43:08.169Z","last_pipeline":null,"owner":{"name":"Administrator","username":"root","id":1,"state":"active","avatar_url":"http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon","web_url":"https://gitlab.example.com/root"}} | 185 |
369 | /*
* Copyright © 2015 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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 io.cdap.cdap.format;
import com.google.common.collect.ImmutableMap;
import io.cdap.cdap.api.common.Bytes;
import io.cdap.cdap.api.data.format.FormatSpecification;
import io.cdap.cdap.api.data.format.Formats;
import io.cdap.cdap.api.data.format.RecordFormat;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.api.data.format.UnexpectedFormatException;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.api.data.schema.UnsupportedTypeException;
import org.junit.Assert;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
/**
*
*/
public class DelimitedStringsRecordFormatTest {
@Test
public void testSimpleSchemaValidation() throws UnsupportedTypeException {
Schema simpleSchema = Schema.recordOf("event",
Schema.Field.of("f1", Schema.of(Schema.Type.BOOLEAN)),
Schema.Field.of("f2", Schema.of(Schema.Type.INT)),
Schema.Field.of("f3", Schema.of(Schema.Type.FLOAT)),
Schema.Field.of("f4", Schema.of(Schema.Type.DOUBLE)),
Schema.Field.of("f5", Schema.of(Schema.Type.BYTES)),
Schema.Field.of("f6", Schema.of(Schema.Type.STRING))
);
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
simpleSchema, Collections.<String, String>emptyMap());
format.initialize(formatSpec);
}
@Test
public void testArrayOfNullableStringsSchema() throws UnsupportedTypeException {
Schema schema = Schema.recordOf(
"event",
Schema.Field.of("arr", Schema.arrayOf(Schema.nullableOf(Schema.of(Schema.Type.STRING)))));
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, Collections.<String, String>emptyMap());
format.initialize(formatSpec);
}
@Test
public void testNullableFieldsAllowedInSchema() throws UnsupportedTypeException {
Schema schema = Schema.recordOf(
"event",
Schema.Field.of("f1", Schema.unionOf(Schema.of(Schema.Type.BOOLEAN), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f2", Schema.unionOf(Schema.of(Schema.Type.INT), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f3", Schema.unionOf(Schema.of(Schema.Type.FLOAT), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f4", Schema.unionOf(Schema.of(Schema.Type.DOUBLE), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f5", Schema.unionOf(Schema.of(Schema.Type.BYTES), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f6", Schema.unionOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.NULL)))
);
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, Collections.<String, String>emptyMap());
format.initialize(formatSpec);
}
@Test
public void testSimpleArraySchemaValidation() throws UnsupportedTypeException {
Schema schema = Schema.recordOf("event",
Schema.Field.of("f1", Schema.of(Schema.Type.BOOLEAN)),
Schema.Field.of("f2", Schema.of(Schema.Type.INT)),
Schema.Field.of("f3", Schema.of(Schema.Type.FLOAT)),
Schema.Field.of("f4", Schema.of(Schema.Type.DOUBLE)),
Schema.Field.of("f5", Schema.of(Schema.Type.BYTES)),
Schema.Field.of("f6", Schema.of(Schema.Type.STRING)),
Schema.Field.of("f7", Schema.arrayOf(Schema.of(Schema.Type.STRING)))
);
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, Collections.<String, String>emptyMap());
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = UnsupportedTypeException.class)
public void testComplexArraySchemaValidation() throws UnsupportedTypeException {
Schema mapSchema = Schema.mapOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.STRING));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", Schema.arrayOf(mapSchema)));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, Collections.<String, String>emptyMap());
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = UnsupportedTypeException.class)
public void testMapFieldInvalid() throws UnsupportedTypeException {
Schema mapSchema = Schema.mapOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.STRING));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", mapSchema));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, Collections.<String, String>emptyMap());
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = UnsupportedTypeException.class)
public void testRecordFieldInvalid() throws UnsupportedTypeException {
Schema recordSchema = Schema.recordOf("record", Schema.Field.of("recordField", Schema.of(Schema.Type.STRING)));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", recordSchema));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, Collections.<String, String>emptyMap());
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = IllegalArgumentException.class)
public void testRecordMappingWithNonSimpleSchema() throws UnsupportedTypeException {
Schema arraySchema = Schema.arrayOf(Schema.of(Schema.Type.STRING));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", arraySchema));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, ImmutableMap.of(DelimitedStringsRecordFormat.MAPPING, "0:f1"));
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = IllegalArgumentException.class)
public void testRecordMappingTooFewMappings() throws UnsupportedTypeException {
Schema arraySchema = Schema.arrayOf(Schema.of(Schema.Type.STRING));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", arraySchema));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, ImmutableMap.of(DelimitedStringsRecordFormat.MAPPING, ""));
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = IllegalArgumentException.class)
public void testRecordMappingTooManyMappings() throws UnsupportedTypeException {
Schema arraySchema = Schema.arrayOf(Schema.of(Schema.Type.STRING));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", arraySchema));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, ImmutableMap.of(DelimitedStringsRecordFormat.MAPPING, "0:f1,1:f2"));
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test(expected = IllegalArgumentException.class)
public void testRecordMappingWrongMapping() throws UnsupportedTypeException {
Schema arraySchema = Schema.arrayOf(Schema.of(Schema.Type.STRING));
Schema schema = Schema.recordOf("event", Schema.Field.of("f1", arraySchema));
FormatSpecification formatSpec =
new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema, ImmutableMap.of(DelimitedStringsRecordFormat.MAPPING, "0:f2"));
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(formatSpec);
}
@Test
public void testStringArrayFormat() throws UnsupportedTypeException, UnexpectedFormatException {
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
format.initialize(null);
String body = "userX,actionY,itemZ";
StructuredRecord output = format.read(ByteBuffer.wrap(Bytes.toBytes(body)));
String[] actual = output.get("body");
String[] expected = body.split(",");
Assert.assertTrue(Arrays.equals(expected, actual));
}
@Test
public void testDelimiter() throws UnsupportedTypeException, UnexpectedFormatException {
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
FormatSpecification spec = new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
null,
ImmutableMap.of(DelimitedStringsRecordFormat.DELIMITER, " "));
format.initialize(spec);
String body = "userX actionY itemZ";
StructuredRecord output = format.read(ByteBuffer.wrap(Bytes.toBytes(body)));
String[] actual = output.get("body");
String[] expected = body.split(" ");
Assert.assertArrayEquals(expected, actual);
}
@Test
public void testCSV() throws Exception {
FormatSpecification spec = new FormatSpecification(Formats.CSV, null, Collections.<String, String>emptyMap());
RecordFormat<ByteBuffer, StructuredRecord> format = RecordFormats.createInitializedFormat(spec);
String body = "userX,actionY,itemZ";
StructuredRecord output = format.read(ByteBuffer.wrap(Bytes.toBytes(body)));
String[] actual = output.get("body");
String[] expected = body.split(",");
Assert.assertArrayEquals(expected, actual);
}
@Test
public void testTSV() throws Exception {
FormatSpecification spec = new FormatSpecification(Formats.TSV, null, Collections.<String, String>emptyMap());
RecordFormat<ByteBuffer, StructuredRecord> format = RecordFormats.createInitializedFormat(spec);
String body = "userX\tactionY\titemZ";
StructuredRecord output = format.read(ByteBuffer.wrap(Bytes.toBytes(body)));
String[] actual = output.get("body");
String[] expected = body.split("\t");
Assert.assertArrayEquals(expected, actual);
}
@Test
public void testFormatRecordWithMapping() throws UnsupportedTypeException {
Schema schema = Schema.recordOf(
"event",
Schema.Field.of("f3", Schema.unionOf(Schema.of(Schema.Type.FLOAT), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f4", Schema.unionOf(Schema.of(Schema.Type.DOUBLE), Schema.of(Schema.Type.NULL))));
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
FormatSpecification spec = new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema,
ImmutableMap.of(
DelimitedStringsRecordFormat.DELIMITER, ",",
DelimitedStringsRecordFormat.MAPPING, "2:f3,3:f4"));
format.initialize(spec);
boolean booleanVal = false;
int intVal = Integer.MAX_VALUE;
float floatVal = Float.MAX_VALUE;
double doubleVal = Double.MAX_VALUE;
byte[] bytesVal = new byte[] { 0, 1, 2 };
String stringVal = "foo bar";
String[] arrayVal = new String[] { "extra1", "extra2", "extra3" };
String body = new StringBuilder()
.append(booleanVal).append(",")
.append(intVal).append(",")
.append(floatVal).append(",")
.append(doubleVal).append(",")
.append(Bytes.toStringBinary(bytesVal)).append(",")
.append(stringVal).append(",")
.append(arrayVal[0]).append(",")
.append(arrayVal[1]).append(",")
.append(arrayVal[2])
.toString();
StructuredRecord output = format.read(ByteBuffer.wrap(Bytes.toBytes(body)));
Assert.assertEquals(2, output.getSchema().getFields().size());
Assert.assertNull(output.get("f1"));
Assert.assertNull(output.get("f2"));
Assert.assertEquals(floatVal, output.get("f3"), 0.0001f);
Assert.assertEquals(doubleVal, output.get("f4"), 0.0001d);
Assert.assertNull(output.get("f5"));
Assert.assertNull(output.get("f6"));
Assert.assertNull(output.get("f7"));
// now try with null fields.
output = format.read(ByteBuffer.wrap(Bytes.toBytes("true,,3.14159,,,hello world,extra1")));
Assert.assertEquals(2, output.getSchema().getFields().size());
Assert.assertNull(output.get("f1"));
Assert.assertNull(output.get("f2"));
Assert.assertEquals(3.14159f, output.get("f3"), 0.0001f);
Assert.assertNull(output.get("f4"));
Assert.assertNull(output.get("f5"));
Assert.assertNull(output.get("f6"));
Assert.assertNull(output.get("f7"));
}
@Test
public void testFormatRecordWithSchema() throws UnsupportedTypeException, UnexpectedFormatException {
Schema schema = Schema.recordOf(
"event",
Schema.Field.of("f1", Schema.unionOf(Schema.of(Schema.Type.BOOLEAN), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f2", Schema.unionOf(Schema.of(Schema.Type.INT), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f3", Schema.unionOf(Schema.of(Schema.Type.FLOAT), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f4", Schema.unionOf(Schema.of(Schema.Type.DOUBLE), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f5", Schema.unionOf(Schema.of(Schema.Type.BYTES), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f6", Schema.unionOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.NULL))),
Schema.Field.of("f7", Schema.arrayOf(Schema.of(Schema.Type.STRING)))
);
DelimitedStringsRecordFormat format = new DelimitedStringsRecordFormat();
FormatSpecification spec = new FormatSpecification(DelimitedStringsRecordFormat.class.getCanonicalName(),
schema,
ImmutableMap.of(DelimitedStringsRecordFormat.DELIMITER, ","));
format.initialize(spec);
boolean booleanVal = false;
int intVal = Integer.MAX_VALUE;
float floatVal = Float.MAX_VALUE;
double doubleVal = Double.MAX_VALUE;
byte[] bytesVal = new byte[] { 0, 1, 2 };
String stringVal = "foo bar";
String[] arrayVal = new String[] { "extra1", "extra2", "extra3" };
String body = new StringBuilder()
.append(booleanVal).append(",")
.append(intVal).append(",")
.append(floatVal).append(",")
.append(doubleVal).append(",")
.append(Bytes.toStringBinary(bytesVal)).append(",")
.append(stringVal).append(",")
.append(arrayVal[0]).append(",")
.append(arrayVal[1]).append(",")
.append(arrayVal[2])
.toString();
StructuredRecord output = format.read(ByteBuffer.wrap(Bytes.toBytes(body)));
Assert.assertEquals(booleanVal, output.get("f1"));
Assert.assertEquals(intVal, (int) output.get("f2"));
Assert.assertEquals(floatVal, output.get("f3"), 0.0001f);
Assert.assertEquals(doubleVal, output.get("f4"), 0.0001d);
Assert.assertArrayEquals(bytesVal, (byte[]) output.get("f5"));
Assert.assertEquals(stringVal, output.get("f6"));
Assert.assertArrayEquals(arrayVal, (String[]) output.get("f7"));
// now try with null fields.
output = format.read(ByteBuffer.wrap(Bytes.toBytes("true,,3.14159,,,hello world,extra1")));
Assert.assertTrue((Boolean) output.get("f1"));
Assert.assertNull(output.get("f2"));
Assert.assertEquals(3.14159f, output.get("f3"), 0.0001f);
Assert.assertNull(output.get("f4"));
Assert.assertNull(output.get("f5"));
Assert.assertEquals("hello world", output.get("f6"));
Assert.assertArrayEquals(new String[] {"extra1"}, (String[]) output.get("f7"));
}
}
| 6,984 |
305 | {
"name": "ember-engines-workspace",
"version": "0.8.22",
"private": true,
"description": "Workspace for ember-engines project",
"repository": {
"type": "git",
"url": "git+https://github.com/ember-engines/ember-engines.git"
},
"license": "MIT",
"workspaces": [
"packages/*"
],
"scripts": {
"build": "yarn workspace ember-engines build",
"lint": "yarn workspace ember-engines lint",
"lint:hbs": "yarn workspace ember-engines lint:hbs",
"lint:js": "yarn workspace ember-engines lint:js",
"start": "yarn workspace ember-engines start",
"test": "yarn workspace ember-engines test",
"test:ember": "yarn workspace ember-engines test:ember",
"test:node": "yarn workspace ember-engines test:node",
"try": "yarn workspace ember-engines try"
},
"prettier": {
"singleQuote": true
},
"devDependencies": {
"release-it": "^14.2.1",
"release-it-lerna-changelog": "^3.1.0",
"release-it-yarn-workspaces": "^2.0.0"
},
"engines": {
"node": "10.* || >= 12"
},
"publishConfig": {
"registry": "https://registry.npmjs.org"
},
"authors": [
"<NAME>",
"<NAME>"
],
"release-it": {
"plugins": {
"release-it-lerna-changelog": {
"infile": "CHANGELOG.md",
"launchEditor": true
},
"release-it-yarn-workspaces": true
},
"git": {
"tagName": "v${version}"
},
"github": {
"release": true,
"tokenRef": "GITHUB_AUTH"
},
"npm": false
}
}
| 680 |
10,225 | package io.quarkus.reactivemessaging.utils;
import org.jboss.logging.Logger;
import io.quarkus.reactivemessaging.http.runtime.serializers.Serializer;
import io.vertx.core.buffer.Buffer;
public class ToUpperCaseSerializer implements Serializer<String> {
private static final Logger log = Logger.getLogger(ToUpperCaseSerializer.class);
@Override
public boolean handles(Object payload) {
log.infof("checking if %s of type %s is handled", payload, payload.getClass());
return payload instanceof String;
}
@Override
public Buffer serialize(String payload) {
log.infof("serializing %s", payload);
return Buffer.buffer(payload.toUpperCase());
}
}
| 245 |
1,540 | package org.testng.internal.junit;
import org.testng.AssertJUnit;
public class ExactComparisonCriteria extends ComparisonCriteria {
@Override
protected void assertElementsEqual(Object expected, Object actual) {
AssertJUnit.assertEquals(expected, actual);
}
}
| 83 |
145,614 | """For more information about the Binomial Distribution -
https://en.wikipedia.org/wiki/Binomial_distribution"""
from math import factorial
def binomial_distribution(successes: int, trials: int, prob: float) -> float:
"""
Return probability of k successes out of n tries, with p probability for one
success
The function uses the factorial function in order to calculate the binomial
coefficient
>>> binomial_distribution(3, 5, 0.7)
0.30870000000000003
>>> binomial_distribution (2, 4, 0.5)
0.375
"""
if successes > trials:
raise ValueError("""successes must be lower or equal to trials""")
if trials < 0 or successes < 0:
raise ValueError("the function is defined for non-negative integers")
if not isinstance(successes, int) or not isinstance(trials, int):
raise ValueError("the function is defined for non-negative integers")
if not 0 < prob < 1:
raise ValueError("prob has to be in range of 1 - 0")
probability = (prob ** successes) * ((1 - prob) ** (trials - successes))
# Calculate the binomial coefficient: n! / k!(n-k)!
coefficient = float(factorial(trials))
coefficient /= factorial(successes) * factorial(trials - successes)
return probability * coefficient
if __name__ == "__main__":
from doctest import testmod
testmod()
print("Probability of 2 successes out of 4 trails")
print("with probability of 0.75 is:", end=" ")
print(binomial_distribution(2, 4, 0.75))
| 547 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Prototype",
"definitions": [
"A first or preliminary version of a device or vehicle from which other forms are developed.",
"The first, original, or typical form of something; an archetype.",
"A basic filter network with specified cut-off frequencies, from which other networks may be derived to obtain sharper cut-offs, constancy of characteristic impedance with frequency, etc."
],
"parts-of-speech": "Noun"
} | 153 |
66,635 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
NO_DEFAULT,
remove_start
)
class OdaTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?odatv\.com/(?:mob|vid)_video\.php\?.*\bid=(?P<id>[^&]+)'
_TESTS = [{
'url': 'http://odatv.com/vid_video.php?id=8E388',
'md5': 'dc61d052f205c9bf2da3545691485154',
'info_dict': {
'id': '8E388',
'ext': 'mp4',
'title': 'Artık Davutoğlu ile devam edemeyiz'
}
}, {
# mobile URL
'url': 'http://odatv.com/mob_video.php?id=8E388',
'only_matching': True,
}, {
# no video
'url': 'http://odatv.com/mob_video.php?id=8E900',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
no_video = 'NO VIDEO!' in webpage
video_url = self._search_regex(
r'mp4\s*:\s*(["\'])(?P<url>http.+?)\1', webpage, 'video url',
default=None if no_video else NO_DEFAULT, group='url')
if no_video:
raise ExtractorError('Video %s does not exist' % video_id, expected=True)
return {
'id': video_id,
'url': video_url,
'title': remove_start(self._og_search_title(webpage), 'Video: '),
'thumbnail': self._og_search_thumbnail(webpage),
}
| 763 |
471 | <gh_stars>100-1000
///////////////////////////////////////////////////////////////////////////////
// Name: src/common/modalhook.cpp
// Purpose: wxModalDialogHook implementation
// Author: <NAME>
// Created: 2013-05-19
// Copyright: (c) 2013 <NAME> <<EMAIL>>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/modalhook.h"
#ifndef WX_PRECOMP
#endif // WX_PRECOMP
wxModalDialogHook::Hooks wxModalDialogHook::ms_hooks;
// ============================================================================
// wxModalDialogHook implementation
// ============================================================================
// ----------------------------------------------------------------------------
// Hooks management
// ----------------------------------------------------------------------------
void wxModalDialogHook::Register()
{
#if wxDEBUG_LEVEL
for ( Hooks::const_iterator it = ms_hooks.begin();
it != ms_hooks.end();
++it)
{
if ( *it == this )
{
wxFAIL_MSG( wxS("Registering already registered hook?") );
return;
}
}
#endif // wxDEBUG_LEVEL
ms_hooks.insert(ms_hooks.begin(), this);
}
void wxModalDialogHook::Unregister()
{
if ( !DoUnregister() )
{
wxFAIL_MSG( wxS("Unregistering not registered hook?") );
}
}
bool wxModalDialogHook::DoUnregister()
{
for ( Hooks::iterator it = ms_hooks.begin();
it != ms_hooks.end();
++it )
{
if ( *it == this )
{
ms_hooks.erase(it);
return true;
}
}
return false;
}
// ----------------------------------------------------------------------------
// Invoking hooks methods
// ----------------------------------------------------------------------------
/* static */
int wxModalDialogHook::CallEnter(wxDialog* dialog)
{
// Make a copy of the hooks list to avoid problems if it's modified while
// we're iterating over it: this is unlikely to happen in our case, but
// quite possible in CallExit() as the hooks may remove themselves after
// the call to their Exit(), so do it here for symmetry as well.
const Hooks hooks = ms_hooks;
for ( Hooks::const_iterator it = hooks.begin(); it != hooks.end(); ++it )
{
const int rc = (*it)->Enter(dialog);
if ( rc != wxID_NONE )
{
// Skip calling all the rest of the hooks if one of them preempts
// showing the dialog completely.
return rc;
}
}
return wxID_NONE;
}
/* static */
void wxModalDialogHook::CallExit(wxDialog* dialog)
{
// See comment in CallEnter() for the reasons for making a copy here.
const Hooks hooks = ms_hooks;
for ( Hooks::const_iterator it = hooks.begin(); it != hooks.end(); ++it )
{
(*it)->Exit(dialog);
}
}
| 1,129 |
347 | package org.ovirt.engine.ui.webadmin.section.main.view;
import org.ovirt.engine.ui.webadmin.section.main.presenter.DynamicUrlContentPresenter;
public class DynamicUrlContentView extends AbstractDynamicUrlContentView implements DynamicUrlContentPresenter.ViewDef {
}
| 74 |
3,102 | // RUN: %clang_cc1 -fsyntax-only -fblocks -Wformat -verify %s -Wno-error=non-pod-varargs
// RUN: %clang_cc1 -fsyntax-only -fblocks -Wformat -verify %s -Wno-error=non-pod-varargs -std=c++98
// RUN: %clang_cc1 -fsyntax-only -fblocks -Wformat -verify %s -Wno-error=non-pod-varargs -std=c++11
int (^block) (int, const char *,...) __attribute__((__format__(__printf__,2,3))) = ^ __attribute__((__format__(__printf__,2,3))) (int arg, const char *format,...) {return 5;};
class HasNoCStr {
const char *str;
public:
HasNoCStr(const char *s): str(s) { }
const char *not_c_str() {return str;}
};
void test_block() {
const char str[] = "test";
HasNoCStr hncs(str);
int n = 4;
block(n, "%s %d", str, n); // no-warning
block(n, "%s %s", hncs, n);
#if __cplusplus <= 199711L // C++03 or earlier modes
// expected-warning@-2{{cannot pass non-POD object of type 'HasNoCStr' to variadic block; expected type from format string was 'char *'}}
#else
// expected-warning@-4{{format specifies type 'char *' but the argument has type 'HasNoCStr'}}
#endif
// expected-warning@-6{{format specifies type 'char *' but the argument has type 'int'}}
}
| 442 |
980 | <filename>src/test/java/org/jcodec/codecs/h264/encode/IntraPredEstimatorTest.java
package org.jcodec.codecs.h264.encode;
import static org.jcodec.codecs.h264.H264Const.BLK_DISP_MAP;
import org.jcodec.codecs.h264.decode.Intra4x4PredictionBuilder;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture;
import org.junit.Assert;
import org.junit.Test;
public class IntraPredEstimatorTest {
@Test
public void testLumaPred4x4() {
int[] pred = new int[] { 0, 7, 8, 6, 6, 6, 7, 2, 2, 2, 4, 5, 3, 8, 3, 7 };
for (int i = 0; i < 10000; i++) {
for (int mbY = 0; mbY < 2; mbY++) {
for (int mbX = 0; mbX < 2; mbX++) {
for (int bInd = 0; bInd < 16; bInd++) {
int dInd = BLK_DISP_MAP[bInd];
boolean hasLeft = (dInd & 0x3) != 0 || mbX != 0;
boolean hasTop = dInd >= 4 || mbY != 0;
do {
pred[bInd] = Math.min(8, (int) (Math.random() * 9));
} while (!Intra4x4PredictionBuilder.available(pred[bInd], hasLeft, hasTop));
// System.out.print(String.format("%d ", pred[bInd]));
}
// System.out.println(String.format(": %d,%d", mbX, mbY));
oneTest(pred, mbX, mbY);
}
}
}
}
private void oneTest(int[] pred, int mbX, int mbY) {
Picture pic0 = Picture.create(16, 16, ColorSpace.YUV420), pic1 = Picture.create(16, 16, ColorSpace.YUV420);
Picture big = Picture.create(32, 32, ColorSpace.YUV420);
byte[] topLine0 = new byte[32];
byte[] topLine1 = new byte[32];
byte[] topLine2 = new byte[32];
byte[] leftRow0 = new byte[16];
byte[] leftRow1 = new byte[16];
byte[] leftRow2 = new byte[16];
byte[] tl0 = new byte[4];
byte[] tl1 = new byte[4];
byte[] tl2 = new byte[4];
EncodingContext ctx = new EncodingContext(2, 2);
int mbOff = mbX << 4;
for (int i = 0; i < 16; i++) {
ctx.topLine[0][mbOff + i] = topLine0[mbOff + i] = topLine1[mbOff + i] = topLine2[mbOff + i] = (byte) (16 * i + 75);
ctx.leftRow[0][i] = leftRow0[i] = leftRow1[i] = leftRow2[i] = (byte) (15 * i + 33);
}
ctx.topLeft[0] = tl0[0] = tl1[0] = tl2[0] = 127;
ctx.topLeft[1] = tl0[1] = tl1[1] = tl2[1] = ctx.leftRow[0][3];
ctx.topLeft[2] = tl0[2] = tl1[2] = tl2[2] = ctx.leftRow[0][7];
ctx.topLeft[3] = tl0[3] = tl1[3] = tl2[3] = ctx.leftRow[0][11];
int[] residual = new int[16];
for (int i8x8 = 0; i8x8 < 4; i8x8++) {
for (int i4x4 = 0; i4x4 < 4; i4x4++) {
int bInd = (i8x8 << 2) + i4x4;
int dInd = BLK_DISP_MAP[bInd];
boolean trAvailable = true;
if ((dInd <= 3 && mbY == 0) || (dInd == 3 && mbX == 1) || dInd == 7 || dInd == 11 || dInd == 15 || dInd == 5 || dInd == 13)
trAvailable = false;
Intra4x4PredictionBuilder.predictWithMode(pred[bInd], residual, (dInd & 0x3) != 0 || mbX != 0, dInd >= 4 || mbY != 0, trAvailable, leftRow0,
topLine0, tl0, mbOff, (dInd & 0x3) << 2, (dInd >> 2) << 2, pic0.getPlaneData(0));
}
}
MBEncoderHelper.putBlkPic(big, pic0, mbX << 4, mbY << 4);
int[] out = IntraPredEstimator.getLumaPred4x4(big, ctx, mbX, mbY, 24);
for (int i8x8 = 0; i8x8 < 4; i8x8++) {
for (int i4x4 = 0; i4x4 < 4; i4x4++) {
int bInd = (i8x8 << 2) + i4x4;
int dInd = BLK_DISP_MAP[bInd];
boolean trAvailable = true;
if ((dInd <= 3 && mbY == 0) || (dInd == 3 && mbX == 1) || dInd == 7 || dInd == 11 || dInd == 15 || dInd == 5 || dInd == 13)
trAvailable = false;
Intra4x4PredictionBuilder.predictWithMode(out[bInd], residual, (dInd & 0x3) != 0 || mbX != 0, dInd >= 4 || mbY != 0, trAvailable, leftRow1,
topLine1, tl1, mbOff, (dInd & 0x3) << 2, (dInd >> 2) << 2, pic0.getPlaneData(0));
Intra4x4PredictionBuilder.predictWithMode(pred[bInd], residual, (dInd & 0x3) != 0 || mbX != 0, dInd >= 4 || mbY != 0, trAvailable, leftRow2,
topLine2, tl2, mbOff, (dInd & 0x3) << 2, (dInd >> 2) << 2, pic1.getPlaneData(0));
}
}
Assert.assertArrayEquals(pic0.getPlaneData(0), pic1.getPlaneData(0));
}
public void testLumaMode() {
}
}
| 2,554 |
852 | <filename>FWCore/ServiceRegistry/interface/ActivityRegistry.h
#ifndef FWCore_ServiceRegistry_ActivityRegistry_h
#define FWCore_ServiceRegistry_ActivityRegistry_h
// -*- C++ -*-
//
// Package: ServiceRegistry
// Class : ActivityRegistry
//
/**\class ActivityRegistry ActivityRegistry.h FWCore/ServiceRegistry/interface/ActivityRegistry.h
Description: Registry holding the signals that Services can subscribe to
Usage:
Services can connect to the signals distributed by the ActivityRegistry in order to monitor the activity of the application.
There are unit tests for the signals that use the Tracer
to print out the transitions as they occur and then
compare to a reference file. One test does this for
a SubProcess test and the other for a test using
unscheduled execution. The tests are in FWCore/Integration/test:
run_SubProcess.sh
testSubProcess_cfg.py
run_TestGetBy.sh
testGetBy1_cfg.py
testGetBy2_cfg.py
There are four little details you should remember when adding new signals
to this file that go beyond the obvious cut and paste type of edits.
1. The number at the end of the AR_WATCH_USING_METHOD_X macro definition
is the number of function arguments. It will not compile if you use the
wrong number there.
2. Use connect or connect_front depending on whether the callback function
should be called for different services in the order the Services were
constructed or in reverse order. Begin signals are usually forward and
End signals in reverse, but if the service does not depend on other services
and vice versa this does not matter.
3. The signal needs to be added to either connectGlobals or connectLocals
in the ActivityRegistry.cc file, depending on whether a signal is seen
by children or parents when there are SubProcesses. For example, source
signals are only generated in the top level process and should be seen
by all child SubProcesses so they are in connectGlobals. Most signals
however belong in connectLocals. It does not really matter in jobs
without at least one SubProcess.
4. Each signal also needs to be added in copySlotsFrom in
ActivityRegistry.cc. Whether it uses copySlotsToFrom or
copySlotsToFromReverse depends on the same ordering issue as the connect
or connect_front choice in item 2 above.
*/
//
// Original Author: <NAME>
// Created: Mon Sep 5 19:53:09 EDT 2005
//
// system include files
#include <functional>
#include <string>
// user include files
#include "FWCore/ServiceRegistry/interface/TerminationOrigin.h"
#include "FWCore/Utilities/interface/LuminosityBlockIndex.h"
#include "FWCore/Utilities/interface/RunIndex.h"
#include "FWCore/Utilities/interface/Signal.h"
#include "FWCore/Utilities/interface/StreamID.h"
#define AR_WATCH_USING_METHOD_0(method) \
template <class TClass, class TMethod> \
void method(TClass* iObject, TMethod iMethod) { \
method(std::bind(std::mem_fn(iMethod), iObject)); \
}
#define AR_WATCH_USING_METHOD_1(method) \
template <class TClass, class TMethod> \
void method(TClass* iObject, TMethod iMethod) { \
method(std::bind(std::mem_fn(iMethod), iObject, std::placeholders::_1)); \
}
#define AR_WATCH_USING_METHOD_2(method) \
template <class TClass, class TMethod> \
void method(TClass* iObject, TMethod iMethod) { \
method(std::bind(std::mem_fn(iMethod), iObject, std::placeholders::_1, std::placeholders::_2)); \
}
#define AR_WATCH_USING_METHOD_3(method) \
template <class TClass, class TMethod> \
void method(TClass* iObject, TMethod iMethod) { \
method(std::bind( \
std::mem_fn(iMethod), iObject, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); \
}
// forward declarations
namespace edm {
class EventID;
class LuminosityBlockID;
class RunID;
class Timestamp;
class ModuleDescription;
class Event;
class LuminosityBlock;
class Run;
class EventSetup;
class HLTPathStatus;
class GlobalContext;
class StreamContext;
class PathContext;
class ProcessContext;
class ModuleCallingContext;
class PathsAndConsumesOfModulesBase;
class ESModuleCallingContext;
namespace eventsetup {
struct ComponentDescription;
class DataKey;
class EventSetupRecordKey;
} // namespace eventsetup
namespace service {
class SystemBounds;
}
namespace signalslot {
void throwObsoleteSignalException();
template <class T>
class ObsoleteSignal {
public:
typedef std::function<T> slot_type;
ObsoleteSignal() = default;
template <typename U>
void connect(U /* iFunc */) {
throwObsoleteSignalException();
}
template <typename U>
void connect_front(U /* iFunc*/) {
throwObsoleteSignalException();
}
};
} // namespace signalslot
class ActivityRegistry {
public:
ActivityRegistry() {}
ActivityRegistry(ActivityRegistry const&) = delete; // Disallow copying and moving
ActivityRegistry& operator=(ActivityRegistry const&) = delete; // Disallow copying and moving
// ---------- signals ------------------------------------
typedef signalslot::Signal<void(service::SystemBounds const&)> Preallocate;
///signal is emitted before beginJob
Preallocate preallocateSignal_;
void watchPreallocate(Preallocate::slot_type const& iSlot) { preallocateSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreallocate)
typedef signalslot::Signal<void(PathsAndConsumesOfModulesBase const&, ProcessContext const&)> PreBeginJob;
///signal is emitted before all modules have gotten their beginJob called
PreBeginJob preBeginJobSignal_;
///convenience function for attaching to signal
void watchPreBeginJob(PreBeginJob::slot_type const& iSlot) { preBeginJobSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPreBeginJob)
typedef signalslot::Signal<void()> PostBeginJob;
///signal is emitted after all modules have gotten their beginJob called
PostBeginJob postBeginJobSignal_;
///convenience function for attaching to signal
void watchPostBeginJob(PostBeginJob::slot_type const& iSlot) { postBeginJobSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_0(watchPostBeginJob)
typedef signalslot::Signal<void()> PreEndJob;
///signal is emitted before any modules have gotten their endJob called
PreEndJob preEndJobSignal_;
void watchPreEndJob(PreEndJob::slot_type const& iSlot) { preEndJobSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_0(watchPreEndJob)
typedef signalslot::Signal<void()> PostEndJob;
///signal is emitted after all modules have gotten their endJob called
PostEndJob postEndJobSignal_;
void watchPostEndJob(PostEndJob::slot_type const& iSlot) { postEndJobSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_0(watchPostEndJob)
typedef signalslot::Signal<void()> JobFailure;
/// signal is emitted if event processing or end-of-job
/// processing fails with an uncaught exception.
JobFailure jobFailureSignal_;
///convenience function for attaching to signal
void watchJobFailure(JobFailure::slot_type const& iSlot) { jobFailureSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_0(watchJobFailure)
/// signal is emitted before the source starts creating an Event
typedef signalslot::Signal<void(StreamID)> PreSourceEvent;
PreSourceEvent preSourceSignal_;
void watchPreSourceEvent(PreSourceEvent::slot_type const& iSlot) { preSourceSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreSourceEvent)
/// signal is emitted after the source starts creating an Event
typedef signalslot::Signal<void(StreamID)> PostSourceEvent;
PostSourceEvent postSourceSignal_;
void watchPostSourceEvent(PostSourceEvent::slot_type const& iSlot) { postSourceSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_1(watchPostSourceEvent)
/// signal is emitted before the source starts creating a Lumi
typedef signalslot::Signal<void(LuminosityBlockIndex)> PreSourceLumi;
PreSourceLumi preSourceLumiSignal_;
void watchPreSourceLumi(PreSourceLumi::slot_type const& iSlot) { preSourceLumiSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreSourceLumi)
/// signal is emitted after the source starts creating a Lumi
typedef signalslot::Signal<void(LuminosityBlockIndex)> PostSourceLumi;
PostSourceLumi postSourceLumiSignal_;
void watchPostSourceLumi(PostSourceLumi::slot_type const& iSlot) { postSourceLumiSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_1(watchPostSourceLumi)
/// signal is emitted before the source starts creating a Run
typedef signalslot::Signal<void(RunIndex)> PreSourceRun;
PreSourceRun preSourceRunSignal_;
void watchPreSourceRun(PreSourceRun::slot_type const& iSlot) { preSourceRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreSourceRun)
/// signal is emitted after the source starts creating a Run
typedef signalslot::Signal<void(RunIndex)> PostSourceRun;
PostSourceRun postSourceRunSignal_;
void watchPostSourceRun(PostSourceRun::slot_type const& iSlot) { postSourceRunSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_1(watchPostSourceRun)
/// signal is emitted before the source starts creating a ProcessBlock
typedef signalslot::Signal<void()> PreSourceProcessBlock;
PreSourceProcessBlock preSourceProcessBlockSignal_;
void watchPreSourceProcessBlock(PreSourceProcessBlock::slot_type const& iSlot) {
preSourceProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_0(watchPreSourceProcessBlock)
/// signal is emitted after the source starts creating a ProcessBlock
typedef signalslot::Signal<void(std::string const&)> PostSourceProcessBlock;
PostSourceProcessBlock postSourceProcessBlockSignal_;
void watchPostSourceProcessBlock(PostSourceProcessBlock::slot_type const& iSlot) {
postSourceProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostSourceProcessBlock)
/// signal is emitted before the source opens a file
typedef signalslot::Signal<void(std::string const&, bool)> PreOpenFile;
PreOpenFile preOpenFileSignal_;
void watchPreOpenFile(PreOpenFile::slot_type const& iSlot) { preOpenFileSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPreOpenFile)
/// signal is emitted after the source opens a file
// Note this is only done for a primary file, not a secondary one.
typedef signalslot::Signal<void(std::string const&, bool)> PostOpenFile;
PostOpenFile postOpenFileSignal_;
void watchPostOpenFile(PostOpenFile::slot_type const& iSlot) { postOpenFileSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_2(watchPostOpenFile)
/// signal is emitted before the Closesource closes a file
// First argument is the LFN of the file which is being closed.
// Second argument is false if fallback is used; true otherwise.
typedef signalslot::Signal<void(std::string const&, bool)> PreCloseFile;
PreCloseFile preCloseFileSignal_;
void watchPreCloseFile(PreCloseFile::slot_type const& iSlot) { preCloseFileSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPreCloseFile)
/// signal is emitted after the source opens a file
typedef signalslot::Signal<void(std::string const&, bool)> PostCloseFile;
PostCloseFile postCloseFileSignal_;
void watchPostCloseFile(PostCloseFile::slot_type const& iSlot) { postCloseFileSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_2(watchPostCloseFile)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleBeginStream;
PreModuleBeginStream preModuleBeginStreamSignal_;
void watchPreModuleBeginStream(PreModuleBeginStream::slot_type const& iSlot) {
preModuleBeginStreamSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleBeginStream)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleBeginStream;
PostModuleBeginStream postModuleBeginStreamSignal_;
void watchPostModuleBeginStream(PostModuleBeginStream::slot_type const& iSlot) {
postModuleBeginStreamSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleBeginStream)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleEndStream;
PreModuleEndStream preModuleEndStreamSignal_;
void watchPreModuleEndStream(PreModuleEndStream::slot_type const& iSlot) {
preModuleEndStreamSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleEndStream)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleEndStream;
PostModuleEndStream postModuleEndStreamSignal_;
void watchPostModuleEndStream(PostModuleEndStream::slot_type const& iSlot) {
postModuleEndStreamSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleEndStream)
typedef signalslot::Signal<void(GlobalContext const&)> PreBeginProcessBlock;
PreBeginProcessBlock preBeginProcessBlockSignal_;
void watchPreBeginProcessBlock(PreBeginProcessBlock::slot_type const& iSlot) {
preBeginProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreBeginProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PostBeginProcessBlock;
PostBeginProcessBlock postBeginProcessBlockSignal_;
void watchPostBeginProcessBlock(PostBeginProcessBlock::slot_type const& iSlot) {
postBeginProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostBeginProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PreAccessInputProcessBlock;
PreAccessInputProcessBlock preAccessInputProcessBlockSignal_;
void watchPreAccessInputProcessBlock(PreAccessInputProcessBlock::slot_type const& iSlot) {
preAccessInputProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreAccessInputProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PostAccessInputProcessBlock;
PostAccessInputProcessBlock postAccessInputProcessBlockSignal_;
void watchPostAccessInputProcessBlock(PostAccessInputProcessBlock::slot_type const& iSlot) {
postAccessInputProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostAccessInputProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PreEndProcessBlock;
PreEndProcessBlock preEndProcessBlockSignal_;
void watchPreEndProcessBlock(PreEndProcessBlock::slot_type const& iSlot) {
preEndProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreEndProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PostEndProcessBlock;
PostEndProcessBlock postEndProcessBlockSignal_;
void watchPostEndProcessBlock(PostEndProcessBlock::slot_type const& iSlot) {
postEndProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostEndProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PreGlobalBeginRun;
/// signal is emitted after the Run has been created by the InputSource but before any modules have seen the Run
PreGlobalBeginRun preGlobalBeginRunSignal_;
void watchPreGlobalBeginRun(PreGlobalBeginRun::slot_type const& iSlot) { preGlobalBeginRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreGlobalBeginRun)
typedef signalslot::Signal<void(GlobalContext const&)> PostGlobalBeginRun;
PostGlobalBeginRun postGlobalBeginRunSignal_;
void watchPostGlobalBeginRun(PostGlobalBeginRun::slot_type const& iSlot) {
postGlobalBeginRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostGlobalBeginRun)
typedef signalslot::Signal<void(GlobalContext const&)> PreGlobalEndRun;
PreGlobalEndRun preGlobalEndRunSignal_;
void watchPreGlobalEndRun(PreGlobalEndRun::slot_type const& iSlot) { preGlobalEndRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreGlobalEndRun)
typedef signalslot::Signal<void(GlobalContext const&)> PostGlobalEndRun;
PostGlobalEndRun postGlobalEndRunSignal_;
void watchPostGlobalEndRun(PostGlobalEndRun::slot_type const& iSlot) {
postGlobalEndRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostGlobalEndRun)
typedef signalslot::Signal<void(GlobalContext const&)> PreWriteProcessBlock;
PreWriteProcessBlock preWriteProcessBlockSignal_;
void watchPreWriteProcessBlock(PreWriteProcessBlock::slot_type const& iSlot) {
preWriteProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreWriteProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PostWriteProcessBlock;
PostWriteProcessBlock postWriteProcessBlockSignal_;
void watchPostWriteProcessBlock(PostWriteProcessBlock::slot_type const& iSlot) {
postWriteProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostWriteProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&)> PreGlobalWriteRun;
PreGlobalWriteRun preGlobalWriteRunSignal_;
void watchPreGlobalWriteRun(PreGlobalWriteRun::slot_type const& iSlot) { preGlobalWriteRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreGlobalWriteRun)
typedef signalslot::Signal<void(GlobalContext const&)> PostGlobalWriteRun;
PostGlobalWriteRun postGlobalWriteRunSignal_;
void watchPostGlobalWriteRun(PostGlobalWriteRun::slot_type const& iSlot) {
postGlobalWriteRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostGlobalWriteRun)
typedef signalslot::Signal<void(StreamContext const&)> PreStreamBeginRun;
PreStreamBeginRun preStreamBeginRunSignal_;
void watchPreStreamBeginRun(PreStreamBeginRun::slot_type const& iSlot) { preStreamBeginRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreStreamBeginRun)
typedef signalslot::Signal<void(StreamContext const&)> PostStreamBeginRun;
PostStreamBeginRun postStreamBeginRunSignal_;
void watchPostStreamBeginRun(PostStreamBeginRun::slot_type const& iSlot) {
postStreamBeginRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostStreamBeginRun)
typedef signalslot::Signal<void(StreamContext const&)> PreStreamEndRun;
PreStreamEndRun preStreamEndRunSignal_;
void watchPreStreamEndRun(PreStreamEndRun::slot_type const& iSlot) { preStreamEndRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreStreamEndRun)
typedef signalslot::Signal<void(StreamContext const&)> PostStreamEndRun;
PostStreamEndRun postStreamEndRunSignal_;
void watchPostStreamEndRun(PostStreamEndRun::slot_type const& iSlot) {
postStreamEndRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostStreamEndRun)
typedef signalslot::Signal<void(GlobalContext const&)> PreGlobalBeginLumi;
PreGlobalBeginLumi preGlobalBeginLumiSignal_;
void watchPreGlobalBeginLumi(PreGlobalBeginLumi::slot_type const& iSlot) {
preGlobalBeginLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreGlobalBeginLumi)
typedef signalslot::Signal<void(GlobalContext const&)> PostGlobalBeginLumi;
PostGlobalBeginLumi postGlobalBeginLumiSignal_;
void watchPostGlobalBeginLumi(PostGlobalBeginLumi::slot_type const& iSlot) {
postGlobalBeginLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostGlobalBeginLumi)
typedef signalslot::Signal<void(GlobalContext const&)> PreGlobalEndLumi;
PreGlobalEndLumi preGlobalEndLumiSignal_;
void watchPreGlobalEndLumi(PreGlobalEndLumi::slot_type const& iSlot) { preGlobalEndLumiSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreGlobalEndLumi)
typedef signalslot::Signal<void(GlobalContext const&)> PostGlobalEndLumi;
PostGlobalEndLumi postGlobalEndLumiSignal_;
void watchPostGlobalEndLumi(PostGlobalEndLumi::slot_type const& iSlot) {
postGlobalEndLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostGlobalEndLumi)
typedef signalslot::Signal<void(GlobalContext const&)> PreGlobalWriteLumi;
PreGlobalEndLumi preGlobalWriteLumiSignal_;
void watchPreGlobalWriteLumi(PreGlobalWriteLumi::slot_type const& iSlot) {
preGlobalWriteLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreGlobalWriteLumi)
typedef signalslot::Signal<void(GlobalContext const&)> PostGlobalWriteLumi;
PostGlobalEndLumi postGlobalWriteLumiSignal_;
void watchPostGlobalWriteLumi(PostGlobalEndLumi::slot_type const& iSlot) {
postGlobalWriteLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostGlobalWriteLumi)
typedef signalslot::Signal<void(StreamContext const&)> PreStreamBeginLumi;
PreStreamBeginLumi preStreamBeginLumiSignal_;
void watchPreStreamBeginLumi(PreStreamBeginLumi::slot_type const& iSlot) {
preStreamBeginLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreStreamBeginLumi)
typedef signalslot::Signal<void(StreamContext const&)> PostStreamBeginLumi;
PostStreamBeginLumi postStreamBeginLumiSignal_;
void watchPostStreamBeginLumi(PostStreamBeginLumi::slot_type const& iSlot) {
postStreamBeginLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostStreamBeginLumi)
typedef signalslot::Signal<void(StreamContext const&)> PreStreamEndLumi;
PreStreamEndLumi preStreamEndLumiSignal_;
void watchPreStreamEndLumi(PreStreamEndLumi::slot_type const& iSlot) { preStreamEndLumiSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreStreamEndLumi)
typedef signalslot::Signal<void(StreamContext const&)> PostStreamEndLumi;
PostStreamEndLumi postStreamEndLumiSignal_;
void watchPostStreamEndLumi(PostStreamEndLumi::slot_type const& iSlot) {
postStreamEndLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostStreamEndLumi)
typedef signalslot::Signal<void(StreamContext const&)> PreEvent;
/// signal is emitted after the Event has been created by the InputSource but before any modules have seen the Event
PreEvent preEventSignal_;
void watchPreEvent(PreEvent::slot_type const& iSlot) { preEventSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreEvent)
typedef signalslot::Signal<void(StreamContext const&)> PostEvent;
/// signal is emitted after all modules have finished processing the Event
PostEvent postEventSignal_;
void watchPostEvent(PostEvent::slot_type const& iSlot) { postEventSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_1(watchPostEvent)
/// signal is emitted before starting to process a Path for an event
typedef signalslot::Signal<void(StreamContext const&, PathContext const&)> PrePathEvent;
PrePathEvent prePathEventSignal_;
void watchPrePathEvent(PrePathEvent::slot_type const& iSlot) { prePathEventSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPrePathEvent)
/// signal is emitted after all modules have finished for the Path for an event
typedef signalslot::Signal<void(StreamContext const&, PathContext const&, HLTPathStatus const&)> PostPathEvent;
PostPathEvent postPathEventSignal_;
void watchPostPathEvent(PostPathEvent::slot_type const& iSlot) { postPathEventSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_3(watchPostPathEvent)
/// signal is emitted when began processing a stream transition and
/// then we began terminating the application
typedef signalslot::Signal<void(StreamContext const&, TerminationOrigin)> PreStreamEarlyTermination;
PreStreamEarlyTermination preStreamEarlyTerminationSignal_;
void watchPreStreamEarlyTermination(PreStreamEarlyTermination::slot_type const& iSlot) {
preStreamEarlyTerminationSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreStreamEarlyTermination)
/// signal is emitted if a began processing a global transition and
/// then we began terminating the application
typedef signalslot::Signal<void(GlobalContext const&, TerminationOrigin)> PreGlobalEarlyTermination;
PreGlobalEarlyTermination preGlobalEarlyTerminationSignal_;
void watchPreGlobalEarlyTermination(PreGlobalEarlyTermination::slot_type const& iSlot) {
preGlobalEarlyTerminationSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreGlobalEarlyTermination)
/// signal is emitted if while communicating with a source we began terminating
/// the application
typedef signalslot::Signal<void(TerminationOrigin)> PreSourceEarlyTermination;
PreSourceEarlyTermination preSourceEarlyTerminationSignal_;
void watchPreSourceEarlyTermination(PreSourceEarlyTermination::slot_type const& iSlot) {
preSourceEarlyTerminationSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPreSourceEarlyTermination)
/// signal is emitted before the esmodule starts processing and before prefetching has started
typedef signalslot::Signal<void(eventsetup::EventSetupRecordKey const&, ESModuleCallingContext const&)>
PreESModulePrefetching;
PreESModulePrefetching preESModulePrefetchingSignal_;
void watchPreESModulePrefetching(PreESModulePrefetching::slot_type const& iSlot) {
preESModulePrefetchingSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreESModulePrefetching)
/// signal is emitted before the esmodule starts processing and after prefetching has finished
typedef signalslot::Signal<void(eventsetup::EventSetupRecordKey const&, ESModuleCallingContext const&)>
PostESModulePrefetching;
PostESModulePrefetching postESModulePrefetchingSignal_;
void watchPostESModulePrefetching(PostESModulePrefetching::slot_type const& iSlot) {
postESModulePrefetchingSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostESModulePrefetching)
/// signal is emitted before the esmodule starts processing
typedef signalslot::Signal<void(eventsetup::EventSetupRecordKey const&, ESModuleCallingContext const&)> PreESModule;
PreESModule preESModuleSignal_;
void watchPreESModule(PreESModule::slot_type const& iSlot) { preESModuleSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPreESModule)
/// signal is emitted after the esmodule finished processing
typedef signalslot::Signal<void(eventsetup::EventSetupRecordKey const&, ESModuleCallingContext const&)> PostESModule;
PostESModule postESModuleSignal_;
void watchPostESModule(PostESModule::slot_type const& iSlot) { postESModuleSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_2(watchPostESModule)
/* Note M:
Concerning use of address of module descriptor
during functions called before/after module or source construction:
Unlike the case in the Run, Lumi, and Event loops,
the Module descriptor (often passed by pointer or reference
as an argument named desc) in the construction phase is NOT
at some permanent fixed address during the construction phase.
Therefore, any optimization of caching the module name keying
off of address of the descriptor will NOT be valid during
such functions. mf / cj 9/11/09
*/
/// signal is emitted before the module is constructed
typedef signalslot::Signal<void(ModuleDescription const&)> PreModuleConstruction;
PreModuleConstruction preModuleConstructionSignal_;
void watchPreModuleConstruction(PreModuleConstruction::slot_type const& iSlot) {
preModuleConstructionSignal_.connect(iSlot);
}
// WARNING - ModuleDescription is not in fixed place. See note M above.
AR_WATCH_USING_METHOD_1(watchPreModuleConstruction)
/// signal is emitted after the module was construction
typedef signalslot::Signal<void(ModuleDescription const&)> PostModuleConstruction;
PostModuleConstruction postModuleConstructionSignal_;
void watchPostModuleConstruction(PostModuleConstruction::slot_type const& iSlot) {
postModuleConstructionSignal_.connect_front(iSlot);
}
// WARNING - ModuleDescription is not in fixed place. See note M above.
AR_WATCH_USING_METHOD_1(watchPostModuleConstruction)
/// signal is emitted before the module is destructed, only for modules deleted before beginJob
typedef signalslot::Signal<void(ModuleDescription const&)> PreModuleDestruction;
PreModuleDestruction preModuleDestructionSignal_;
void watchPreModuleDestruction(PreModuleDestruction::slot_type const& iSlot) {
preModuleDestructionSignal_.connect(iSlot);
}
// note: ModuleDescription IS in the fixed place. See note M above.
AR_WATCH_USING_METHOD_1(watchPreModuleDestruction)
/// signal is emitted after the module is destructed, only for modules deleted before beginJob
typedef signalslot::Signal<void(ModuleDescription const&)> PostModuleDestruction;
PostModuleDestruction postModuleDestructionSignal_;
void watchPostModuleDestruction(PostModuleDestruction::slot_type const& iSlot) {
postModuleDestructionSignal_.connect_front(iSlot);
}
// WARNING - ModuleDescription is not in fixed place. See note M above.
AR_WATCH_USING_METHOD_1(watchPostModuleDestruction)
/// signal is emitted before the module does beginJob
typedef signalslot::Signal<void(ModuleDescription const&)> PreModuleBeginJob;
PreModuleBeginJob preModuleBeginJobSignal_;
void watchPreModuleBeginJob(PreModuleBeginJob::slot_type const& iSlot) { preModuleBeginJobSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreModuleBeginJob)
/// signal is emitted after the module had done beginJob
typedef signalslot::Signal<void(ModuleDescription const&)> PostModuleBeginJob;
PostModuleBeginJob postModuleBeginJobSignal_;
void watchPostModuleBeginJob(PostModuleBeginJob::slot_type const& iSlot) {
postModuleBeginJobSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostModuleBeginJob)
/// signal is emitted before the module does endJob
typedef signalslot::Signal<void(ModuleDescription const&)> PreModuleEndJob;
PreModuleEndJob preModuleEndJobSignal_;
void watchPreModuleEndJob(PreModuleEndJob::slot_type const& iSlot) { preModuleEndJobSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_1(watchPreModuleEndJob)
/// signal is emitted after the module had done endJob
typedef signalslot::Signal<void(ModuleDescription const&)> PostModuleEndJob;
PostModuleEndJob postModuleEndJobSignal_;
void watchPostModuleEndJob(PostModuleEndJob::slot_type const& iSlot) {
postModuleEndJobSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_1(watchPostModuleEndJob)
/// signal is emitted before the module starts processing the Event and before prefetching has started
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleEventPrefetching;
PreModuleEventPrefetching preModuleEventPrefetchingSignal_;
void watchPreModuleEventPrefetching(PreModuleEventPrefetching::slot_type const& iSlot) {
preModuleEventPrefetchingSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleEventPrefetching)
/// signal is emitted before the module starts processing the Event and after prefetching has finished
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleEventPrefetching;
PostModuleEventPrefetching postModuleEventPrefetchingSignal_;
void watchPostModuleEventPrefetching(PostModuleEventPrefetching::slot_type const& iSlot) {
postModuleEventPrefetchingSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleEventPrefetching)
/// signal is emitted before the module starts processing the Event
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleEvent;
PreModuleEvent preModuleEventSignal_;
void watchPreModuleEvent(PreModuleEvent::slot_type const& iSlot) { preModuleEventSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPreModuleEvent)
/// signal is emitted after the module finished processing the Event
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleEvent;
PostModuleEvent postModuleEventSignal_;
void watchPostModuleEvent(PostModuleEvent::slot_type const& iSlot) { postModuleEventSignal_.connect_front(iSlot); }
AR_WATCH_USING_METHOD_2(watchPostModuleEvent)
/// signal is emitted before the module starts the acquire method for the Event
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleEventAcquire;
PreModuleEventAcquire preModuleEventAcquireSignal_;
void watchPreModuleEventAcquire(PreModuleEventAcquire::slot_type const& iSlot) {
preModuleEventAcquireSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleEventAcquire)
/// signal is emitted after the module finishes the acquire method for the Event
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleEventAcquire;
PostModuleEventAcquire postModuleEventAcquireSignal_;
void watchPostModuleEventAcquire(PostModuleEventAcquire::slot_type const& iSlot) {
postModuleEventAcquireSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleEventAcquire)
/// signal is emitted after the module starts processing the Event and before a delayed get has started
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleEventDelayedGet;
PreModuleEventDelayedGet preModuleEventDelayedGetSignal_;
void watchPreModuleEventDelayedGet(PreModuleEventDelayedGet::slot_type const& iSlot) {
preModuleEventDelayedGetSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleEventDelayedGet)
/// signal is emitted after the module starts processing the Event and after a delayed get has finished
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleEventDelayedGet;
PostModuleEventDelayedGet postModuleEventDelayedGetSignal_;
void watchPostModuleEventDelayedGet(PostModuleEventDelayedGet::slot_type const& iSlot) {
postModuleEventDelayedGetSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleEventDelayedGet)
/// signal is emitted after the module starts processing the Event, after a delayed get has started, and before a source read
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreEventReadFromSource;
PreEventReadFromSource preEventReadFromSourceSignal_;
void watchPreEventReadFromSource(PreEventReadFromSource::slot_type const& iSlot) {
preEventReadFromSourceSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreEventReadFromSource)
/// signal is emitted after the module starts processing the Event, after a delayed get has started, and after a source read
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostEventReadFromSource;
PostEventReadFromSource postEventReadFromSourceSignal_;
void watchPostEventReadFromSource(PostEventReadFromSource::slot_type const& iSlot) {
postEventReadFromSourceSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostEventReadFromSource)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleStreamBeginRun;
PreModuleStreamBeginRun preModuleStreamBeginRunSignal_;
void watchPreModuleStreamBeginRun(PreModuleStreamBeginRun::slot_type const& iSlot) {
preModuleStreamBeginRunSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleStreamBeginRun)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleStreamBeginRun;
PostModuleStreamBeginRun postModuleStreamBeginRunSignal_;
void watchPostModuleStreamBeginRun(PostModuleStreamBeginRun::slot_type const& iSlot) {
postModuleStreamBeginRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleStreamBeginRun)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleStreamEndRun;
PreModuleStreamEndRun preModuleStreamEndRunSignal_;
void watchPreModuleStreamEndRun(PreModuleStreamEndRun::slot_type const& iSlot) {
preModuleStreamEndRunSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleStreamEndRun)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleStreamEndRun;
PostModuleStreamEndRun postModuleStreamEndRunSignal_;
void watchPostModuleStreamEndRun(PostModuleStreamEndRun::slot_type const& iSlot) {
postModuleStreamEndRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleStreamEndRun)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleStreamBeginLumi;
PreModuleStreamBeginLumi preModuleStreamBeginLumiSignal_;
void watchPreModuleStreamBeginLumi(PreModuleStreamBeginLumi::slot_type const& iSlot) {
preModuleStreamBeginLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleStreamBeginLumi)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleStreamBeginLumi;
PostModuleStreamBeginLumi postModuleStreamBeginLumiSignal_;
void watchPostModuleStreamBeginLumi(PostModuleStreamBeginLumi::slot_type const& iSlot) {
postModuleStreamBeginLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleStreamBeginLumi)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PreModuleStreamEndLumi;
PreModuleStreamEndLumi preModuleStreamEndLumiSignal_;
void watchPreModuleStreamEndLumi(PreModuleStreamEndLumi::slot_type const& iSlot) {
preModuleStreamEndLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleStreamEndLumi)
typedef signalslot::Signal<void(StreamContext const&, ModuleCallingContext const&)> PostModuleStreamEndLumi;
PostModuleStreamEndLumi postModuleStreamEndLumiSignal_;
void watchPostModuleStreamEndLumi(PostModuleStreamEndLumi::slot_type const& iSlot) {
postModuleStreamEndLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleStreamEndLumi)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleBeginProcessBlock;
PreModuleBeginProcessBlock preModuleBeginProcessBlockSignal_;
void watchPreModuleBeginProcessBlock(PreModuleBeginProcessBlock::slot_type const& iSlot) {
preModuleBeginProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleBeginProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleBeginProcessBlock;
PostModuleBeginProcessBlock postModuleBeginProcessBlockSignal_;
void watchPostModuleBeginProcessBlock(PostModuleBeginProcessBlock::slot_type const& iSlot) {
postModuleBeginProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleBeginProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleAccessInputProcessBlock;
PreModuleAccessInputProcessBlock preModuleAccessInputProcessBlockSignal_;
void watchPreModuleAccessInputProcessBlock(PreModuleAccessInputProcessBlock::slot_type const& iSlot) {
preModuleAccessInputProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleAccessInputProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)>
PostModuleAccessInputProcessBlock;
PostModuleAccessInputProcessBlock postModuleAccessInputProcessBlockSignal_;
void watchPostModuleAccessInputProcessBlock(PostModuleAccessInputProcessBlock::slot_type const& iSlot) {
postModuleAccessInputProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleAccessInputProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleEndProcessBlock;
PreModuleEndProcessBlock preModuleEndProcessBlockSignal_;
void watchPreModuleEndProcessBlock(PreModuleEndProcessBlock::slot_type const& iSlot) {
preModuleEndProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleEndProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleEndProcessBlock;
PostModuleEndProcessBlock postModuleEndProcessBlockSignal_;
void watchPostModuleEndProcessBlock(PostModuleEndProcessBlock::slot_type const& iSlot) {
postModuleEndProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleEndProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleGlobalBeginRun;
PreModuleGlobalBeginRun preModuleGlobalBeginRunSignal_;
void watchPreModuleGlobalBeginRun(PreModuleGlobalBeginRun::slot_type const& iSlot) {
preModuleGlobalBeginRunSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleGlobalBeginRun)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleGlobalBeginRun;
PostModuleGlobalBeginRun postModuleGlobalBeginRunSignal_;
void watchPostModuleGlobalBeginRun(PostModuleGlobalBeginRun::slot_type const& iSlot) {
postModuleGlobalBeginRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleGlobalBeginRun)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleGlobalEndRun;
PreModuleGlobalEndRun preModuleGlobalEndRunSignal_;
void watchPreModuleGlobalEndRun(PreModuleGlobalEndRun::slot_type const& iSlot) {
preModuleGlobalEndRunSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleGlobalEndRun)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleGlobalEndRun;
PostModuleGlobalEndRun postModuleGlobalEndRunSignal_;
void watchPostModuleGlobalEndRun(PostModuleGlobalEndRun::slot_type const& iSlot) {
postModuleGlobalEndRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleGlobalEndRun)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleGlobalBeginLumi;
PreModuleGlobalBeginLumi preModuleGlobalBeginLumiSignal_;
void watchPreModuleGlobalBeginLumi(PreModuleGlobalBeginLumi::slot_type const& iSlot) {
preModuleGlobalBeginLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleGlobalBeginLumi)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleGlobalBeginLumi;
PostModuleGlobalBeginLumi postModuleGlobalBeginLumiSignal_;
void watchPostModuleGlobalBeginLumi(PostModuleGlobalBeginLumi::slot_type const& iSlot) {
postModuleGlobalBeginLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleGlobalBeginLumi)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleGlobalEndLumi;
PreModuleGlobalEndLumi preModuleGlobalEndLumiSignal_;
void watchPreModuleGlobalEndLumi(PreModuleGlobalEndLumi::slot_type const& iSlot) {
preModuleGlobalEndLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleGlobalEndLumi)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleGlobalEndLumi;
PostModuleGlobalEndLumi postModuleGlobalEndLumiSignal_;
void watchPostModuleGlobalEndLumi(PostModuleGlobalEndLumi::slot_type const& iSlot) {
postModuleGlobalEndLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleGlobalEndLumi)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleWriteProcessBlock;
PreModuleWriteProcessBlock preModuleWriteProcessBlockSignal_;
void watchPreModuleWriteProcessBlock(PreModuleWriteProcessBlock::slot_type const& iSlot) {
preModuleWriteProcessBlockSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleWriteProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleWriteProcessBlock;
PostModuleWriteProcessBlock postModuleWriteProcessBlockSignal_;
void watchPostModuleWriteProcessBlock(PostModuleWriteProcessBlock::slot_type const& iSlot) {
postModuleWriteProcessBlockSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleWriteProcessBlock)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleWriteRun;
PreModuleWriteRun preModuleWriteRunSignal_;
void watchPreModuleWriteRun(PreModuleWriteRun::slot_type const& iSlot) { preModuleWriteRunSignal_.connect(iSlot); }
AR_WATCH_USING_METHOD_2(watchPreModuleWriteRun)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleWriteRun;
PostModuleWriteRun postModuleWriteRunSignal_;
void watchPostModuleWriteRun(PostModuleWriteRun::slot_type const& iSlot) {
postModuleWriteRunSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleWriteRun)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PreModuleWriteLumi;
PreModuleWriteLumi preModuleWriteLumiSignal_;
void watchPreModuleWriteLumi(PreModuleWriteLumi::slot_type const& iSlot) {
preModuleWriteLumiSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPreModuleWriteLumi)
typedef signalslot::Signal<void(GlobalContext const&, ModuleCallingContext const&)> PostModuleWriteLumi;
PostModuleWriteLumi postModuleWriteLumiSignal_;
void watchPostModuleWriteLumi(PostModuleWriteLumi::slot_type const& iSlot) {
postModuleWriteLumiSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_2(watchPostModuleWriteLumi)
/// signal is emitted before the source is constructed
typedef signalslot::Signal<void(ModuleDescription const&)> PreSourceConstruction;
PreSourceConstruction preSourceConstructionSignal_;
void watchPreSourceConstruction(PreSourceConstruction::slot_type const& iSlot) {
preSourceConstructionSignal_.connect(iSlot);
}
// WARNING - ModuleDescription is not in fixed place. See note M above.
AR_WATCH_USING_METHOD_1(watchPreSourceConstruction)
/// signal is emitted after the source was construction
typedef signalslot::Signal<void(ModuleDescription const&)> PostSourceConstruction;
PostSourceConstruction postSourceConstructionSignal_;
void watchPostSourceConstruction(PostSourceConstruction::slot_type const& iSlot) {
postSourceConstructionSignal_.connect_front(iSlot);
}
// WARNING - ModuleDescription is not in fixed place. See note M above.
AR_WATCH_USING_METHOD_1(watchPostSourceConstruction)
//DEPRECATED
typedef signalslot::Signal<void(
eventsetup::ComponentDescription const*, eventsetup::EventSetupRecordKey const&, eventsetup::DataKey const&)>
PreLockEventSetupGet;
///signal is emitted before lock taken in EventSetup DataProxy::get function
PreLockEventSetupGet preLockEventSetupGetSignal_;
void watchPreLockEventSetupGet(PreLockEventSetupGet::slot_type const& iSlot) {
preLockEventSetupGetSignal_.connect(iSlot);
}
AR_WATCH_USING_METHOD_3(watchPreLockEventSetupGet)
//DEPRECATED
typedef signalslot::Signal<void(
eventsetup::ComponentDescription const*, eventsetup::EventSetupRecordKey const&, eventsetup::DataKey const&)>
PostLockEventSetupGet;
///signal is emitted after lock taken in EventSetup DataProxy::get function
PostLockEventSetupGet postLockEventSetupGetSignal_;
void watchPostLockEventSetupGet(PostLockEventSetupGet::slot_type const& iSlot) {
postLockEventSetupGetSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_3(watchPostLockEventSetupGet)
//DEPRECATED
typedef signalslot::Signal<void(
eventsetup::ComponentDescription const*, eventsetup::EventSetupRecordKey const&, eventsetup::DataKey const&)>
PostEventSetupGet;
///signal is emitted after getImpl has returned in the EventSetup DataProxy::get function
PostEventSetupGet postEventSetupGetSignal_;
void watchPostEventSetupGet(PostEventSetupGet::slot_type const& iSlot) {
postEventSetupGetSignal_.connect_front(iSlot);
}
AR_WATCH_USING_METHOD_3(watchPostEventSetupGet)
// ---------- member functions ---------------------------
///forwards our signals to slots connected to iOther
void connect(ActivityRegistry& iOther);
///forwards our subprocess independent signals to slots connected to iOther
///forwards iOther's subprocess dependent signals to slots connected to this
void connectToSubProcess(ActivityRegistry& iOther);
///copy the slots from iOther and connect them directly to our own
/// this allows us to 'forward' signals more efficiently,
/// BUT if iOther gains new slots after this call, we will not see them
/// This is also careful to keep the order of the slots proper
/// for services.
void copySlotsFrom(ActivityRegistry& iOther);
private:
// forwards subprocess independent signals to slots connected to iOther
void connectGlobals(ActivityRegistry& iOther);
// forwards subprocess dependent signals to slots connected to iOther
void connectLocals(ActivityRegistry& iOther);
};
} // namespace edm
#undef AR_WATCH_USING_METHOD
#endif
| 16,694 |
4,538 | <filename>sdk/include/alibabacloud/oss/model/ListObjectVersionsResult.h
/*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#pragma once
#include <alibabacloud/oss/model/Bucket.h>
#include <vector>
#include <memory>
#include <iostream>
#include <alibabacloud/oss/OssResult.h>
#include <alibabacloud/oss/model/Owner.h>
namespace AlibabaCloud
{
namespace OSS
{
class ListObjectVersionsResult;
class ALIBABACLOUD_OSS_EXPORT ObjectVersionSummary
{
public:
ObjectVersionSummary() = default;
const std::string& Key() const { return key_; }
const std::string& VersionId() const { return versionid_; }
const std::string& ETag()const { return eTag_; }
const std::string& LastModified() const { return lastModified_; }
const std::string& StorageClass() const { return storageClass_; }
const std::string& Type() const { return type_; }
int64_t Size() const { return size_; }
bool IsLatest() const { return isLatest_; }
const AlibabaCloud::OSS::Owner& Owner() const { return owner_; }
private:
friend class ListObjectVersionsResult;
std::string key_;
std::string versionid_;
std::string eTag_;
std::string lastModified_;
std::string storageClass_;
std::string type_;
int64_t size_;
bool isLatest_;
AlibabaCloud::OSS::Owner owner_;
};
using ObjectVersionSummaryList = std::vector<ObjectVersionSummary>;
class ALIBABACLOUD_OSS_EXPORT DeleteMarkerSummary
{
public:
DeleteMarkerSummary() = default;
const std::string& Key() const { return key_; }
const std::string& VersionId() const { return versionid_; }
const std::string& LastModified() const { return lastModified_; }
bool IsLatest() const { return isLatest_; }
const AlibabaCloud::OSS::Owner& Owner() const { return owner_; }
private:
friend class ListObjectVersionsResult;
std::string key_;
std::string versionid_;
std::string lastModified_;
bool isLatest_;
AlibabaCloud::OSS::Owner owner_;
};
using DeleteMarkerSummaryList = std::vector<DeleteMarkerSummary>;
class ALIBABACLOUD_OSS_EXPORT ListObjectVersionsResult : public OssResult
{
public:
ListObjectVersionsResult();
ListObjectVersionsResult(const std::string& data);
ListObjectVersionsResult(const std::shared_ptr<std::iostream>& data);
ListObjectVersionsResult& operator=(const std::string& data);
const std::string& Name() const { return name_; }
const std::string& Prefix() const { return prefix_; }
const std::string& KeyMarker() const { return keyMarker_; }
const std::string& NextKeyMarker() const { return nextKeyMarker_; }
const std::string& VersionIdMarker() const { return versionIdMarker_; }
const std::string& NextVersionIdMarker() const { return nextVersionIdMarker_; }
const std::string& Delimiter() const { return delimiter_; }
const std::string& EncodingType() const { return encodingType_; }
int MaxKeys() const { return maxKeys_; }
bool IsTruncated() const { return isTruncated_; }
const CommonPrefixeList& CommonPrefixes() const { return commonPrefixes_; }
const ObjectVersionSummaryList& ObjectVersionSummarys() const { return objectVersionSummarys_; }
const DeleteMarkerSummaryList& DeleteMarkerSummarys() const { return deleteMarkerSummarys_; }
private:
std::string name_;
std::string prefix_;
std::string keyMarker_;
std::string nextKeyMarker_;
std::string versionIdMarker_;
std::string nextVersionIdMarker_;
std::string delimiter_;
std::string encodingType_;
bool isTruncated_;
int maxKeys_;
CommonPrefixeList commonPrefixes_;
ObjectVersionSummaryList objectVersionSummarys_;
DeleteMarkerSummaryList deleteMarkerSummarys_;
};
}
}
| 1,835 |
2,706 | /* Copyright (c) 2013-2016 <NAME>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef GB_H
#define GB_H
#include <mgba-util/common.h>
CXX_GUARD_START
#include <mgba/core/cpu.h>
#include <mgba/core/interface.h>
#include <mgba/core/log.h>
#include <mgba/core/timing.h>
#include <mgba/internal/gb/audio.h>
#include <mgba/internal/gb/memory.h>
#include <mgba/internal/gb/sio.h>
#include <mgba/internal/gb/timer.h>
#include <mgba/internal/gb/video.h>
extern const uint32_t DMG_LR35902_FREQUENCY;
extern const uint32_t CGB_LR35902_FREQUENCY;
extern const uint32_t SGB_LR35902_FREQUENCY;
mLOG_DECLARE_CATEGORY(GB);
// TODO: Prefix GBAIRQ
enum GBIRQ {
GB_IRQ_VBLANK = 0x0,
GB_IRQ_LCDSTAT = 0x1,
GB_IRQ_TIMER = 0x2,
GB_IRQ_SIO = 0x3,
GB_IRQ_KEYPAD = 0x4,
};
enum GBIRQVector {
GB_VECTOR_VBLANK = 0x40,
GB_VECTOR_LCDSTAT = 0x48,
GB_VECTOR_TIMER = 0x50,
GB_VECTOR_SIO = 0x58,
GB_VECTOR_KEYPAD = 0x60,
};
enum GBSGBCommand {
SGB_PAL01 = 0,
SGB_PAL23,
SGB_PAL03,
SGB_PAL12,
SGB_ATTR_BLK,
SGB_ATTR_LIN,
SGB_ATTR_DIV,
SGB_ATTR_CHR,
SGB_SOUND,
SGB_SOU_TRN,
SGB_PAL_SET,
SGB_PAL_TRN,
SGB_ATRC_EN,
SGB_TEST_EN,
SGB_PICON_EN,
SGB_DATA_SND,
SGB_DATA_TRN,
SGB_MLT_REG,
SGB_JUMP,
SGB_CHR_TRN,
SGB_PCT_TRN,
SGB_ATTR_TRN,
SGB_ATTR_SET,
SGB_MASK_EN,
SGB_OBJ_TRN
};
struct LR35902Core;
struct mCoreSync;
struct mAVStream;
struct GB {
struct mCPUComponent d;
struct LR35902Core* cpu;
struct GBMemory memory;
struct GBVideo video;
struct GBTimer timer;
struct GBAudio audio;
struct GBSIO sio;
enum GBModel model;
struct mCoreSync* sync;
struct mTiming timing;
uint8_t* keySource;
bool isPristine;
size_t pristineRomSize;
size_t yankedRomSize;
uint32_t romCrc32;
struct VFile* romVf;
struct VFile* biosVf;
struct VFile* sramVf;
struct VFile* sramRealVf;
uint32_t sramSize;
int sramDirty;
int32_t sramDirtAge;
bool sramMaskWriteback;
int sgbBit;
int currentSgbBits;
uint8_t sgbPacket[16];
struct mCoreCallbacksList coreCallbacks;
struct mAVStream* stream;
bool cpuBlocked;
bool earlyExit;
struct mTimingEvent eiPending;
unsigned doubleSpeed;
};
struct GBCartridge {
uint8_t entry[4];
uint8_t logo[48];
union {
char titleLong[16];
struct {
char titleShort[11];
char maker[4];
uint8_t cgb;
};
};
char licensee[2];
uint8_t sgb;
uint8_t type;
uint8_t romSize;
uint8_t ramSize;
uint8_t region;
uint8_t oldLicensee;
uint8_t version;
uint8_t headerChecksum;
uint16_t globalChecksum;
// And ROM data...
};
void GBCreate(struct GB* gb);
void GBDestroy(struct GB* gb);
void GBReset(struct LR35902Core* cpu);
void GBSkipBIOS(struct GB* gb);
void GBUnmapBIOS(struct GB* gb);
void GBDetectModel(struct GB* gb);
void GBUpdateIRQs(struct GB* gb);
void GBHalt(struct LR35902Core* cpu);
struct VFile;
bool GBLoadROM(struct GB* gb, struct VFile* vf);
bool GBLoadSave(struct GB* gb, struct VFile* vf);
void GBUnloadROM(struct GB* gb);
void GBSynthesizeROM(struct VFile* vf);
bool GBIsBIOS(struct VFile* vf);
void GBLoadBIOS(struct GB* gb, struct VFile* vf);
void GBSramClean(struct GB* gb, uint32_t frameCount);
void GBResizeSram(struct GB* gb, size_t size);
void GBSavedataMask(struct GB* gb, struct VFile* vf, bool writeback);
void GBSavedataUnmask(struct GB* gb);
struct Patch;
void GBApplyPatch(struct GB* gb, struct Patch* patch);
bool GBIsROM(struct VFile* vf);
void GBGetGameTitle(const struct GB* gba, char* out);
void GBGetGameCode(const struct GB* gba, char* out);
void GBTestKeypadIRQ(struct GB* gb);
void GBFrameEnded(struct GB* gb);
CXX_GUARD_END
#endif
| 1,687 |
4,054 | <reponame>Anlon-Burke/vespa
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server;
import com.yahoo.vespa.config.ConfigCacheKey;
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.PayloadChecksums;
import com.yahoo.vespa.config.buildergen.ConfigDefinition;
import com.yahoo.vespa.config.protocol.ConfigResponse;
import com.yahoo.vespa.config.protocol.SlimeConfigResponse;
import org.junit.Before;
import org.junit.Test;
import static com.yahoo.vespa.config.PayloadChecksum.Type.XXHASH64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* @author <NAME>
*/
public class ServerCacheTest {
private ServerCache cache;
private static final String defMd5 = "595f44fec1e92a71d3e9e77456ba80d1";
private static final String defMd5_2 = "a2f8edfc965802bf6d44826f9da7e2b0";
private static final String xxhash64 = "595f44fec1e92a71d";
private static final String xxhash64_2 = "a2f8edfc965802bf6";
private static final ConfigDefinition def = new ConfigDefinition("mypayload", new String[0]);
private static final ConfigDefinitionKey fooBarDefKey = new ConfigDefinitionKey("foo", "bar");
private static final ConfigDefinitionKey fooBazDefKey = new ConfigDefinitionKey("foo", "baz");
private static final ConfigDefinitionKey fooBimDefKey = new ConfigDefinitionKey("foo", "bim");
private static final ConfigKey<?> fooConfigKey = new ConfigKey<>("foo", "id", "bar");
private static final ConfigKey<?> bazConfigKey = new ConfigKey<>("foo", "id2", "bar");
private final ConfigCacheKey fooBarCacheKey = new ConfigCacheKey(fooConfigKey, defMd5);
private final ConfigCacheKey bazQuuxCacheKey = new ConfigCacheKey(bazConfigKey, defMd5);
private final ConfigCacheKey fooBarCacheKeyDifferentMd5 = new ConfigCacheKey(fooConfigKey, defMd5_2);
@Before
public void setup() {
UserConfigDefinitionRepo userConfigDefinitionRepo = new UserConfigDefinitionRepo();
userConfigDefinitionRepo.add(fooBarDefKey, def);
userConfigDefinitionRepo.add(fooBazDefKey, new com.yahoo.vespa.config.buildergen.ConfigDefinition("baz", new String[0]));
userConfigDefinitionRepo.add(fooBimDefKey, new ConfigDefinition("mynode", new String[0]));
cache = new ServerCache(new TestConfigDefinitionRepo(), userConfigDefinitionRepo);
cache.computeIfAbsent(fooBarCacheKey, (ConfigCacheKey key) -> createResponse(xxhash64));
cache.computeIfAbsent(bazQuuxCacheKey, (ConfigCacheKey key) -> createResponse(xxhash64));
cache.computeIfAbsent(fooBarCacheKeyDifferentMd5, (ConfigCacheKey key) -> createResponse(xxhash64_2));
}
@Test
public void testThatCacheWorks() {
assertNotNull(cache.getDef(fooBazDefKey));
assertEquals(def, cache.getDef(fooBarDefKey));
assertEquals("mynode", cache.getDef(fooBimDefKey).getCNode().getName());
ConfigResponse raw = cache.get(fooBarCacheKey);
assertEquals(xxhash64, raw.getPayloadChecksums().getForType(XXHASH64).asString());
}
@Test
public void testThatCacheWorksWithSameKeyDifferentMd5() {
assertEquals(def, cache.getDef(fooBarDefKey));
ConfigResponse raw = cache.get(fooBarCacheKey);
assertEquals(xxhash64, raw.getPayloadChecksums().getForType(XXHASH64).asString());
raw = cache.get(fooBarCacheKeyDifferentMd5);
assertEquals(xxhash64_2, raw.getPayloadChecksums().getForType(XXHASH64).asString());
}
@Test
public void testThatCacheWorksWithDifferentKeySameMd5() {
assertSame(cache.get(fooBarCacheKey), cache.get(bazQuuxCacheKey));
}
SlimeConfigResponse createResponse(String xxhash64) {
return SlimeConfigResponse.fromConfigPayload(ConfigPayload.empty(), 2, false,
PayloadChecksums.from("", xxhash64));
}
}
| 1,486 |
369 | #!/usr/bin/python
# coding: UTF-8
import sys
from itertools import product
from multiprocessing.dummy import Pool as ThreadPool
import util.fuzz as fuzz
from util import cmd, pprint, execute
from const import PARSERS, REQUESTERS
DEBUG = 'debug' in sys.argv
INS_COUNT = [0, 3, 0]
WHITELIST = ['127.0.0.1', '127.1.1.1', '127.2.2.2', '127.1.1.1\n127.2.2.2']
CHARSETS = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0cA01\x00'
FORMAT = 'http://%s127.1.1.1%s127.2.2.2%s' % ('%c'*INS_COUNT[0], '%c'*INS_COUNT[1], '%c'*INS_COUNT[2])
def _print(msg):
sys.stdout.write("%s\n" % msg)
def run_parser(url):
res = {}
for key, binary in PARSERS.iteritems():
lang, libname = key.split('.', 1)
r = execute(lang, binary, url, base='bin/parser/')
# parse host, change here to get the result you want
if 'host=' in r and 'port=' in r:
res[key] = r.split('host=')[-1].split(', ')[0]
else:
res[key] = 'err'
return res
def run_requester(url):
res = {}
for key, binary in REQUESTERS.iteritems():
lang, libname = key.split('.', 1)
r = execute(lang, binary, url, base='bin/requester/')
res[key] = r
return res
def run(random_data):
url = FORMAT % random_data
url = url + '/' + (''.join(random_data).encode('hex'))
url = url.replace('\x00', '%00')
urls = run_parser(url)
gets = run_requester(url)
total_urls = {}
for k,v in urls.iteritems():
# filter
if v not in WHITELIST:
continue
if total_urls.get(v):
total_urls[v].append(k)
else:
total_urls[v] = [k]
if len(total_urls) > 1:
msg = 'parsed url = %s\n' % url
for k, v in sorted(total_urls.iteritems(), key=lambda x: len(x[1]), reverse=True):
msg += '%-16s %d = %s\n'%(k, len(v), repr(v))
_print(msg)
total_gets = {}
for k, v in gets.iteritems():
v = v.split('/')[0]
# filter
if v == 'err':
continue
if total_gets.get(v):
total_gets[v].append(k)
else:
total_gets[v] = [k]
if len(total_gets) > 1:
msg = 'got url = %s\n'%url
for k, v in sorted(total_gets.iteritems(), key=lambda x: len(x[1]), reverse=True):
msg += '%-24s %d = %s\n'%(k, len(v), repr(v))
_print(msg)
data_set = product(list(CHARSETS), repeat=sum(INS_COUNT))
if DEBUG:
for i in data_set: run(i)
else:
pool = ThreadPool( 32 )
result = pool.map_async( run, data_set ).get(0xfffff)
| 1,293 |
3,145 | //
// BuiltInConversionsModel.h
// JSONModelDemo
//
// Created by <NAME> on 02/12/2012.
// Copyright (c) 2012 Underplot ltd. All rights reserved.
//
@import JSONModel;
@interface BuiltInConversionsModel : JSONModel
/* BOOL automatically converted from a number */
@property (assign, nonatomic) BOOL isItYesOrNo;
@property (assign, nonatomic) BOOL boolFromString;
@property (assign, nonatomic) BOOL boolFromNumber;
@property (assign, nonatomic) BOOL boolFromBoolean;
@property (strong, nonatomic) NSSet* unorderedList;
@property (strong, nonatomic) NSMutableSet* dynamicUnorderedList;
/* automatically convert JSON data types */
@property (strong, nonatomic) NSString* stringFromNumber;
@property (strong, nonatomic) NSNumber* numberFromString;
@property (strong, nonatomic) NSNumber* doubleFromString;
@property (strong, nonatomic) NSDate* importantEvent;
@property (strong, nonatomic) NSURL* websiteURL;
@property (strong, nonatomic) NSTimeZone *timeZone;
@property (strong, nonatomic) NSArray* stringArray;
@end
| 315 |
1,001 | # Copyright 2019 Alibaba Cloud Inc. 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.
import os
import unittest
from aliyunsdkcore.http.http_response import HttpResponse
class VerifyTest(unittest.TestCase):
def test_response_set_path(self):
response = HttpResponse(verify=False)
os.environ["ALIBABA_CLOUD_CA_BUNDLE"] = '/path/cacerts.pem'
self.assertEqual(response.get_verify_value(), False)
response = HttpResponse(verify=True)
os.environ["ALIBABA_CLOUD_CA_BUNDLE"] = '/path/cacerts.pem'
self.assertEqual(response.get_verify_value(), True)
response = HttpResponse(verify=None)
os.environ["ALIBABA_CLOUD_CA_BUNDLE"] = '/path/cacerts.pem'
self.assertEqual(response.get_verify_value(), '/path/cacerts.pem')
response = HttpResponse(verify='/path/cacerts1.pem')
os.environ["ALIBABA_CLOUD_CA_BUNDLE"] = '/path/cacerts.pem'
self.assertEqual(response.get_verify_value(), '/path/cacerts1.pem')
os.environ.pop("ALIBABA_CLOUD_CA_BUNDLE", None)
response = HttpResponse()
self.assertEqual(response.get_verify_value(), True)
os.environ["ALIBABA_CLOUD_CA_BUNDLE"] = '/path/cacerts.pem'
response = HttpResponse()
self.assertEqual(response.get_verify_value(), '/path/cacerts.pem')
os.environ.pop("ALIBABA_CLOUD_CA_BUNDLE", None)
if __name__ == '__main__':
unittest.main()
| 791 |
1,542 | <reponame>uaomer/psdash
from psdash.run import main
main()
| 24 |
2,338 | #ifndef CONTAINERS_H
#define CONTAINERS_H
namespace std {
template <typename T>
class iterator {
public:
iterator() {}
iterator(const iterator<T> &iter) : ptr(iter.ptr) {}
typedef T value_type;
typedef T *pointer;
typedef T &reference;
reference operator*() const { return *ptr; }
pointer operator->() const { return ptr; }
iterator &operator++() {
++ptr;
return *this;
}
iterator &operator--() {
--ptr;
return *this;
}
iterator operator++(int) {
iterator res(*this);
++ptr;
return res;
}
iterator operator--(int) {
iterator res(*this);
--ptr;
return res;
}
bool operator!=(const iterator<T> &iter) const {
return ptr != iter.operator->();
}
private:
T *ptr;
};
template <class Iterator>
class const_iterator {
public:
const_iterator() {}
const_iterator(const Iterator &iter) : iter(iter) {}
const_iterator(const const_iterator<Iterator> &citer) : iter(citer.iter) {}
typedef const typename Iterator::value_type value_type;
typedef const typename Iterator::pointer pointer;
typedef const typename Iterator::reference reference;
reference operator*() const { return *iter; }
pointer operator->() const { return iter.operator->(); }
const_iterator &operator++() { return ++iter; }
const_iterator &operator--() { return --iter; }
const_iterator operator++(int) { return iter--; }
const_iterator operator--(int) { return iter--; }
bool operator!=(const Iterator &it) const {
return iter->operator->() != it.operator->();
}
bool operator!=(const const_iterator<Iterator> &it) const {
return iter.operator->() != it.operator->();
}
private:
Iterator iter;
};
template <class Iterator>
class forward_iterable {
public:
forward_iterable() {}
typedef Iterator iterator;
typedef const_iterator<Iterator> const_iterator;
iterator begin() { return _begin; }
iterator end() { return _end; }
const_iterator begin() const { return _begin; }
const_iterator end() const { return _end; }
const_iterator cbegin() const { return _begin; }
const_iterator cend() const { return _end; }
private:
iterator _begin, _end;
};
template <class Iterator>
class reverse_iterator {
public:
reverse_iterator() {}
reverse_iterator(const Iterator &iter) : iter(iter) {}
reverse_iterator(const reverse_iterator<Iterator> &rit) : iter(rit.iter) {}
typedef typename Iterator::value_type value_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
reference operator*() { return *iter; }
pointer operator->() { return iter.operator->(); }
reverse_iterator &operator++() { return --iter; }
reverse_iterator &operator--() { return ++iter; }
reverse_iterator operator++(int) { return iter--; }
reverse_iterator operator--(int) { return iter++; }
private:
Iterator iter;
};
template <class Iterator>
class backward_iterable {
public:
backward_iterable() {}
typedef reverse_iterator<Iterator> reverse_iterator;
typedef const_iterator<reverse_iterator> const_reverse_iterator;
reverse_iterator rbegin() { return _rbegin; }
reverse_iterator rend() { return _rend; }
const_reverse_iterator rbegin() const { return _rbegin; }
const_reverse_iterator rend() const { return _rend; }
const_reverse_iterator crbegin() const { return _rbegin; }
const_reverse_iterator crend() const { return _rend; }
private:
reverse_iterator _rbegin, _rend;
};
template <class Iterator>
class bidirectional_iterable : public forward_iterable<Iterator>,
public backward_iterable<Iterator> {};
template <typename A, typename B>
struct pair {
pair(A f, B s) : first(f), second(s) {}
A first;
B second;
};
class string {
public:
string() {}
string(const char *) {}
};
template <typename T, int n>
class array : public backward_iterable<iterator<T>> {
public:
array() {}
typedef T *iterator;
typedef const T *const_iterator;
iterator begin() { return &v[0]; }
iterator end() { return &v[n - 1]; }
const_iterator begin() const { return &v[0]; }
const_iterator end() const { return &v[n - 1]; }
const_iterator cbegin() const { return &v[0]; }
const_iterator cend() const { return &v[n - 1]; }
private:
T v[n];
};
template <typename T>
class deque : public bidirectional_iterable<iterator<T>> {
public:
deque() {}
};
template <typename T>
class list : public bidirectional_iterable<iterator<T>> {
public:
list() {}
};
template <typename T>
class forward_list : public forward_iterable<iterator<T>> {
public:
forward_list() {}
};
template <typename T>
class vector : public bidirectional_iterable<iterator<T>> {
public:
vector() {}
};
template <typename T>
class set : public bidirectional_iterable<iterator<T>> {
public:
set() {}
};
template <typename T>
class multiset : public bidirectional_iterable<iterator<T>> {
public:
multiset() {}
};
template <typename key, typename value>
class map : public bidirectional_iterable<iterator<pair<key, value>>> {
public:
map() {}
iterator<pair<key, value>> find(const key &) {}
const_iterator<iterator<pair<key, value>>> find(const key &) const {}
};
template <typename key, typename value>
class multimap : public bidirectional_iterable<iterator<pair<key, value>>> {
public:
multimap() {}
};
template <typename T>
class unordered_set : public forward_iterable<iterator<T>> {
public:
unordered_set() {}
};
template <typename T>
class unordered_multiset : public forward_iterable<iterator<T>> {
public:
unordered_multiset() {}
};
template <typename key, typename value>
class unordered_map : public forward_iterable<iterator<pair<key, value>>> {
public:
unordered_map() {}
};
template <typename key, typename value>
class unordered_multimap : public forward_iterable<iterator<pair<key, value>>> {
public:
unordered_multimap() {}
};
} // namespace std
#endif // CONTAINERS_H
| 1,940 |
403 | #include <gtest/gtest.h>
#include <rv/ParameterListIterator.h>
#include <rv/PrimitiveParameters.h>
#include <rv/CompositeParameter.h>
#include <rv/RangeParameter.h>
using namespace rv;
namespace
{
}
class ParameterListIteratorTest: public ::testing::Test
{
};
//void ParameterListIteratorTestCase::testCopy()
//{
// ParameterList params1;
// params1.insert(IntegerParameter("foo", 1337));
// params1.insert(StringParameter("bar", "bla"));
// ParameterList rlist;
// rlist.insert(IntegerParameter("value0", 1));
// rlist.insert(IntegerParameter("value1", 3));
// rlist.insert(IntegerParameter("value2", 3));
// rlist.insert(IntegerParameter("value3", 7));
// RangeParameter rparam("range", rlist);
// params1.insert(rparam);
//
// ParameterListIterator it(params1);
// it.next();
// it.next();
//
// /** now testing the copy actions. **/
// ParameterListIterator it2(it);
// ParameterListIterator it3(params1);
// it3 = it;
//
// ASSERT_TRUE(it.hasNext());
// ASSERT_EQ(it.hasNext(), it2.hasNext());
// ASSERT_EQ(it.hasNext(), it3.hasNext());
//
// const ParameterList& goldparams = it.next();
// const ParameterList& testparams1 = it2.next();
// const ParameterList& testparams2 = it3.next();
//
// ASSERT_TRUE((goldparams == testparams1));
// ASSERT_TRUE((goldparams == testparams2));
//
//}
TEST_F(ParameterListIteratorTest, testIterate)
{
{
ParameterList params1;
params1.insert(IntegerParameter("foo", 1337));
params1.insert(StringParameter("bar", "bla"));
ParameterListIterator it(params1);
ASSERT_TRUE(it.hasNext());
const ParameterList& params = it.next();
ASSERT_FALSE(it.hasNext());
ASSERT_TRUE(params.hasParam("foo"));
ASSERT_TRUE(params.hasParam("bar"));
ASSERT_EQ(1337, params.getValue<int>("foo"));
ASSERT_EQ("bla", params.getValue<std::string>("bar"));
}
{
ParameterList params1;
params1.insert(IntegerParameter("foo", 1337));
params1.insert(StringParameter("bar", "bla"));
ParameterList rlist;
rlist.insert(IntegerParameter("value0", 1));
rlist.insert(IntegerParameter("value1", 3));
rlist.insert(IntegerParameter("value2", 3));
rlist.insert(IntegerParameter("value3", 7));
RangeParameter rparam("range", rlist);
params1.insert(rparam);
ParameterListIterator it(params1);
double values[] =
{ 1, 3, 3, 7 };
for (uint32_t i = 0; i < 4; ++i)
{
ASSERT_TRUE(it.hasNext());
const ParameterList& params = it.next();
ASSERT_TRUE(params.hasParam("foo"));
ASSERT_TRUE(params.hasParam("bar"));
ASSERT_TRUE(params.hasParam("range"));
ASSERT_EQ(1337, params.getValue<int>("foo"));
ASSERT_EQ("bla", params.getValue<std::string>("bar"));
ASSERT_EQ(values[i], params.getValue<int>("range"));
}
ASSERT_FALSE(it.hasNext());
}
{
ParameterList params1;
params1.insert(IntegerParameter("foo", 1337));
params1.insert(StringParameter("bar", "bla"));
ParameterList range;
range.insert(IntegerParameter("value0", 1));
range.insert(IntegerParameter("value1", 3));
RangeParameter rparam("range1", range);
params1.insert(rparam);
range.insert(IntegerParameter("value0", 4));
range.insert(IntegerParameter("value1", 7));
RangeParameter rparam2("range2", range);
ParameterList cparam_list;
cparam_list.insert(FloatParameter("foo", 1.337));
cparam_list.insert(rparam2);
CompositeParameter cparam("comp", cparam_list);
params1.insert(cparam);
// std::cout << "----------------------------" << std::endl;
// for (ParameterList::const_iterator it = params1.begin(); it != params1.end(); ++it)
// std::cout << *it << std::endl;
ParameterListIterator it(params1);
double values1[] =
{ 1, 1, 3, 3 };
double values2[] =
{ 4, 7, 4, 7 };
for (uint32_t i = 0; i < 4; ++i)
{
ASSERT_TRUE(it.hasNext());
const ParameterList& params = it.next();
// std::cout << "number of parameters = " << params.size() << std::endl;
// for (ParameterList::const_iterator it = params.begin(); it != params.end(); ++it)
// std::cout << *it << std::endl;
ASSERT_TRUE(params.hasParam("foo"));
ASSERT_TRUE(params.hasParam("bar"));
ASSERT_TRUE(params.hasParam("range1"));
ASSERT_TRUE(params.hasParam("comp"));
ASSERT_EQ(1337, params.getValue<int>("foo"));
ASSERT_EQ("bla", params.getValue<std::string>("bar"));
ASSERT_EQ(values1[i], params.getValue<int>("range1"));
const CompositeParameter* cparam1 = params.getParameter<CompositeParameter>("comp");
const ParameterList& clist = cparam1->getParams();
ASSERT_TRUE(clist.hasParam("foo"));
ASSERT_TRUE(clist.hasParam("range2"));
ASSERT_NEAR(1.337, clist.getValue<double>("foo"), 0.0001);
ASSERT_EQ(values2[i], clist.getValue<int>("range2"));
}
ASSERT_FALSE(it.hasNext());
}
/** now testing with some filter. **/
{
ParameterList params1;
params1.insert(IntegerParameter("foo", 1337));
params1.insert(StringParameter("bar", "bla"));
ParameterList rlist;
rlist.insert(IntegerParameter("value0", 1));
rlist.insert(IntegerParameter("value1", 3));
rlist.insert(IntegerParameter("value2", 3));
rlist.insert(IntegerParameter("value3", 7));
RangeParameter rparam("range", rlist);
params1.insert(rparam);
ParameterList rlist2;
rlist2.insert(IntegerParameter("value0", 10));
rlist2.insert(IntegerParameter("value1", 11));
rlist2.insert(IntegerParameter("value2", 12));
RangeParameter rparam2("another-range", rlist2);
params1.insert(rparam2);
std::vector<std::string> filtered_names;
filtered_names.push_back("range");
ParameterListIterator it(params1, filtered_names);
double values[] =
{ 1, 3, 3, 7 };
for (uint32_t i = 0; i < 4; ++i)
{
ASSERT_TRUE(it.hasNext());
const ParameterList& params = it.next();
// std::cout << " ===== current params ==== " << std::endl;
// for (ParameterList::const_iterator pit = params.begin(); pit != params.end(); ++pit)
// std::cout << *pit << std::endl;
ASSERT_TRUE(params.hasParam("foo"));
ASSERT_TRUE(params.hasParam("bar"));
ASSERT_TRUE(params.hasParam("range"));
ASSERT_TRUE(params.hasParam("another-range"));
ASSERT_EQ(1337, params.getValue<int>("foo"));
ASSERT_EQ("bla", params.getValue<std::string>("bar"));
ASSERT_EQ(values[i], params.getValue<int>("range"));
ASSERT_EQ("range", params["another-range"].type());
ParameterListIterator it2(params);
int values2[] =
{ 10, 11, 12 };
for (uint32_t j = 0; j < 3; ++j)
{
ASSERT_TRUE(it2.hasNext());
const ParameterList& params2 = it2.next();
ASSERT_TRUE(params2.hasParam("foo"));
ASSERT_TRUE(params2.hasParam("bar"));
ASSERT_TRUE(params2.hasParam("range"));
ASSERT_TRUE(params2.hasParam("another-range"));
ASSERT_EQ(1337, params2.getValue<int>("foo"));
ASSERT_EQ("bla", params2.getValue<std::string>("bar"));
ASSERT_EQ(values[i], params2.getValue<int>("range"));
ASSERT_EQ(values2[j], params2.getValue<int>("another-range"));
}
ASSERT_FALSE(it2.hasNext());
}
ASSERT_FALSE(it.hasNext());
}
}
| 2,979 |
590 | <filename>MyGUIEngine/include/MyGUI_ScrollBar.h
/*
* This source file is part of MyGUI. For the latest info, see http://mygui.info/
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#ifndef MYGUI_SCROLL_BAR_H_
#define MYGUI_SCROLL_BAR_H_
#include "MyGUI_Prerequest.h"
#include "MyGUI_Widget.h"
namespace MyGUI
{
class ControllerItem;
typedef delegates::CMultiDelegate2<ScrollBar*, size_t> EventHandle_ScrollBarPtrSizeT;
/** \brief @wpage{ScrollBar}
ScrollBar widget description should be here.
*/
class MYGUI_EXPORT ScrollBar :
public Widget,
public MemberObsolete<ScrollBar>
{
MYGUI_RTTI_DERIVED( ScrollBar )
public:
ScrollBar();
/** Set vertical alignment grid mode */
void setVerticalAlignment(bool _value);
/** Get vertical alignment grid mode flag */
bool getVerticalAlignment() const;
/** Set scroll range */
void setScrollRange(size_t _value);
/** Get scroll range */
size_t getScrollRange() const;
/** Set scroll position (value from 0 to range - 1) */
void setScrollPosition(size_t _value);
/** Get scroll position (value from 0 to range - 1) */
size_t getScrollPosition() const;
/** Set scroll page
@param _value Tracker step when buttons pressed
*/
void setScrollPage(size_t _value);
/** Get scroll page */
size_t getScrollPage() const;
/** Set scroll view page
@param _value Tracker step when pressed on scroll line
*/
void setScrollViewPage(size_t _value);
/** Get scroll view page */
size_t getScrollViewPage() const;
/** Set scroll view page
@param _value Tracker step when mouse wheel scrolled
*/
void setScrollWheelPage(size_t _value);
/** Get scroll view page */
size_t getScrollWheelPage() const;
/** Get size in pixels of area where scroll moves */
int getLineSize() const;
/** Set size of track in pixels
@param _value in pixels, if less than MinTrackSize, MinTrackSize used
*/
void setTrackSize(int _value);
/** Get size of track in pixels */
int getTrackSize() const;
/** Set minimal track size (used for setTrackSize)*/
void setMinTrackSize(int _value);
/** Get minimal track size */
int getMinTrackSize() const;
/** Enable or disable move to click mode.\n
Move to click mode: Tracker moves to cursor when pressed on scroll line.\n
Disabled (false) by default.
*/
void setMoveToClick(bool _value);
/** Get move to click mode flag */
bool getMoveToClick() const;
/** Set whether clicks on scrollbar buttons should be repeated at set intervals
as long as the mouse button is pressed down. Enabled (true) by default.
*/
void setRepeatEnabled(bool enabled);
/** Get whether Repeat mode is enabled
@see setRepeatEnabled
*/
bool getRepeatEnabled() const;
/** Set time that buttons need to be pressed down to start repeating. */
void setRepeatTriggerTime(float time);
/** Get time that buttons need to be pressed down to start repeating. */
float getRepeatTriggerTime(float time) const;
/** Set how much time between scrollbar button repeats. */
void setRepeatStepTime(float time);
/** Get how much time between scrollbar button repeats. */
float getRepeatStepTime(float time) const;
//! @copydoc Widget::setPosition(const IntPoint& _value)
void setPosition(const IntPoint& _value) override;
//! @copydoc Widget::setSize(const IntSize& _value)
void setSize(const IntSize& _value) override;
//! @copydoc Widget::setCoord(const IntCoord& _value)
void setCoord(const IntCoord& _value) override;
using Widget::setPosition;
using Widget::setSize;
using Widget::setCoord;
/*events:*/
/** Event : scroll tracker position changed.\n
signature : void method(MyGUI::ScrollBar* _sender, size_t _position)\n
@param _sender widget that called this event
@param _position - new tracker position
*/
EventHandle_ScrollBarPtrSizeT eventScrollChangePosition;
protected:
void initialiseOverride() override;
void shutdownOverride() override;
void updateTrack();
void TrackMove(int _left, int _top);
void onMouseWheel(int _rel) override;
void notifyMousePressed(Widget* _sender, int _left, int _top, MouseButton _id);
void notifyMouseReleased(Widget* _sender, int _left, int _top, MouseButton _id);
void notifyMouseDrag(Widget* _sender, int _left, int _top, MouseButton _id);
void notifyMouseWheel(Widget* _sender, int _rel);
void setPropertyOverride(const std::string& _key, const std::string& _value) override;
int getTrackPlaceLength() const;
private:
void repeatClick(MyGUI::Widget* _widget, MyGUI::ControllerItem* _controller);
void widgetStartPressed();
void widgetEndPressed();
void widgetFirstPartPressed();
void widgetSecondPartPressed();
protected:
// наши кнопки
Button* mWidgetStart;
Button* mWidgetEnd;
Button* mWidgetTrack;
// куски между кнопками
Widget* mWidgetFirstPart;
Widget* mWidgetSecondPart;
// смещение внутри окна
IntPoint mPreActionOffset;
// диапазон на который трек может двигаться
size_t mSkinRangeStart;
size_t mSkinRangeEnd;
size_t mScrollRange;
size_t mScrollPosition;
size_t mScrollPage; // track step, when clicking buttons
size_t mScrollViewPage; // track step, when clicking scroll line
size_t mScrollWheelPage; // track step, when scrolling with mouse wheel
bool mEnableRepeat; // Repeat clicks on the scrollbar buttons when the mouse button remains pressed down
float mRepeatTriggerTime; // Time the mouse button needs to be held for repeating to start
float mRepeatStepTime; // Time between repeats
int mMinTrackSize;
bool mMoveToClick;
bool mVerticalAlignment;
};
} // namespace MyGUI
#endif // MYGUI_SCROLL_BAR_H_
| 1,939 |
488 | <gh_stars>100-1000
#include "main.h"
extern "C"
{
EXPORT btVehicleRaycaster_btVehicleRaycasterResult* btVehicleRaycaster_btVehicleRaycasterResult_new();
EXPORT btScalar btVehicleRaycaster_btVehicleRaycasterResult_getDistFraction(btVehicleRaycaster_btVehicleRaycasterResult* obj);
EXPORT void btVehicleRaycaster_btVehicleRaycasterResult_getHitNormalInWorld(btVehicleRaycaster_btVehicleRaycasterResult* obj, btScalar* value);
EXPORT void btVehicleRaycaster_btVehicleRaycasterResult_getHitPointInWorld(btVehicleRaycaster_btVehicleRaycasterResult* obj, btScalar* value);
EXPORT void btVehicleRaycaster_btVehicleRaycasterResult_setDistFraction(btVehicleRaycaster_btVehicleRaycasterResult* obj, btScalar value);
EXPORT void btVehicleRaycaster_btVehicleRaycasterResult_setHitNormalInWorld(btVehicleRaycaster_btVehicleRaycasterResult* obj, const btScalar* value);
EXPORT void btVehicleRaycaster_btVehicleRaycasterResult_setHitPointInWorld(btVehicleRaycaster_btVehicleRaycasterResult* obj, const btScalar* value);
EXPORT void btVehicleRaycaster_btVehicleRaycasterResult_delete(btVehicleRaycaster_btVehicleRaycasterResult* obj);
EXPORT void* btVehicleRaycaster_castRay(btVehicleRaycaster* obj, const btScalar* from, const btScalar* to, btVehicleRaycaster_btVehicleRaycasterResult* result);
EXPORT void btVehicleRaycaster_delete(btVehicleRaycaster* obj);
}
| 461 |
370 | /*
* Copyright (C) 2015-2019 Dubalu LLC
* Copyright (C) 2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019 <NAME>
* Copyright (C) 2006,2007,2009,2010 Lemur Consulting Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "remote_protocol_client.h"
#ifdef XAPIAND_CLUSTERING
#include <cassert> // for assert
#include <errno.h> // for errno
#include <fcntl.h>
#include <limits.h> // for PATH_MAX
#include <sys/socket.h>
#include <sys/stat.h>
#include <sysexits.h>
#include <unistd.h>
#include "aggregations/aggregations.h" // for AggregationMatchSpy
#include "database/flags.h" // for DB_*
#include "database/lock.h" // for lock_shard
#include "database/shard.h" // for Shard
#include "error.hh" // for error:name, error::description
#include "fs.hh" // for delete_files, build_path_index
#include "io.hh" // for io::*
#include "lru.h" // for lru::aging_lru
#include "manager.h" // for XapiandManager
#include "metrics.h" // for Metrics::metrics
#include "repr.hh" // for repr
#include "utype.hh" // for toUType
#include "multivalue/geospatialrange.h" // for GeoSpatialRange
#include "multivalue/range.h" // for MultipleValueRange, MultipleValueGE, MultipleValueLE
#include "multivalue/keymaker.h" // for Multi_MultiValueKeyMaker
#include "server/remote_protocol_client.h" // for RemoteProtocolClient
#include "xapian/common/pack.h" // for pack_* unpack_*
#include "xapian/common/serialise-double.h" // for unserialise_double
#include "xapian/net/serialise-error.h" // for serialise_error
// #undef L_DEBUG
// #define L_DEBUG L_GREY
// #undef L_CALL
// #define L_CALL L_STACKED_DIM_GREY
// #undef L_REPLICATION
// #define L_REPLICATION L_RED
// #undef L_CONN
// #define L_CONN L_GREEN
// #undef L_BINARY_WIRE
// #define L_BINARY_WIRE L_ORANGE
// #undef L_BINARY
// #define L_BINARY L_TEAL
// #undef L_BINARY_PROTO
// #define L_BINARY_PROTO L_TEAL
// #undef L_OBJ_BEGIN
// #define L_OBJ_BEGIN L_DELAYED_600
// #undef L_OBJ_END
// #define L_OBJ_END L_DELAYED_N_UNLOG
static inline std::string::size_type common_prefix_length(const std::string &a, const std::string &b) {
std::string::size_type minlen = std::min(a.size(), b.size());
std::string::size_type common;
for (common = 0; common < minlen; ++common) {
if (a[common] != b[common]) break;
}
return common;
}
/* ____ _ ____ _ _
* | _ \ ___ _ __ ___ ___ | |_ ___| _ \ _ __ ___ | |_ ___ ___ ___ | |
* | |_) / _ \ '_ ` _ \ / _ \| __/ _ \ |_) | '__/ _ \| __/ _ \ / __/ _ \| |
* | _ < __/ | | | | | (_) | || __/ __/| | | (_) | || (_) | (_| (_) | |
* |_| \_\___|_| |_| |_|\___/ \__\___|_| |_| \___/ \__\___/ \___\___/|_|
*
* Based on xapian/xapian-core/net/remoteserver.cc @ db790e9e1<PASSWORD>ebeaf<PASSWORD>
*/
static std::mutex pending_queries_mtx;
static lru::aging_lru<std::string, RemoteProtocolPendingQuery> pending_queries(0, 600s);
RemoteProtocolClient::RemoteProtocolClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_, double /*active_timeout_*/, double /*idle_timeout_*/, bool cluster_database_)
: BaseClient<RemoteProtocolClient>(std::move(parent_), ev_loop_, ev_flags_),
flags(0),
state(RemoteState::INIT_REMOTE),
#ifdef SAVE_LAST_MESSAGES
last_message_received('\xff'),
last_message_sent('\xff'),
#endif
file_descriptor(-1),
file_message_type('\xff'),
temp_file_template("xapiand.XXXXXX"),
cluster_database(cluster_database_)
{
auto manager = XapiandManager::manager();
if (manager) {
++manager->remote_clients;
}
Metrics::metrics()
.xapiand_remote_connections
.Increment();
registry.register_posting_source(GeoSpatialRange{});
registry.register_posting_source(MultipleValueRange{});
registry.register_posting_source(MultipleValueGE{});
registry.register_posting_source(MultipleValueLE{});
registry.register_match_spy(AggregationMatchSpy{});
registry.register_key_maker(Multi_MultiValueKeyMaker{});
L_CONN("New Remote Protocol Client, {} client(s) of a total of {} connected.", manager ? manager->remote_clients.load() : 0, manager ? manager->total_clients.load() : 0);
}
RemoteProtocolClient::~RemoteProtocolClient() noexcept
{
try {
if (auto manager = XapiandManager::manager()) {
if (manager->remote_clients.fetch_sub(1) == 0) {
L_CRIT("Inconsistency in number of binary clients");
sig_exit(-EX_SOFTWARE);
}
}
if (file_descriptor != -1) {
io::close(file_descriptor);
file_descriptor = -1;
}
for (const auto& filename : temp_files) {
io::unlink(filename.c_str());
}
if (!temp_directory.empty()) {
delete_files(temp_directory.c_str());
}
if (is_shutting_down() && !is_idle()) {
L_INFO("Remote Protocol client killed!");
}
if (cluster_database) {
L_CRIT("Cannot synchronize cluster database!");
sig_exit(-EX_CANTCREAT);
}
} catch (...) {
L_EXC("Unhandled exception in destructor");
}
}
void
RemoteProtocolClient::send_message(RemoteReplyType type, const std::string& message)
{
L_CALL("RemoteProtocolClient::send_message({}, <message>)", enum_name(type));
L_BINARY_PROTO("<< send_message ({}): {}", enum_name(type), repr(message));
send_message(toUType(type), message);
}
void
RemoteProtocolClient::remote_server(RemoteMessageType type, const std::string &message)
{
L_CALL("RemoteProtocolClient::remote_server({}, <message>)", enum_name(type));
L_OBJ_BEGIN("RemoteProtocolClient::remote_server:BEGIN {{type:{}}}", enum_name(type));
L_OBJ_END("RemoteProtocolClient::remote_server:END {{type:{}}}", enum_name(type));
L_DEBUG("{} ({}) -> {}", enum_name(type), strings::from_bytes(message.size()), repr(endpoint.to_string()));
try {
switch (type) {
case RemoteMessageType::MSG_ALLTERMS:
msg_allterms(message);
return;
case RemoteMessageType::MSG_COLLFREQ:
msg_collfreq(message);
return;
case RemoteMessageType::MSG_DOCUMENT:
msg_document(message);
return;
case RemoteMessageType::MSG_TERMEXISTS:
msg_termexists(message);
return;
case RemoteMessageType::MSG_TERMFREQ:
msg_termfreq(message);
return;
case RemoteMessageType::MSG_VALUESTATS:
msg_valuestats(message);
return;
case RemoteMessageType::MSG_KEEPALIVE:
msg_keepalive(message);
return;
case RemoteMessageType::MSG_DOCLENGTH:
msg_doclength(message);
return;
case RemoteMessageType::MSG_QUERY:
msg_query(message);
return;
case RemoteMessageType::MSG_TERMLIST:
msg_termlist(message);
return;
case RemoteMessageType::MSG_POSITIONLIST:
msg_positionlist(message);
return;
case RemoteMessageType::MSG_POSTLIST:
msg_postlist(message);
return;
case RemoteMessageType::MSG_REOPEN:
msg_reopen(message);
return;
case RemoteMessageType::MSG_UPDATE:
msg_update(message);
return;
case RemoteMessageType::MSG_ADDDOCUMENT:
msg_adddocument(message);
return;
case RemoteMessageType::MSG_CANCEL:
msg_cancel(message);
return;
case RemoteMessageType::MSG_DELETEDOCUMENTTERM:
msg_deletedocumentterm(message);
return;
case RemoteMessageType::MSG_COMMIT:
msg_commit(message);
return;
case RemoteMessageType::MSG_REPLACEDOCUMENT:
msg_replacedocument(message);
return;
case RemoteMessageType::MSG_REPLACEDOCUMENTTERM:
msg_replacedocumentterm(message);
return;
case RemoteMessageType::MSG_DELETEDOCUMENT:
msg_deletedocument(message);
return;
case RemoteMessageType::MSG_WRITEACCESS:
msg_writeaccess(message);
return;
case RemoteMessageType::MSG_GETMETADATA:
msg_getmetadata(message);
return;
case RemoteMessageType::MSG_SETMETADATA:
msg_setmetadata(message);
return;
case RemoteMessageType::MSG_ADDSPELLING:
msg_addspelling(message);
return;
case RemoteMessageType::MSG_REMOVESPELLING:
msg_removespelling(message);
return;
case RemoteMessageType::MSG_GETMSET:
msg_getmset(message);
return;
case RemoteMessageType::MSG_SHUTDOWN:
msg_shutdown(message);
return;
case RemoteMessageType::MSG_METADATAKEYLIST:
msg_metadatakeylist(message);
return;
case RemoteMessageType::MSG_FREQS:
msg_freqs(message);
return;
case RemoteMessageType::MSG_UNIQUETERMS:
msg_uniqueterms(message);
return;
case RemoteMessageType::MSG_POSITIONLISTCOUNT:
msg_positionlistcount(message);
return;
case RemoteMessageType::MSG_READACCESS:
msg_readaccess(message);
return;
default: {
std::string errmsg("Unexpected message type ");
errmsg += std::to_string(toUType(type));
THROW(InvalidArgumentError, errmsg);
}
}
} catch (const Xapian::NetworkTimeoutError& exc) {
L_EXC("ERROR: Dispatching replication protocol message");
try {
// We've had a timeout, so the client may not be listening, if we can't
// send the message right away, just exit and the client will cope.
send_message(RemoteReplyType::REPLY_EXCEPTION, serialise_error(exc));
} catch (...) { }
destroy();
detach();
} catch (const Xapian::NetworkError&) {
// All other network errors mean we are fatally confused and are unlikely
// to be able to communicate further across this connection. So we don't
// try to propagate the error to the client, but instead just log the
// exception and close the connection.
L_EXC("ERROR: Dispatching remote protocol message");
destroy();
detach();
} catch (const Xapian::Error& exc) {
// Propagate the exception to the client, then return to the main
// message handling loop.
send_message(RemoteReplyType::REPLY_EXCEPTION, serialise_error(exc));
} catch (...) {
L_EXC("ERROR: Dispatching remote protocol message");
send_message(RemoteReplyType::REPLY_EXCEPTION, std::string());
destroy();
detach();
}
}
void
RemoteProtocolClient::msg_allterms(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_allterms(<message>)");
std::string prev = message;
std::string reply;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
const std::string& prefix = message;
const Xapian::TermIterator end = db->allterms_end(prefix);
for (Xapian::TermIterator t = db->allterms_begin(prefix); t != end; ++t) {
if unlikely(prev.size() > 255)
prev.resize(255);
const std::string& term = *t;
size_t reuse = common_prefix_length(prev, term);
reply.append(1, char(reuse));
pack_uint(reply, term.size() - reuse);
reply.append(term, reuse, std::string::npos);
pack_uint(reply, t.get_termfreq());
prev = term;
}
}
send_message(RemoteReplyType::REPLY_ALLTERMS, reply);
}
void
RemoteProtocolClient::msg_termlist(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_termlist(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint_last(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_TERMLIST");
}
std::string reply;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
Xapian::TermIterator t = db->termlist_begin(did);
Xapian::termcount num_terms = t.get_approx_size();
pack_uint(reply, db->get_doclength(did));
pack_uint_last(reply, num_terms);
send_message(RemoteReplyType::REPLY_TERMLISTHEADER, reply);
reply.resize(0);
std::string prev;
while (t != db->termlist_end(did)) {
if unlikely(prev.size() > 255) {
prev.resize(255);
}
const std::string& term = *t;
size_t reuse = common_prefix_length(prev, term);
reply.append(1, char(reuse));
pack_uint(reply, term.size() - reuse);
reply.append(term, reuse, std::string::npos);
pack_uint(reply, t.get_wdf());
pack_uint(reply, t.get_termfreq());
prev = term;
++t;
}
}
send_message(RemoteReplyType::REPLY_TERMLIST, reply);
}
void
RemoteProtocolClient::msg_positionlist(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_positionlist(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_POSITIONLIST");
}
std::string term(p, p_end - p);
std::string reply;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
Xapian::termpos lastpos = static_cast<Xapian::termpos>(-1);
const Xapian::PositionIterator end = db->positionlist_end(did, term);
for (Xapian::PositionIterator i = db->positionlist_begin(did, term);
i != end; ++i) {
Xapian::termpos pos = *i;
pack_uint(reply, pos - lastpos - 1);
lastpos = pos;
}
}
send_message(RemoteReplyType::REPLY_POSITIONLIST, reply);
}
void
RemoteProtocolClient::msg_positionlistcount(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_positionlistcount(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_POSITIONLISTCOUNT");
}
Xapian::termcount result = 0;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
// This is kind of clumsy, but what the public API requires.
Xapian::TermIterator termit = db->termlist_begin(did);
if (termit != db->termlist_end(did)) {
std::string term(p, p_end - p);
termit.skip_to(term);
if (termit != db->termlist_end(did)) {
result = termit.positionlist_count();
}
}
}
std::string reply;
pack_uint_last(reply, result);
send_message(RemoteReplyType::REPLY_POSITIONLISTCOUNT, reply);
}
void
RemoteProtocolClient::msg_postlist(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_postlist(<message>)");
std::string reply;
const std::string& term = message;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
Xapian::doccount termfreq = db->get_termfreq(term);
pack_uint_last(reply, termfreq);
send_message(RemoteReplyType::REPLY_POSTLISTHEADER, reply);
reply.resize(0);
Xapian::docid lastdocid = 0;
const Xapian::PostingIterator end = db->postlist_end(term);
for (Xapian::PostingIterator i = db->postlist_begin(term);
i != end; ++i) {
Xapian::docid newdocid = *i;
pack_uint(reply, newdocid - lastdocid - 1);
pack_uint(reply, i.get_wdf());
lastdocid = newdocid;
}
}
send_message(RemoteReplyType::REPLY_POSTLIST, reply);
}
void
RemoteProtocolClient::msg_readaccess(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_readaccess(<message>)");
flags = 0;
const char *p = message.c_str();
const char *p_end = p + message.size();
if (p != p_end) {
unsigned flag_bits;
if (!unpack_uint(&p, p_end, &flag_bits)) {
throw Xapian::NetworkError("Bad flags in MSG_READACCESS");
}
flags = static_cast<int>(flag_bits);
if (has_db_writable(flags)) {
throw Xapian::NetworkError("Bad flags in MSG_READACCESS");
}
}
if (p != p_end) {
std::string path;
if (!unpack_string(&p, p_end, path)) {
throw Xapian::NetworkError("Bad path in MSG_READACCESS");
}
endpoint = Endpoint(path);
if (p != p_end) {
THROW(NetworkError, "only one database allowed on remote databases");
}
}
msg_update(message);
}
void
RemoteProtocolClient::msg_writeaccess(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_writeaccess(<message>)");
flags = 0;
const char *p = message.c_str();
const char *p_end = p + message.size();
if (p != p_end) {
unsigned flag_bits;
if (!unpack_uint(&p, p_end, &flag_bits)) {
throw Xapian::NetworkError("Bad flags in MSG_WRITEACCESS");
}
flags = static_cast<int>(flag_bits);
if (!has_db_writable(flags)) {
throw Xapian::NetworkError("Bad flags in MSG_WRITEACCESS");
}
}
if (p != p_end) {
std::string path;
if (!unpack_string(&p, p_end, path)) {
throw Xapian::NetworkError("Bad path in MSG_WRITEACCESS");
}
endpoint = Endpoint(path);
if (p != p_end) {
THROW(NetworkError, "only one database allowed on remote databases");
}
}
msg_update(message);
}
void
RemoteProtocolClient::msg_reopen(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_reopen(<message>)");
lock_shard lk_shard(endpoint, flags);
if (!lk_shard->reopen()) {
lk_shard.unlock();
send_message(RemoteReplyType::REPLY_DONE, std::string());
} else {
lk_shard.unlock();
msg_update(message);
}
}
void
RemoteProtocolClient::msg_update(const std::string &)
{
L_CALL("RemoteProtocolClient::msg_update(<message>)");
static const char protocol[2] = {
char(XAPIAN_REMOTE_PROTOCOL_MAJOR_VERSION),
char(XAPIAN_REMOTE_PROTOCOL_MINOR_VERSION)
};
std::string message(protocol, 2);
if (!endpoint.empty()) {
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
Xapian::doccount num_docs = db->get_doccount();
pack_uint(message, num_docs);
pack_uint(message, db->get_lastdocid() - num_docs);
Xapian::termcount doclen_lb = db->get_doclength_lower_bound();
pack_uint(message, doclen_lb);
pack_uint(message, db->get_doclength_upper_bound() - doclen_lb);
pack_bool(message, db->has_positions());
pack_uint(message, db->get_total_length());
pack_uint(message, db->get_revision());
message += db->get_uuid();
}
send_message(RemoteReplyType::REPLY_UPDATE, message);
}
void
RemoteProtocolClient::msg_query(const std::string &message_in)
{
L_CALL("RemoteProtocolClient::msg_query(<message>)");
const char *p = message_in.c_str();
const char *p_end = p + message_in.size();
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
RemoteProtocolPendingQuery pending_query;
pending_query.revision = db->get_revision();
pending_query.enquire = std::make_unique<Xapian::Enquire>(*db);
////////////////////////////////////////////////////////////////////////////
// Unserialise Query ID
std::string query_id;
if (!unpack_string(&p, p_end, query_id)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
////////////////////////////////////////////////////////////////////////////
// Unserialise the Query.
std::string serialisation;
if (!unpack_string(&p, p_end, serialisation)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
Xapian::Query query(Xapian::Query::unserialise(serialisation, registry));
// Unserialise assorted Enquire settings.
Xapian::termcount qlen;
if (!unpack_uint(&p, p_end, &qlen)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
pending_query.enquire->set_query(query, qlen);
////////////////////////////////////////////////////////////////////////////
// Collapse key
Xapian::valueno collapse_max;
if (!unpack_uint(&p, p_end, &collapse_max)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
Xapian::valueno collapse_key = Xapian::BAD_VALUENO;
if (collapse_max) {
if (!unpack_uint(&p, p_end, &collapse_key)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
}
pending_query.enquire->set_collapse_key(collapse_key, collapse_max);
////////////////////////////////////////////////////////////////////////////
// docid order
if (p_end - p < 4 || static_cast<unsigned char>(*p) > 2) {
THROW(NetworkError, "bad message (docid_order)");
}
Xapian::Enquire::docid_order order;
order = static_cast<Xapian::Enquire::docid_order>(*p++);
pending_query.enquire->set_docid_order(order);
////////////////////////////////////////////////////////////////////////////
// Sort by
using sort_setting = enum { REL, VAL, VAL_REL, REL_VAL, DOCID };
if (static_cast<unsigned char>(*p) > 4) {
throw Xapian::NetworkError("bad message (sort_by)");
}
sort_setting sort_by;
sort_by = static_cast<sort_setting>(*p++);
Xapian::valueno sort_key = Xapian::BAD_VALUENO;
if (sort_by != REL) {
if (!unpack_uint(&p, p_end, &sort_key)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
}
bool sort_value_forward;
if (!unpack_bool(&p, p_end, &sort_value_forward)) {
throw Xapian::NetworkError("bad message (sort_value_forward)");
}
switch (sort_by) {
case REL:
pending_query.enquire->set_sort_by_relevance();
break;
case VAL:
pending_query.enquire->set_sort_by_value(sort_key, sort_value_forward);
break;
case VAL_REL:
pending_query.enquire->set_sort_by_value_then_relevance(sort_key, sort_value_forward);
break;
case REL_VAL:
pending_query.enquire->set_sort_by_relevance_then_value(sort_key, sort_value_forward);
break;
case DOCID:
pending_query.enquire->set_weighting_scheme(Xapian::BoolWeight());
break;
}
////////////////////////////////////////////////////////////////////////////
// Has positions
bool full_db_has_positions;
if (!unpack_bool(&p, p_end, &full_db_has_positions)) {
throw Xapian::NetworkError("bad message (full_db_has_positions)");
}
////////////////////////////////////////////////////////////////////////////
// Time limit
double time_limit = unserialise_double(&p, p_end);
pending_query.enquire->set_time_limit(time_limit);
////////////////////////////////////////////////////////////////////////////
// Threshold
int percent_threshold = *p++;
if (percent_threshold < 0 || percent_threshold > 100) {
THROW(NetworkError, "bad message (percent_threshold)");
}
double weight_threshold = unserialise_double(&p, p_end);
if (weight_threshold < 0) {
THROW(NetworkError, "bad message (weight_threshold)");
}
pending_query.enquire->set_cutoff(percent_threshold, weight_threshold);
////////////////////////////////////////////////////////////////////////////
// Unserialise the Weight object.
std::string wtname;
if (!unpack_string(&p, p_end, wtname)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
const Xapian::Weight * wttype = registry.get_weighting_scheme(wtname);
if (wttype == nullptr) {
// Note: user weighting schemes should be registered by adding them to
// a Registry, and setting the context using
// RemoteServer::set_registry().
THROW(InvalidArgumentError, "Weighting scheme " + wtname + " not registered");
}
if (!unpack_string(&p, p_end, serialisation)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
std::unique_ptr<Xapian::Weight> wt(wttype->unserialise(serialisation));
pending_query.enquire->set_weighting_scheme(*wt);
////////////////////////////////////////////////////////////////////////////
// Unserialise the RSet object.
if (!unpack_string(&p, p_end, serialisation)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
Xapian::RSet rset = Xapian::RSet::unserialise(serialisation);
////////////////////////////////////////////////////////////////////////////
// Unserialise any MatchSpy or KeyMaker objects.
while (p != p_end) {
std::string classtype;
if (!unpack_string(&p, p_end, classtype)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
if (classtype.size() < 8) {
THROW(InvalidArgumentError, "Class type {} is invalid", classtype);
}
std::string_view type(classtype);
type.remove_prefix(classtype.size() - 8);
if (!unpack_string(&p, p_end, serialisation)) {
throw Xapian::NetworkError("Bad MSG_QUERY");
}
if (type == "KeyMaker") {
const Xapian::KeyMaker * sorterclass = registry.get_key_maker(classtype);
if (sorterclass == nullptr) {
THROW(InvalidArgumentError, "Key maker {} not registered", classtype);
}
Xapian::KeyMaker * sorter = sorterclass->unserialise(serialisation, registry);
switch (sort_by) {
case REL:
break;
case VAL:
pending_query.enquire->set_sort_by_key(sorter->release(), sort_value_forward);
break;
case VAL_REL:
pending_query.enquire->set_sort_by_key_then_relevance(sorter->release(), sort_value_forward);
break;
case REL_VAL:
pending_query.enquire->set_sort_by_relevance_then_key(sorter->release(), sort_value_forward);
break;
case DOCID:
break;
}
} else if (type == "MatchSpy") {
const Xapian::MatchSpy * spyclass = registry.get_match_spy(classtype);
if (spyclass == nullptr) {
THROW(InvalidArgumentError, "Match spy {} not registered", classtype);
}
Xapian::MatchSpy * spy = spyclass->unserialise(serialisation, registry);
pending_query.matchspies.push_back(spy);
pending_query.enquire->add_matchspy(spy->release());
} else {
THROW(InvalidArgumentError, "Class type {} is invalid", classtype);
}
}
////////////////////////////////////////////////////////////////////////////
auto prepared_mset = pending_query.enquire->prepare_mset(query_id, full_db_has_positions, &rset, nullptr);
// Clear internal database, as it's going to be checked in.
pending_query.enquire->set_database(Xapian::Database{});
{
std::lock_guard<std::mutex> lk(pending_queries_mtx);
pending_queries[query_id] = std::move(pending_query);
}
send_message(RemoteReplyType::REPLY_STATS, prepared_mset.serialise_stats());
}
void
RemoteProtocolClient::msg_getmset(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_getmset(<message>)");
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
const char *p = message.c_str();
const char *p_end = p + message.size();
std::string query_id;
Xapian::termcount first;
Xapian::termcount maxitems;
Xapian::termcount check_at_least;
if (!unpack_string(&p, p_end, query_id) ||
!unpack_uint(&p, p_end, &first) ||
!unpack_uint(&p, p_end, &maxitems) ||
!unpack_uint(&p, p_end, &check_at_least)) {
throw Xapian::NetworkError("Bad MSG_GETMSET");
}
RemoteProtocolPendingQuery pending_query;
{
std::lock_guard<std::mutex> lk(pending_queries_mtx);
auto it = pending_queries.find(query_id);
if (it == pending_queries.end()) {
throw Xapian::DatabaseModifiedError("The query ID is not available - you should call Xapian::Database::reopen() and retry the operation");
}
pending_query = std::move(it->second);
pending_queries.erase(it);
}
if (pending_query.revision != db->get_revision()) {
throw Xapian::DatabaseModifiedError("The revision being read has been discarded - you should call Xapian::Database::reopen() and retry the operation");
}
// Set internal database from checked out database.
pending_query.enquire->set_database(*db);
pending_query.enquire->set_prepared_mset(Xapian::MSet::unserialise_stats(std::string(p, p_end)));
std::string msg;
{
Xapian::MSet mset = pending_query.enquire->get_mset(first, maxitems, check_at_least);
for (auto& i : pending_query.matchspies) {
pack_string(msg, i->serialise_results());
}
msg += mset.serialise();
// Make sure mset is destroyed before the database is
// checked in by the enquire reset() below, hence the scope.
}
send_message(RemoteReplyType::REPLY_RESULTS, msg);
}
void
RemoteProtocolClient::msg_document(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_document(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint_last(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_DOCUMENT");
}
{
lock_shard lk_shard(endpoint, flags);
Xapian::Document doc = lk_shard->get_document(did, false);
send_message(RemoteReplyType::REPLY_DOCDATA, doc.get_data());
Xapian::ValueIterator i;
for (i = doc.values_begin(); i != doc.values_end(); ++i) {
std::string item;
pack_uint(item, i.get_valueno());
item += *i;
send_message(RemoteReplyType::REPLY_VALUE, item);
}
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_keepalive(const std::string &)
{
L_CALL("RemoteProtocolClient::msg_keepalive(<message>)");
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
// Ensure *our* database stays alive, as it may contain remote databases!
db->keep_alive();
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_termexists(const std::string &term)
{
L_CALL("RemoteProtocolClient::msg_termexists(<term>)");
bool term_exists;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
term_exists = db->term_exists(term);
}
auto reply_type = term_exists ? RemoteReplyType::REPLY_TERMEXISTS : RemoteReplyType::REPLY_TERMDOESNTEXIST;
send_message(reply_type, std::string());
}
void
RemoteProtocolClient::msg_collfreq(const std::string &term)
{
L_CALL("RemoteProtocolClient::msg_collfreq(<term>)");
Xapian::termcount collection_freq;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
collection_freq = db->get_collection_freq(term);
}
std::string reply;
pack_uint_last(reply, collection_freq);
send_message(RemoteReplyType::REPLY_COLLFREQ, reply);
}
void
RemoteProtocolClient::msg_termfreq(const std::string &term)
{
L_CALL("RemoteProtocolClient::msg_termfreq(<term>)");
Xapian::doccount termfreq;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
termfreq = db->get_termfreq(term);
}
std::string reply;
pack_uint_last(reply, termfreq);
send_message(RemoteReplyType::REPLY_TERMFREQ, reply);
}
void
RemoteProtocolClient::msg_freqs(const std::string &term)
{
L_CALL("RemoteProtocolClient::msg_freqs(<term>)");
Xapian::doccount termfreq;
Xapian::termcount collection_freq;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
termfreq = db->get_termfreq(term);
collection_freq = db->get_collection_freq(term);
}
std::string reply;
pack_uint(reply, termfreq);
pack_uint_last(reply, collection_freq);
send_message(RemoteReplyType::REPLY_FREQS, reply);
}
void
RemoteProtocolClient::msg_valuestats(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_valuestats(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::valueno slot;
if (!unpack_uint_last(&p, p_end, &slot)) {
throw Xapian::NetworkError("Bad MSG_VALUESTATS");
}
Xapian::doccount value_freq;
std::string value_lower_bound;
std::string value_upper_bound;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
value_freq = db->get_value_freq(slot);
value_lower_bound = db->get_value_lower_bound(slot);
value_upper_bound = db->get_value_upper_bound(slot);
}
std::string reply;
pack_uint(reply, value_freq);
pack_string(reply, value_lower_bound);
reply += value_upper_bound;
send_message(RemoteReplyType::REPLY_VALUESTATS, reply);
}
void
RemoteProtocolClient::msg_doclength(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_doclength(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint_last(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_DOCLENGTH");
}
Xapian::termcount doclength;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
doclength = db->get_doclength(did);
}
std::string reply;
pack_uint_last(reply, doclength);
send_message(RemoteReplyType::REPLY_DOCLENGTH, reply);
}
void
RemoteProtocolClient::msg_uniqueterms(const std::string &message)
{
L_CALL("RemoteProtocolClient::msg_uniqueterms(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint_last(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_UNIQUETERMS");
}
Xapian::termcount unique_terms;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
unique_terms = db->get_unique_terms(did);
}
std::string reply;
pack_uint_last(reply, unique_terms);
send_message(RemoteReplyType::REPLY_UNIQUETERMS, reply);
}
void
RemoteProtocolClient::msg_commit(const std::string &)
{
L_CALL("RemoteProtocolClient::msg_commit(<message>)");
{
lock_shard lk_shard(endpoint, flags);
lk_shard->commit();
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_cancel(const std::string &)
{
L_CALL("RemoteProtocolClient::msg_cancel(<message>)");
{
lock_shard lk_shard(endpoint, flags);
// We can't call cancel since that's an internal method, but this
// has the same effect with minimal additional overhead.
lk_shard->begin_transaction(false);
lk_shard->cancel_transaction();
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_adddocument(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_adddocument(<message>)");
auto document = Xapian::Document::unserialise(message);
Xapian::DocumentInfo info;
{
lock_shard lk_shard(endpoint, flags);
info = lk_shard->add_document(std::move(document));
}
std::string reply;
pack_uint(reply, info.did);
pack_uint(reply, info.version);
reply += info.term;
send_message(RemoteReplyType::REPLY_ADDDOCUMENT, reply);
}
void
RemoteProtocolClient::msg_deletedocument(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_deletedocument(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint_last(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_DELETEDOCUMENT");
}
{
lock_shard lk_shard(endpoint, flags);
lk_shard->delete_document(did);
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_deletedocumentterm(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_deletedocumentterm(<message>)");
{
lock_shard lk_shard(endpoint, flags);
lk_shard->delete_document_term(message);
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_replacedocument(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_replacedocument(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::docid did;
if (!unpack_uint(&p, p_end, &did)) {
throw Xapian::NetworkError("Bad MSG_REPLACEDOCUMENT");
}
auto document = Xapian::Document::unserialise(std::string(p, p_end));
Xapian::DocumentInfo info;
{
lock_shard lk_shard(endpoint, flags);
info = lk_shard->replace_document(did, std::move(document));
}
std::string reply;
pack_uint(reply, info.did);
pack_uint(reply, info.version);
reply += info.term;
send_message(RemoteReplyType::REPLY_ADDDOCUMENT, reply);
}
void
RemoteProtocolClient::msg_replacedocumentterm(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_replacedocumentterm(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
std::string unique_term;
if (!unpack_string(&p, p_end, unique_term)) {
throw Xapian::NetworkError("Bad MSG_REPLACEDOCUMENTTERM");
}
auto document = Xapian::Document::unserialise(std::string(p, p_end));
Xapian::DocumentInfo info;
{
lock_shard lk_shard(endpoint, flags);
info = lk_shard->replace_document_term(unique_term, std::move(document));
}
std::string reply;
pack_uint(reply, info.did);
pack_uint(reply, info.version);
reply += info.term;
send_message(RemoteReplyType::REPLY_ADDDOCUMENT, reply);
}
void
RemoteProtocolClient::msg_getmetadata(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_getmetadata(<message>)");
std::string value;
{
lock_shard lk_shard(endpoint, flags);
value = lk_shard->get_metadata(message);
}
send_message(RemoteReplyType::REPLY_METADATA, value);
}
void
RemoteProtocolClient::msg_metadatakeylist(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_metadatakeylist(<message>)");
std::string reply;
{
lock_shard lk_shard(endpoint, flags);
auto db = lk_shard->db();
std::string prev = message;
const std::string& prefix = message;
for (Xapian::TermIterator t = db->metadata_keys_begin(prefix);
t != db->metadata_keys_end(prefix);
++t) {
if unlikely(prev.size() > 255)
prev.resize(255);
const std::string& term = *t;
size_t reuse = common_prefix_length(prev, term);
reply.append(1, char(reuse));
pack_uint(reply, term.size() - reuse);
reply.append(term, reuse, std::string::npos);
prev = term;
}
}
send_message(RemoteReplyType::REPLY_METADATAKEYLIST, reply);
}
void
RemoteProtocolClient::msg_setmetadata(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_setmetadata(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
std::string key;
if (!unpack_string(&p, p_end, key)) {
throw Xapian::NetworkError("Bad MSG_SETMETADATA");
}
std::string val(p, p_end - p);
{
lock_shard lk_shard(endpoint, flags);
lk_shard->set_metadata(key, val);
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_addspelling(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_addspelling(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::termcount freqinc;
if (!unpack_uint(&p, p_end, &freqinc)) {
throw Xapian::NetworkError("Bad MSG_ADDSPELLING");
}
{
lock_shard lk_shard(endpoint, flags);
lk_shard->add_spelling(std::string(p, p_end - p), freqinc);
}
send_message(RemoteReplyType::REPLY_DONE, std::string());
}
void
RemoteProtocolClient::msg_removespelling(const std::string & message)
{
L_CALL("RemoteProtocolClient::msg_removespelling(<message>)");
const char *p = message.data();
const char *p_end = p + message.size();
Xapian::termcount freqdec;
if (!unpack_uint(&p, p_end, &freqdec)) {
throw Xapian::NetworkError("Bad MSG_REMOVESPELLING");
}
Xapian::termcount result;
{
lock_shard lk_shard(endpoint, flags);
result = lk_shard->remove_spelling(std::string(p, p_end - p), freqdec);
}
std::string reply;
pack_uint_last(reply, result);
send_message(RemoteReplyType::REPLY_REMOVESPELLING, reply);
}
void
RemoteProtocolClient::msg_shutdown(const std::string &)
{
L_CALL("RemoteProtocolClient::msg_shutdown(<message>)");
destroy();
detach();
}
size_t
RemoteProtocolClient::pending_messages() const
{
std::lock_guard<std::mutex> lk(runner_mutex);
return messages.size();
}
bool
RemoteProtocolClient::is_idle() const
{
L_CALL("RemoteProtocolClient::is_idle() {{is_waiting:{}, is_running:{}, write_queue_empty:{}, pending_messages:{}}}", is_waiting(), is_running(), write_queue.empty(), pending_messages());
return !is_waiting() && !is_running() && write_queue.empty() && !pending_messages();
}
void
RemoteProtocolClient::shutdown_impl(long long asap, long long now)
{
L_CALL("RemoteProtocolClient::shutdown_impl({}, {})", asap, now);
Worker::shutdown_impl(asap, now);
if (asap) {
shutting_down = true;
auto manager = XapiandManager::manager();
if (now != 0 || !manager || manager->ready_to_end_remote() || is_idle()) {
stop(false);
destroy(false);
detach();
}
} else {
if (is_idle()) {
stop(false);
destroy(false);
detach();
}
}
}
bool
RemoteProtocolClient::init_remote(int sock_) noexcept
{
L_CALL("RemoteProtocolClient::init_remote({})", sock_);
if (!init(sock_)) {
return false;
}
std::lock_guard<std::mutex> lk(runner_mutex);
assert(!running);
// Setup state...
state = RemoteState::INIT_REMOTE;
// And start a runner.
running = true;
XapiandManager::manager(true)->remote_client_pool->enqueue(share_this<RemoteProtocolClient>());
return true;
}
ssize_t
RemoteProtocolClient::on_read(const char *buf, ssize_t received)
{
L_CALL("RemoteProtocolClient::on_read(<buf>, {})", received);
if (received <= 0) {
std::string reason;
if (received < 0) {
reason = strings::format("{} ({}): {}", error::name(errno), errno, error::description(errno));
if (errno != ENOTCONN && errno != ECONNRESET && errno != ESPIPE) {
L_NOTICE("Remote Protocol {} connection closed unexpectedly: {}", enum_name(state.load(std::memory_order_relaxed)), reason);
close();
return received;
}
} else {
reason = "EOF";
}
if (is_waiting()) {
L_NOTICE("Remote Protocol {} closed unexpectedly: There was still a request in progress: {}", enum_name(state.load(std::memory_order_relaxed)), reason);
close();
return received;
}
if (!write_queue.empty()) {
L_NOTICE("Remote Protocol {} closed unexpectedly: There is still pending data: {}", enum_name(state.load(std::memory_order_relaxed)), reason);
close();
return received;
}
if (pending_messages()) {
L_NOTICE("Remote Protocol {} closed unexpectedly: There are still pending messages: {}", enum_name(state.load(std::memory_order_relaxed)), reason);
close();
return received;
}
// Remote Protocol normally closed connection.
close();
return received;
}
L_BINARY_WIRE("RemoteProtocolClient::on_read: {} bytes", received);
ssize_t processed = -buffer.size();
buffer.append(buf, received);
while (buffer.size() >= 2) {
const char *o = buffer.data();
const char *p = o;
const char *p_end = p + buffer.size();
char type = *p++;
L_BINARY_WIRE("on_read message: {} {{state:{}}}", repr(std::string(1, type)), enum_name(state));
switch (type) {
case FILE_FOLLOWS: {
char path[PATH_MAX + 1];
if (temp_directory.empty()) {
if (temp_directory_template.empty()) {
temp_directory = "/tmp";
} else {
strncpy(path, temp_directory_template.c_str(), PATH_MAX);
build_path_index(temp_directory_template);
if (io::mkdtemp(path) == nullptr) {
L_ERR("Directory {} not created: {} ({}): {}", temp_directory_template, error::name(errno), errno, error::description(errno));
detach();
return processed;
}
temp_directory = path;
}
}
strncpy(path, (temp_directory + "/" + temp_file_template).c_str(), PATH_MAX);
file_descriptor = io::mkstemp(path);
temp_files.push_back(path);
file_message_type = *p++;
if (file_descriptor == -1) {
L_ERR("Cannot create temporary file: {} ({}): {}", error::name(errno), errno, error::description(errno));
detach();
return processed;
} else {
L_BINARY("Start reading file: {} ({})", path, file_descriptor);
}
read_file();
processed += p - o;
buffer.clear();
return processed;
}
}
size_t len;
if (!unpack_uint(&p, p_end, &len)) {
return received;
}
if (size_t(p_end - p) != len) {
return received;
}
if (!closed) {
std::lock_guard<std::mutex> lk(runner_mutex);
if (!running) {
// Enqueue message...
messages.push_back(Buffer(type, p, len));
// And start a runner.
running = true;
XapiandManager::manager(true)->remote_client_pool->enqueue(share_this<RemoteProtocolClient>());
} else {
// There should be a runner, just enqueue message.
messages.push_back(Buffer(type, p, len));
}
}
buffer.erase(0, p - o + len);
processed += p - o + len;
}
return received;
}
void
RemoteProtocolClient::on_read_file(const char *buf, ssize_t received)
{
L_CALL("RemoteProtocolClient::on_read_file(<buf>, {})", received);
L_BINARY_WIRE("RemoteProtocolClient::on_read_file: {} bytes", received);
io::write(file_descriptor, buf, received);
}
void
RemoteProtocolClient::on_read_file_done()
{
L_CALL("RemoteProtocolClient::on_read_file_done()");
L_BINARY_WIRE("RemoteProtocolClient::on_read_file_done");
io::close(file_descriptor);
file_descriptor = -1;
const auto& temp_file = temp_files.back();
if (!closed) {
std::lock_guard<std::mutex> lk(runner_mutex);
if (!running) {
// Enqueue message...
messages.push_back(Buffer(file_message_type, temp_file.data(), temp_file.size()));
// And start a runner.
running = true;
XapiandManager::manager(true)->remote_client_pool->enqueue(share_this<RemoteProtocolClient>());
} else {
// There should be a runner, just enqueue message.
messages.push_back(Buffer(file_message_type, temp_file.data(), temp_file.size()));
}
}
}
char
RemoteProtocolClient::get_message(std::string &result, char max_type)
{
L_CALL("RemoteProtocolClient::get_message(<result>, <max_type>)");
auto& msg = messages.front();
char type = msg.type;
#ifdef SAVE_LAST_MESSAGES
last_message_received.store(type, std::memory_order_relaxed);
#endif
if (type >= max_type) {
std::string errmsg("Invalid message type ");
errmsg += std::to_string(int(type));
THROW(InvalidArgumentError, errmsg);
}
const char *msg_str = msg.dpos();
size_t msg_size = msg.nbytes();
result.assign(msg_str, msg_size);
messages.pop_front();
return type;
}
void
RemoteProtocolClient::send_message(char type_as_char, const std::string &message)
{
L_CALL("RemoteProtocolClient::send_message(<type_as_char>, <message>)");
#ifdef SAVE_LAST_MESSAGES
last_message_sent.store(type_as_char, std::memory_order_relaxed);
#endif
std::string buf;
buf.push_back(type_as_char);
pack_uint(buf, message.size());
buf.append(message);
write(buf);
}
void
RemoteProtocolClient::send_file(char type_as_char, int fd)
{
L_CALL("RemoteProtocolClient::send_file(<type_as_char>, <fd>)");
std::string buf;
buf.push_back(FILE_FOLLOWS);
buf.push_back(type_as_char);
write(buf);
BaseClient<RemoteProtocolClient>::send_file(fd);
}
void
RemoteProtocolClient::operator()()
{
L_CALL("RemoteProtocolClient::operator()()");
L_CONN("Start running in binary worker...");
std::unique_lock<std::mutex> lk(runner_mutex);
switch (state) {
case RemoteState::INIT_REMOTE:
state = RemoteState::REMOTE_SERVER;
lk.unlock();
try {
msg_update(std::string());
} catch (...) {
lk.lock();
running = false;
L_CONN("Running in worker ended with an exception.");
lk.unlock();
L_EXC("ERROR: Remote server ended with an unhandled exception");
detach();
throw;
}
lk.lock();
break;
default:
break;
}
while (!messages.empty() && !closed) {
switch (state) {
case RemoteState::REMOTE_SERVER: {
std::string message;
RemoteMessageType type = static_cast<RemoteMessageType>(get_message(message, static_cast<char>(RemoteMessageType::MSG_MAX)));
lk.unlock();
try {
L_BINARY_PROTO(">> get_message[REMOTE_SERVER] ({}): {}", enum_name(type), repr(message));
remote_server(type, message);
auto sent = total_sent_bytes.exchange(0);
Metrics::metrics()
.xapiand_remote_protocol_sent_bytes
.Increment(sent);
auto received = total_received_bytes.exchange(0);
Metrics::metrics()
.xapiand_remote_protocol_received_bytes
.Increment(received);
} catch (...) {
lk.lock();
running = false;
L_CONN("Running in worker ended with an exception.");
lk.unlock();
L_EXC("ERROR: Remote server ended with an unhandled exception");
detach();
throw;
}
lk.lock();
break;
}
default:
running = false;
L_CONN("Running in worker ended with unexpected state.");
lk.unlock();
L_ERR("ERROR: Unexpected RemoteProtocolClient state");
stop();
destroy();
detach();
return;
}
}
running = false;
L_CONN("Running in replication worker ended. {{messages_empty:{}, closed:{}, is_shutting_down:{}}}", messages.empty(), closed.load(), is_shutting_down());
lk.unlock();
if (is_shutting_down() && is_idle()) {
detach();
return;
}
redetach(); // try re-detaching if already flagged as detaching
}
std::string
RemoteProtocolClient::__repr__() const
{
#ifdef SAVE_LAST_MESSAGES
auto state_repr = ([this]() -> std::string {
auto received = last_message_received.load(std::memory_order_relaxed);
auto sent = last_message_sent.load(std::memory_order_relaxed);
auto st = state.load(std::memory_order_relaxed);
switch (st) {
case RemoteState::INIT_REMOTE:
case RemoteState::REMOTE_SERVER:
return strings::format("{}) ({}<->{}",
enum_name(st),
enum_name(static_cast<RemoteMessageType>(received)),
enum_name(static_cast<RemoteReplyType>(sent)));
default:
return "";
}
})();
#else
const auto& state_repr = enum_name(state.load(std::memory_order_relaxed));
#endif
return strings::format(STEEL_BLUE + "<RemoteProtocolClient ({}) {{cnt:{}, sock:{}}}{}{}{}{}{}{}{}{}>",
state_repr,
use_count(),
sock,
is_runner() ? " " + DARK_STEEL_BLUE + "(runner)" + STEEL_BLUE : " " + DARK_STEEL_BLUE + "(worker)" + STEEL_BLUE,
is_running_loop() ? " " + DARK_STEEL_BLUE + "(running loop)" + STEEL_BLUE : " " + DARK_STEEL_BLUE + "(stopped loop)" + STEEL_BLUE,
is_detaching() ? " " + ORANGE + "(detaching)" + STEEL_BLUE : "",
is_idle() ? " " + DARK_STEEL_BLUE + "(idle)" + STEEL_BLUE : "",
is_waiting() ? " " + LIGHT_STEEL_BLUE + "(waiting)" + STEEL_BLUE : "",
is_running() ? " " + DARK_ORANGE + "(running)" + STEEL_BLUE : "",
is_shutting_down() ? " " + ORANGE + "(shutting down)" + STEEL_BLUE : "",
is_closed() ? " " + ORANGE + "(closed)" + STEEL_BLUE : "");
}
#endif /* XAPIAND_CLUSTERING */
| 19,473 |
453 | /*
(C) Copyright 2001,2006,
International Business Machines Corporation,
Sony Computer Entertainment, Incorporated,
Toshiba Corporation,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this 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 names of the copyright holders nor the names of their
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
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.
*/
/*
* Functions to pack/unpack the 128 bit fpscr to/from the 32 bit fenv_t.
* The fpscr currently has 32 of 128 bits defined.
*/
#ifndef _FEFPSCR_H_
#define _FEFPSCR_H_ 1
#include <spu_intrinsics.h>
#include <fenv.h>
static __inline vec_uint4 __unpack_fpscr(fenv_t word)
{
vec_uint4 fpscr;
vec_uchar16 splat = { 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 2, 3, 2, 3 };
vec_short8 rotm = { -12, -9, -3, 0, -10, -7, -3, 0 };
vec_uint4 mask = { 0x00000f07, 0x00003f07, 0x00003f07, 0x00000f07 };
fpscr = spu_promote (word, 0);
fpscr = spu_shuffle (fpscr, fpscr, splat);
/*
* The casts here are important, so we generate different code.
*/
fpscr = (vec_uint4) spu_rlmask ((vec_short8) fpscr, rotm);
fpscr = (vec_uint4) spu_and ((vec_short8) fpscr, 0xff);
fpscr = spu_or (spu_rlmask(fpscr, -8), fpscr);
fpscr = spu_and (fpscr, mask);
return fpscr;
}
static __inline fenv_t __pack_fpscr(vec_uint4 fpscr)
{
vec_uchar16 pat = { 0x80, 2, 0x80, 10, 0x80, 3, 0x80, 11,
0x80, 6, 0x80, 14, 0x80, 7, 0x80, 15 };
vec_ushort8 shl = { 12, 10, 9, 7, 3, 3, 0, 0 };
vec_uint4 mask = { 0x00000f07, 0x00003f07, 0x00003f07, 0x00000f07 };
vec_uint4 word;
word = spu_and (fpscr, mask);
word = spu_shuffle (word, word, pat);
word = (vec_uint4) spu_sl ((vec_short8) word, shl);
word = spu_orx (word);
return spu_extract (word, 0);
}
#endif
| 1,094 |
5,597 | package com.intuit.karate.shell;
import java.io.File;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.intuit.karate.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author pthomas3
*/
class CommandTest {
static final Logger logger = LoggerFactory.getLogger(CommandTest.class);
@Test
void testCommand() {
String cmd = FileUtils.isOsWindows() ? "print \"hello\"" : "ls";
Command command = new Command(false, null, null, "target/command.log", new File("src"), cmd, "-al");
command.start();
int exitCode = command.waitSync();
assertEquals(exitCode, 0);
}
@Test
void testCommandReturn() {
String cmd = FileUtils.isOsWindows() ? "cmd /c dir" : "ls";
String result = Command.execLine(new File("target"), cmd);
assertTrue(result.contains("karate"));
}
@Test
void testTokenize() {
String[] args = Command.tokenize("hello \"foo bar\" world");
assertEquals(3, args.length);
assertEquals("hello", args[0]);
assertEquals("foo bar", args[1]);
assertEquals("world", args[2]);
args = Command.tokenize("-Dexec.classpathScope=test \"-Dexec.args=-f json test\"");
assertEquals(2, args.length);
assertEquals("-Dexec.classpathScope=test", args[0]);
assertEquals("-Dexec.args=-f json test", args[1]);
args = Command.tokenize("-v \"$PWD\":/src -v \"$HOME/.m2\":/root/.m2 ptrthomas/karate-chrome");
assertEquals(5, args.length);
assertEquals("-v", args[0]);
assertEquals("\"$PWD\":/src", args[1]);
assertEquals("-v", args[2]);
assertEquals("\"$HOME/.m2\":/root/.m2", args[3]);
assertEquals("ptrthomas/karate-chrome", args[4]);
}
}
| 773 |
25,073 | package cc.mrbird.sso;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.builder.SpringApplicationBuilder;
/**
* @author MrBird
*/
@EnableOAuth2Sso
@SpringBootApplication
public class SsoApplicaitonOne {
public static void main(String[] args) {
new SpringApplicationBuilder(SsoApplicaitonOne.class).run(args);
}
}
| 152 |
2,219 | <reponame>km2m/nasm<gh_stars>1000+
/* hash.h Routines to calculate a CRC32 hash value
*
* These routines donated to the NASM effort by <NAME>.
*
* The Netwide Assembler is copyright (C) 1996 <NAME> and
* <NAME>. All rights reserved. The software is
* redistributable under the license given in the file "LICENSE"
* distributed in the NASM archive.
*/
#ifndef RDOFF_HASH_H
#define RDOFF_HASH_H 1
uint32_t hash(const char *name);
#endif
| 158 |
381 | package org.apache.helix.zookeeper.util;
/*
* 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 org.apache.helix.zookeeper.constant.ZkSystemPropertyKeys;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
/**
* This utility class contains various methods for manipulating ZNRecord.
*/
public class ZNRecordUtil {
/**
* Checks whether or not a serialized ZNRecord bytes should be compressed before being written to
* Zookeeper.
*
* @param record raw ZNRecord before being serialized
* @param serializedLength length of the serialized bytes array
* @return
*/
public static boolean shouldCompress(ZNRecord record, int serializedLength) {
if (record.getBooleanField(ZNRecord.ENABLE_COMPRESSION_BOOLEAN_FIELD, false)) {
return true;
}
boolean autoCompressEnabled = Boolean.parseBoolean(System
.getProperty(ZkSystemPropertyKeys.ZK_SERIALIZER_ZNRECORD_AUTO_COMPRESS_ENABLED,
ZNRecord.ZK_SERIALIZER_ZNRECORD_AUTO_COMPRESS_DEFAULT));
return autoCompressEnabled && serializedLength > getSerializerCompressThreshold();
}
/**
* Returns the threshold in bytes that ZNRecord serializer should compress a ZNRecord with larger size.
* If threshold is configured to be less than or equal to 0, the serializer will always compress ZNRecords as long as
* auto-compression is enabled.
* If threshold is not configured or the threshold is larger than ZNRecord write size limit, the default value
* ZNRecord write size limit will be used instead.
*/
private static int getSerializerCompressThreshold() {
Integer autoCompressThreshold =
Integer.getInteger(ZkSystemPropertyKeys.ZK_SERIALIZER_ZNRECORD_AUTO_COMPRESS_THRESHOLD_BYTES);
if (autoCompressThreshold == null || autoCompressThreshold > getSerializerWriteSizeLimit()) {
return getSerializerWriteSizeLimit();
}
return autoCompressThreshold;
}
/**
* Returns ZNRecord serializer write size limit in bytes. If size limit is configured to be less
* than or equal to 0, the default value {@link ZNRecord#SIZE_LIMIT} will be used instead.
*/
public static int getSerializerWriteSizeLimit() {
Integer writeSizeLimit =
Integer.getInteger(ZkSystemPropertyKeys.ZK_SERIALIZER_ZNRECORD_WRITE_SIZE_LIMIT_BYTES);
if (writeSizeLimit == null || writeSizeLimit <= 0) {
return ZNRecord.SIZE_LIMIT;
}
return writeSizeLimit;
}
}
| 984 |
377 | <gh_stars>100-1000
package com.impetus.kundera.datatypes.datagenerator;
import java.util.UUID;
public class UUIDDataGenerator implements DataGenerator<UUID>
{
private static final UUID RANDOM_UUID = UUID.randomUUID();
private static final UUID MAX_UUID = UUID.randomUUID();
private static final UUID MIN_UUID = UUID.randomUUID();
@Override
public UUID randomValue()
{
return RANDOM_UUID;
}
@Override
public UUID maxValue()
{
return MAX_UUID;
}
@Override
public UUID minValue()
{
return MIN_UUID;
}
@Override
public UUID partialValue()
{
return null;
}
}
| 284 |
375 | <reponame>jangalda-nsc/git-plugin<filename>src/main/java/jenkins/plugins/git/GitToolChooser.java<gh_stars>100-1000
package jenkins.plugins.git;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.EnvVars;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.model.Item;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.plugins.git.GitTool;
import hudson.plugins.git.util.GitUtils;
import jenkins.model.Jenkins;
import org.apache.commons.io.FileUtils;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.JGitApacheTool;
import org.jenkinsci.plugins.gitclient.JGitTool;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* A class which allows Git Plugin to choose a git implementation by estimating the size of a repository from a distance
* without requiring a local checkout.
*/
public class GitToolChooser {
private long sizeOfRepo = 0L;
private String implementation;
private String gitTool;
private TaskListener listener;
private Node currentNode;
/**
* Size to switch implementation in KiB
*/
private static final int SIZE_TO_SWITCH = 5000;
private boolean JGIT_SUPPORTED = false;
/** Cache of repository sizes based on remoteURL. **/
private static ConcurrentHashMap<String, Long> repositorySizeCache = new ConcurrentHashMap<>();
/**
* Instantiate class using the remote name. It looks for a cached .git directory first, calculates the
* size if it is found else checks if the extension point has been implemented and asks for the size.
* @param remoteName the repository url
* @param projectContext the context where repository size is being estimated
* @param credentialsId credential used to access the repository or null if no credential is required
* @param gitExe Git tool ('git', 'jgit', 'jgitapache') to be used as the default tool
* @param n A Jenkins agent used to check validity of git installation
* @param listener TaskListener required by GitUtils.resolveGitTool()
* @param useJGit if true the JGit is allowed as an implementation
* @throws IOException on error
* @throws InterruptedException on error
*/
@SuppressFBWarnings(value="EI_EXPOSE_REP2", justification="Low risk")
public GitToolChooser(String remoteName, Item projectContext, String credentialsId,
GitTool gitExe, Node n, TaskListener listener, Boolean useJGit) throws IOException, InterruptedException {
boolean useCache = false;
if (useJGit != null) {
JGIT_SUPPORTED = useJGit;
}
currentNode = n;
this.listener = listener;
implementation = "NONE";
useCache = decideAndUseCache(remoteName);
if (useCache) {
implementation = determineSwitchOnSize(sizeOfRepo, gitExe);
} else {
decideAndUseAPI(remoteName, projectContext, credentialsId, gitExe);
}
gitTool = implementation;
}
/**
* Determine and estimate the size of a .git cached directory
* @param remoteName: Use the repository url to access a cached Jenkins directory, we do not lock it.
* @return useCache
* @throws IOException on error
* @throws InterruptedException on error
*/
private boolean decideAndUseCache(String remoteName) throws IOException, InterruptedException {
boolean useCache = false;
if (setSizeFromInternalCache(remoteName)) {
LOGGER.log(Level.FINE,
"Found cache key for {0} with size {1}",
new Object[]{remoteName, sizeOfRepo});
useCache = true;
return useCache;
}
for (String repoUrl : remoteAlternatives(remoteName)) {
String cacheEntry = AbstractGitSCMSource.getCacheEntry(repoUrl);
File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry, false);
if (cacheDir != null) {
Git git = Git.with(TaskListener.NULL, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir).using("git");
GitClient client = git.getClient();
if (client.hasGitRepo(false)) {
long clientRepoSize = FileUtils.sizeOfDirectory(cacheDir) / 1024; // Conversion from Bytes to Kilo Bytes
if (clientRepoSize > sizeOfRepo) {
if (sizeOfRepo > 0) {
LOGGER.log(Level.FINE, "Replacing prior size estimate {0} with new size estimate {1} for remote {2} from cache {3}",
new Object[]{sizeOfRepo, clientRepoSize, remoteName, cacheDir});
}
sizeOfRepo = clientRepoSize;
assignSizeToInternalCache(remoteName, sizeOfRepo);
}
useCache = true;
if (remoteName.equals(repoUrl)) {
LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}",
new Object[]{remoteName, cacheDir, sizeOfRepo});
} else {
LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}, alternative URL {3}",
new Object[]{remoteName, cacheDir, sizeOfRepo, repoUrl});
}
} else {
// Log the surprise but continue looking for a cache
LOGGER.log(Level.FINE, "Remote URL {0} cache {1} has no git dir", new Object[]{remoteName, cacheDir});
}
}
}
if (!useCache) {
LOGGER.log(Level.FINE, "Remote URL {0} cache not found", remoteName);
}
return useCache;
}
private void decideAndUseAPI(String remoteName, Item context, String credentialsId, GitTool gitExe) {
if (setSizeFromAPI(remoteName, context, credentialsId)) {
implementation = determineSwitchOnSize(sizeOfRepo, gitExe);
}
}
/* Git repository URLs frequently end with the ".git" suffix.
* However, many repositories (especially https) do not require the ".git" suffix.
*
* Add remoteURL with the ".git" suffix and without the ".git" suffix to the
* list of alternatives.
*/
private void addSuffixVariants(@NonNull String remoteURL, @NonNull Set<String> alternatives) {
alternatives.add(remoteURL);
String suffix = ".git";
if (remoteURL.endsWith(suffix)) {
alternatives.add(remoteURL.substring(0, remoteURL.length() - suffix.length()));
} else {
alternatives.add(remoteURL + suffix);
}
}
/* Git repository URLs frequently end with the ".git" suffix.
* However, many repositories (especially https) do not require the ".git" suffix.
*
* Add remoteURL with the ".git" suffix if not present
*/
private String addSuffix(@NonNull String canonicalURL) {
String suffix = ".git";
if (!canonicalURL.endsWith(suffix)) {
canonicalURL = canonicalURL + suffix;
}
return canonicalURL;
}
/* Protocol patterns to extract hostname and path from typical repository URLs */
private static Pattern gitProtocolPattern = Pattern.compile("^git://([^/]+)/(.+?)/*$");
private static Pattern httpProtocolPattern = Pattern.compile("^https?://([^/]+)/(.+?)/*$");
private static Pattern sshAltProtocolPattern = Pattern.compile("^[\\w]+@(.+):(.+?)/*$");
private static Pattern sshProtocolPattern = Pattern.compile("^ssh://[\\w]+@([^/]+)/(.+?)/*$");
/* Return a list of alternate remote URL's based on permutations of remoteURL.
* Varies the protocol (https, git, ssh) and the suffix of the repository URL.
* Package protected for testing
*/
/* package */ @NonNull String convertToCanonicalURL(String remoteURL) {
if (remoteURL == null || remoteURL.isEmpty()) {
LOGGER.log(Level.FINE, "Null or empty remote URL not cached");
return ""; // return an empty string
}
Pattern [] protocolPatterns = {
sshAltProtocolPattern,
sshProtocolPattern,
gitProtocolPattern,
};
String matcherReplacement = "https://$1/$2";
/* For each matching protocol, convert alternatives to canonical form by https replacement */
remoteURL = addSuffix(remoteURL);
String canonicalURL = remoteURL;
if (httpProtocolPattern.matcher(remoteURL).matches()) {
canonicalURL = remoteURL;
} else {
for (Pattern protocolPattern: protocolPatterns) {
Matcher protocolMatcher = protocolPattern.matcher(remoteURL);
if (protocolMatcher.matches()) {
canonicalURL = protocolMatcher.replaceAll(matcherReplacement);
break;
}
}
}
LOGGER.log(Level.FINE, "Cache repo URL: {0}", canonicalURL);
return canonicalURL;
}
private boolean setSizeFromInternalCache(String repoURL) {
repoURL = convertToCanonicalURL(repoURL);
if (repositorySizeCache.containsKey(repoURL)) {
sizeOfRepo = repositorySizeCache.get(repoURL);
return true;
}
return false;
}
/* Return a list of alternate remote URL's based on permutations of remoteURL.
* Varies the protocol (https, git, ssh) and the suffix of the repository URL.
* Package protected for testing
*/
/* package */ @NonNull Set<String> remoteAlternatives(String remoteURL) {
Set<String> alternatives = new LinkedHashSet<>();
if (remoteURL == null || remoteURL.isEmpty()) {
LOGGER.log(Level.FINE, "Null or empty remote URL not cached");
return alternatives;
}
Pattern [] protocolPatterns = {
gitProtocolPattern,
httpProtocolPattern,
sshAltProtocolPattern,
sshProtocolPattern,
};
String[] matcherReplacements = {
"git://$1/$2", // git protocol
"git@$1:$2", // ssh protocol alternate URL
"https://$1/$2", // https protocol
"ssh://git@$1/$2", // ssh protocol
};
/* For each matching protocol, form alternatives by iterating over replacements */
boolean matched = false;
for (Pattern protocolPattern : protocolPatterns) {
Matcher protocolMatcher = protocolPattern.matcher(remoteURL);
if (protocolMatcher.matches()) {
for (String replacement : matcherReplacements) {
String alternativeURL = protocolMatcher.replaceAll(replacement);
addSuffixVariants(alternativeURL, alternatives);
}
matched = true;
}
}
// Must include original remote in case none of the protocol patterns match
// For example, file://srv/git/repo.git is matched by none of the patterns
if (!matched) {
addSuffixVariants(remoteURL, alternatives);
}
LOGGER.log(Level.FINE, "Cache repo alternative URLs: {0}", alternatives);
return alternatives;
}
/** Cache the estimated repository size for variants of repository URL */
private void assignSizeToInternalCache(String repoURL, long repoSize) {
repoURL = convertToCanonicalURL(repoURL);
if (repositorySizeCache.containsKey(repoURL)) {
long oldSize = repositorySizeCache.get(repoURL);
if (oldSize < repoSize) {
LOGGER.log(Level.FINE, "Replacing old repo size {0} with new size {1} for repo {2}", new Object[]{oldSize, repoSize, repoURL});
repositorySizeCache.put(repoURL, repoSize);
} else if (oldSize > repoSize) {
LOGGER.log(Level.FINE, "Ignoring new size {1} in favor of old size {0} for repo {2}", new Object[]{oldSize, repoSize, repoURL});
}
} else {
LOGGER.log(Level.FINE, "Caching repo size {0} for repo {1}", new Object[]{repoSize, repoURL});
repositorySizeCache.put(repoURL, repoSize);
}
}
/**
* Check if the desired implementation of extension is present and ask for the size of repository if it does
* @param repoUrl: The remote name derived from {@link GitSCMSource} object
* @return boolean useAPI or not.
*/
private boolean setSizeFromAPI(String repoUrl, Item context, String credentialsId) {
List<RepositorySizeAPI> acceptedRepository = Objects.requireNonNull(RepositorySizeAPI.all())
.stream()
.filter(r -> r.isApplicableTo(repoUrl, context, credentialsId))
.collect(Collectors.toList());
if (acceptedRepository.size() > 0) {
try {
for (RepositorySizeAPI repo: acceptedRepository) {
long size = repo.getSizeOfRepository(repoUrl, context, credentialsId);
if (size != 0) {
sizeOfRepo = size;
assignSizeToInternalCache(repoUrl, size);
}
}
} catch (Exception e) {
LOGGER.log(Level.INFO, "Not using performance improvement from REST API: {0}", e.getMessage());
return false;
}
return sizeOfRepo != 0; // Check if the size of the repository is zero
} else {
return false;
}
}
/**
* Recommend a git implementation on the basis of the given size of a repository
* @param sizeOfRepo: Size of a repository (in KiBs)
* @return a git implementation, "git" or "jgit"
*/
String determineSwitchOnSize(Long sizeOfRepo, GitTool tool) {
if (sizeOfRepo != 0L) {
if (sizeOfRepo < SIZE_TO_SWITCH) {
if (!JGIT_SUPPORTED) {
return "NONE";
}
GitTool rTool = resolveGitToolForRecommendation(tool, JGitTool.MAGIC_EXENAME);
if (rTool == null) {
return "NONE";
}
return rTool.getGitExe();
} else {
GitTool rTool = resolveGitToolForRecommendation(tool, "git");
return rTool.getGitExe();
}
}
return "NONE";
}
private GitTool resolveGitToolForRecommendation(GitTool userChoice, String recommendation) {
GitTool tool;
if (recommendation.equals(JGitTool.MAGIC_EXENAME)) {
if (userChoice.getGitExe().equals(JGitApacheTool.MAGIC_EXENAME)) {
recommendation = JGitApacheTool.MAGIC_EXENAME;
}
// check if jgit or jgitapache is enabled
tool = getResolvedGitTool(recommendation);
if (tool.getName().equals(recommendation)) {
return tool;
} else {
return null;
}
} else {
if (!userChoice.getName().equals(JGitTool.MAGIC_EXENAME) && !userChoice.getName().equals(JGitApacheTool.MAGIC_EXENAME)) {
return userChoice;
}
else {
return recommendGitToolOnAgent(userChoice);
}
}
}
public GitTool recommendGitToolOnAgent(GitTool userChoice) {
List<GitTool> preferredToolList = new ArrayList<>();
GitTool correctTool = GitTool.getDefaultInstallation();
String toolName = userChoice.getName();
if (toolName.equals(JGitTool.MAGIC_EXENAME) || toolName.equals(JGitApacheTool.MAGIC_EXENAME)) {
GitTool[] toolList = Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getInstallations();
for (GitTool tool : toolList) {
if (!tool.getProperties().isEmpty()) {
preferredToolList.add(tool);
}
}
for (GitTool tool: preferredToolList) {
if (tool.getName().equals(getResolvedGitTool(tool.getName()).getName())) {
correctTool = getResolvedGitTool(tool.getName());
}
}
}
return correctTool;
}
/**
* Provide a git tool considering the node specific installations
* @param recommendation: Tool name
* @return resolved git tool
*/
private GitTool getResolvedGitTool(String recommendation) {
if (currentNode == null) {
currentNode = Jenkins.get();
}
return GitUtils.resolveGitTool(recommendation, currentNode, null, listener);
}
/**
* Recommend git tool to be used by the git client
* @return git implementation recommendation in the form of a string
*/
public String getGitTool() {
return gitTool;
}
/**
* Other plugins can estimate the size of repository using this extension point
* The size is assumed to be in KiBs
*/
public static abstract class RepositorySizeAPI implements ExtensionPoint {
public abstract boolean isApplicableTo(String remote, Item context, String credentialsId);
public abstract Long getSizeOfRepository(String remote, Item context, String credentialsId) throws Exception;
public static ExtensionList<RepositorySizeAPI> all() {
return Jenkins.get().getExtensionList(RepositorySizeAPI.class);
}
}
/**
* Clear the cache of repository sizes.
*/
public static void clearRepositorySizeCache() {
repositorySizeCache = new ConcurrentHashMap<>();
}
/**
* Insert an entry into the cache of repository sizes.
* For testing only - not to be used outside the git plugin.
*
* @param repoURL repository URL to be added as a cache key
* @param repoSize repository size in kilobytes
*/
@Restricted(NoExternalUse.class)
public static void putRepositorySizeCache(String repoURL, long repoSize) {
/* Half-baked conversion to canonical URL for test use */
if (!repoURL.endsWith(".git")) {
repoURL = repoURL + ".git";
}
repositorySizeCache.put(repoURL, repoSize);
}
private static final Logger LOGGER = Logger.getLogger(GitToolChooser.class.getName());
}
| 7,922 |
338 | package io.grpc.grpcswagger.store;
import com.google.common.collect.ImmutableMap;
/**
* @author <NAME>
* @date 2019-08-24
*/
public interface BaseStorage<K, V> {
void put(K key, V value);
V get(K key);
void remove(K key);
boolean exists(K key);
ImmutableMap<K, V> getAll();
}
| 121 |
929 | //
// HWInputTableViewCell.h
// HWPanModal_Example
//
// Created by <NAME> on 2019/6/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface HWInputTableViewCell : UITableViewCell
@property (nonatomic, readonly) UITextField *textField;
@end
NS_ASSUME_NONNULL_END
| 129 |
1,068 | from __future__ import print_function
import numpy as np
import falconn
import timeit
import math
if __name__ == '__main__':
dataset_file = 'dataset/glove.840B.300d.npy'
number_of_queries = 1000
# we build only 50 tables, increasing this quantity will improve the query time
# at a cost of slower preprocessing and larger memory footprint, feel free to
# play with this number
number_of_tables = 50
print('Reading the dataset')
dataset = np.load(dataset_file)
print('Done')
# It's important not to use doubles, unless they are strictly necessary.
# If your dataset consists of doubles, convert it to floats using `astype`.
assert dataset.dtype == np.float32
# Normalize all the lenghts, since we care about the cosine similarity.
print('Normalizing the dataset')
dataset /= np.linalg.norm(dataset, axis=1).reshape(-1, 1)
print('Done')
# Choose random data points to be queries.
print('Generating queries')
np.random.seed(4057218)
np.random.shuffle(dataset)
queries = dataset[len(dataset) - number_of_queries:]
dataset = dataset[:len(dataset) - number_of_queries]
print('Done')
# Perform linear scan using NumPy to get answers to the queries.
print('Solving queries using linear scan')
t1 = timeit.default_timer()
answers = []
for query in queries:
answers.append(np.dot(dataset, query).argmax())
t2 = timeit.default_timer()
print('Done')
print('Linear scan time: {} per query'.format((t2 - t1) / float(
len(queries))))
# Center the dataset and the queries: this improves the performance of LSH quite a bit.
print('Centering the dataset and queries')
center = np.mean(dataset, axis=0)
dataset -= center
queries -= center
print('Done')
params_cp = falconn.LSHConstructionParameters()
params_cp.dimension = len(dataset[0])
params_cp.lsh_family = falconn.LSHFamily.CrossPolytope
params_cp.distance_function = falconn.DistanceFunction.EuclideanSquared
params_cp.l = number_of_tables
# we set one rotation, since the data is dense enough,
# for sparse data set it to 2
params_cp.num_rotations = 1
params_cp.seed = 5721840
# we want to use all the available threads to set up
params_cp.num_setup_threads = 0
params_cp.storage_hash_table = falconn.StorageHashTable.BitPackedFlatHashTable
# we build 18-bit hashes so that each table has
# 2^18 bins; this is a good choise since 2^18 is of the same
# order of magnitude as the number of data points
falconn.compute_number_of_hash_functions(18, params_cp)
print('Constructing the LSH table')
t1 = timeit.default_timer()
table = falconn.LSHIndex(params_cp)
table.setup(dataset)
t2 = timeit.default_timer()
print('Done')
print('Construction time: {}'.format(t2 - t1))
query_object = table.construct_query_object()
# find the smallest number of probes to achieve accuracy 0.9
# using the binary search
print('Choosing number of probes')
number_of_probes = number_of_tables
def evaluate_number_of_probes(number_of_probes):
query_object.set_num_probes(number_of_probes)
score = 0
for (i, query) in enumerate(queries):
if answers[i] in query_object.get_candidates_with_duplicates(
query):
score += 1
return float(score) / len(queries)
while True:
accuracy = evaluate_number_of_probes(number_of_probes)
print('{} -> {}'.format(number_of_probes, accuracy))
if accuracy >= 0.9:
break
number_of_probes = number_of_probes * 2
if number_of_probes > number_of_tables:
left = number_of_probes // 2
right = number_of_probes
while right - left > 1:
number_of_probes = (left + right) // 2
accuracy = evaluate_number_of_probes(number_of_probes)
print('{} -> {}'.format(number_of_probes, accuracy))
if accuracy >= 0.9:
right = number_of_probes
else:
left = number_of_probes
number_of_probes = right
print('Done')
print('{} probes'.format(number_of_probes))
# final evaluation
t1 = timeit.default_timer()
score = 0
for (i, query) in enumerate(queries):
if query_object.find_nearest_neighbor(query) == answers[i]:
score += 1
t2 = timeit.default_timer()
print('Query time: {}'.format((t2 - t1) / len(queries)))
print('Precision: {}'.format(float(score) / len(queries)))
| 1,795 |
740 | <filename>src/main/com/ggstar/example/JPMMLModelServing.java
package com.ggstar.example;
import com.ggstar.serving.jpmml.load.JavaModelServer;
import org.dmg.pmml.FieldName;
import java.util.HashMap;
import java.util.Map;
public class JPMMLModelServing {
public static void main(String[] args){
JavaModelServer javaModelServer = new JavaModelServer("model/inn.model.jpmml.xml");
HashMap<String, Object> featureMap = new HashMap<>();
featureMap.put("user_id", 20143);
featureMap.put("item_id", 52);
featureMap.put("category_id", 16);
featureMap.put("content_type", "movie");
featureMap.put("timestamp", "1533487890");
featureMap.put("user_item_click", 0L);
featureMap.put("user_item_imp", 0.69314718d);
featureMap.put("item_ctr", 0.00617256d);
featureMap.put("is_new_user", 0);
featureMap.put("embedding_inner_product", 0.5);
Map<FieldName, ?> result = javaModelServer.forecast(featureMap);
for (Map.Entry<FieldName, ?> field : result.entrySet()){
System.out.println(field.getKey().getValue() + ":\t" + field.getValue());
}
for(int i = 0 ; i < result.size(); i++){
System.out.println(result);
}
System.out.println(result.get(new FieldName("probability(1)")));
}
}
| 572 |
3,285 | /*
Copyright 2020 The OneFlow 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.
*/
#ifndef ONEFLOW_CORE_VM_REF_CNT_VM_INSTRUCTION_STATUS_QUERIER_H_
#define ONEFLOW_CORE_VM_REF_CNT_VM_INSTRUCTION_STATUS_QUERIER_H_
#include <atomic>
#include <memory>
namespace oneflow {
namespace vm {
class RefCntInstrStatusQuerier {
public:
~RefCntInstrStatusQuerier() = default;
bool done() const { return launched_ && *ref_cnt_ == 0; }
void SetRefCntAndSetLaunched(const std::shared_ptr<std::atomic<int64_t>>& ref_cnt) {
// No lock needed. This function will be called only one time.
// In most cases, errors will be successfully detected by CHECK
// even though run in different threads.
CHECK(!launched_);
ref_cnt_ = ref_cnt;
launched_ = true;
}
static const RefCntInstrStatusQuerier* Cast(const char* mem_ptr) {
return reinterpret_cast<const RefCntInstrStatusQuerier*>(mem_ptr);
}
static RefCntInstrStatusQuerier* MutCast(char* mem_ptr) {
return reinterpret_cast<RefCntInstrStatusQuerier*>(mem_ptr);
}
static RefCntInstrStatusQuerier* PlacementNew(char* mem_ptr) {
return new (mem_ptr) RefCntInstrStatusQuerier();
}
private:
RefCntInstrStatusQuerier() : launched_(false), ref_cnt_() {}
std::atomic<bool> launched_;
std::shared_ptr<std::atomic<int64_t>> ref_cnt_;
};
} // namespace vm
} // namespace oneflow
#endif // ONEFLOW_CORE_VM_REF_CNT_VM_INSTRUCTION_STATUS_QUERIER_H_
| 678 |
14,668 | // Copyright 2019 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.
#ifndef CHROME_CHROME_CLEANER_ENGINES_BROKER_CLEANER_SANDBOX_INTERFACE_H_
#define CHROME_CHROME_CLEANER_ENGINES_BROKER_CLEANER_SANDBOX_INTERFACE_H_
#include <stdint.h>
#include <memory>
#include "base/callback_forward.h"
#include "chrome/chrome_cleaner/os/file_path_set.h"
#include "chrome/chrome_cleaner/os/file_remover_api.h"
#include "chrome/chrome_cleaner/strings/wstring_embedded_nulls.h"
namespace chrome_cleaner_sandbox {
enum class TerminateProcessResult {
kSuccess,
kFailed,
kDenied,
};
bool SandboxNtDeleteRegistryKey(
const chrome_cleaner::WStringEmbeddedNulls& key);
bool SandboxNtDeleteRegistryValue(
const chrome_cleaner::WStringEmbeddedNulls& key,
const chrome_cleaner::WStringEmbeddedNulls& value_name);
typedef base::RepeatingCallback<bool(
const chrome_cleaner::WStringEmbeddedNulls& key,
const chrome_cleaner::WStringEmbeddedNulls& value_name)>
ShouldNormalizeRegistryValue;
bool DefaultShouldValueBeNormalized(
const chrome_cleaner::WStringEmbeddedNulls& key,
const chrome_cleaner::WStringEmbeddedNulls& value_name);
bool SandboxNtChangeRegistryValue(
const chrome_cleaner::WStringEmbeddedNulls& key,
const chrome_cleaner::WStringEmbeddedNulls& value_name,
const chrome_cleaner::WStringEmbeddedNulls& new_value,
const ShouldNormalizeRegistryValue& should_normalize_callback);
bool SandboxDeleteService(const std::wstring& name);
bool SandboxDeleteTask(const std::wstring& name);
TerminateProcessResult SandboxTerminateProcess(uint32_t process_id);
} // namespace chrome_cleaner_sandbox
#endif // CHROME_CHROME_CLEANER_ENGINES_BROKER_CLEANER_SANDBOX_INTERFACE_H_
| 641 |
734 | <filename>app/src/main/java/com/cheikh/lazywaimai/model/event/OrderStatusChangedEvent.java
package com.cheikh.lazywaimai.model.event;
/**
* author:cheikh.wang on 16/7/18 14:21
* email:<EMAIL>
*/
public class OrderStatusChangedEvent extends BaseArgumentEvent<String> {
public OrderStatusChangedEvent(int callingId, String orderId) {
super(callingId, orderId);
}
public String getOrderId() {
return arg;
}
} | 168 |
645 | // Copyright 2012 Viewfinder. All rights reserved.
// Author: <NAME>.
#ifdef TESTING
#include "Diff.h"
#include "Testing.h"
#include "Utils.h"
namespace {
string DiffStringsDebug(Slice from, Slice to) {
vector<DiffOp> out;
DiffStrings(from, to, &out, DIFF_CHARACTERS);
string r;
for (int i = 0; i < out.size(); ++i) {
const DiffOp& op = out[i];
const char* prefix = "";
switch (op.type) {
case DiffOp::MATCH:
break;
case DiffOp::INSERT:
prefix = "+";
break;
case DiffOp::DELETE:
prefix = "-";
break;
}
if (!r.empty()) {
r += ":";
}
Slice use = (op.type == DiffOp::MATCH || op.type == DiffOp::DELETE) ?
from : to;
const char* start = NULL;
for (int j = 0; j < op.offset + op.length; ++j) {
if (j == op.offset) {
start = use.data();
}
CHECK_NE(-1, utfnext(&use));
}
r += Format("%s%s", prefix, Slice(start, use.data() - start));
// Append the offset if not 0.
if (op.offset != 0) {
r += Format("@%d", op.offset);
}
}
return r;
}
string DiffStringsMetrics(Slice from, Slice to, DiffMetric metric) {
vector<DiffOp> out;
DiffStrings(from, to, &out, metric);
string r;
for (int i = 0; i < out.size(); i++) {
const DiffOp& op = out[i];
const char* prefix = "";
switch (op.type) {
case DiffOp::MATCH:
prefix = "=";
break;
case DiffOp::INSERT:
prefix = "+";
break;
case DiffOp::DELETE:
prefix = "-";
break;
};
if (!r.empty()) {
r += ":";
}
r += Format("%s%d", prefix, op.length);
if (op.offset != 0) {
r += Format("@%d", op.offset);
}
}
return r;
}
TEST(DiffTest, Basic) {
EXPECT_EQ("a", DiffStringsDebug("a", "a"));
EXPECT_EQ("+a", DiffStringsDebug("", "a"));
EXPECT_EQ("-a", DiffStringsDebug("a", ""));
EXPECT_EQ("a:+bc@1", DiffStringsDebug("a", "abc"));
EXPECT_EQ("a:-bc@1", DiffStringsDebug("abc", "a"));
EXPECT_EQ("+ab:c", DiffStringsDebug("c", "abc"));
EXPECT_EQ("-ab:c@2", DiffStringsDebug("abc", "c"));
EXPECT_EQ("a:+bc@1:d@1", DiffStringsDebug("ad", "abcd"));
EXPECT_EQ("a:-bc@1:d@3", DiffStringsDebug("abcd", "ad"));
EXPECT_EQ("a:+b@1:c@1:+d@3", DiffStringsDebug("ac", "abcd"));
EXPECT_EQ("a:-b@1:c@2:-d@3", DiffStringsDebug("abcd", "ac"));
EXPECT_EQ("-abc:+def", DiffStringsDebug("abc", "def"));
}
TEST(DiffTest, UTF8) {
EXPECT_EQ("\u8000", DiffStringsDebug("\u8000", "\u8000"));
EXPECT_EQ("\u8000:+\u801A@1", DiffStringsDebug("\u8000", "\u8000\u801A"));
EXPECT_EQ("\u8000:-\u801A@1", DiffStringsDebug("\u8000\u801A", "\u8000"));
EXPECT_EQ("-\u8000:\u801A@1", DiffStringsDebug("\u8000\u801A", "\u801A"));
EXPECT_EQ("-a:\u8000@1:-b@2:\u801A@3", DiffStringsDebug("a\u8000b\u801A", "\u8000\u801A"));
EXPECT_EQ("\u8000:+a@1:\u801A@1:+b@3", DiffStringsDebug("\u8000\u801A", "\u8000a\u801Ab"));
}
TEST(DiffTest, Emoji) {
// Emoji are special because they're outside the basic multilingual plane.
// In utf8 everything works normally, but in utf16 they take up two
// codepoints.
const char* kManWithTurban = "\U0001f473";
const char* kPileOfPoo = "\U0001f4a9";
const char* kMoonViewingCeremony = "\U0001F391";
// Make sure that the compiler turns \U escapes into utf8.
EXPECT_EQ("\xf0\x9f\x91\xb3", kManWithTurban);
// Basic insertion and removal.
EXPECT_EQ("+\U0001f473", DiffStringsDebug("", kManWithTurban));
EXPECT_EQ("-\U0001f391", DiffStringsDebug(kMoonViewingCeremony, ""));
// Edits happen with characters, not bytes.
EXPECT_EQ("-\U0001f473:+\U0001f4a9", DiffStringsDebug(kManWithTurban, kPileOfPoo));
// Offsets are measured in characters by default.
const char* kAddRemoveWithOffset1 = "\U0001f391a b\U0001f473";
const char* kAddRemoveWithOffset2 = "\U0001f391a c\U0001f4a9";
EXPECT_EQ("\U0001f391a :-b\U0001f473@3:+c\U0001f4a9@3", DiffStringsDebug(kAddRemoveWithOffset1, kAddRemoveWithOffset2));
// Check the offset measurements for different metrics.
EXPECT_EQ("=3:-2@3:+2@3", DiffStringsMetrics(kAddRemoveWithOffset1, kAddRemoveWithOffset2, DIFF_CHARACTERS));
EXPECT_EQ("=4:-3@4:+3@4", DiffStringsMetrics(kAddRemoveWithOffset1, kAddRemoveWithOffset2, DIFF_UTF16));
// When lengths change, make sure the metrics are reported for the correct
// string.
EXPECT_EQ("-1:+1", DiffStringsMetrics("a", kMoonViewingCeremony, DIFF_CHARACTERS));
EXPECT_EQ("-1:+2", DiffStringsMetrics("a", kMoonViewingCeremony, DIFF_UTF16));
// A more complicated (and unfortunately illegible) string that tests
// some more cases, with changes before and after emoji characters,
// as well as regular unicode characters (which still count as one
// codepoint).
const char* kLongString1 = "\U0001f473 abc 123 \u1234 \U0001f4a9";
const char* kLongString2 = "\U0001f473 abd 145 \U0001f4a9 \u1200";
EXPECT_EQ("\U0001f473 ab:-c@4:+d@4: 1@5:-23 \u1234@7:+45@7: \U0001f4a9@11:+ \u1200@11", DiffStringsDebug(kLongString1, kLongString2));
EXPECT_EQ("=4:-1@4:+1@4:=2@5:-4@7:+2@7:=2@11:+2@11", DiffStringsMetrics(kLongString1, kLongString2, DIFF_CHARACTERS));
EXPECT_EQ("=5:-1@5:+1@5:=2@6:-4@8:+2@8:=3@12:+2@13", DiffStringsMetrics(kLongString1, kLongString2, DIFF_UTF16));
}
TEST(DiffTest, States) {
EXPECT_EQ("A:-L@1:+labama@1", DiffStringsDebug("AL", "Alabama"));
EXPECT_EQ("A:-K@1:+laska@1", DiffStringsDebug("AK", "Alaska"));
EXPECT_EQ("A:-Z@1:+rizona@1", DiffStringsDebug("AZ", "Arizona"));
EXPECT_EQ("A:-R@1:+rkansas@1", DiffStringsDebug("AR", "Arkansas"));
EXPECT_EQ("C:-A@1:+alifornia@1", DiffStringsDebug("CA", "California"));
EXPECT_EQ("C:-O@1:+olorado@1", DiffStringsDebug("CO", "Colorado"));
EXPECT_EQ("C:-T@1:+onnecticut@1", DiffStringsDebug("CT", "Connecticut"));
EXPECT_EQ("D:-E@1:+elaware@1", DiffStringsDebug("DE", "Delaware"));
EXPECT_EQ("F:-L@1:+lorida@1", DiffStringsDebug("FL", "Florida"));
EXPECT_EQ("G:-A@1:+eorgia@1", DiffStringsDebug("GA", "Georgia"));
EXPECT_EQ("H:-I@1:+awaii@1", DiffStringsDebug("HI", "Hawaii"));
EXPECT_EQ("I:-D@1:+daho@1", DiffStringsDebug("ID", "Idaho"));
EXPECT_EQ("I:-L@1:+llinois@1", DiffStringsDebug("IL", "Illinois"));
EXPECT_EQ("I:-N@1:+ndiana@1", DiffStringsDebug("IN", "Indiana"));
EXPECT_EQ("I:-A@1:+owa@1", DiffStringsDebug("IA", "Iowa"));
EXPECT_EQ("K:-S@1:+ansas@1", DiffStringsDebug("KS", "Kansas"));
EXPECT_EQ("K:-Y@1:+entucky@1", DiffStringsDebug("KY", "Kentucky"));
EXPECT_EQ("L:-A@1:+ouisiana@1", DiffStringsDebug("LA", "Louisiana"));
EXPECT_EQ("M:-E@1:+aine@1", DiffStringsDebug("ME", "Maine"));
EXPECT_EQ("M:-D@1:+aryland@1", DiffStringsDebug("MD", "Maryland"));
EXPECT_EQ("M:-A@1:+assachusetts@1", DiffStringsDebug("MA", "Massachusetts"));
EXPECT_EQ("M:-I@1:+ichigan@1", DiffStringsDebug("MI", "Michigan"));
EXPECT_EQ("M:-N@1:+innesota@1", DiffStringsDebug("MN", "Minnesota"));
EXPECT_EQ("M:-S@1:+ississippi@1", DiffStringsDebug("MS", "Mississippi"));
EXPECT_EQ("M:-O@1:+issouri@1", DiffStringsDebug("MO", "Missouri"));
EXPECT_EQ("M:-T@1:+ontana@1", DiffStringsDebug("MT", "Montana"));
EXPECT_EQ("N:-E@1:+ebraska@1", DiffStringsDebug("NE", "Nebraska"));
EXPECT_EQ("N:-V@1:+evada@1", DiffStringsDebug("NV", "Nevada"));
EXPECT_EQ("N:+ew @1:H@1:+ampshire@5", DiffStringsDebug("NH", "New Hampshire"));
EXPECT_EQ("N:+ew @1:J@1:+ersey@5", DiffStringsDebug("NJ", "New Jersey"));
EXPECT_EQ("N:+ew @1:M@1:+exico@5", DiffStringsDebug("NM", "New Mexico"));
EXPECT_EQ("N:+ew @1:Y@1:+ork@5", DiffStringsDebug("NY", "New York"));
EXPECT_EQ("N:+orth @1:C@1:+arolina@7", DiffStringsDebug("NC", "North Carolina"));
EXPECT_EQ("N:+orth @1:D@1:+akota@7", DiffStringsDebug("ND", "North Dakota"));
EXPECT_EQ("O:-H@1:+hio@1", DiffStringsDebug("OH", "Ohio"));
EXPECT_EQ("O:-K@1:+klahoma@1", DiffStringsDebug("OK", "Oklahoma"));
EXPECT_EQ("O:-R@1:+regon@1", DiffStringsDebug("OR", "Oregon"));
EXPECT_EQ("P:-A@1:+ennsylvania@1", DiffStringsDebug("PA", "Pennsylvania"));
EXPECT_EQ("R:+hode @1:I@1:+sland@7", DiffStringsDebug("RI", "Rhode Island"));
EXPECT_EQ("S:+outh @1:C@1:+arolina@7", DiffStringsDebug("SC", "South Carolina"));
EXPECT_EQ("S:+outh @1:D@1:+akota@7", DiffStringsDebug("SD", "South Dakota"));
EXPECT_EQ("T:-N@1:+ennessee@1", DiffStringsDebug("TN", "Tennessee"));
EXPECT_EQ("T:-X@1:+exas@1", DiffStringsDebug("TX", "Texas"));
EXPECT_EQ("U:-T@1:+tah@1", DiffStringsDebug("UT", "Utah"));
EXPECT_EQ("V:-T@1:+ermont@1", DiffStringsDebug("VT", "Vermont"));
EXPECT_EQ("V:-A@1:+irginia@1", DiffStringsDebug("VA", "Virginia"));
EXPECT_EQ("W:-A@1:+ashington@1", DiffStringsDebug("WA", "Washington"));
EXPECT_EQ("W:+est @1:V@1:+irginia@6", DiffStringsDebug("WV", "West Virginia"));
EXPECT_EQ("W:-I@1:+isconsin@1", DiffStringsDebug("WI", "Wisconsin"));
EXPECT_EQ("W:-Y@1:+yoming@1", DiffStringsDebug("WY", "Wyoming"));
}
} // namespace
#endif // TESTING
| 4,000 |
496 | <gh_stars>100-1000
package me.j360.dubbo.batch.listener;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
/**
* Package: me.j360.dubbo.batch.listener
* User: min_xu
* Date: 2017/11/1 下午7:56
* 说明:
*/
public class SampleStepListener implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
//使用环境容器自定义变量
stepExecution.getExecutionContext().putLong("id", 100L);
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
| 270 |
337 | <gh_stars>100-1000
package testing;
import testing.rename.C;
class JavaClient {
public void foo() {
new C().second();
}
}
| 58 |
3,372 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.finspace.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/finspace-2021-03-12/UpdateEnvironment" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateEnvironmentRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The identifier of the FinSpace environment.
* </p>
*/
private String environmentId;
/**
* <p>
* The name of the environment.
* </p>
*/
private String name;
/**
* <p>
* The description of the environment.
* </p>
*/
private String description;
/**
* <p>
* Authentication mode for the environment.
* </p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* </ul>
*/
private String federationMode;
private FederationParameters federationParameters;
/**
* <p>
* The identifier of the FinSpace environment.
* </p>
*
* @param environmentId
* The identifier of the FinSpace environment.
*/
public void setEnvironmentId(String environmentId) {
this.environmentId = environmentId;
}
/**
* <p>
* The identifier of the FinSpace environment.
* </p>
*
* @return The identifier of the FinSpace environment.
*/
public String getEnvironmentId() {
return this.environmentId;
}
/**
* <p>
* The identifier of the FinSpace environment.
* </p>
*
* @param environmentId
* The identifier of the FinSpace environment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateEnvironmentRequest withEnvironmentId(String environmentId) {
setEnvironmentId(environmentId);
return this;
}
/**
* <p>
* The name of the environment.
* </p>
*
* @param name
* The name of the environment.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the environment.
* </p>
*
* @return The name of the environment.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the environment.
* </p>
*
* @param name
* The name of the environment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateEnvironmentRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The description of the environment.
* </p>
*
* @param description
* The description of the environment.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The description of the environment.
* </p>
*
* @return The description of the environment.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The description of the environment.
* </p>
*
* @param description
* The description of the environment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateEnvironmentRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* Authentication mode for the environment.
* </p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* </ul>
*
* @param federationMode
* Authentication mode for the environment.</p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* @see FederationMode
*/
public void setFederationMode(String federationMode) {
this.federationMode = federationMode;
}
/**
* <p>
* Authentication mode for the environment.
* </p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* </ul>
*
* @return Authentication mode for the environment.</p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace
* environment.
* </p>
* </li>
* @see FederationMode
*/
public String getFederationMode() {
return this.federationMode;
}
/**
* <p>
* Authentication mode for the environment.
* </p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* </ul>
*
* @param federationMode
* Authentication mode for the environment.</p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see FederationMode
*/
public UpdateEnvironmentRequest withFederationMode(String federationMode) {
setFederationMode(federationMode);
return this;
}
/**
* <p>
* Authentication mode for the environment.
* </p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* </ul>
*
* @param federationMode
* Authentication mode for the environment.</p>
* <ul>
* <li>
* <p>
* <code>FEDERATED</code> - Users access FinSpace through Single Sign On (SSO) via your Identity provider.
* </p>
* </li>
* <li>
* <p>
* <code>LOCAL</code> - Users access FinSpace via email and password managed within the FinSpace environment.
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
* @see FederationMode
*/
public UpdateEnvironmentRequest withFederationMode(FederationMode federationMode) {
this.federationMode = federationMode.toString();
return this;
}
/**
* @param federationParameters
*/
public void setFederationParameters(FederationParameters federationParameters) {
this.federationParameters = federationParameters;
}
/**
* @return
*/
public FederationParameters getFederationParameters() {
return this.federationParameters;
}
/**
* @param federationParameters
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateEnvironmentRequest withFederationParameters(FederationParameters federationParameters) {
setFederationParameters(federationParameters);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEnvironmentId() != null)
sb.append("EnvironmentId: ").append(getEnvironmentId()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getFederationMode() != null)
sb.append("FederationMode: ").append(getFederationMode()).append(",");
if (getFederationParameters() != null)
sb.append("FederationParameters: ").append(getFederationParameters());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateEnvironmentRequest == false)
return false;
UpdateEnvironmentRequest other = (UpdateEnvironmentRequest) obj;
if (other.getEnvironmentId() == null ^ this.getEnvironmentId() == null)
return false;
if (other.getEnvironmentId() != null && other.getEnvironmentId().equals(this.getEnvironmentId()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getFederationMode() == null ^ this.getFederationMode() == null)
return false;
if (other.getFederationMode() != null && other.getFederationMode().equals(this.getFederationMode()) == false)
return false;
if (other.getFederationParameters() == null ^ this.getFederationParameters() == null)
return false;
if (other.getFederationParameters() != null && other.getFederationParameters().equals(this.getFederationParameters()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEnvironmentId() == null) ? 0 : getEnvironmentId().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getFederationMode() == null) ? 0 : getFederationMode().hashCode());
hashCode = prime * hashCode + ((getFederationParameters() == null) ? 0 : getFederationParameters().hashCode());
return hashCode;
}
@Override
public UpdateEnvironmentRequest clone() {
return (UpdateEnvironmentRequest) super.clone();
}
}
| 5,344 |
872 | package com.github.glomadrian.mvpcleanarchitecture.ui.view;
import com.github.glomadrian.mvpcleanarchitecture.ui.viewmodel.CharacterInfoViewModel;
/**
* @author glomadrian
*/
public interface ModelInfoView extends View {
void showCharacterInfo(CharacterInfoViewModel characterInfoViewModel);
}
| 93 |
522 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""Confusion matrix related metrics."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import confusion_matrix as cm
def confusion_matrix(labels, predictions, num_classes=None, dtype=dtypes.int32,
name=None, weights=None):
"""Deprecated. Use tf.confusion_matrix instead."""
return cm.confusion_matrix(labels=labels, predictions=predictions,
num_classes=num_classes, dtype=dtype, name=name,
weights=weights)
| 401 |
336 | package me.saket.dank.data;
import androidx.annotation.StringRes;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class EmptyState {
@StringRes
public abstract int emojiRes();
@StringRes
public abstract int messageRes();
public static EmptyState create(@StringRes int emojisRes, @StringRes int messageRes) {
return new AutoValue_EmptyState(emojisRes, messageRes);
}
}
| 127 |
439 |
import java.lang.reflect.Array;
import java.util.NoSuchElementException;
import java.util.Objects;
class SimpleLinkedList<T> {
private static class Element<T> {
final T value;
Element<T> next;
Element(T value) {
this.value = value;
}
}
private Element<T> head;
private int size;
SimpleLinkedList() {
}
SimpleLinkedList(T[] values) {
for (int i = values.length - 1; i >= 0; i--) {
push(values[i]);
}
}
final void push(T value) {
Element<T> newElement = new Element<>(value);
this.size++;
if (Objects.isNull(head)) {
head = newElement;
} else {
newElement.next = head;
head = newElement;
}
}
T pop() {
if (Objects.isNull(head)) {
throw new NoSuchElementException();
}
T value = head.value;
head = head.next;
this.size--;
return value;
}
void reverse() {
Element<T> current = head;
Element<T> next;
Element<T> previous = null;
while (Objects.nonNull(current)) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
head = previous;
}
T[] asArray(Class<T> clazz) {
T[] result = newArray(clazz, size);
int index = 0;
Element<T> current = head;
while (Objects.nonNull(current)) {
result[index++] = current.value;
current = current.next;
}
return result;
}
private T[] newArray(Class<T> clazz, int size) {
@SuppressWarnings("unchecked")
T[] arr = (T[]) Array.newInstance(clazz, size);
return arr;
}
int size() {
return this.size;
}
}
| 914 |
25,151 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.remote.http;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An incredibly bad implementation of URL Templates, but enough for our needs.
*/
public class UrlTemplate {
private static final Pattern GROUP_NAME = Pattern.compile("\\(\\?<([a-zA-Z][a-zA-Z0-9]*)>");
private final List<Matches> template;
public UrlTemplate(String template) {
if (template == null || template.isEmpty()) {
throw new IllegalArgumentException("Template must not be 0 length");
}
ImmutableList.Builder<Matches> fragments = ImmutableList.builder();
for (String fragment : template.split("/")) {
// Convert the fragment to a pattern by replacing "{...}" with a capturing group. We capture
// from the opening '{' and do a non-greedy match of letters until the closing '}'.
Matcher matcher = Pattern.compile("\\{(\\p{Alnum}+?)\\}").matcher(fragment);
String toCompile = matcher.replaceAll("(?<$1>[^/]+)");
// There's no API for getting the names of capturing groups from a pattern in java. So we're
// going to use a regex to find them. ffs.
Matcher groupNameMatcher = GROUP_NAME.matcher(toCompile);
ImmutableList.Builder<String> names = ImmutableList.builder();
while (groupNameMatcher.find()) {
names.add(groupNameMatcher.group(1));
}
fragments.add(new Matches(Pattern.compile(Matcher.quoteReplacement(toCompile)), names.build()));
}
this.template = fragments.build();
}
/**
* @return A {@link Match} with all parameters filled if successful, null otherwise.
*/
public UrlTemplate.Match match(String matchAgainst) {
if (matchAgainst == null) {
return null;
}
String[] fragments = matchAgainst.split("/");
if (fragments.length != template.size()) {
return null;
}
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
for (int i = 0; i < fragments.length; i++) {
Matcher matcher = template.get(i).matcher(fragments[i]);
if (!matcher.find()) {
return null;
}
for (String name : template.get(i).groupNames) {
params.put(name, matcher.group(name));
}
}
return new Match(matchAgainst, params.build());
}
@SuppressWarnings("InnerClassMayBeStatic")
public class Match {
private final String url;
private final Map<String, String> parameters;
private Match(String url, Map<String, String> parameters) {
this.url = url;
this.parameters = ImmutableMap.copyOf(parameters);
}
public String getUrl() {
return url;
}
public Map<String, String> getParameters() {
return parameters;
}
}
private static class Matches {
private final Pattern pattern;
private final List<String> groupNames;
private Matches(Pattern pattern, List<String> groupNames) {
this.pattern = pattern;
this.groupNames = groupNames;
}
public Matcher matcher(String fragment) {
return pattern.matcher(fragment);
}
}
}
| 1,323 |
886 | <reponame>sbrown-uhd/hazelcast-cpp-client<gh_stars>100-1000
#ifndef BOOST_ARCHIVE_ITERATORS_MB_FROM_WCHAR_HPP
#define BOOST_ARCHIVE_ITERATORS_MB_FROM_WCHAR_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// mb_from_wchar.hpp
// (C) Copyright 2002 <NAME> - http://www.rrsd.com .
// Use, modification and distribution is subject to 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 for updates, documentation, and revision history.
#include <boost/assert.hpp>
#include <cstddef> // size_t
#include <cwchar> // mbstate_t
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::mbstate_t;
} // namespace std
#endif
#include <boost/archive/detail/utf8_codecvt_facet.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
namespace boost {
namespace archive {
namespace iterators {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// class used by text archives to translate wide strings and to char
// strings of the currently selected locale
template<class Base> // the input iterator
class mb_from_wchar
: public boost::iterator_adaptor<
mb_from_wchar<Base>,
Base,
wchar_t,
single_pass_traversal_tag,
char
>
{
friend class boost::iterator_core_access;
typedef typename boost::iterator_adaptor<
mb_from_wchar<Base>,
Base,
wchar_t,
single_pass_traversal_tag,
char
> super_t;
typedef mb_from_wchar<Base> this_t;
char dereference_impl() {
if(! m_full){
fill();
m_full = true;
}
return m_buffer[m_bnext];
}
char dereference() const {
return (const_cast<this_t *>(this))->dereference_impl();
}
// test for iterator equality
bool equal(const mb_from_wchar<Base> & rhs) const {
// once the value is filled, the base_reference has been incremented
// so don't permit comparison anymore.
return
0 == m_bend
&& 0 == m_bnext
&& this->base_reference() == rhs.base_reference()
;
}
void fill(){
wchar_t value = * this->base_reference();
const wchar_t *wend;
char *bend;
std::codecvt_base::result r = m_codecvt_facet.out(
m_mbs,
& value, & value + 1, wend,
m_buffer, m_buffer + sizeof(m_buffer), bend
);
BOOST_ASSERT(std::codecvt_base::ok == r);
m_bnext = 0;
m_bend = bend - m_buffer;
}
void increment(){
if(++m_bnext < m_bend)
return;
m_bend =
m_bnext = 0;
++(this->base_reference());
m_full = false;
}
boost::archive::detail::utf8_codecvt_facet m_codecvt_facet;
std::mbstate_t m_mbs;
// buffer to handle pending characters
char m_buffer[9 /* MB_CUR_MAX */];
std::size_t m_bend;
std::size_t m_bnext;
bool m_full;
public:
// make composible buy using templated constructor
template<class T>
mb_from_wchar(T start) :
super_t(Base(static_cast< T >(start))),
m_mbs(std::mbstate_t()),
m_bend(0),
m_bnext(0),
m_full(false)
{}
// intel 7.1 doesn't like default copy constructor
mb_from_wchar(const mb_from_wchar & rhs) :
super_t(rhs.base_reference()),
m_bend(rhs.m_bend),
m_bnext(rhs.m_bnext),
m_full(rhs.m_full)
{}
};
} // namespace iterators
} // namespace archive
} // namespace boost
#endif // BOOST_ARCHIVE_ITERATORS_MB_FROM_WCHAR_HPP
| 1,738 |
1,345 | """Evented dictionary"""
import sys
from typing import (
Any,
Dict,
Iterator,
Mapping,
MutableMapping,
Sequence,
Type,
TypeVar,
Union,
)
_K = TypeVar("_K")
_T = TypeVar("_T")
class TypedMutableMapping(MutableMapping[_K, _T]):
"""Dictionary mixin that enforces item type."""
def __init__(
self,
data: Mapping[_K, _T] = None,
basetype: Union[Type[_T], Sequence[Type[_T]]] = (),
):
if data is None:
data = {}
self._dict: Dict[_K, _T] = dict()
self._basetypes = (
basetype if isinstance(basetype, Sequence) else (basetype,)
)
self.update(data)
# #### START Required Abstract Methods
def __setitem__(self, key: int, value: _T): # noqa: F811
self._dict[key] = self._type_check(value)
def __delitem__(self, key: _K) -> None:
del self._dict[key]
def __getitem__(self, key: _K) -> _T:
return self._dict[key]
def __len__(self) -> int:
return len(self._dict)
def __iter__(self) -> Iterator[_T]:
return iter(self._dict)
def __repr__(self):
return str(self._dict)
if sys.version_info < (3, 8):
def __hash__(self):
# We've explicitly added __hash__ for python < 3.8 because otherwise
# nested evented dictionaries fail tests.
# This can be removed once we drop support for python < 3.8
# see: https://github.com/napari/napari/pull/2994#issuecomment-877105434
return hash(frozenset(self))
def _type_check(self, e: Any) -> _T:
if self._basetypes and not any(
isinstance(e, t) for t in self._basetypes
):
raise TypeError(
f"Cannot add object with type {type(e)} to TypedDict expecting type {self._basetypes}",
)
return e
def __newlike__(self, iterable: MutableMapping[_K, _T]):
new = self.__class__()
# separating this allows subclasses to omit these from their `__init__`
new._basetypes = self._basetypes
new.update(**iterable)
return new
def copy(self) -> "TypedMutableMapping[_T]":
"""Return a shallow copy of the dictionary."""
return self.__newlike__(self)
| 1,044 |
313 | {"status_id":8748557077053440,"text":"Ofa nab mi alo avatewce zaeto ud focu jef fu jo fu gaocauga bospeb sapbonbo repbu fadpi. #moko","user":{"user_id":874677912207360,"name":"<NAME>","screen_name":"@dead","created_at":826410191,"followers_count":59,"friends_count":23,"favourites_count":13},"created_at":213585489,"favorite_count":16,"retweet_count":632,"entities":{"hashtags":[{"text":"#moko","indices":[2,11]}]},"in_reply_to_status_id":null} | 173 |
2,261 | #ifndef CTRE__STARTS_WITH_ANCHOR__HPP
#define CTRE__STARTS_WITH_ANCHOR__HPP
#include "flags_and_modes.hpp"
namespace ctre {
template <typename... Content>
constexpr bool starts_with_anchor(const flags &, ctll::list<Content...>) noexcept {
return false;
}
template <typename... Content>
constexpr bool starts_with_anchor(const flags &, ctll::list<assert_subject_begin, Content...>) noexcept {
// yes! start subject anchor is here
return true;
}
template <typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<assert_line_begin, Content...>) noexcept {
// yes! start line anchor is here
return !ctre::multiline_mode(f) || starts_with_anchor(f, ctll::list<Content...>{});
}
template <typename CharLike, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<boundary<CharLike>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Content...>{});
}
template <typename... Options, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<select<Options...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return (starts_with_anchor(f, ctll::list<Options, Content...>{}) && ... && true);
}
template <typename... Optional, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<optional<Optional...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Optional..., Content...>{}) && starts_with_anchor(f, ctll::list<Content...>{});
}
template <typename... Optional, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<lazy_optional<Optional...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Optional..., Content...>{}) && starts_with_anchor(f, ctll::list<Content...>{});
}
template <typename... Seq, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<sequence<Seq...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Seq..., Content...>{});
}
template <size_t A, size_t B, typename... Seq, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<repeat<A, B, Seq...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Seq..., Content...>{});
}
template <size_t A, size_t B, typename... Seq, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<lazy_repeat<A, B, Seq...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Seq..., Content...>{});
}
template <size_t A, size_t B, typename... Seq, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<possessive_repeat<A, B, Seq...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Seq..., Content...>{});
}
template <size_t Index, typename... Seq, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<capture<Index, Seq...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Seq..., Content...>{});
}
template <size_t Index, typename... Seq, typename... Content>
constexpr bool starts_with_anchor(const flags & f, ctll::list<capture_with_name<Index, Seq...>, Content...>) noexcept {
// check if all options starts with anchor or if they are empty, there is an anchor behind them
return starts_with_anchor(f, ctll::list<Seq..., Content...>{});
}
}
#endif
| 1,388 |
589 | package rocks.inspectit.shared.cs.ci.assignment.impl;
import javax.xml.bind.annotation.XmlTransient;
import rocks.inspectit.shared.cs.ci.sensor.method.special.AbstractSpecialMethodSensorConfig;
/**
* Special {@link MethodSensorAssignment} that server for defining special instrumentation points
* with the already existing assignment approach.
*
* @see AbstractSpecialMethodSensorConfig
* @author <NAME>
*
*/
@XmlTransient
public class SpecialMethodSensorAssignment extends MethodSensorAssignment {
/**
* {@link AbstractSpecialMethodSensorConfig}.
*/
private AbstractSpecialMethodSensorConfig specialMethodSensorConfig;
/**
* No-arg constructor.
*/
protected SpecialMethodSensorAssignment() {
}
/**
* Default constructor.
*
* @param specialMethodSensorConfig
* {@link AbstractSpecialMethodSensorConfig}.
*/
public SpecialMethodSensorAssignment(AbstractSpecialMethodSensorConfig specialMethodSensorConfig) {
super(specialMethodSensorConfig.getClass());
this.specialMethodSensorConfig = specialMethodSensorConfig;
}
/**
* Gets {@link #specialMethodSensorConfig}.
*
* @return {@link #specialMethodSensorConfig}
*/
public AbstractSpecialMethodSensorConfig getSpecialMethodSensorConfig() {
return this.specialMethodSensorConfig;
}
/**
* Sets {@link #specialMethodSensorConfig}.
*
* @param specialMethodSensorConfig
* New value for {@link #specialMethodSensorConfig}
*/
public void setSpecialMethodSensorConfig(AbstractSpecialMethodSensorConfig specialMethodSensorConfig) {
this.specialMethodSensorConfig = specialMethodSensorConfig;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = (prime * result) + ((this.specialMethodSensorConfig == null) ? 0 : this.specialMethodSensorConfig.hashCode());
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SpecialMethodSensorAssignment other = (SpecialMethodSensorAssignment) obj;
if (this.specialMethodSensorConfig == null) {
if (other.specialMethodSensorConfig != null) {
return false;
}
} else if (!this.specialMethodSensorConfig.equals(other.specialMethodSensorConfig)) {
return false;
}
return true;
}
}
| 761 |
1,338 | /*
Copyright (c) 2002/03, <NAME>
Part of Radeon accelerant
Programming of internal TV-out unit
*/
#include "radeon_interface.h"
#include "radeon_accelerant.h"
#include "tv_out_regs.h"
#include "pll_access.h"
#include "mmio.h"
#include "utils.h"
#include "set_mode.h"
#include <stdlib.h>
// mapping of offset in impactv_regs to register address
typedef struct register_mapping {
uint16 address; // register address
uint16 offset; // offset in impactv_regs
} register_mapping;
// internal TV-encoder:
// registers to write before programming PLL
static const register_mapping intern_reg_mapping_before_pll[] = {
{ RADEON_TV_MASTER_CNTL, offsetof( impactv_regs, tv_master_cntl ) },
{ RADEON_TV_HRESTART, offsetof( impactv_regs, tv_hrestart ) },
{ RADEON_TV_VRESTART, offsetof( impactv_regs, tv_vrestart ) },
{ RADEON_TV_FRESTART, offsetof( impactv_regs, tv_frestart ) },
{ RADEON_TV_FTOTAL, offsetof( impactv_regs, tv_ftotal ) },
{ 0, 0 }
};
// PLL registers to program
static const register_mapping intern_reg_mapping_pll[] = {
{ RADEON_TV_PLL_CNTL, offsetof( impactv_regs, tv_tv_pll_cntl ) },
{ RADEON_TV_PLL_CNTL1, offsetof( impactv_regs, tv_pll_cntl1 ) },
{ RADEON_TV_PLL_FINE_CNTL, offsetof( impactv_regs, tv_pll_fine_cntl ) },
{ 0, 0 }
};
// registers to write after programming of PLL
static const register_mapping intern_reg_mapping_after_pll[] = {
{ RADEON_TV_HTOTAL, offsetof( impactv_regs, tv_htotal ) },
{ RADEON_TV_HDISP, offsetof( impactv_regs, tv_hdisp ) },
{ RADEON_TV_HSTART, offsetof( impactv_regs, tv_hstart ) },
{ RADEON_TV_VTOTAL, offsetof( impactv_regs, tv_vtotal ) },
{ RADEON_TV_VDISP, offsetof( impactv_regs, tv_vdisp ) },
{ RADEON_TV_TIMING_CNTL, offsetof( impactv_regs, tv_timing_cntl ) },
{ RADEON_TV_VSCALER_CNTL1, offsetof( impactv_regs, tv_vscaler_cntl1 ) },
{ RADEON_TV_VSCALER_CNTL2, offsetof( impactv_regs, tv_vscaler_cntl2 ) },
{ RADEON_TV_Y_SAW_TOOTH_CNTL, offsetof( impactv_regs, tv_y_saw_tooth_cntl ) },
{ RADEON_TV_Y_RISE_CNTL, offsetof( impactv_regs, tv_y_rise_cntl ) },
{ RADEON_TV_Y_FALL_CNTL, offsetof( impactv_regs, tv_y_fall_cntl ) },
{ RADEON_TV_MODULATOR_CNTL1, offsetof( impactv_regs, tv_modulator_cntl1 ) },
{ RADEON_TV_MODULATOR_CNTL2, offsetof( impactv_regs, tv_modulator_cntl2 ) },
{ RADEON_TV_RGB_CNTL, offsetof( impactv_regs, tv_rgb_cntl ) },
{ RADEON_TV_UV_ADR, offsetof( impactv_regs, tv_uv_adr ) },
{ RADEON_TV_PRE_DAC_MUX_CNTL, offsetof( impactv_regs, tv_pre_dac_mux_cntl ) },
{ RADEON_TV_CRC_CNTL, offsetof( impactv_regs, tv_crc_cntl ) },
{ 0, 0 }
};
// registers to write when things settled down
static const register_mapping intern_reg_mapping_finish[] = {
{ RADEON_TV_GAIN_LIMIT_SETTINGS, offsetof( impactv_regs, tv_gain_limit_settings ) },
{ RADEON_TV_LINEAR_GAIN_SETTINGS, offsetof( impactv_regs, tv_linear_gain_settings ) },
{ RADEON_TV_UPSAMP_AND_GAIN_CNTL, offsetof( impactv_regs, tv_upsamp_and_gain_cntl ) },
{ RADEON_TV_DAC_CNTL, offsetof( impactv_regs, tv_dac_cntl ) },
{ RADEON_TV_MASTER_CNTL, offsetof( impactv_regs, tv_master_cntl ) },
{ 0, 0 }
};
// write list of MM I/O registers
static void writeMMIORegList(
accelerator_info *ai, impactv_regs *values, const register_mapping *mapping )
{
vuint8 *regs = ai->regs;
for( ; mapping->address != 0 && mapping->offset != 0; ++mapping ) {
/*SHOW_FLOW( 2, "%x=%x", mapping->address,
*(uint32 *)((char *)(values) + mapping->offset) );*/
OUTREG( regs, mapping->address, *(uint32 *)((char *)(values) + mapping->offset) );
}
//snooze( 1000000 );
}
// write list of PLL registers
static void writePLLRegList(
accelerator_info *ai, impactv_regs *values, const register_mapping *mapping )
{
for( ; mapping->address != 0 && mapping->offset != 0; ++mapping ) {
/*SHOW_FLOW( 2, "%x=%x", mapping->address,
*(uint32 *)((char *)(values) + mapping->offset) );*/
Radeon_OUTPLL( ai->regs, ai->si->asic,
mapping->address, *(uint32 *)((char *)(values) + mapping->offset) );
}
//snooze( 1000000 );
}
// read timing FIFO
#if 0
static uint32 Radeon_InternalTVOutReadFIFO(
accelerator_info *ai, uint16 addr )
{
vuint8 *regs = ai->regs;
bigtime_t start_time;
uint32 res = ~0;
//SHOW_FLOW( 2, "addr=%d", addr );
OUTREG( regs, RADEON_TV_HOST_RD_WT_CNTL, addr | RADEON_TV_HOST_RD_WT_CNTL_RD);
start_time = system_time();
do {
uint32 status;
status = INREG( regs, RADEON_TV_HOST_RD_WT_CNTL );
if( (status & RADEON_TV_HOST_RD_WT_CNTL_RD_ACK) != 0 )
break;
} while( system_time() - start_time < 2000000 );
OUTREG( regs, RADEON_TV_HOST_RD_WT_CNTL, 0);
res = INREG( regs, RADEON_TV_HOST_READ_DATA );
//SHOW_FLOW( 2, "res=%x %x", res >> 14, res & 0x3fff );
return res;
}
#endif
// write to timing FIFO
static void Radeon_InternalTVOutWriteFIFO(
accelerator_info *ai, uint16 addr, uint32 value )
{
vuint8 *regs = ai->regs;
bigtime_t start_time;
//readFIFO( ai, addr, internal_encoder );
//SHOW_FLOW( 2, "addr=%d, value=%x %x", addr, value >> 14, value & 0x3fff );
OUTREG( regs, RADEON_TV_HOST_WRITE_DATA, value );
OUTREG( regs, RADEON_TV_HOST_RD_WT_CNTL, addr | RADEON_TV_HOST_RD_WT_CNTL_WT );
start_time = system_time();
do {
uint32 status;
status = INREG( regs, RADEON_TV_HOST_RD_WT_CNTL );
if( (status & RADEON_TV_HOST_RD_WT_CNTL_WT_ACK) != 0 )
break;
} while( system_time() - start_time < 2000000 );
OUTREG( regs, RADEON_TV_HOST_RD_WT_CNTL, 0 );
}
// program TV-Out registers
void Radeon_InternalTVOutProgramRegisters(
accelerator_info *ai, impactv_regs *values )
{
uint32 orig_tv_master_cntl = values->tv_master_cntl;
SHOW_FLOW0( 2, "" );
// disable TV-out when registers are setup
// it gets enabled again when things have settled down
values->tv_master_cntl |=
RADEON_TV_MASTER_CNTL_TV_ASYNC_RST |
RADEON_TV_MASTER_CNTL_CRT_ASYNC_RST |
RADEON_TV_MASTER_CNTL_TV_FIFO_ASYNC_RST |
RADEON_TV_MASTER_CNTL_VIN_ASYNC_RST |
RADEON_TV_MASTER_CNTL_AUD_ASYNC_RST |
RADEON_TV_MASTER_CNTL_DVS_ASYNC_RST;
writeMMIORegList( ai, values, intern_reg_mapping_before_pll );
writePLLRegList( ai, values, intern_reg_mapping_pll );
writeMMIORegList( ai, values, intern_reg_mapping_after_pll );
// un-reset FIFO to access timing table
OUTREG( ai->regs, RADEON_TV_MASTER_CNTL,
orig_tv_master_cntl |
RADEON_TV_MASTER_CNTL_TV_ASYNC_RST |
RADEON_TV_MASTER_CNTL_CRT_ASYNC_RST |
RADEON_TV_MASTER_CNTL_VIN_ASYNC_RST |
RADEON_TV_MASTER_CNTL_AUD_ASYNC_RST |
RADEON_TV_MASTER_CNTL_DVS_ASYNC_RST );
Radeon_ImpacTVwriteHorTimingTable( ai, Radeon_InternalTVOutWriteFIFO, values, true );
Radeon_ImpacTVwriteVertTimingTable( ai, Radeon_InternalTVOutWriteFIFO, values );
snooze( 50000 );
values->tv_master_cntl = orig_tv_master_cntl;
writeMMIORegList( ai, values, intern_reg_mapping_finish );
}
// read list of MM I/O registers
static void readMMIORegList(
accelerator_info *ai, impactv_regs *values, const register_mapping *mapping )
{
vuint8 *regs = ai->regs;
for( ; mapping->address != 0 && mapping->offset != 0; ++mapping ) {
*(uint32 *)((char *)(values) + mapping->offset) =
INREG( regs, mapping->address );
/*SHOW_FLOW( 2, "%x=%x", mapping->address,
*(uint32 *)((char *)(values) + mapping->offset) );*/
}
//snooze( 1000000 );
}
// read list of PLL registers
static void readPLLRegList(
accelerator_info *ai, impactv_regs *values, const register_mapping *mapping )
{
for( ; mapping->address != 0 && mapping->offset != 0; ++mapping ) {
*(uint32 *)((char *)(values) + mapping->offset) =
Radeon_INPLL( ai->regs, ai->si->asic, mapping->address );
/*SHOW_FLOW( 2, "%x=%x", mapping->address,
*(uint32 *)((char *)(values) + mapping->offset) );*/
}
//snooze( 1000000 );
}
// read TV-Out registers
void Radeon_InternalTVOutReadRegisters(
accelerator_info *ai, impactv_regs *values )
{
readMMIORegList( ai, values, intern_reg_mapping_before_pll );
readPLLRegList( ai, values, intern_reg_mapping_pll );
readMMIORegList( ai, values, intern_reg_mapping_after_pll );
readMMIORegList( ai, values, intern_reg_mapping_finish );
//snooze( 1000000 );
}
| 3,737 |
603 | """Test QtConsoleApp"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import sys
from subprocess import check_output
from jupyter_core import paths
import pytest
from traitlets.tests.utils import check_help_all_output
from . import no_display
@pytest.mark.skipif(no_display, reason="Doesn't work without a display")
def test_help_output():
"""jupyter qtconsole --help-all works"""
check_help_all_output('qtconsole')
@pytest.mark.skipif(no_display, reason="Doesn't work without a display")
@pytest.mark.skipif(os.environ.get('CI', None) is None,
reason="Doesn't work outside of our CIs")
def test_generate_config():
"""jupyter qtconsole --generate-config"""
config_dir = paths.jupyter_config_dir()
check_output([sys.executable, '-m', 'qtconsole', '--generate-config'])
assert os.path.isfile(os.path.join(config_dir,
'jupyter_qtconsole_config.py'))
| 387 |
1,047 | #import tensorflow as tf
import jinja2
import os
import pickle
from collections import namedtuple
import re
import numpy as np
TFLM_Tensor = namedtuple('TFLM_Tensor', ['tensor', 'quantization'])
test_name = "3_fully_connected"
output_file = "test_quantized_fully_connected.cpp"
const_file = "constants_quantized_fully_connected.hpp"
def import_test_data(dir_path="."):
test = {}
with open(dir_path + '/inputs.pkl','rb') as pickle_in:
test["inputs"] = pickle.load(pickle_in)
with open(dir_path + '/outputs.pkl','rb') as pickle_in:
test["outputs"] = pickle.load(pickle_in)
with open(dir_path + '/option.pkl','rb') as pickle_in:
test["option"] = pickle.load(pickle_in)
return test
def get_name_map(dir_path="."):
name_map = { "inputs":{}, "outputs": {} }
with open(dir_path + "/name_map.mp") as fp:
for line in fp:
line = line.lstrip()
if line[0] == "#":
continue
m = re.match("(?P<mkey>\w+):\s+(?P<from>[a-zA-Z0-9_/]+)\s+->\s+(?P<to>\w+)", line)
if m:
g = m.groupdict()
name_map[g["mkey"]][g["from"]] = g["to"]
return name_map
def dtype_to_ctype(x):
if x == "int8":
return "int8_t"
elif x == "uint8":
return "uint8_t"
elif x == "int16":
return "int16_t"
elif x == "uint16":
return "uint16_t"
elif x == "int32":
return "int32_t"
elif x == "uint32":
return "uint32_t"
else:
print("unexpected DTYPE", x)
return None
def dtype_to_utype(x):
if x == "int8":
return "i8"
elif x == "uint8":
return "u8"
elif x == "int16":
return "i16"
elif x == "uint16":
return "u16"
elif x == "int32":
return "i32"
elif x == "uint32":
return "u32"
elif x == "float":
return "flt"
else:
print("unexpected DTYPE", x)
return None
const_str = """
{% for tensor in reference_tensors %}
static const {{ tensor.type }} {{ tensor.r_name }}[{{ tensor.flat_num_elems }}] = {
{% for x in tensor.data %} {{ x }}{{ "," if not loop.last }}{{ "\n" if loop.index0 != 0 and loop.index0 % 10 == 0 }} {% endfor %}
};
static const int32_t {{ tensor.r_zp_name }} [1] = { {{ tensor.zp }} };
static const float {{ tensor.r_scale_name }} [1] = { {{ tensor.scale }} };
{% endfor %}
"""
test_str = """
TEST(Quantized, reference_{{ test_name }}) {
localCircularArenaAllocator<1024> meta_allocator;
localCircularArenaAllocator<{{ out_tensor.flat_num_elems }}*2*sizeof({{ out_tensor.utype }}), uint32_t> ram_allocator;
Context::get_default_context()->set_metadata_allocator(&meta_allocator);
Context::get_default_context()->set_ram_data_allocator(&ram_allocator);
{% for tensor in reference_tensors %}
Tensor {{ tensor.name }} = new RomTensor({ {% for x in tensor.shape %}{{ x }}{{ ", " if not loop.last }}{% endfor %} }, {{ tensor.utype }}, {{ tensor.r_name }})
.set_quantization_params(PerTensorQuantizationParams({{ tensor.r_zp_name }}, {{ tensor.r_scale_name }}));
{% endfor %}
Tensor out = new RamTensor({ {% for x in out_tensor.shape %}{{ x }}{{ ", " if not loop.last }}{% endfor %} }, {{ out_tensor.utype }})
.set_quantization_params(PerTensorQuantizationParams({{ out_tensor.r_zp_name }}, {{ out_tensor.r_scale_name }} ));
/*
ConvOperator<float> conv_Aw({ {% for x in strides %}{{ x }}{{ "," if not loop.last }}{% endfor %}}, {{ PADDING }});
conv_Aw
.set_inputs({ {ConvOperator<float>::in, in}, {ConvOperator<float>::filter, w} })
.set_outputs({ {ConvOperator<float>::out, out} })
.eval();
*/
for(int i = 0; i < {{ out_size }}; i++) {
//EXPECT_NEAR((float) out(i), {{ out_tensor.r_name }}[i], 0.0001);
}
}
"""
container_str = """
#include <cstring>
#include <iostream>
#include "uTensor.h"
#include "gtest/gtest.h"
#include "{{ constants_header }}"
using std::cout;
using std::endl;
using namespace uTensor;
{{ test }}
"""
const_container_str = """
#ifndef {{ constants_header | replace(".", "_") }}
#define {{ constants_header | replace(".", "_") }}
{{ constant_snippet }}
#endif
"""
test_Template = jinja2.Template(test_str)
const_Template = jinja2.Template(const_str)
container_Template = jinja2.Template(container_str)
const_container_Template = jinja2.Template(const_container_str)
if __name__ == "__main__":
tests=[]
constants=[]
reference_tensors = []
out_tensor = {}
ref_test_data = import_test_data()
name_map = get_name_map()
for key in name_map:
for t in ref_test_data[key]:
tensor = {}
test = ref_test_data[key][t]
test_data = test.tensor
(q_scale, q_zp) = test.quantization
tensor["name"] = name_map[key][t]
tensor["r_name"] = "s_ref_%s" % tensor["name"]
tensor["type"] = dtype_to_ctype(test_data.dtype)
tensor["utype"] = dtype_to_utype(test_data.dtype)
tensor["shape"] = test_data.shape
tensor["data"] = test_data.flatten()
tensor["flat_num_elems"] = len(tensor["data"])
tensor["zp"] = q_zp
tensor["scale"] = q_scale
tensor["r_zp_name"] = tensor["r_name"] + "_zp"
tensor["r_scale_name"] = tensor["r_name"] + "_scale"
tensor["io"] = key
# hack for now
if key == "outputs":
out_tensor = tensor
reference_tensors.append(tensor)
#print(reference_tensors)
const_str_rendered = const_Template.render(reference_tensors=reference_tensors)
const_container_rendered = const_container_Template.render(constant_snippet=const_str_rendered, constants_header=const_file)
test_str_rendered = test_Template.render(test_name=test_name, reference_tensors=reference_tensors, out_tensor=out_tensor)
container_rendered = container_Template.render(test=test_str_rendered, constants_header=const_file)
with open(const_file, "w") as fp:
fp.write(const_container_rendered)
with open(output_file, "w") as fp:
fp.write(container_rendered)
#for i in range(num_tests):
# for stride in [1, 2]:
# w = tf.Variable(tf.random.normal([5, 5, 1, 32]))
# in_1 = tf.Variable(tf.random.normal([1, 28, 28, 1]))
# strides = [1, stride, stride, 1]
# out_1 = tf.nn.conv2d(in_1, w, strides=strides, padding=PADDING)
# w_flat = w.numpy().flatten()
# in_flat = in_1.numpy().flatten()
# out_flat = out_1.numpy().flatten()
# stride_str = "_stride_%d" % stride
# test_name = "%s_%d%s" % (PADDING, i, stride_str)
#
# test_str_rendered = test_Template.render(test_name=test_name, input_size=in_flat.shape[0], w_size=w_flat.shape[0], out_size=out_flat.shape[0], ref_in=in_flat, ref_w=w_flat, ref_out=out_flat, strides=strides, in_shape=in_1.shape, w_shape=w.shape, out_shape=out_1.shape, PADDING=PADDING)
# const_str_rendered = const_Template.render(test_name=test_name, input_size=in_flat.shape[0], w_size=w_flat.shape[0], out_size=out_flat.shape[0], ref_in=in_flat, ref_w=w_flat, ref_out=out_flat, strides=strides, in_shape=in_1.shape, w_shape=w.shape, out_shape=out_1.shape)
# tests.append(test_str_rendered)
# constants.append(const_str_rendered)
#
#container_rendered = container_Template.render(tests=tests, constants_header=const_file)
#consts_container_rendered = const_container_Template.render(constants=constants, constants_header=const_file)
#with open(output_file, "w") as fp:
# fp.write(container_rendered)
#with open(const_file, "w") as fp:
# fp.write(consts_container_rendered)
print("Complete");
| 3,513 |
1,444 | package mage.cards.t;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.continuous.BoostEnchantedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.keyword.TotemArmorAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.permanent.PermanentIdPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class TreefolkUmbra extends CardImpl {
public TreefolkUmbra(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{G}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature));
Ability ability = new EnchantAbility(auraTarget.getTargetName());
this.addAbility(ability);
// Enchanted creature gets +0/+2 and assigns combat damage equal to its toughness rather than its power.
ability = new SimpleStaticAbility(new BoostEnchantedEffect(0, 2));
ability.addEffect(new TreefolkUmbraEffect());
this.addAbility(ability);
// Totem armor
this.addAbility(new TotemArmorAbility());
}
private TreefolkUmbra(final TreefolkUmbra card) {
super(card);
}
@Override
public TreefolkUmbra copy() {
return new TreefolkUmbra(this);
}
}
class TreefolkUmbraEffect extends ContinuousEffectImpl {
TreefolkUmbraEffect() {
super(Duration.WhileOnBattlefield, Outcome.Benefit);
staticText = "and assigns combat damage equal to its toughness rather than its power";
}
private TreefolkUmbraEffect(final TreefolkUmbraEffect effect) {
super(effect);
}
@Override
public TreefolkUmbraEffect copy() {
return new TreefolkUmbraEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
return false;
}
@Override
public boolean apply(Layer layer, SubLayer sublayer, Ability source, Game game) {
Permanent permanent = game.getPermanent(source.getSourceId());
if (permanent == null || permanent.getAttachedTo() == null) {
return false;
}
FilterCreaturePermanent filter = new FilterCreaturePermanent();
filter.add(new PermanentIdPredicate(permanent.getAttachedTo()));
game.getCombat().setUseToughnessForDamage(true);
game.getCombat().addUseToughnessForDamageFilter(filter);
return true;
}
@Override
public boolean hasLayer(Layer layer) {
return layer == Layer.RulesEffects;
}
} | 1,097 |
403 | <gh_stars>100-1000
package org.camunda.bpm.demo.invoice.ui.servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.camunda.bpm.demo.invoice.ProcessConstants;
import org.camunda.bpm.engine.RuntimeService;
@WebServlet(value = "/startByUpload", loadOnStartup = 1)
public class StartByUpload extends HttpServlet {
private static Logger log = Logger.getLogger(StartByUpload.class.getName());
private static final long serialVersionUID = 1L;
@Inject
private RuntimeService runtimeService;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, Object> processVariables = new HashMap<String, Object>();
RequestMetaData metaData = extractProcessVariablesFromRequest(request, processVariables);
runtimeService.startProcessInstanceByKey(metaData.processDefinitionKey, processVariables);
log.log(Level.INFO, "redirect to " + metaData.callbackUrl);
response.sendRedirect(metaData.callbackUrl);
}
private static class RequestMetaData {
String processDefinitionKey = null;
String callbackUrl = null;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private RequestMetaData extractProcessVariablesFromRequest(HttpServletRequest request, Map<String, Object> processVariables) {
RequestMetaData metaData = new RequestMetaData();
try {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
if (item.getFieldName().equals("processDefinitionKey")) {
metaData.processDefinitionKey = item.getString();
} else if (item.getFieldName().equals("callbackUrl")) {
metaData.callbackUrl = item.getString();
} else {
processVariables.put(item.getFieldName(), item.getString());
}
} else {
processVariables.put(ProcessConstants.VARIABLE_INVOICE, item.get());
}
}
} catch (Exception ex) {
log.log(Level.SEVERE, "Exception while extracting content from HTTP parameters", ex);
}
return metaData;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
String redirectUrl = request.getRequestURL().toString().replace("startByUpload", "taskList.jsf");
log.log(Level.INFO, "redirect to " + redirectUrl);
response.sendRedirect(redirectUrl);
}
}
| 1,182 |
379 | def data_bars(df, column):
n_bins = 100
bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
ranges = [
((df[column].max() - df[column].min()) * i) + df[column].min()
for i in bounds
]
styles = []
for i in range(1, len(bounds)):
min_bound = ranges[i - 1]
max_bound = ranges[i]
max_bound_percentage = bounds[i] * 100
styles.append({
'if': {
'filter_query': (
'{{{column}}} >= {min_bound}' +
(' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
).format(column=column, min_bound=min_bound, max_bound=max_bound),
'column_id': column
},
'background': (
"""
linear-gradient(90deg,
#0074D9 0%,
#0074D9 {max_bound_percentage}%,
white {max_bound_percentage}%,
white 100%)
""".format(max_bound_percentage=max_bound_percentage)
),
'paddingBottom': 2,
'paddingTop': 2
})
return styles
def data_bars_diverging(df, column, color_above='#3D9970', color_below='#FF4136'):
n_bins = 100
bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
col_max = df[column].max()
col_min = df[column].min()
ranges = [
((col_max - col_min) * i) + col_min
for i in bounds
]
midpoint = (col_max + col_min) / 2.
styles = []
for i in range(1, len(bounds)):
min_bound = ranges[i - 1]
max_bound = ranges[i]
min_bound_percentage = bounds[i - 1] * 100
max_bound_percentage = bounds[i] * 100
style = {
'if': {
'filter_query': (
'{{{column}}} >= {min_bound}' +
(' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
).format(column=column, min_bound=min_bound, max_bound=max_bound),
'column_id': column
},
'paddingBottom': 2,
'paddingTop': 2
}
if max_bound > midpoint:
background = (
"""
linear-gradient(90deg,
white 0%,
white 50%,
{color_above} 50%,
{color_above} {max_bound_percentage}%,
white {max_bound_percentage}%,
white 100%)
""".format(
max_bound_percentage=max_bound_percentage,
color_above=color_above
)
)
else:
background = (
"""
linear-gradient(90deg,
white 0%,
white {min_bound_percentage}%,
{color_below} {min_bound_percentage}%,
{color_below} 50%,
white 50%,
white 100%)
""".format(
min_bound_percentage=min_bound_percentage,
color_below=color_below
)
)
style['background'] = background
styles.append(style)
return styles
| 1,903 |
684 | <filename>src/src/glApp.h<gh_stars>100-1000
//------------------------------------------------------------------------------
// Copyright (c) 2018-2020 <NAME>
// All rights reserved.
//
// https://michelemorrone.eu - https://BrutPitt.com
//
// twitter: https://twitter.com/BrutPitt - github: https://github.com/BrutPitt
//
// mailto:<EMAIL> - mailto:<EMAIL>
//
// This software is distributed under the terms of the BSD 2-Clause license
//------------------------------------------------------------------------------
#pragma once
#include "appDefines.h"
// For compilers that support precompilation, includes "wx/wx.h".
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <iostream>
#include <GLFW/glfw3.h>
enum ScreeShotReq {
ScrnSht_NO_REQUEST, //0x00
ScrnSht_SILENT_MODE, //0x01
ScrnSht_FILE_NAME, //0x02
ScrnSht_CAPTURE_ALL = 4, //0x04
ScrnSht_SILENT_MODE_ALPHA = 0x8,
ScrnSht_FILE_NAME_ALPHA = 0x10
};
enum normalType { ptCoR, ptPt1, ptPt1CoR };
enum enumEmitterType { emitter_singleThread_externalBuffer, // webGL and APPLE
emitter_separateThread_externalBuffer, // max performance for OGL 4.1
emitter_separateThread_mappedBuffer}; // max performance for OGL 4.5
enum enumEmitterEngine { emitterEngine_staticParticles,
emitterEngine_transformFeedback };
enum glslPrecision { low, medium, hight };
#define GLAPP_PROG_NAME "glChAoS.P"
#define PALETTE_PATH "ColorMaps/"
#define STRATT_PATH "ChaoticAttractors/"
#define CAPTURE_PATH "imgsCapture/"
#define EXPORT_PLY_PATH CAPTURE_PATH
#define RENDER_CFG_PATH "renderCfg/"
#define GLAPP_PROG_CONFIG "glChAoSP.cfg"
class glWindow;
#include "ui/uiMainDlg.h"
#ifdef __EMSCRIPTEN__
#include "emsTouch.h"
#endif
bool fileExist(const char *filename);
/*
///////////////////////////////////////////
//Data Init for 32/64 bit systems
//////////////////////////////////////////
template<int> void IntDataHelper();
template<> void IntDataHelper<4>()
{
// do 32-bits operations
}
template<> void IntDataHelper<8>()
{
// do 64-bits operations
}
// helper function just to hide clumsy syntax
inline void IntData() { IntDataHelper<sizeof(size_t)>(); }
*/
#include <cstdint>
#if INTPTR_MAX == INT32_MAX
#define PARTICLES_MAX 67000000
#elif INTPTR_MAX == INT64_MAX
#define PARTICLES_MAX 267000000
#else
#error "Environment not 32 or 64-bit."
#endif
#ifdef NDEBUG
#if !defined(GLCHAOSP_LIGHTVER)
#define EMISSION_STEP (200*1024)
#else
#define EMISSION_STEP 20000
#endif
#else
#define EMISSION_STEP 7777
#endif
#if !defined(GLCHAOSP_LIGHTVER)
#define ALLOCATED_BUFFER 30000000
#define CIRCULAR_BUFFER 10000000
#else
#define ALLOCATED_BUFFER 10000000
#define CIRCULAR_BUFFER 5000000
#endif
#define GET_TIME_FUNC glfwGetTime()
enum loadSettings { ignoreNone, ignoreCircBuffer, ignoreConfig=0x4 };
void exportPLY(bool wantBinary, bool wantColors, bool alphaDist, bool wantNormals, bool bCoR, bool wantNormalized, normalType nType = normalType::ptCoR);
bool importPLY(bool wantColors, int velType);
class particlesBaseClass;
class timerClass
{
public:
timerClass() {
#ifdef GLAPP_TIMER_RT_AVG
memset((void *)fpsBuff, sizeof(fpsBuff), 0);
#endif
}
void init() { last = prev = startAVG = glfwGetTime(); }
void tick() {
prev = last;
last = glfwGetTime();
count++;
#ifdef GLAPP_TIMER_RT_AVG
const float dt = elapsed();
fpsAccum += dt - fpsBuff[fpsIDX];
fpsBuff[fpsIDX] = dt;
fpsIDX++;
framerate = (fpsAccum > 0.0f) ? (1.0f / (fpsAccum / 256.f)) : FLT_MAX;
#endif
}
float elapsed() { last = glfwGetTime(); return static_cast<float>(last-prev); }
void start() { prev = last = glfwGetTime(); }
void resetAVG() { startAVG = glfwGetTime(); count = 0; }
float fps() { const float elaps = static_cast<float>(last-prev); return 1.f/elaps>0 ? elaps : FLT_EPSILON; }
float fpsAVG() { return static_cast<float>(count/(last-startAVG)); }
private:
double last = 0.0, prev = 0.0, startAVG = 0.0;
long count = 0;
#ifdef GLAPP_TIMER_RT_AVG
uint8_t fpsIDX = 0;
float fpsBuff[256];
float fpsAccum;
#endif
};
/////////////////////////////////////////////////
// theApp -> Main App -> container
/////////////////////////////////////////////////
class mainGLApp
{
public:
// self pointer .. static -> the only one
static mainGLApp* theMainApp;
mainGLApp();
~mainGLApp();
void onInit(int w = INIT_WINDOW_W, int h = INIT_WINDOW_H);
int onExit();
void mainLoop();
//GLFW Utils
/////////////////////////////////////////////////
GLFWwindow* getGLFWWnd() const { return(mainGLFWwnd); }
glWindow *getEngineWnd() { return glEngineWnd; }
void setGLFWWnd(GLFWwindow* wnd) { mainGLFWwnd = wnd; }
//Only for initial position (save/Load)
int getPosX() const { return xPosition; }
int getPosY() const { return yPosition; }
void setPosX(int v) { xPosition = v; }
void setPosY(int v) { yPosition = v; }
int GetWidth() const { return width; }
int GetHeight() const { return height; }
void SetWidth(int v) { width = v; }
void SetHeight(int v) { height = v; }
const char* getWindowTitle() const { return(windowTitle.c_str()); }
void setWindowSize(int w, int h) { glfwSetWindowSize(mainGLFWwnd, w, h); }
void getWindowSize(int *w, int *h) { glfwGetWindowSize(mainGLFWwnd, w, h); }
// Request for scrrenshot
//////////////////////////////////////////////////////////////////
void setScreenShotRequest(int val) { screenShotRequest = val; }
void getScreenShot(GLuint tex, bool is32bit=false);
char const *openFile(char const *startDir, char const * patterns[], int numPattern);
char const *saveFile(char const *startDir, char const * patterns[], int numPattern);
void saveScreenShot(unsigned char *data, int w, int h, bool is32bit=false);
void saveSettings(const char *name);
bool loadSettings(const char *name, const int type = loadSettings::ignoreNone);
void saveAttractor(const char *name);
bool loadAttractor(const char *name);
void saveProgConfig();
bool loadProgConfig();
void invertSettings();
void setLastFile(const char *s) { lastAttractor = s; }
void setLastFile(const std::string &s) { lastAttractor = s; }
std::string &getLastFile() { return lastAttractor; }
std::string &get_glslVer() {return glslVersion; }
std::string &get_glslDef() {return glslDefines; }
unsigned getMaxAllocatedBuffer() { return maxAllocatedBuffer; }
void setMaxAllocatedBuffer(unsigned v) { maxAllocatedBuffer = v; }
unsigned getEmissionStepBuffer() { return emissionStepBuffer; }
void setEmissionStepBuffer(unsigned v) { emissionStepBuffer = v; }
bool isParticlesSizeConstant() { return particlesSizeConstant; }
void setParticlesSizeConstant(bool b) { particlesSizeConstant = b; }
bool useDetailedShadows() { return detailedShadows; }
void useDetailedShadows(bool b) { detailedShadows = b; }
std::string& getStartWithAttractorName() { return startWithAttractorName; }
void setStartWithAttractorName(const std::string& s) { startWithAttractorName = s; }
void setVSync(int v) { vSync = v; }
int getVSync() { return vSync; }
bool fullScreen() { return isFullScreen; }
void fullScreen(bool b) { isFullScreen = b; }
std::string &getCapturePath() { return capturePath; }
void setCapturePath(const char * const s) { capturePath = s; }
std::string &getPlyPath() { return exportPlyPath; }
void setPlyPath(const char * const s) { exportPlyPath = s; }
std::string &getRenderCfgPath() { return renderCfgPath; }
void setRenderCfgPath(const char * const s) { renderCfgPath = s; }
void setPalInternalPrecision(GLenum e) { palInternalPrecision = e; }
GLenum getPalInternalPrecision() { return palInternalPrecision; }
void setTexInternalPrecision(GLenum e) { texInternalPrecision = e; }
GLenum getTexInternalPrecision() { return texInternalPrecision; }
void setFBOInternalPrecision(GLenum e) { fboInternalPrecision = e; }
GLenum getFBOInternalPrecision() { return fboInternalPrecision; }
void setDBInterpolation(GLenum e) { dbInterpolation = e; }
GLuint getDBInterpolation() { return dbInterpolation; }
void setFBOInterpolation(GLenum e) { fboInterpolation = e; }
GLuint getFBOInterpolation() { return fboInterpolation; }
void setShaderFloatPrecision(glslPrecision e) { shaderFloatPrecision = e; }
glslPrecision getShaderFloatPrecision() { return shaderFloatPrecision; }
void setShaderIntPrecision(glslPrecision e) { shaderIntPrecision = e; }
glslPrecision getShaderIntPrecision() { return shaderIntPrecision; }
int getMultisamplingIdx() { return multisamplingIdx; }
void setMultisamplingIdx(int v) { multisamplingIdx = v; }
int getMultisamplingValue() { return fbMultisampling[multisamplingIdx]; }
GLuint getClampToBorder() { return clampToBorder; }
void setLowPrecision() {
useLowPrecision(true);
setTexInternalPrecision(GL_R16F);
setPalInternalPrecision(GL_RGB16F);
setFBOInternalPrecision(GL_RGBA16F);
setDBInterpolation(GL_NEAREST);
setFBOInterpolation(GL_LINEAR);
setShaderFloatPrecision(glslPrecision::low);
setShaderIntPrecision(glslPrecision::medium);
multisamplingIdx = 3;
}
void setHighPrecision() {
useLowPrecision(false);
setTexInternalPrecision(GL_R32F);
setPalInternalPrecision(GL_RGB32F);
setFBOInternalPrecision(GL_RGBA32F);
setDBInterpolation(GL_NEAREST);
setFBOInterpolation(GL_LINEAR);
setShaderFloatPrecision(glslPrecision::hight);
setShaderIntPrecision(glslPrecision::hight);
multisamplingIdx = 3;
}
// wgl command line settings
bool isTabletMode() { return tabletMode; }
void setTabletMode(bool b) { tabletMode=b; }
bool useLowPrecision() { return lowPrecision; }
void useLowPrecision(bool b) { lowPrecision = b; }
bool useLightGUI() { return lightGUI; }
void useLightGUI(bool b) { lightGUI = b; }
bool useFixedCanvas() { return fixedCanvas; }
void useFixedCanvas(bool b) { fixedCanvas = b; }
bool startWithGlowOFF() { return initialGlowOFF; }
void startWithGlowOFF(bool b) { initialGlowOFF = b; }
bool slowGPU() { return isSlowGPU; }
void slowGPU(bool b) { isSlowGPU = b; }
bool needRestart() { return appNeedRestart; }
void needRestart(bool b) { appNeedRestart = b; }
bool useSyncOGL() { return syncOGL; }
void useSyncOGL(bool b) { syncOGL = b; }
void selectFolder(std::string &s);
mainImGuiDlgClass &getMainDlg() { return mainImGuiDlg; }
std::vector<std::string> & getListQuickView() { return listQuickView; }
void getQuickViewDirList();
void loadQuikViewSelection(int idx);
void selectedListQuickView(int i) { idxListQuickView = i; }
int selectedListQuickView() { return idxListQuickView; }
bool idleRotation() { return isIdleRotation; }
void idleRotation(bool b) { isIdleRotation = b; }
// imGui utils
/////////////////////////////////////////////////
void imguiInit();
int imguiExit();
void selectEmitterType(int type) {
#if !defined(GLCHAOSP_LIGHTVER)
#ifdef GLAPP_REQUIRE_OGL45
emitterType = type;
#else
#if !defined(GLCHAOSP_NO_MB)
emitterType = type == emitter_separateThread_mappedBuffer ? emitter_separateThread_externalBuffer : type;
#else
emitterType = emitter_singleThread_externalBuffer;
#endif
#endif
#endif
}
int getEmitterType() { return emitterType; }
void setEmitterEngineType(int i) {
#if !defined(GLCHAOSP_NO_TF)
emitterEngineType = i;
#else
emitterEngineType = emitterEngine_staticParticles;
#endif
}
int getEmitterEngineType() { return emitterEngineType; }
timerClass& getTimer() { return timer; }
int getMaxCombTexImgUnits() { return maxCombTexImgUnits; }
bool checkMaxCombTexImgUnits() { return (maxCombTexImgUnits>32); }
protected:
// The Position of the window
int xPosition, yPosition;
int width, height;
/** The title of the window */
bool exitFullScreen;
bool particlesSizeConstant = false;
// The title of the window
std::string windowTitle;
std::string glslVersion;
std::string glslDefines;
std::vector<std::string> listQuickView;
int idxListQuickView = 0;
int maxCombTexImgUnits = 0;
private:
// imGui Dlg
/////////////////////////////////////////////////
mainImGuiDlgClass mainImGuiDlg;
// glfw utils
/////////////////////////////////////////////////
void glfwInit();
int glfwExit();
int getModifier();
unsigned maxAllocatedBuffer = ALLOCATED_BUFFER;
unsigned emissionStepBuffer = EMISSION_STEP;
bool tabletMode = false;
bool lightGUI = false;
bool fixedCanvas = false;
bool initialGlowOFF = false;
bool detailedShadows = false;
bool isIdleRotation = true;
bool isSlowGPU = false;
bool appNeedRestart = false;
#if defined(__APPLE__) || defined(GLCHAOSP_LIGHTVER) || defined(GLAPP_USES_ES3)
bool syncOGL = true;
#else
bool syncOGL = false;
#endif
int emitterEngineType = emitterEngine_staticParticles;
std::string startWithAttractorName = std::string("random"); // -1 Random start
int screenShotRequest;
int vSync = 0;
bool isFullScreen = false;
#if defined(__EMSCRIPTEN__) || defined(GLCHAOSP_NO_TH)
int emitterType = emitter_singleThread_externalBuffer;
#else
int emitterType = emitter_separateThread_externalBuffer;
#endif
#if !defined(GL_CLAMP_TO_BORDER)
const GLuint clampToBorder = GL_CLAMP_TO_EDGE;
#else
const GLuint clampToBorder = GL_CLAMP_TO_BORDER;
#endif
int fbMultisampling[6] = { GLFW_DONT_CARE, 0, 2, 4, 8, 16 };
//Values of this block can be overwritten from #define in constructor
bool lowPrecision = false;
GLenum fboInternalPrecision = GL_RGBA32F;
GLenum palInternalPrecision = GL_RGB32F;
GLenum texInternalPrecision = GL_R32F;
GLuint dbInterpolation = GL_NEAREST;
GLuint fboInterpolation = GL_LINEAR;
glslPrecision shaderFloatPrecision = glslPrecision::hight;
glslPrecision shaderIntPrecision = glslPrecision::hight;
int multisamplingIdx = 3;
////////////////////////////////
std::string lastAttractor = std::string("");
std::string capturePath = std::string(CAPTURE_PATH);
std::string exportPlyPath = std::string(EXPORT_PLY_PATH);
std::string renderCfgPath = std::string(RENDER_CFG_PATH);
GLFWwindow* mainGLFWwnd = nullptr;
glWindow *glEngineWnd = nullptr;
timerClass timer;
#ifdef __EMSCRIPTEN__
public:
emsMDeviceClass &getEmsDevice() { return emsDevice; }
int getCanvasX() { return canvasX; }
int getCanvasY() { return canvasY; }
int getSizeX() { return GetWidth(); }
int getSizeY() { return GetHeight(); }
void setCanvasX(int i) { canvasX = i; }
void setCanvasY(int i) { canvasY = i; }
private:
emsMDeviceClass emsDevice;
int canvasX=0, canvasY=0;
#endif
friend class glWindow;
};
| 6,349 |
407 | /**
* Copyright 2010 The Apache Software Foundation
*
* 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.hadoop.hbase.zookeeper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(SmallTests.class)
public class TestZooKeeperMainServerArg {
private final ZooKeeperMainServerArg parser = new ZooKeeperMainServerArg();
@Test public void test() {
Configuration c = HBaseConfiguration.create();
assertEquals("localhost:" + c.get(HConstants.ZOOKEEPER_CLIENT_PORT),
parser.parse(c));
final String port = "1234";
c.set(HConstants.ZOOKEEPER_CLIENT_PORT, port);
c.set("hbase.zookeeper.quorum", "example.com");
assertEquals("example.com:" + port, parser.parse(c));
c.set("hbase.zookeeper.quorum", "example1.com,example2.com,example3.com");
assertTrue(port,
parser.parse(c).matches("(example[1-3]\\.com,){2}example[1-3]\\.com:" + port));
}
@org.junit.Rule
public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
}
| 637 |
983 | package org.xm.classification;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* 分类的类别
*/
public class Variable {
/**
* 类别信息
*/
Map<String, CategoryInfo> categoryMap = new HashMap<>();
Map<String, Feature> features = new HashMap<>();
/**
* 所有文档的数量
*/
private int docCount = 0;
public void write(DataOutput out) throws IOException {
//保存文档总数
out.writeInt(docCount);
//写入类别总数
out.writeInt(categoryMap.size());
for (String category : categoryMap.keySet()) {
out.writeUTF(category);
categoryMap.get(category).write(out);
}
//写入Feature总数
out.writeInt(features.size());
for (String key : features.keySet()) {
out.writeUTF(key);
features.get(key).write(out);
}
}
public void readFields(DataInput in) throws IOException {
this.docCount = in.readInt();
int size = in.readInt();
categoryMap = new HashMap<>();
for (int i = 0; i < size; i++) {
String category = in.readUTF();
CategoryInfo info = CategoryInfo.read(in);
categoryMap.put(category, info);
}
size = in.readInt();
features = new HashMap<>();
for (int i = 0; i < size; i++) {
String word = in.readUTF();
Feature feature = Feature.read(in);
features.put(word, feature);
}
}
public static Variable read(DataInput in) throws IOException {
Variable v = new Variable();
v.readFields(in);
return v;
}
public Collection<String> getCategories() {
return categoryMap.keySet();
}
public int getFeatureCount() {
return features.size();
}
public boolean containFeature(String feature) {
return features.containsKey(feature);
}
public void incDocCount() {
this.docCount++;
}
public int getDocCount() {
return this.docCount;
}
/**
* 获取置顶类别下的文档数量
*
* @param category
* @return
*/
public int getDocCount(String category) {
return categoryMap.get(category).getDocCount();
}
/**
* 获取feature在指定类别下的文档出现数量
*
* @param feature
* @param category
* @return
*/
public int getDocCount(String feature, String category) {
Feature f = features.get(feature);
if (f != null) {
return f.getDocCount(category);
}
return 0;
}
public void addInstance(Instance instance) {
incDocCount();
CategoryInfo info;
if (categoryMap.containsKey(instance.getCategory())) {
info = categoryMap.get(instance.getCategory());
} else {
info = new CategoryInfo();
}
info.incDocCount();
categoryMap.put(instance.getCategory(), info);
for (String word : instance.getWords()) {
Feature feature = features.get(word);
if (feature == null)
feature = new Feature();
feature.setName(word);
feature.incDocCount(instance.getCategory());
features.put(word, feature);
}
}
public static class CategoryInfo {
private int docCount;
public int getDocCount() {
return docCount;
}
public void incDocCount() {
this.docCount++;
}
public void setDocCount(int docCount) {
this.docCount = docCount;
}
public void write(DataOutput out) throws IOException {
out.writeInt(docCount);
}
public void readFields(DataInput in) throws IOException {
this.docCount = in.readInt();
}
public static CategoryInfo read(DataInput in) throws IOException {
CategoryInfo c = new CategoryInfo();
c.readFields(in);
return c;
}
}
}
| 1,927 |
322 | /*
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.eagle.app.service;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.collections.map.HashedMap;
import org.apache.eagle.alert.engine.coordinator.StreamDefinition;
import org.apache.eagle.alert.metadata.IMetadataDao;
import org.apache.eagle.alert.metadata.impl.InMemMetadataDaoImpl;
import org.apache.eagle.alert.metric.MetricConfigs;
import org.apache.eagle.app.Application;
import org.apache.eagle.app.environment.impl.StaticEnvironment;
import org.apache.eagle.metadata.model.ApplicationDesc;
import org.apache.eagle.metadata.model.ApplicationEntity;
import org.apache.eagle.metadata.model.SiteEntity;
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ApplicationActionTest {
/**
* appConfig.withFallback(envConfig): appConfig will override envConfig, envConfig is used as default config
*/
@Test
public void testTypeSafeConfigMerge(){
Config appConfig = ConfigFactory.parseMap(new HashMap<String,String>(){{
put("APP_CONFIG",ApplicationActionTest.this.getClass().getCanonicalName());
put("SCOPE","APP");
}});
Config envConfig = ConfigFactory.parseMap(new HashMap<String,String>(){{
put("ENV_CONFIG",ApplicationActionTest.this.getClass().getCanonicalName());
put("SCOPE","ENV");
}});
Config mergedConfig = appConfig.withFallback(envConfig);
Assert.assertTrue(mergedConfig.hasPath("APP_CONFIG"));
Assert.assertTrue(mergedConfig.hasPath("ENV_CONFIG"));
Assert.assertEquals("appConfig.withFallback(envConfig): appConfig will override envConfig, envConfig is used as default config",
"APP",mergedConfig.getString("SCOPE"));
}
@Test
public void testDoAction() {
Application application = mock(Application.class);
when(application.getEnvironmentType()).thenReturn(StaticEnvironment.class);
SiteEntity siteEntity = new SiteEntity();
siteEntity.setSiteId("testsiteid");
siteEntity.setSiteName("testsitename");
siteEntity.setDescription("testdesc");
ApplicationDesc applicationDesc = new ApplicationDesc();
List<StreamDefinition> streamDefinitions = new ArrayList<>();
StreamDefinition sd = new StreamDefinition();
sd.setStreamId("streamId");
sd.setDescription("desc");
sd.setValidate(true);
sd.setTimeseries(false);
sd.setDataSource("ds1");
sd.setSiteId("siteId");
streamDefinitions.add(sd);
applicationDesc.setStreams(streamDefinitions);
applicationDesc.setType("type1");
ApplicationEntity metadata = new ApplicationEntity();
metadata.setAppId("appId");
metadata.setSite(siteEntity);
metadata.setDescriptor(applicationDesc);
metadata.setMode(ApplicationEntity.Mode.LOCAL);
metadata.setJarPath(applicationDesc.getJarPath());
Map<String, Object> configure = new HashedMap();
configure.put("dataSinkConfig.topic", "test_topic");
configure.put("dataSinkConfig.brokerList", "sandbox.hortonworks.com:6667");
configure.put(MetricConfigs.METRIC_PREFIX_CONF, "eagle.");
metadata.setConfiguration(configure);
metadata.setContext(configure);
Config serverConfig = ConfigFactory.parseMap(new HashMap<String,String>(){{
put("coordinator.metadataService.host", "localhost");
put("coordinator.metadataService.context", "/rest");
}});
IMetadataDao alertMetadataService = new InMemMetadataDaoImpl(serverConfig);
ApplicationAction applicationAction = new ApplicationAction(application, metadata, serverConfig, alertMetadataService);
applicationAction.doInstall();
applicationAction.doUninstall();
applicationAction.doStart();
applicationAction.doStop();
Assert.assertEquals(ApplicationEntity.Status.INITIALIZED, applicationAction.getStatus());
}
} | 1,712 |
609 | <reponame>0xflotus/token-core-android
package org.consenlabs.tokencore.wallet.transaction;
import java.util.List;
public class TxMultiSignResult {
public TxMultiSignResult(String txHash, List<String> signed) {
this.txHash = txHash;
this.signed = signed;
}
String txHash;
List<String> signed;
public String getTxHash() {
return txHash;
}
public void setTxHash(String txHash) {
this.txHash = txHash;
}
public List<String> getSigned() {
return signed;
}
public void setSigned(List<String> signed) {
this.signed = signed;
}
}
| 212 |
2,305 | """
Code snippet card, used in index page.
"""
from docutils.parsers.rst import Directive, directives
from docutils.statemachine import StringList
from docutils import nodes
from sphinx.addnodes import pending_xref
CARD_TEMPLATE_HEADER = """
.. raw:: html
<div class="codesnippet-card admonition">
<div class="codesnippet-card-body">
<div class="codesnippet-card-title-container">
<div class="codesnippet-card-icon">
.. image:: {icon}
.. raw:: html
</div>
<h4>{title}</h4>
</div>
"""
CARD_TEMPLATE_FOOTER = """
.. raw:: html
</div>
"""
CARD_TEMPLATE_LINK_CONTAINER_HEADER = """
.. raw:: html
<div class="codesnippet-card-footer">
"""
CARD_TEMPLATE_LINK = """
.. raw:: html
<div class="codesnippet-card-link">
{seemore}
<span class="material-icons right">arrow_forward</span>
</div>
"""
class CodeSnippetCardDirective(Directive):
option_spec = {
'icon': directives.unchanged,
'title': directives.unchanged,
'link': directives.unchanged,
'seemore': directives.unchanged,
}
has_content = True
def run(self):
anchor_node = nodes.paragraph()
try:
title = self.options['title']
link = directives.uri(self.options['link'])
icon = directives.uri(self.options['icon'])
seemore = self.options.get('seemore', 'For a full tutorial, please go here.')
except ValueError as e:
print(e)
raise
# header, title, icon...
card_rst = CARD_TEMPLATE_HEADER.format(title=title, icon=icon)
card_list = StringList(card_rst.split('\n'))
self.state.nested_parse(card_list, self.content_offset, anchor_node)
# code snippet
self.state.nested_parse(self.content, self.content_offset, anchor_node)
# close body
self.state.nested_parse(StringList(CARD_TEMPLATE_FOOTER.split('\n')), self.content_offset, anchor_node)
# start footer
self.state.nested_parse(StringList(CARD_TEMPLATE_LINK_CONTAINER_HEADER.split('\n')), self.content_offset, anchor_node)
# full tutorial link
link_node = pending_xref(CARD_TEMPLATE_LINK,
reftype='doc',
refdomain='std',
reftarget=link,
refexplicit=False,
refwarn=True,
refkeepformat=True)
# refkeepformat is handled in `patch_autodoc.py`
self.state.nested_parse(StringList(CARD_TEMPLATE_LINK.format(seemore=seemore).split('\n')), self.content_offset, link_node)
anchor_node += link_node
# close footer
self.state.nested_parse(StringList(CARD_TEMPLATE_FOOTER.split('\n')), self.content_offset, anchor_node)
# close whole
self.state.nested_parse(StringList(CARD_TEMPLATE_FOOTER.split('\n')), self.content_offset, anchor_node)
return [anchor_node]
def setup(app):
app.add_directive('codesnippetcard', CodeSnippetCardDirective)
| 1,438 |
2,415 | <filename>tools/c7n_azure/c7n_azure/resources/traffic_manager.py
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n_azure.resources.arm import ArmResourceManager
from c7n_azure.provider import resources
@resources.register('traffic-manager-profile')
class TrafficManagerProfile(ArmResourceManager):
"""Azure Traffic Manager Resource
:example:
This policy will find all Azure Traffic Manager profiles
.. code-block:: yaml
policies:
- name: traffic-manager-profiles
resource: azure.traffic-manager-profile
"""
class resource_type(ArmResourceManager.resource_type):
doc_groups = ['Network']
service = 'azure.mgmt.trafficmanager'
client = 'TrafficManagerManagementClient'
enum_spec = ('profiles', 'list_by_subscription', None)
default_report_fields = (
'name',
'location',
'resourceGroup'
)
resource_type = 'Microsoft.Network/trafficmanagerprofiles'
| 394 |
468 | {
"name": "powerlevel9k",
"author": "toish",
"license": "CC-BY-SA",
"raster": "http://hexb.in/hexagons/powerlevel9k.png",
"vector": "http://hexb.in/vector/powerlevel9k.ai",
"description": "Sticker for the PowerLevel9K ZSH theme! https://github.com/bhilburn/powerlevel9k"
}
| 115 |
575 | // Copyright 2014 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.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_BODY_STREAM_BUFFER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_BODY_STREAM_BUFFER_H_
#include <memory>
#include "base/types/pass_key.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/network/public/mojom/chunked_data_pipe_getter.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/fetch/fetch_data_loader.h"
#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/bytes_consumer.h"
namespace blink {
class BytesUploader;
class EncodedFormData;
class ExceptionState;
class ReadableStream;
class ScriptState;
class ScriptCachedMetadataHandler;
class CORE_EXPORT BodyStreamBuffer final : public UnderlyingSourceBase,
public BytesConsumer::Client {
public:
using PassKey = base::PassKey<BodyStreamBuffer>;
// Create a BodyStreamBuffer for |consumer|.
// |consumer| must not have a client.
// This function must be called after entering an appropriate V8 context.
// |signal| should be non-null when this BodyStreamBuffer is associated with a
// Response that was created by fetch().
static BodyStreamBuffer* Create(
ScriptState*,
BytesConsumer* consumer,
AbortSignal* signal,
ScriptCachedMetadataHandler* cached_metadata_handler,
scoped_refptr<BlobDataHandle> side_data_blob = nullptr);
// Create() should be used instead of calling this constructor directly.
BodyStreamBuffer(PassKey,
ScriptState*,
BytesConsumer* consumer,
AbortSignal* signal,
ScriptCachedMetadataHandler* cached_metadata_handler,
scoped_refptr<BlobDataHandle> side_data_blob);
BodyStreamBuffer(ScriptState*,
ReadableStream* stream,
ScriptCachedMetadataHandler* cached_metadata_handler,
scoped_refptr<BlobDataHandle> side_data_blob = nullptr);
ReadableStream* Stream() { return stream_; }
// Callable only when neither locked nor disturbed.
scoped_refptr<BlobDataHandle> DrainAsBlobDataHandle(
BytesConsumer::BlobSizePolicy);
scoped_refptr<EncodedFormData> DrainAsFormData();
void DrainAsChunkedDataPipeGetter(
ScriptState*,
mojo::PendingReceiver<network::mojom::blink::ChunkedDataPipeGetter>);
void StartLoading(FetchDataLoader*,
FetchDataLoader::Client* /* client */,
ExceptionState&);
void Tee(BodyStreamBuffer**, BodyStreamBuffer**, ExceptionState&);
// UnderlyingSourceBase
ScriptPromise pull(ScriptState*) override;
ScriptPromise Cancel(ScriptState*, ScriptValue reason) override;
bool HasPendingActivity() const override;
void ContextDestroyed() override;
// BytesConsumer::Client
void OnStateChange() override;
String DebugName() const override { return "BodyStreamBuffer"; }
bool IsStreamReadable() const;
bool IsStreamClosed() const;
bool IsStreamErrored() const;
bool IsStreamLocked() const;
bool IsStreamDisturbed() const;
// Closes the stream if necessary, and then locks and disturbs it. Should not
// be called if |stream_broken_| is true.
void CloseAndLockAndDisturb();
ScriptState* GetScriptState() { return script_state_; }
bool IsAborted();
// Returns the ScriptCachedMetadataHandler associated with the contents of
// this stream. This can return nullptr. Streams' ownership model applies, so
// this function is expected to be called by the owner of this stream.
ScriptCachedMetadataHandler* GetCachedMetadataHandler() {
DCHECK(!IsStreamLocked());
DCHECK(!IsStreamDisturbed());
return cached_metadata_handler_;
}
// Take the blob representing any side data associated with this body
// stream. This must be called before the body is drained or begins
// loading.
scoped_refptr<BlobDataHandle> TakeSideDataBlob();
scoped_refptr<BlobDataHandle> GetSideDataBlobForTest() const {
return side_data_blob_;
}
bool IsMadeFromReadableStream() const { return made_from_readable_stream_; }
void Trace(Visitor*) const override;
private:
class LoaderClient;
// This method exists to avoid re-entrancy inside the BodyStreamBuffer
// constructor. It is called by Create(). It should not be called after
// using the ReadableStream* constructor.
void Init();
BytesConsumer* ReleaseHandle(ExceptionState&);
void Abort();
void Close();
void GetError();
void CancelConsumer();
void ProcessData();
void EndLoading();
void StopLoading();
Member<ScriptState> script_state_;
Member<ReadableStream> stream_;
Member<BytesUploader> stream_uploader_;
Member<BytesConsumer> consumer_;
// We need this member to keep it alive while loading.
Member<FetchDataLoader> loader_;
// We need this to ensure that we detect that abort has been signalled
// correctly.
Member<AbortSignal> signal_;
// CachedMetadata handler used for loading compiled WASM code.
Member<ScriptCachedMetadataHandler> cached_metadata_handler_;
// Additional side data associated with this body stream. It should only be
// retained until the body is drained or starts loading. Client code, such
// as service workers, can call TakeSideDataBlob() prior to consumption.
scoped_refptr<BlobDataHandle> side_data_blob_;
bool stream_needs_more_ = false;
bool made_from_readable_stream_;
bool in_process_data_ = false;
// TODO(ricea): Remove remaining uses of |stream_broken_|.
bool stream_broken_ = false;
DISALLOW_COPY_AND_ASSIGN(BodyStreamBuffer);
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_BODY_STREAM_BUFFER_H_
| 2,152 |
389 | <filename>Vesper/Classes/VSMenuButton.h
//
// VSMenuButton.h
// Vesper
//
// Created by <NAME> on 5/6/13.
// Copyright (c) 2013 Q Branch LLC. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef struct {
CGFloat cornerRadius;
CGFloat borderWidth;
VSTextCaseTransform textCaseTransform;
} VSMenuButtonLayoutBits;
@class VSMenuItem;
@interface VSMenuButton : UIButton
- (instancetype)initWithFrame:(CGRect)frame menuItem:(VSMenuItem *)menuItem destructive:(BOOL)destructive popoverSpecifier:(NSString *)popoverSpecifier;
@property (nonatomic, weak, readonly) VSMenuItem *menuItem;
@property (nonatomic, assign) VSMenuButtonLayoutBits layoutBits;
@property (nonatomic, strong) UIColor *borderColor;
@property (nonatomic, assign) BOOL destructive;
- (NSAttributedString *)attributedTitleStringWithColor:(UIColor *)color;
- (NSAttributedString *)attributedTitle;
- (NSAttributedString *)attributedTitlePressed;
@end
| 310 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-gqcf-83rq-gpfr",
"modified": "2021-09-14T18:35:35Z",
"published": "2021-09-14T20:24:44Z",
"aliases": [
],
"summary": "Any storage file can be downloaded from p.sh if full server path is known",
"details": "The default configuration for platform.sh (.platform.app.yaml) allows access to uploaded files if you know or can guess their location, regardless of whether roles grant content read access to the content containing those files. If you're using Legacy Bridge, the default configuration also allows access to certain legacy files that should not be readable, including the legacy var directory and extension directories.",
"severity": [
],
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "ibexa/post-install"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.0.4.1"
}
]
}
],
"database_specific": {
"last_known_affected_version_range": "<= 1.0.4"
}
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/ibexa/post-install/security/advisories/GHSA-gqcf-83rq-gpfr"
},
{
"type": "WEB",
"url": "https://developers.ibexa.co/security-advisories/ibexa-sa-2021-006-storage-and-legacy-files-accessible-if-path-is-known"
},
{
"type": "PACKAGE",
"url": "https://github.com/ibexa/post-install"
}
],
"database_specific": {
"cwe_ids": [
"CWE-200"
],
"severity": "HIGH",
"github_reviewed": true
}
} | 768 |
854 | /*
* This file is part of Kintinuous.
*
* Copyright (C) 2015 The National University of Ireland Maynooth and
* Massachusetts Institute of Technology
*
* The use of the code within this file and all code within files that
* make up the software that is Kintinuous is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.cs.nuim.ie/research/vision/data/kintinuous/code.php>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email <EMAIL>.
*/
#ifndef CLOUDSLICEPROCESSOR_H_
#define CLOUDSLICEPROCESSOR_H_
#include "../frontend/Volume.h"
#include "../utils/ThreadObject.h"
#include <sstream>
#include <map>
#include <boost/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/filesystem.hpp>
#include <pcl/filters/voxel_grid.h>
#include <pcl/features/normal_3d.h>
#include <pcl/io/pcd_io.h>
class CloudSliceProcessor : public ThreadObject
{
public:
CloudSliceProcessor();
virtual ~CloudSliceProcessor();
void reset();
void save();
private:
bool inline process();
int latestPushedCloud;
int numClouds;
bool cycledMutex;
};
#endif /* CLOUDSLICEPROCESSOR_H_ */
| 502 |
864 | /**********************************************************************************************************************
This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.
Licensed under the BSD-2 license (see LICENSE file in main directory)
**********************************************************************************************************************/
#pragma once
namespace ct {
namespace optcon {
/**
* @ingroup Constraint
*
* @brief Base class for the constraints used in this toolbox
*
* @tparam STATE_DIM The state dimension
* @tparam CONTROL_DIM The control dimension
* @tparam SCALAR The Scalar type
*/
template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR = double>
class ConstraintBase
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef typename ct::core::tpl::TraitSelector<SCALAR>::Trait Trait;
typedef core::StateVector<STATE_DIM, SCALAR> state_vector_t;
typedef core::ControlVector<CONTROL_DIM, SCALAR> control_vector_t;
typedef Eigen::Matrix<SCALAR, Eigen::Dynamic, 1> VectorXs;
typedef Eigen::Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> MatrixXs;
/**
* @brief Custom constructor
*
* @param[in] name The name of the constraint
*/
ConstraintBase(std::string name = "Unnamed");
/**
* @brief Copy constructor
*
* @param[in] arg The object to be copied
*/
ConstraintBase(const ConstraintBase& arg);
/**
* @brief Creates a new instance of the object with same properties than original.
*
* @return Copy of this object.
*/
virtual ConstraintBase<STATE_DIM, CONTROL_DIM, SCALAR>* clone() const = 0;
/**
* @brief Destructor
*/
virtual ~ConstraintBase();
/**
* @brief The evaluation of the constraint violation. Note this method
* is SCALAR typed
*
* @param[in] x The state vector
* @param[in] u The control vector
* @param[in] t The time
*
* @return The constraint violation
*/
virtual VectorXs evaluate(const state_vector_t& x, const control_vector_t& u, const SCALAR t) = 0;
/**
* @brief The evaluate method used for jit compilation in constraint
* container ad
*
* @param[in] x The state vector
* @param[in] u The control vector
* @param[in] t The time
*
* @return The constraint violation
*/
#ifdef CPPADCG
virtual Eigen::Matrix<ct::core::ADCGScalar, Eigen::Dynamic, 1> evaluateCppadCg(
const core::StateVector<STATE_DIM, ct::core::ADCGScalar>& x,
const core::ControlVector<CONTROL_DIM, ct::core::ADCGScalar>& u,
ct::core::ADCGScalar t);
#endif
/**
* @brief Returns the number of constraints
*
* @return The number of constraints
*/
virtual size_t getConstraintSize() const = 0;
/**
* @brief Returns the constraint jacobian wrt state
*
* @return The constraint jacobian
*/
virtual MatrixXs jacobianState(const state_vector_t& x, const control_vector_t& u, const SCALAR t);
/**
* @brief Returns the constraint jacobian wrt input
*
* @return The constraint jacobian
*/
virtual MatrixXs jacobianInput(const state_vector_t& x, const control_vector_t& u, const SCALAR t);
/**
* @brief Returns the lower constraint bound
*
* @return The lower constraint bound
*/
virtual VectorXs getLowerBound() const;
/**
* @brief Returns the upper constraint bound
*
* @return The upper constraint bound
*/
virtual VectorXs getUpperBound() const;
/**
* @brief Returns the constraint name
*
* @param[out] constraintName The constraint name
*/
void getName(std::string& constraintName) const;
/**
* @brief Sets the constraint name.
*
* @param[in] constraintName The constraint name
*/
void setName(const std::string constraintName);
/**
* @brief Returns the number of nonzeros in the jacobian wrt state. The
* default implementation assumes a dense matrix with only
* nonzero elements.
*
* @return The number of non zeros
*/
virtual size_t getNumNonZerosJacobianState() const;
/**
* @brief Returns the number of nonzeros in the jacobian wrt control
* input. The default implementation assumes a dense matrix with
* only nonzero elements
*
* @return The number of non zeros
*/
virtual size_t getNumNonZerosJacobianInput() const;
/**
* @brief Returns the constraint jacobian wrt state in sparse
* structure. The default implementation maps the JacobianState
* matrix to a vector
*
* @return The sparse constraint jacobian
*/
virtual VectorXs jacobianStateSparse(const state_vector_t& x, const control_vector_t& u, const SCALAR t);
/**
* @brief Returns the constraint jacobian wrt control input in sparse
* structure. The default implementation maps the JacobianState
* matrix to a vector
*
* @return The sparse constraint jacobian
*/
virtual VectorXs jacobianInputSparse(const state_vector_t& x, const control_vector_t& u, const SCALAR t);
/**
* @brief Generates the sparsity pattern of the jacobian wrt state. The
* default implementation returns a vector of ones corresponding
* to the dense jacobianState
*
* @param rows The vector of the row indices containing non zero
* elements in the constraint jacobian
* @param cols The vector of the column indices containing non zero
* elements in the constraint jacobian
*/
virtual void sparsityPatternState(Eigen::VectorXi& rows, Eigen::VectorXi& cols);
/**
* @brief Generates the sparsity pattern of the jacobian wrt control
* input. The default implementation returns a vector of ones
* corresponding to the dense jacobianInput
*
* @param rows The vector of the row indices containing non zero
* elements in the constraint jacobian
* @param cols The vector of the column indices containing non zero
* elements in the constraint jacobian
*/
virtual void sparsityPatternInput(Eigen::VectorXi& rows, Eigen::VectorXi& cols);
protected:
VectorXs lb_; //! lower bound on the constraints
VectorXs ub_; //! upper bound on the constraints
/**
* @brief Generates indices of a diagonal square matrix
*
* @param[in] num_elements The number of elements
* @param[out] iRow_vec The row vector
* @param[out] jCol_vec The column vector
*/
static void genDiagonalIndices(const size_t num_elements, Eigen::VectorXi& iRow_vec, Eigen::VectorXi& jCol_vec);
/**
* @brief Generates indices of a sparse diagonal square matrix
*
* @param[in] diag_sparsity Sparsity pattern for the diagonal (Example: [0 1 0 0 1 1])
* @param[out] iRow_vec The row vector
* @param[out] jCol_vec The column vector
*/
static void genSparseDiagonalIndices(const Eigen::VectorXi& diag_sparsity,
Eigen::VectorXi& iRow_vec,
Eigen::VectorXi& jCol_vec);
/**
* @brief Generates indices of a full matrix
*
* @param[in] num_rows The number of rows of the matrix
* @param[in] num_cols The number columns of the matrix
* @param[out] iRow_vec The row vector
* @param[out] jCol_vec The col vector
*/
static void genBlockIndices(const size_t num_rows,
const size_t num_cols,
Eigen::VectorXi& iRow_vec,
Eigen::VectorXi& jCol_vec);
private:
std::string name_;
};
} // namespace optcon
} // namespace ct
| 2,942 |
322 | <gh_stars>100-1000
from json import dump
from steampy.client import SteamClient, InvalidCredentials
from steampy.models import GameOptions
#Your steam username
username = ''
#Path to steam guard file
steam_guard_path = ''
#Your steam password
password = ''
#Your steam api key (http://steamcommunity.com/dev/apikey)
steam_key = ''
#The game's app id. If not supplied, it will ask for input later
app_id = ''
#The game's context id. If not supplied, it will ask for input later
context_id = ''
#Log into steam. First, we create the SteamClient object, then we login
print("Logging into steam")
steam_client = SteamClient(steam_key)
try:
steam_client.login(username, password, steam_guard_path)
except (ValueError, InvalidCredentials):
print('Your login credentials are invalid')
exit(1)
print("Finished! Logged into steam")
#we will ask them for the game's app id and context id of the inventory
if not app_id:
app_id = input('What is the app id?\n')
if not context_id:
context_id = input('What is the context id of that game\'s inventory? (usually 2)\n')
#get all the items in inventory, and save each name of item and the amount
print('Obtaining inventory...')
item_amounts = {}
inventory = steam_client.get_my_inventory(GameOptions(app_id,context_id))
for item in inventory.values():
if item["market_name"] in item_amounts:
item_amounts[item['market_name']] += 1
else:
item_amounts[item['market_name']] = 1
print('Done reading inventory for game: {}'.format(app_id))
#dump all the information into inventory_(app_id)_(context_id).json file
print('Saving information....')
with open('inventory_{0}_{1}.json'.format(app_id, context_id), 'w') as file:
dump(item_amounts, file)
print('Done! Saved to file: inventory_{0}_{1}.json'.format(app_id, context_id))
| 585 |
450 | /*
* 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.
*/
#ifndef SRC_INCLUDE_PG_STAT_ACTIVITY_HISTORY_PROCESS_H_
#define SRC_INCLUDE_PG_STAT_ACTIVITY_HISTORY_PROCESS_H_
#include "utils/timestamp.h"
#include "postgres_ext.h"
#define MAXTIMELENGTH 100
#define MAXDATABASENAME 100
#define MAXUSERNAME 100
#define MAXAPPNAMELENGTH 100
#define MAXERRORINFOLENGTH 1000
#define MAXCLIENTADDRLENGTH 1025
#define MAXSTATUSLENGTH 10
typedef struct queryHistoryInfo
{
Oid databaseId;
Oid userId;
int processId;
Oid sessionId;
int client_port;
uint32_t memoryUsage;
double cpuUsage;
char database_name[MAXDATABASENAME];
char user_name[MAXUSERNAME];
char creation_time[MAXTIMELENGTH];
char end_time[MAXTIMELENGTH];
char client_addr[MAXCLIENTADDRLENGTH];
char application_name[MAXAPPNAMELENGTH];
char status[MAXSTATUSLENGTH];
char errorInfo[MAXERRORINFOLENGTH];
uint32_t queryLen;
}queryHistoryInfo;
extern void pgStatActivityHistory_send(Oid databaseId, Oid userId, int processId,
Oid sessionId, const char *creation_time, const char *end_time,
struct Port *tmpProcPort, char *application_name, double cpuUsage,
uint32_t memoryUsage, int status, char *errorInfo,const char *query);
extern int pgStatActivityHistorySock;
extern void pgstatactivityhistory_init(void);
extern int pgstatactivityhistory_start(void);
extern void allow_immediate_pgStatActivityHistory_restart(void);
#endif /* SRC_INCLUDE_PG_STAT_ACTIVITY_HISTORY_PROCESS_H_ */
| 749 |
2,542 | <gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
using namespace Management::ImageStore;
ImageStoreListDescription::ImageStoreListDescription()
: remoteLocation_()
, continuationToken_()
, isRecursive_(false)
{
}
ImageStoreListDescription::ImageStoreListDescription(
wstring const & remoteLocation,
wstring const & continuationToken,
bool isRecursive)
: remoteLocation_(remoteLocation)
, continuationToken_(continuationToken)
, isRecursive_(isRecursive)
{
}
Common::ErrorCode ImageStoreListDescription::FromPublicApi(__in FABRIC_IMAGE_STORE_LIST_DESCRIPTION const & listDes)
{
HRESULT hr = StringUtility::LpcwstrToWstring(listDes.RemoteLocation, true, remoteLocation_);
if (FAILED(hr)) { return ErrorCode::FromHResult(hr); }
hr = StringUtility::LpcwstrToWstring(listDes.ContinuationToken, true, continuationToken_);
if (FAILED(hr)) { return ErrorCode::FromHResult(hr); }
isRecursive_ = (listDes.IsRecursive == TRUE) ? true : false;
return ErrorCodeValue::Success;
}
void ImageStoreListDescription::ToPublicApi(__in Common::ScopedHeap & heap, __out FABRIC_IMAGE_STORE_LIST_DESCRIPTION & listDes) const
{
listDes.RemoteLocation = heap.AddString(remoteLocation_);
listDes.ContinuationToken = heap.AddString(continuationToken_);
listDes.IsRecursive = isRecursive_ ? TRUE : FALSE;
}
| 515 |
5,169 | {
"name": "OSWebViewPreCache",
"version": "1.0",
"summary": "Offline cache ready-to-go solution for web sites like 'Terms and Conditions' and 'Privacy policy'",
"description": "99% of business projects require to have 'Terms and Conditions' and 'Privacy policy' pages. Moreover, in most cases it is legal obligation to have these pages accessible even when device is offline, without internet connection. OSWebViewPreCache is easy-to-go solution for offline caching of web pages.",
"homepage": "https://github.com/OlexandrStepanov/OSWebViewPreCache",
"license": "Apache 2.0",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/OlexandrStepanov/OSWebViewPreCache.git",
"tag": "1.0"
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"source_files": "Pod/Classes/**/*",
"resource_bundles": {
"OSWebViewPreCache": [
"Pod/Assets/*.png"
]
},
"public_header_files": "Pod/Classes/**/*.h",
"frameworks": "UIKit",
"dependencies": {
"Reachability": [
]
}
}
| 380 |
777 | <gh_stars>100-1000
/*
* Copyright (C) 2004, 2005, 2006, 2007 <NAME> <<EMAIL>>
* Copyright (C) 2004, 2005 <NAME> <<EMAIL>>
* Copyright (C) 2005 <NAME> <<EMAIL>>
* Copyright (C) 2009 <NAME> <<EMAIL>>
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef LayoutSVGResourceFilter_h
#define LayoutSVGResourceFilter_h
#include "core/layout/svg/LayoutSVGResourceContainer.h"
#include "core/svg/SVGUnitTypes.h"
namespace blink {
class FilterEffect;
class SVGFilterElement;
class SVGFilterGraphNodeMap;
class FilterData final : public GarbageCollected<FilterData> {
public:
/*
* The state transitions should follow the following:
* Initial->RecordingContent->ReadyToPaint->PaintingFilter->ReadyToPaint
* | ^ | ^
* v | v |
* RecordingContentCycleDetected PaintingFilterCycle
*/
enum FilterDataState {
Initial,
RecordingContent,
RecordingContentCycleDetected,
ReadyToPaint,
PaintingFilter,
PaintingFilterCycleDetected
};
static FilterData* create() { return new FilterData(); }
void dispose();
DECLARE_TRACE();
Member<FilterEffect> lastEffect;
Member<SVGFilterGraphNodeMap> nodeMap;
FilterDataState m_state;
private:
FilterData() : m_state(Initial) {}
};
class LayoutSVGResourceFilter final : public LayoutSVGResourceContainer {
public:
explicit LayoutSVGResourceFilter(SVGFilterElement*);
~LayoutSVGResourceFilter() override;
bool isChildAllowed(LayoutObject*, const ComputedStyle&) const override;
const char* name() const override { return "LayoutSVGResourceFilter"; }
bool isOfType(LayoutObjectType type) const override {
return type == LayoutObjectSVGResourceFilter ||
LayoutSVGResourceContainer::isOfType(type);
}
void removeAllClientsFromCache(bool markForInvalidation = true) override;
void removeClientFromCache(LayoutObject*,
bool markForInvalidation = true) override;
FloatRect resourceBoundingBox(const LayoutObject*);
SVGUnitTypes::SVGUnitType filterUnits() const;
SVGUnitTypes::SVGUnitType primitiveUnits() const;
void primitiveAttributeChanged(LayoutObject*, const QualifiedName&);
static const LayoutSVGResourceType s_resourceType = FilterResourceType;
LayoutSVGResourceType resourceType() const override { return s_resourceType; }
FilterData* getFilterDataForLayoutObject(const LayoutObject* object) {
return m_filter.get(const_cast<LayoutObject*>(object));
}
void setFilterDataForLayoutObject(LayoutObject* object,
FilterData* filterData) {
m_filter.set(object, filterData);
}
protected:
void willBeDestroyed() override;
private:
void disposeFilterMap();
using FilterMap = PersistentHeapHashMap<LayoutObject*, Member<FilterData>>;
FilterMap m_filter;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutSVGResourceFilter, isSVGResourceFilter());
} // namespace blink
#endif
| 1,221 |
315 | <gh_stars>100-1000
#include <utility>
#include <sstream>
#include <cmath>
#include "Tools/Exception/exception.hpp"
#include "Tools/Documentation/documentation.h"
#include "Module/Decoder/RS/Standard/Decoder_RS_std.hpp"
#include "Module/Decoder/RS/Genius/Decoder_RS_genius.hpp"
#include "Factory/Module/Decoder/RS/Decoder_RS.hpp"
using namespace aff3ct;
using namespace aff3ct::factory;
const std::string aff3ct::factory::Decoder_RS_name = "Decoder RS";
const std::string aff3ct::factory::Decoder_RS_prefix = "dec";
Decoder_RS
::Decoder_RS(const std::string &prefix)
: Decoder(Decoder_RS_name, prefix)
{
this->type = "ALGEBRAIC";
this->implem = "STD";
}
Decoder_RS* Decoder_RS
::clone() const
{
return new Decoder_RS(*this);
}
void Decoder_RS
::get_description(cli::Argument_map_info &args) const
{
Decoder::get_description(args);
auto p = this->get_prefix();
const std::string class_name = "factory::Decoder_RS::";
tools::add_arg(args, p, class_name+"p+corr-pow,T",
cli::Integer(cli::Positive(), cli::Non_zero()));
args.add_link({p+"-corr-pow", "T"}, {p+"-info-bits", "K"});
cli::add_options(args.at({p+"-type", "D"}), 0, "ALGEBRAIC");
cli::add_options(args.at({p+"-implem" }), 0, "GENIUS");
}
void Decoder_RS
::store(const cli::Argument_map_value &vals)
{
Decoder::store(vals);
auto p = this->get_prefix();
this->m = (int)std::ceil(std::log2(this->N_cw));
if (this->m == 0)
{
std::stringstream message;
message << "The Galois Field order is null (because N_cw = " << this->N_cw << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
if (vals.exist({p+"-corr-pow", "T"}))
{
this->t = vals.to_int({p + "-corr-pow", "T"});
if (K == 0)
{
this->K = this->N_cw - this->t * 2;
this->R = (float) this->K / (float) this->N_cw;
}
}
else
this->t = (this->N_cw - this->K) / 2;
}
void Decoder_RS
::get_headers(std::map<std::string,tools::header_list>& headers, const bool full) const
{
Decoder::get_headers(headers, full);
if (this->type != "ML" && this->type != "CHASE")
{
auto p = this->get_prefix();
headers[p].push_back(std::make_pair("Galois field order (m)", std::to_string(this->m)));
headers[p].push_back(std::make_pair("Correction power (T)", std::to_string(this->t)));
}
}
template <typename B, typename Q>
module::Decoder_SIHO<B,Q>* Decoder_RS
::build(const tools::RS_polynomial_generator &GF, module::Encoder<B> *encoder) const
{
try
{
return Decoder::build<B,Q>(encoder);
}
catch (tools::cannot_allocate const&)
{
if (this->type == "ALGEBRAIC")
{
if (this->implem == "STD") return new module::Decoder_RS_std<B,Q>(this->K, this->N_cw, GF);
if (encoder)
{
if (this->implem == "GENIUS") return new module::Decoder_RS_genius<B,Q>(this->K, this->N_cw, GF, *encoder);
}
}
}
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef AFF3CT_MULTI_PREC
template aff3ct::module::Decoder_SIHO<B_8 ,Q_8 >* aff3ct::factory::Decoder_RS::build<B_8 ,Q_8 >(const aff3ct::tools::RS_polynomial_generator&, module::Encoder<B_8 >*) const;
template aff3ct::module::Decoder_SIHO<B_16,Q_16>* aff3ct::factory::Decoder_RS::build<B_16,Q_16>(const aff3ct::tools::RS_polynomial_generator&, module::Encoder<B_16>*) const;
template aff3ct::module::Decoder_SIHO<B_32,Q_32>* aff3ct::factory::Decoder_RS::build<B_32,Q_32>(const aff3ct::tools::RS_polynomial_generator&, module::Encoder<B_32>*) const;
template aff3ct::module::Decoder_SIHO<B_64,Q_64>* aff3ct::factory::Decoder_RS::build<B_64,Q_64>(const aff3ct::tools::RS_polynomial_generator&, module::Encoder<B_64>*) const;
#else
template aff3ct::module::Decoder_SIHO<B,Q>* aff3ct::factory::Decoder_RS::build<B,Q>(const aff3ct::tools::RS_polynomial_generator&, module::Encoder<B>*) const;
#endif
// ==================================================================================== explicit template instantiation
| 1,633 |
742 | #ifndef ARENA_FONT_NAME_H
#define ARENA_FONT_NAME_H
#include <array>
namespace ArenaFontName
{
// Can't be std::string due to global initialization order issues.
constexpr const char *A = "FONT_A.DAT";
constexpr const char *Arena = "ARENAFNT.DAT";
constexpr const char *B = "FONT_B.DAT";
constexpr const char *C = "FONT_C.DAT";
constexpr const char *Char = "CHARFNT.DAT";
constexpr const char *D = "FONT_D.DAT";
constexpr const char *Four = "FONT4.DAT";
constexpr const char *S = "FONT_S.DAT";
constexpr const char *Teeny = "TEENYFNT.DAT";
constexpr std::array<const char*, 9> FontPtrs =
{
ArenaFontName::A,
ArenaFontName::Arena,
ArenaFontName::B,
ArenaFontName::C,
ArenaFontName::Char,
ArenaFontName::D,
ArenaFontName::Four,
ArenaFontName::S,
ArenaFontName::Teeny
};
}
#endif
| 341 |
995 | //Copyright (c) 2008-2016 <NAME> and <NAME>, Inc.
//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)
#ifndef UUID_49C5A1042AEF11DF9603880056D89593
#define UUID_49C5A1042AEF11DF9603880056D89593
#include <boost/qvm/detail/quat_assign.hpp>
#include <boost/qvm/assert.hpp>
#include <boost/qvm/static_assert.hpp>
namespace
boost
{
namespace
qvm
{
template <class T>
struct
quat
{
T a[4];
template <class R>
operator R() const
{
R r;
assign(r,*this);
return r;
}
};
template <class Q>
struct quat_traits;
template <class T>
struct
quat_traits< quat<T> >
{
typedef quat<T> this_quaternion;
typedef T scalar_type;
template <int I>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type
read_element( this_quaternion const & x )
{
BOOST_QVM_STATIC_ASSERT(I>=0);
BOOST_QVM_STATIC_ASSERT(I<4);
return x.a[I];
}
template <int I>
static
BOOST_QVM_INLINE_CRITICAL
scalar_type &
write_element( this_quaternion & x )
{
BOOST_QVM_STATIC_ASSERT(I>=0);
BOOST_QVM_STATIC_ASSERT(I<4);
return x.a[I];
}
};
}
}
#endif
| 1,074 |
407 | package com.alibaba.sreworks.appcenter.server.params;
import com.alibaba.sreworks.domain.DO.AppInstance;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AppInstanceUpdateParam {
private String description;
public void patchAppInstance(AppInstance appInstance, String operator) {
appInstance.setGmtModified(System.currentTimeMillis() / 1000);
appInstance.setLastModifier(operator);
appInstance.setDescription(description);
}
}
| 198 |
418 | # type: ignore
from setuptools import setup
setup()
| 15 |
828 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or 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 net.hasor.db.dal.dynamic.segment;
import net.hasor.db.dal.dynamic.BuilderContext;
import net.hasor.db.dal.dynamic.DynamicSql;
import net.hasor.db.dal.dynamic.QuerySqlBuilder;
import net.hasor.db.dal.dynamic.rule.ParameterSqlBuildRule;
import net.hasor.db.dal.dynamic.rule.SqlBuildRule;
import net.hasor.db.dal.dynamic.rule.TextSqlBuildRule;
import net.hasor.utils.StringUtils;
import net.hasor.utils.ref.LinkedCaseInsensitiveMap;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static net.hasor.db.dal.dynamic.ognl.OgnlUtils.evalOgnl;
import static net.hasor.db.dal.dynamic.rule.ParameterSqlBuildRule.*;
/**
* 本处理器,兼容 @{...}、#{...}、${...} 三种写法。
* @author 赵永春 (<EMAIL>)
* @version : 2020-03-28
*/
public class DefaultSqlSegment implements Cloneable, DynamicSql {
private final StringBuilder queryStringOri = new StringBuilder("");
private final List<FxSegment> queryStringPlan = new LinkedList<>();
private boolean havePlaceholder = false;
/** 追加 字符串 */
public void appendString(String append) {
this.queryStringOri.append(append);
if (!this.queryStringPlan.isEmpty()) {
Object ss = this.queryStringPlan.get(this.queryStringPlan.size() - 1);
if (ss instanceof TextFxSegment) {
((TextFxSegment) ss).append(append);
return;
}
}
this.queryStringPlan.add(new TextFxSegment(append));
}
/** 追加 注入语句 */
public void appendPlaceholderExpr(String exprString) {
this.queryStringOri.append("${" + exprString + "}");
this.queryStringPlan.add(new PlaceholderFxSegment(exprString));
this.havePlaceholder = true;
}
/** 追加 规则 */
public void appendRuleExpr(String ruleName, String activateExpr, String exprString) {
this.queryStringOri.append("@{" + ruleName + ", " + activateExpr + ", " + exprString + "}");
this.queryStringPlan.add(new RuleFxSegment(ruleName, activateExpr, exprString));
this.havePlaceholder = true;
}
/** 添加一个 SQL 参数,最终这个参数会通过 PreparedStatement 形式传递。 */
public void appendValueExpr(String exprString, String sqlMode, String jdbcType, String javaType, String typeHandler) {
this.queryStringOri.append("#{");
this.queryStringOri.append(exprString);
if (sqlMode != null) {
this.queryStringOri.append(", mode=" + sqlMode);
}
if (StringUtils.isNotBlank(jdbcType)) {
this.queryStringOri.append(", jdbcType=" + jdbcType);
}
if (StringUtils.isNotBlank(javaType)) {
this.queryStringOri.append(", javaType=" + javaType);
}
if (StringUtils.isNotBlank(typeHandler)) {
this.queryStringOri.append(", typeHandler=" + typeHandler);
}
this.queryStringOri.append("}");
//
this.queryStringPlan.add(new ParameterFxSegment(exprString, sqlMode, jdbcType, javaType, typeHandler));
}
/** 是否包含替换占位符,如果包含替换占位符那么不能使用批量模式 */
public boolean isHavePlaceholder() {
return this.havePlaceholder;
}
public String getOriSqlString() {
return this.queryStringOri.toString();
}
@Override
public void buildQuery(BuilderContext builderContext, QuerySqlBuilder querySqlBuilder) throws SQLException {
for (FxSegment fxSegment : this.queryStringPlan) {
fxSegment.buildQuery(builderContext, querySqlBuilder);
}
}
@Override
public DynamicSql clone() {
DefaultSqlSegment clone = new DefaultSqlSegment();
clone.queryStringOri.append(this.queryStringOri);
for (FxSegment fxSegment : this.queryStringPlan) {
clone.queryStringPlan.add(fxSegment.clone());
}
clone.havePlaceholder = this.havePlaceholder;
return clone;
}
public static interface FxSegment extends Cloneable {
public void buildQuery(BuilderContext builderContext, QuerySqlBuilder querySqlBuilder) throws SQLException;
public FxSegment clone();
}
protected static class TextFxSegment implements FxSegment {
private final StringBuilder textString;
public TextFxSegment(String exprString) {
this.textString = new StringBuilder(exprString);
}
public void append(String append) {
this.textString.append(append);
}
@Override
public void buildQuery(BuilderContext builderContext, QuerySqlBuilder querySqlBuilder) throws SQLException {
TextSqlBuildRule.INSTANCE.executeRule(builderContext, querySqlBuilder, this.textString.toString(), Collections.emptyMap());
}
@Override
public TextFxSegment clone() {
return new TextFxSegment(this.textString.toString());
}
@Override
public String toString() {
return "Text [" + this.textString + "]";
}
}
protected static class PlaceholderFxSegment implements FxSegment {
private final StringBuilder exprString;
public PlaceholderFxSegment(String exprString) {
this.exprString = new StringBuilder(exprString);
}
@Override
public void buildQuery(BuilderContext builderContext, QuerySqlBuilder querySqlBuilder) throws SQLException {
String placeholderQuery = String.valueOf(evalOgnl(this.exprString.toString(), builderContext.getContext()));
TextSqlBuildRule.INSTANCE.executeRule(builderContext, querySqlBuilder, placeholderQuery, Collections.emptyMap());
}
@Override
public PlaceholderFxSegment clone() {
return new PlaceholderFxSegment(this.exprString.toString());
}
@Override
public String toString() {
return "Placeholder [" + this.exprString + "]";
}
}
protected static class RuleFxSegment implements FxSegment {
private final String ruleName;
private final String activateExpr;
private final String ruleValue;
public RuleFxSegment(String ruleName, String activateExpr, String ruleValue) {
this.ruleName = ruleName;
this.activateExpr = activateExpr;
this.ruleValue = ruleValue;
}
@Override
public void buildQuery(BuilderContext builderContext, QuerySqlBuilder querySqlBuilder) throws SQLException {
SqlBuildRule ruleByName = builderContext.getRuleRegistry().findByName(this.ruleName);
if (ruleByName == null) {
throw new UnsupportedOperationException("rule `" + this.ruleName + "` Unsupported.");
}
if (ruleByName.test(builderContext, this.activateExpr)) {
ruleByName.executeRule(builderContext, querySqlBuilder, this.ruleValue, Collections.emptyMap());
}
}
@Override
public RuleFxSegment clone() {
return new RuleFxSegment(this.ruleName, this.activateExpr, this.ruleValue);
}
@Override
public String toString() {
return "Rule [" + this.ruleName + ", body=" + this.ruleValue + "]";
}
}
protected static class ParameterFxSegment implements FxSegment {
private final String exprString;
private final Map<String, String> config;
public ParameterFxSegment(String exprString, String sqlMode, String jdbcType, String javaType, String typeHandler) {
this.exprString = exprString;
this.config = new LinkedCaseInsensitiveMap<String>() {{
put(CFG_KEY_MODE, sqlMode);
put(CFG_KEY_JDBC_TYPE, jdbcType);
put(CFG_KEY_JAVA_TYPE, javaType);
put(CFG_KEY_HANDLER, typeHandler);
}};
}
@Override
public void buildQuery(BuilderContext builderContext, QuerySqlBuilder querySqlBuilder) throws SQLException {
ParameterSqlBuildRule.INSTANCE.executeRule(builderContext, querySqlBuilder, this.exprString, this.config);
}
@Override
public ParameterFxSegment clone() {
return new ParameterFxSegment(this.exprString, this.config.get(CFG_KEY_MODE), this.config.get(CFG_KEY_JDBC_TYPE), this.config.get(CFG_KEY_JAVA_TYPE), this.config.get(CFG_KEY_HANDLER));
}
@Override
public String toString() {
return "Parameter [" + this.exprString + "]";
}
}
}
| 3,812 |
327 | <filename>projects/testable-project/src/org/lsp/runnable/test/Testable.java<gh_stars>100-1000
package org.lsp.runnable.test;
import junit.framework.TestCase;
public class Testable extends TestCase {
public void test1() {
try { Thread.sleep(2000); } catch (Exception e) { e.printStackTrace(); }
}
public void test2() {
try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); }
fail("test2 failed");
}
}
| 179 |
5,079 | <reponame>fmadrid-ana/jaeger-client-python<filename>tests/test_local_agent_net.py
# Copyright (c) 2016 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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 pytest
import tornado.web
from urllib.parse import urlparse
from jaeger_client.local_agent_net import LocalAgentSender
from jaeger_client.config import DEFAULT_REPORTING_PORT
test_strategy = """
{
"strategyType":0,
"probabilisticSampling":
{
"samplingRate":0.002
}
}
"""
test_credits = """
{
\"balances\": [
{
\"operation\": \"test-operation\",
\"balance\": 2.0
}
]
}
"""
test_client_id = 12345678
class AgentHandler(tornado.web.RequestHandler):
def get(self):
self.write(test_strategy)
class CreditHandler(tornado.web.RequestHandler):
def get(self):
self.write(test_credits)
application = tornado.web.Application([
(r'/sampling', AgentHandler),
(r'/credits', CreditHandler),
])
@pytest.fixture
def app():
return application
@pytest.mark.gen_test
def test_request_sampling_strategy(http_client, base_url):
o = urlparse(base_url)
sender = LocalAgentSender(
host='localhost',
sampling_port=o.port,
reporting_port=DEFAULT_REPORTING_PORT
)
response = yield sender.request_sampling_strategy(service_name='svc', timeout=15)
assert response.body == test_strategy.encode('utf-8')
@pytest.mark.gen_test
def test_request_throttling_credits(http_client, base_url):
o = urlparse(base_url)
sender = LocalAgentSender(
host='localhost',
sampling_port=o.port,
reporting_port=DEFAULT_REPORTING_PORT,
throttling_port=o.port,
)
response = yield sender.request_throttling_credits(
service_name='svc',
client_id=test_client_id,
operations=['test-operation'],
timeout=15)
assert response.body == test_credits.encode('utf-8')
| 973 |
10,225 | <gh_stars>1000+
package io.quarkus.it.vertx;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.net.JdkSSLEngineOptions;
import io.vertx.core.net.JksOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
@QuarkusTest
public class Http2TestCase {
protected static final String PING_DATA = "12345678";
@TestHTTPResource(value = "/ping", ssl = true)
URL sslUrl;
@TestHTTPResource(value = "/ping", ssl = false)
URL url;
@Test
public void testHttp2EnabledSsl() throws ExecutionException, InterruptedException {
runHttp2EnabledSsl("client-keystore-1.jks");
}
@Test
public void testHttp2EnabledSslWithNotSelectedClientCert() throws ExecutionException, InterruptedException {
// client-keystore-2.jks contains the key pair matching mykey-2 in server-truststore.jks,
// but only mykey-1 is "selected" via its alias in application.properties
ExecutionException exc = Assertions.assertThrows(ExecutionException.class,
() -> runHttp2EnabledSsl("client-keystore-2.jks"));
Assertions.assertEquals("SSLHandshakeException: Received fatal alert: bad_certificate",
ExceptionUtils.getRootCauseMessage(exc));
}
private void runHttp2EnabledSsl(String keystoreName) throws InterruptedException, ExecutionException {
Assumptions.assumeTrue(JdkSSLEngineOptions.isAlpnAvailable()); //don't run on JDK8
Vertx vertx = Vertx.vertx();
try {
WebClientOptions options = new WebClientOptions()
.setUseAlpn(true)
.setProtocolVersion(HttpVersion.HTTP_2)
.setSsl(true)
.setKeyStoreOptions(
new JksOptions().setPath("src/test/resources/" + keystoreName).setPassword("password"))
.setTrustStoreOptions(
new JksOptions().setPath("src/test/resources/client-truststore.jks").setPassword("password"));
WebClient client = WebClient.create(vertx, options);
int port = sslUrl.getPort();
runTest(client, port);
} finally {
vertx.close();
}
}
@Test
public void testHttp2EnabledPlain() throws ExecutionException, InterruptedException {
Vertx vertx = Vertx.vertx();
try {
WebClientOptions options = new WebClientOptions()
.setProtocolVersion(HttpVersion.HTTP_2)
.setHttp2ClearTextUpgrade(true);
WebClient client = WebClient.create(vertx, options);
runTest(client, url.getPort());
} finally {
vertx.close();
}
}
private void runTest(WebClient client, int port) throws InterruptedException, ExecutionException {
CompletableFuture<String> result = new CompletableFuture<>();
client
.get(port, "localhost", "/ping")
.virtualHost("server")
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();
result.complete(response.bodyAsString());
} else {
result.completeExceptionally(ar.cause());
}
});
Assertions.assertEquals(PING_DATA, result.get());
}
@ApplicationScoped
static class MyBean {
public void register(@Observes Router router) {
//ping only works on HTTP/2
router.get("/ping").handler(rc -> {
rc.request().connection().ping(Buffer.buffer(PING_DATA), new Handler<AsyncResult<Buffer>>() {
@Override
public void handle(AsyncResult<Buffer> event) {
rc.response().end(event.result());
}
});
});
}
}
}
| 2,085 |
312 | <filename>3rd_party/occa/src/occa/internal/lang/expr/typeNode.cpp
#include <occa/internal/lang/expr/typeNode.hpp>
namespace occa {
namespace lang {
typeNode::typeNode(token_t *token_,
type_t &value_) :
exprNode(token_),
value(value_) {}
typeNode::typeNode(const typeNode &node) :
exprNode(node.token),
value(node.value) {}
typeNode::~typeNode() {}
udim_t typeNode::type() const {
return exprNodeType::type;
}
exprNode* typeNode::clone() const {
return new typeNode(token, value);
}
bool typeNode::hasAttribute(const std::string &attr) const {
return value.hasAttribute(attr);
}
void typeNode::print(printer &pout) const {
pout << value;
}
void typeNode::debugPrint(const std::string &prefix) const {
printer pout(io::stderr);
io::stderr << prefix << "|\n"
<< prefix << "|---[";
pout << (*this);
io::stderr << "] (type)\n";
}
}
}
| 445 |
5,169 | {
"name": "InfiniteScrolling",
"version": "1.0.2",
"summary": "Add infinite scrolling to collection view.",
"description": "'This pod adds infinite scrolling ability in UICollectionView'.",
"homepage": "https://github.com/Vishal-Singh-Panwar/InfiniteScrolling",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/Vishal-Singh-Panwar/InfiniteScrolling.git",
"tag": "1.0.2"
},
"platforms": {
"ios": "9.0"
},
"source_files": "InfiniteScrolling/Classes/**/*",
"pushed_with_swift_version": "3.0"
}
| 252 |
303 | <filename>XRTCDemo_iOS/XrtcDemo/NMCBasicModuleFramework.framework/Headers/NMC_Reachability.h
//
// NMC_Reachability.h
// NMCBasicModule
//
// Created by taojinliang on 2018/4/25.
// Copyright © 2018年 taojinliang. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import <CoreTelephony/CTCarrier.h>
// Reachability is available for iOS 7 or higher, fully support IPv6.
typedef NS_ENUM(NSInteger, NMCNetworkStatus) {
NMCNetworkStatusNotReachable, // 未检测到
NMCNetworkStatusNotSure, // 无法确定
NMCNetworkStatusReachableVia2G, // 2G
NMCNetworkStatusReachableVia3G, // 3G
NMCNetworkStatusReachableVia4G, // 4G
NMCNetworkStatusReachableVia5G, // 5G
NMCNetworkStatusReachableViaWiFi, // WiFi
NMCNetworkStatusReachableViaWWAN, // WWAN not sure, should not use
};
typedef NS_ENUM(NSInteger, NMCMAMCarrier) {
NMCMAMOperatorChinaMobile, // 中国移动
NMCMAMOperatorChinaUnicom, // 中国联通
NMCMAMOperatorChinaTelecom, // 中国电信
NMCMAMOperatorOther, // 其他
NMCMAMOperatorNone, // None,无 sim 卡
};
extern NSString *nmc_kReachabilityChangedNotification;
@interface NMC_Reachability : NSObject
// 当前网络类型
@property (nonatomic, readonly) NMCNetworkStatus currentNetworkStatus;
// 变化之前网络类型(当网络没有变化时,值为 NMCNetworkStatusNotSure;变化一次后,值为变化之前的网络类型)
@property (nonatomic, readonly) NMCNetworkStatus oldNetworkStatus;
// 当前运营商
@property (nonatomic, readonly) NMCMAMCarrier currentCarrier;
@property (nonatomic, readonly) CTCarrier *currentCTCarrier;
/*!
* Use to check the reachability of a given host name.
*/
+ (instancetype)nmc_reachabilityWithHostName:(NSString *)hostName;
/*!
* Use to check the reachability of a given IP address.
*/
+ (instancetype)nmc_reachabilityWithAddress:(const struct sockaddr_in *)hostAddress;
/*!
* Checks whether the default route is available. Should be used by applications that do not connect to a particular host.
*/
+ (instancetype)nmc_reachabilityForInternetConnection;
/*!
* Checks whether a local WiFi connection is available.
*/
+ (instancetype)nmc_reachabilityForLocalWiFi;
/*!
* Start listening for reachability notifications on the current run loop.
*/
- (BOOL)nmc_startNotifier;
- (void)nmc_stopNotifier;
- (NMCNetworkStatus)nmc_currentReachabilityStatus;
/*!
* WWAN may be available, but not active until a connection has been established. WiFi may require a connection for VPN on Demand.
*/
- (BOOL)nmc_connectionRequired;
+ (BOOL)isWiFi;
@end
| 1,058 |
13,648 | <gh_stars>1000+
# Test uasyncio TCP stream closing then writing
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
PORT = 8000
async def handle_connection(reader, writer):
# Write data to ensure connection
writer.write(b"x")
await writer.drain()
# Read, should return nothing
print("read:", await reader.read(100))
# Close connection
print("close")
writer.close()
await writer.wait_closed()
print("done")
ev.set()
async def tcp_server():
global ev
ev = asyncio.Event()
server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT)
print("server running")
multitest.next()
async with server:
await asyncio.wait_for(ev.wait(), 5)
async def tcp_client():
reader, writer = await asyncio.open_connection(IP, PORT)
# Read data to ensure connection
print("read:", await reader.read(1))
# Close connection
print("close")
writer.close()
await writer.wait_closed()
# Try writing data to the closed connection
print("write")
try:
writer.write(b"x")
await writer.drain()
except OSError:
print("OSError")
def instance0():
multitest.globals(IP=multitest.get_network_ip())
asyncio.run(tcp_server())
def instance1():
multitest.next()
asyncio.run(tcp_client())
| 561 |
82,043 | {
"name": "dart",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"license": "MIT",
"engines": {
"vscode": "0.10.x"
},
"scripts": {
"update-grammar": "node ../node_modules/vscode-grammar-updater/bin dart-lang/dart-syntax-highlight grammars/dart.json ./syntaxes/dart.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "dart",
"extensions": [
".dart"
],
"aliases": [
"Dart"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "dart",
"scopeName": "source.dart",
"path": "./syntaxes/dart.tmLanguage.json"
}
]
}
}
| 350 |
523 | <filename>UAlbertaBot/Source/research/visualizer/ReplayVisualizer.cpp
#include "ReplayVisualizer.h"
#ifdef USING_VISUALIZATION_LIBRARIES
/*
ReplayVisualizer::ReplayVisualizer()
: map(BWAPI::Broodwar)
{
}
void ReplayVisualizer::launchSimulation(const BWAPI::Position & center, const int & radius)
{
// set up the display object
SparCraft::Display display(SparCraft::Display(BWAPI::Broodwar->mapWidth(), BWAPI::Broodwar->mapHeight()));
display.OnStart();
display.LoadMapTexture(&map, 19);
// extract the state from the current state of BWAPI
SparCraft::GameState state;
setCombatUnits(state, center, radius);
state.setMap(&map);
// get search player objects for us and the opponent
PlayerPtr selfPlayer(getSearchPlayer(SparCraft::PlayerToMove::Alternate, SparCraft::Players::Player_One, SparCraft::EvaluationMethods::Playout, 40));
PlayerPtr enemyPlayer(SparCraft::AllPlayers::getPlayerPtr(SparCraft::Players::Player_Two, SparCraft::PlayerModels::AttackClosest));
// set up the game
SparCraft::Game g(state, selfPlayer, enemyPlayer, 1000);
g.disp = &display;
// play the game to the end
g.play();
}
void ReplayVisualizer::setCombatUnits(SparCraft::GameState & state, const BWAPI::Position & center, const int radius)
{
int selfUnits = 0;
BOOST_FOREACH (BWAPI::UnitInterface* unit, BWAPI::Broodwar->getPlayer(1)->getUnits())
{
bool inRadius = unit->getDistance(center) < radius;
if (selfUnits < 8 && inRadius && isCombatUnit(unit->getType()))
{
selfUnits++;
// FIX state.addUnit(SparCraft::Unit(unit, SparCraft::Players::Player_One, BWAPI::Broodwar->getFrameCount()));
}
else
{
// FIX state.addNeutralUnit(SparCraft::Unit(unit, SparCraft::Players::Player_One, BWAPI::Broodwar->getFrameCount()));
}
}
int enemyUnits = 0;
BOOST_FOREACH (BWAPI::UnitInterface* unit, BWAPI::Broodwar->getPlayer(0)->getUnits())
{
if (enemyUnits >= 8)
{
break;
}
bool inRadius = unit->getDistance(center) < radius;
if (enemyUnits < 8 && inRadius && isCombatUnit(unit->getType()) && !unit->getType().isFlyer())
{
enemyUnits++;
// FIX state.addUnit(SparCraft::Unit(unit,Search::Players::Player_Two, BWAPI::Broodwar->getFrameCount()));
}
else
{
// FIX state.addNeutralUnit(SparCraft::Unit(unit, Search::Players::Player_Two, BWAPI::Broodwar->getFrameCount()));
}
}
int neutralUnits = 0;
BOOST_FOREACH (BWAPI::UnitInterface* unit, BWAPI::Broodwar->getAllUnits())
{
neutralUnits++;
const IDType player(getPlayer(unit->getPlayer()));
if (unit->getType() == BWAPI::UnitTypes::Resource_Mineral_Field ||
unit->getType() == BWAPI::UnitTypes::Resource_Vespene_Geyser)
{
// FIX state.addNeutralUnit(SparCraft::Unit(unit, Search::Players::Player_None, BWAPI::Broodwar->getFrameCount()));
}
}
state.finishedMoving();
}
bool ReplayVisualizer::isCombatUnit(BWAPI::UnitType type) const
{
if (type == BWAPI::UnitTypes::Zerg_Lurker || type == BWAPI::UnitTypes::Protoss_Dark_Templar)
{
return false;
}
// no workers or buildings allowed
if (type.isWorker())
{
return false;
}
// check for various types of combat units
if (type.canAttack() || type == BWAPI::UnitTypes::Terran_Medic)
{
return true;
}
return false;
}
PlayerPtr ReplayVisualizer::getSearchPlayer(const IDType & playerToMoveMethod, const IDType & playerID, const IDType & evalMethod, const size_t & timeLimitMS)
{
IDType bestResponseTo = SparCraft::PlayerModels::NOKDPS;
// base parameters to use in search
SparCraft::AlphaBetaSearchParameters baseParameters;
baseParameters.setMaxPlayer(playerID);
baseParameters.setSearchMethod(SparCraft::SearchMethods::IDAlphaBeta);
baseParameters.setEvalMethod(evalMethod);
baseParameters.setMaxDepth(SparCraft::Constants::Max_Search_Depth);
//baseParameters.setScriptMoveFirstMethod(SparCraft::PlayerModels::NOKDPS);
baseParameters.setTimeLimit(timeLimitMS);
// IF USING OPPONENT MODELING SET IT HERE
baseParameters.setModelSimMethod(bestResponseTo);
baseParameters.setPlayerModel(Search::Players::Player_Two, bestResponseTo, true);
baseParameters.setPlayerToMoveMethod(playerToMoveMethod);
return PlayerPtr(new MicroSearch::Player_AlphaBeta(playerID, baseParameters, MicroSearch::TTPtr(new MicroSearch::TranspositionTable())));
}
const MicroSearch::Unit ReplayVisualizer::getUnit(const UnitInfo & ui, const IDType & playerID) const
{
BWAPI::UnitType type = ui.type;
return MicroSearch::Unit(ui.type, MicroSearch::Position(ui.lastPosition.x, ui.lastPosition.y), ui.unitID, playerID, ui.lastHealth, 0,
BWAPI::Broodwar->getFrameCount(), BWAPI::Broodwar->getFrameCount());
}
const IDType ReplayVisualizer::getPlayer(BWAPI::UnitInterface* unit) const
{
return getPlayer(unit->getPlayer());
}
const IDType ReplayVisualizer::getPlayer(BWAPI::PlayerInterface * player) const
{
if (player == BWAPI::Broodwar->self())
{
return SparCraft::Players::Player_Two;
}
else if (player == BWAPI::Broodwar->enemy())
{
return SparCraft::Players::Player_One;
}
return SparCraft::Players::Player_None;
}
*/
#endif | 1,753 |
1,043 | /*
* Copyright (c) 1993-2014, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef _cl827e_h_
#define _cl827e_h_
#ifdef __cplusplus
extern "C" {
#endif
#define NV827E_OVERLAY_CHANNEL_DMA (0x0000827E)
#define NV_DISP_NOTIFICATION_1 0x00000000
#define NV_DISP_NOTIFICATION_1_SIZEOF 0x00000010
#define NV_DISP_NOTIFICATION_1_TIME_STAMP_0 0x00000000
#define NV_DISP_NOTIFICATION_1_TIME_STAMP_0_NANOSECONDS0 31:0
#define NV_DISP_NOTIFICATION_1_TIME_STAMP_1 0x00000001
#define NV_DISP_NOTIFICATION_1_TIME_STAMP_1_NANOSECONDS1 31:0
#define NV_DISP_NOTIFICATION_1__2 0x00000002
#define NV_DISP_NOTIFICATION_1__2_AUDIT_TIMESTAMP 31:0
#define NV_DISP_NOTIFICATION_1__3 0x00000003
#define NV_DISP_NOTIFICATION_1__3_PRESENT_COUNT 7:0
#define NV_DISP_NOTIFICATION_1__3_R0 15:8
#define NV_DISP_NOTIFICATION_1__3_STATUS 31:16
#define NV_DISP_NOTIFICATION_1__3_STATUS_NOT_BEGUN 0x00008000
#define NV_DISP_NOTIFICATION_1__3_STATUS_BEGUN 0x0000FFFF
#define NV_DISP_NOTIFICATION_1__3_STATUS_FINISHED 0x00000000
#define NV_DISP_NOTIFICATION_INFO16 0x00000000
#define NV_DISP_NOTIFICATION_INFO16_SIZEOF 0x00000002
#define NV_DISP_NOTIFICATION_INFO16__0 0x00000000
#define NV_DISP_NOTIFICATION_INFO16__0_PRESENT_COUNT 7:0
#define NV_DISP_NOTIFICATION_INFO16__0_R0 15:8
#define NV_DISP_NOTIFICATION_STATUS 0x00000000
#define NV_DISP_NOTIFICATION_STATUS_SIZEOF 0x00000002
#define NV_DISP_NOTIFICATION_STATUS__0 0x00000000
#define NV_DISP_NOTIFICATION_STATUS__0_STATUS 15:0
#define NV_DISP_NOTIFICATION_STATUS__0_STATUS_NOT_BEGUN 0x00008000
#define NV_DISP_NOTIFICATION_STATUS__0_STATUS_BEGUN 0x0000FFFF
#define NV_DISP_NOTIFICATION_STATUS__0_STATUS_FINISHED 0x00000000
// dma opcode instructions
#define NV827E_DMA 0x00000000
#define NV827E_DMA_OPCODE 31:29
#define NV827E_DMA_OPCODE_METHOD 0x00000000
#define NV827E_DMA_OPCODE_JUMP 0x00000001
#define NV827E_DMA_OPCODE_NONINC_METHOD 0x00000002
#define NV827E_DMA_OPCODE_SET_SUBDEVICE_MASK 0x00000003
#define NV827E_DMA_OPCODE 31:29
#define NV827E_DMA_OPCODE_METHOD 0x00000000
#define NV827E_DMA_OPCODE_NONINC_METHOD 0x00000002
#define NV827E_DMA_METHOD_COUNT 27:18
#define NV827E_DMA_METHOD_OFFSET 11:2
#define NV827E_DMA_DATA 31:0
#define NV827E_DMA_NOP 0x00000000
#define NV827E_DMA_OPCODE 31:29
#define NV827E_DMA_OPCODE_JUMP 0x00000001
#define NV827E_DMA_JUMP_OFFSET 11:2
#define NV827E_DMA_OPCODE 31:29
#define NV827E_DMA_OPCODE_SET_SUBDEVICE_MASK 0x00000003
#define NV827E_DMA_SET_SUBDEVICE_MASK_VALUE 11:0
// class methods
#define NV827E_PUT (0x00000000)
#define NV827E_PUT_PTR 11:2
#define NV827E_GET (0x00000004)
#define NV827E_GET_PTR 11:2
#define NV827E_UPDATE (0x00000080)
#define NV827E_UPDATE_INTERLOCK_WITH_CORE 0:0
#define NV827E_UPDATE_INTERLOCK_WITH_CORE_DISABLE (0x00000000)
#define NV827E_UPDATE_INTERLOCK_WITH_CORE_ENABLE (0x00000001)
#define NV827E_SET_PRESENT_CONTROL (0x00000084)
#define NV827E_SET_PRESENT_CONTROL_BEGIN_MODE 1:0
#define NV827E_SET_PRESENT_CONTROL_BEGIN_MODE_ASAP (0x00000000)
#define NV827E_SET_PRESENT_CONTROL_BEGIN_MODE_TIMESTAMP (0x00000003)
#define NV827E_SET_PRESENT_CONTROL_MIN_PRESENT_INTERVAL 7:4
#define NV827E_SET_SEMAPHORE_ACQUIRE (0x00000088)
#define NV827E_SET_SEMAPHORE_ACQUIRE_VALUE 31:0
#define NV827E_SET_SEMAPHORE_RELEASE (0x0000008C)
#define NV827E_SET_SEMAPHORE_RELEASE_VALUE 31:0
#define NV827E_SET_SEMAPHORE_CONTROL (0x00000090)
#define NV827E_SET_SEMAPHORE_CONTROL_OFFSET 11:2
#define NV827E_SET_CONTEXT_DMA_SEMAPHORE (0x00000094)
#define NV827E_SET_CONTEXT_DMA_SEMAPHORE_HANDLE 31:0
#define NV827E_SET_NOTIFIER_CONTROL (0x000000A0)
#define NV827E_SET_NOTIFIER_CONTROL_MODE 30:30
#define NV827E_SET_NOTIFIER_CONTROL_MODE_WRITE (0x00000000)
#define NV827E_SET_NOTIFIER_CONTROL_MODE_WRITE_AWAKEN (0x00000001)
#define NV827E_SET_NOTIFIER_CONTROL_OFFSET 11:2
#define NV827E_SET_CONTEXT_DMA_NOTIFIER (0x000000A4)
#define NV827E_SET_CONTEXT_DMA_NOTIFIER_HANDLE 31:0
#define NV827E_SET_CONTEXT_DMA_ISO (0x000000C0)
#define NV827E_SET_CONTEXT_DMA_ISO_HANDLE 31:0
#define NV827E_SET_POINT_IN (0x000000E0)
#define NV827E_SET_POINT_IN_X 14:0
#define NV827E_SET_POINT_IN_Y 30:16
#define NV827E_SET_SIZE_IN (0x000000E4)
#define NV827E_SET_SIZE_IN_WIDTH 14:0
#define NV827E_SET_SIZE_IN_HEIGHT 30:16
#define NV827E_SET_SIZE_OUT (0x000000E8)
#define NV827E_SET_SIZE_OUT_WIDTH 14:0
#define NV827E_SET_COMPOSITION_CONTROL (0x00000100)
#define NV827E_SET_COMPOSITION_CONTROL_MODE 3:0
#define NV827E_SET_COMPOSITION_CONTROL_MODE_SOURCE_COLOR_VALUE_KEYING (0x00000000)
#define NV827E_SET_COMPOSITION_CONTROL_MODE_DESTINATION_COLOR_VALUE_KEYING (0x00000001)
#define NV827E_SET_COMPOSITION_CONTROL_MODE_OPAQUE_SUSPEND_BASE (0x00000002)
#define NV827E_SET_KEY_COLOR (0x00000104)
#define NV827E_SET_KEY_COLOR_COLOR 31:0
#define NV827E_SET_KEY_MASK (0x00000108)
#define NV827E_SET_KEY_MASK_MASK 31:0
#define NV827E_SET_TIMESTAMP_ORIGIN_LO (0x00000130)
#define NV827E_SET_TIMESTAMP_ORIGIN_LO_TIMESTAMP_LO 31:0
#define NV827E_SET_TIMESTAMP_ORIGIN_HI (0x00000134)
#define NV827E_SET_TIMESTAMP_ORIGIN_HI_TIMESTAMP_HI 31:0
#define NV827E_SET_UPDATE_TIMESTAMP_LO (0x00000138)
#define NV827E_SET_UPDATE_TIMESTAMP_LO_TIMESTAMP_LO 31:0
#define NV827E_SET_UPDATE_TIMESTAMP_HI (0x0000013C)
#define NV827E_SET_UPDATE_TIMESTAMP_HI_TIMESTAMP_HI 31:0
#define NV827E_SET_SPARE (0x000007BC)
#define NV827E_SET_SPARE_UNUSED 31:0
#define NV827E_SET_SPARE_NOOP(b) (0x000007C0 + (b)*0x00000004)
#define NV827E_SET_SPARE_NOOP_UNUSED 31:0
#define NV827E_SURFACE_SET_OFFSET (0x00000800)
#define NV827E_SURFACE_SET_OFFSET_ORIGIN 31:0
#define NV827E_SURFACE_SET_SIZE (0x00000808)
#define NV827E_SURFACE_SET_SIZE_WIDTH 14:0
#define NV827E_SURFACE_SET_SIZE_HEIGHT 30:16
#define NV827E_SURFACE_SET_STORAGE (0x0000080C)
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT 3:0
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT_ONE_GOB (0x00000000)
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT_TWO_GOBS (0x00000001)
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT_FOUR_GOBS (0x00000002)
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT_EIGHT_GOBS (0x00000003)
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT_SIXTEEN_GOBS (0x00000004)
#define NV827E_SURFACE_SET_STORAGE_BLOCK_HEIGHT_THIRTYTWO_GOBS (0x00000005)
#define NV827E_SURFACE_SET_STORAGE_PITCH 17:8
#define NV827E_SURFACE_SET_STORAGE_MEMORY_LAYOUT 20:20
#define NV827E_SURFACE_SET_STORAGE_MEMORY_LAYOUT_BLOCKLINEAR (0x00000000)
#define NV827E_SURFACE_SET_STORAGE_MEMORY_LAYOUT_PITCH (0x00000001)
#define NV827E_SURFACE_SET_PARAMS (0x00000810)
#define NV827E_SURFACE_SET_PARAMS_FORMAT 15:8
#define NV827E_SURFACE_SET_PARAMS_FORMAT_VE8YO8UE8YE8 (0x00000028)
#define NV827E_SURFACE_SET_PARAMS_FORMAT_YO8VE8YE8UE8 (0x00000029)
#define NV827E_SURFACE_SET_PARAMS_FORMAT_A2B10G10R10 (0x000000D1)
#define NV827E_SURFACE_SET_PARAMS_FORMAT_A8R8G8B8 (0x000000CF)
#define NV827E_SURFACE_SET_PARAMS_FORMAT_A1R5G5B5 (0x000000E9)
#define NV827E_SURFACE_SET_PARAMS_COLOR_SPACE 1:0
#define NV827E_SURFACE_SET_PARAMS_COLOR_SPACE_RGB (0x00000000)
#define NV827E_SURFACE_SET_PARAMS_COLOR_SPACE_YUV_601 (0x00000001)
#define NV827E_SURFACE_SET_PARAMS_COLOR_SPACE_YUV_709 (0x00000002)
#define NV827E_SURFACE_SET_PARAMS_RESERVED0 22:16
#define NV827E_SURFACE_SET_PARAMS_RESERVED1 24:24
#ifdef __cplusplus
}; /* extern "C" */
#endif
#endif // _cl827e_h
| 9,033 |
560 | <reponame>Jan-Shing/facebooc
#include <signal.h>
#include <sqlite3.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "bs.h"
#include "kv.h"
#include "server.h"
#include "template.h"
#include "models/account.h"
#include "models/connection.h"
#include "models/like.h"
#include "models/post.h"
#include "models/session.h"
Server *server = NULL;
sqlite3 *DB = NULL;
static void sig(int signum)
{
if (server) serverDel(server);
if (DB) sqlite3_close(DB);
fprintf(stdout, "\n[%d] Bye!\n", signum);
exit(0);
}
static void createDB(const char *e)
{
char *err;
if (sqlite3_exec(DB, e, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "error: initDB: %s\n", err);
sqlite3_free(err);
exit(1);
}
}
static void initDB()
{
if (sqlite3_open("db.sqlite3", &DB)) {
fprintf(stderr, "error: unable to open DB: %s\n", sqlite3_errmsg(DB));
exit(1);
}
createDB("CREATE TABLE IF NOT EXISTS accounts ("
" id INTEGER PRIMARY KEY ASC"
", createdAt INTEGER"
", name TEXT"
", username TEXT"
", email TEXT UNIQUE"
", password TEXT"
")");
createDB("CREATE TABLE IF NOT EXISTS sessions ("
" id INTEGER PRIMARY KEY ASC"
", createdAt INTEGER"
", account INTEGER"
", session TEXT"
")");
createDB("CREATE TABLE IF NOT EXISTS connections ("
" id INTEGER PRIMARY KEY ASC"
", createdAt INTEGER"
", account1 INTEGER"
", account2 INTEGER"
")");
createDB("CREATE TABLE IF NOT EXISTS posts ("
" id INTEGER PRIMARY KEY ASC"
", createdAt INTEGER"
", author INTEGER"
", body TEXT"
")");
createDB("CREATE TABLE IF NOT EXISTS likes ("
" id INTEGER PRIMARY KEY ASC"
", createdAt INTEGER"
", account INTEGER"
", author INTEGER"
", post INTEGER"
")");
}
static Response *session(Request *);
static Response *home(Request *);
static Response *dashboard(Request *);
static Response *profile(Request *);
static Response *post(Request *);
static Response *like(Request *);
static Response *unlike(Request *);
static Response *connect(Request *);
static Response *search(Request *);
static Response *login(Request *);
static Response *logout(Request *);
static Response *signup(Request *);
static Response *about(Request *);
static Response *notFound(Request *);
int main(int argc, char *argv[])
{
if (signal(SIGINT, sig) == SIG_ERR ||
signal(SIGTERM, sig) == SIG_ERR) {
fprintf(stderr, "error: failed to bind signal handler\n");
return 1;
}
srand(time(NULL));
initDB();
uint16_t server_port = 8080;
if (argc > 1) {
if (sscanf(argv[1], "%u", &server_port) == 0 || server_port > 65535) {
fprintf(stderr, "error: invalid command line argument, using default port 8080.\n");
server_port = 8080;
}
}
Server *server = serverNew(server_port);
serverAddHandler(server, notFound);
serverAddStaticHandler(server);
serverAddHandler(server, about);
serverAddHandler(server, signup);
serverAddHandler(server, logout);
serverAddHandler(server, login);
serverAddHandler(server, search);
serverAddHandler(server, connect);
serverAddHandler(server, like);
serverAddHandler(server, unlike);
serverAddHandler(server, post);
serverAddHandler(server, profile);
serverAddHandler(server, dashboard);
serverAddHandler(server, home);
serverAddHandler(server, session);
serverServe(server);
return 0;
}
/* handlers */
#define invalid(k, v) { \
templateSet(template, k, v); \
valid = false; \
}
static Response *session(Request *req)
{
char *sid = kvFindList(req->cookies, "sid");
if (sid)
req->account = accountGetBySId(DB, sid);
return NULL;
}
static Response *home(Request *req)
{
EXACT_ROUTE(req, "/");
if (req->account)
return responseNewRedirect("/dashboard/");
Response *response = responseNew();
Template *template = templateNew("templates/index.html");
responseSetStatus(response, OK);
templateSet(template, "active", "home");
templateSet(template, "subtitle", "Home");
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
static Response *dashboard(Request *req)
{
EXACT_ROUTE(req, "/dashboard/");
if (!req->account)
return responseNewRedirect("/login/");
Response *response = responseNew();
Template *template = templateNew("templates/dashboard.html");
char *res = NULL;
char sbuff[128];
char *bbuff = NULL;
time_t t;
bool liked;
struct tm *info;
Account *account = NULL;
Post *post = NULL;
ListCell *postPCell = NULL;
ListCell *postCell = postGetLatestGraph(DB, req->account->id, 0);
if (postCell)
res = bsNew("<ul class=\"posts\">");
while (postCell) {
post = (Post *)postCell->value;
account = accountGetById(DB, post->authorId);
liked = likeLiked(DB, req->account->id, post->id);
bbuff = bsNewLen("", strlen(post->body) + 256);
sprintf(bbuff,
"<li class=\"post-item\">"
"<div class=\"post-author\">%s</div>"
"<div class=\"post-content\">"
"%s"
"</div>",
account->name,
post->body);
accountDel(account);
bsLCat(&res, bbuff);
if (liked) {
sprintf(sbuff, "<a class=\"btn\" href=\"/unlike/%d/\">Liked</a> - ", post->id);
bsLCat(&res, sbuff);
} else {
sprintf(sbuff, "<a class=\"btn\" href=\"/like/%d/\">Like</a> - ", post->id);
bsLCat(&res, sbuff);
}
t = post->createdAt;
info = gmtime(&t);
info->tm_hour = info->tm_hour + 8;
strftime(sbuff, 128, "%c GMT+8", info);
bsLCat(&res, sbuff);
bsLCat(&res, "</li>");
bsDel(bbuff);
postDel(post);
postPCell = postCell;
postCell = postCell->next;
free(postPCell);
}
if (res) {
bsLCat(&res, "</ul>");
templateSet(template, "graph", res);
bsDel(res);
} else {
templateSet(template, "graph",
"<ul class=\"posts\"><div class=\"not-found\">Nothing here.</div></ul>");
}
templateSet(template, "active", "dashboard");
templateSet(template, "loggedIn", "t");
templateSet(template, "subtitle", "Dashboard");
templateSet(template, "accountName", req->account->name);
responseSetStatus(response, OK);
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
static Response *profile(Request *req)
{
ROUTE(req, "/profile/");
if (!req->account) return NULL;
int id = -1;
int idStart = strchr(req->uri + 1, '/') + 1 - req->uri;
char *idStr = bsSubstr(req->uri, idStart, -1);
sscanf(idStr, "%d", &id);
Account *account = accountGetById(DB, id);
if (!account) return NULL;
if (account->id == req->account->id)
return responseNewRedirect("/dashboard/");
Response *response = responseNew();
Template *template = templateNew("templates/profile.html");
Connection *connection = connectionGetByAccountIds(DB,
req->account->id,
account->id);
char connectStr[512];
if (connection) {
sprintf(connectStr, "You and %s are connected!", account->name);
} else {
sprintf(connectStr,
"You and %s are not connected."
" <a href=\"/connect/%d/\">Click here</a> to connect!",
account->name,
account->id);
}
char *res = NULL;
char sbuff[128];
char *bbuff = NULL;
time_t t;
bool liked;
Post *post = NULL;
ListCell *postPCell = NULL;
ListCell *postCell = postGetLatest(DB, account->id, 0);
if (postCell)
res = bsNew("<ul class=\"posts\">");
while (postCell) {
post = (Post *)postCell->value;
liked = likeLiked(DB, req->account->id, post->id);
bbuff = bsNewLen("", strlen(post->body) + 256);
sprintf(bbuff, "<li class=\"post-item\"><div class=\"post-author\">%s</div>", post->body);
bsLCat(&res, bbuff);
if (liked) {
bsLCat(&res, "Liked - ");
} else {
sprintf(sbuff, "<a class=\"btn\" href=\"/like/%d/\">Like</a> - ", post->id);
bsLCat(&res, sbuff);
}
t = post->createdAt;
strftime(sbuff, 128, "%c GMT", gmtime(&t));
bsLCat(&res, sbuff);
bsLCat(&res, "</li>");
bsDel(bbuff);
postDel(post);
postPCell = postCell;
postCell = postCell->next;
free(postPCell);
}
if (res) {
bsLCat(&res, "</ul>");
templateSet(template, "profilePosts", res);
bsDel(res);
} else {
templateSet(template, "profilePosts",
"<h4 class=\"not-found\">This person has not posted "
"anything yet!</h4>");
}
templateSet(template, "active", "profile");
templateSet(template, "loggedIn", "t");
templateSet(template, "subtitle", account->name);
templateSet(template, "profileId", idStr);
templateSet(template, "profileName", account->name);
templateSet(template, "profileEmail", account->email);
templateSet(template, "profileConnect", connectStr);
templateSet(template, "accountName", req->account->name);
responseSetStatus(response, OK);
responseSetBody(response, templateRender(template));
connectionDel(connection);
accountDel(account);
bsDel(idStr);
templateDel(template);
return response;
}
static Response *post(Request *req)
{
EXACT_ROUTE(req, "/post/");
if (req->method != POST) return NULL;
char *postStr = kvFindList(req->postBody, "post");
if (bsGetLen(postStr) == 0)
return responseNewRedirect("/dashboard/");
else if (bsGetLen(postStr) < MAX_BODY_LEN)
postDel(postCreate(DB, req->account->id, postStr));
return responseNewRedirect("/dashboard/");
}
static Response *unlike(Request *req)
{
ROUTE(req, "/unlike/");
if (!req->account) return NULL;
int id = -1;
int idStart = strchr(req->uri + 1, '/') + 1 - req->uri;
char *idStr = bsSubstr(req->uri, idStart, -1);
sscanf(idStr, "%d", &id);
Post *post = postGetById(DB, id);
if (!post) goto fail;
likeDel(likeDelete(DB, req->account->id, post->authorId, post->id));
if (kvFindList(req->queryString, "r")) {
char sbuff[1024];
sprintf(sbuff, "/profile/%d/", post->authorId);
bsDel(idStr);
return responseNewRedirect(sbuff);
}
fail:
bsDel(idStr);
return responseNewRedirect("/dashboard/");
}
static Response *like(Request *req)
{
ROUTE(req, "/like/");
if (!req->account) return NULL;
int id = -1;
int idStart = strchr(req->uri + 1, '/') + 1 - req->uri;
char *idStr = bsSubstr(req->uri, idStart, -1);
sscanf(idStr, "%d", &id);
Post *post = postGetById(DB, id);
if (!post) goto fail;
likeDel(likeCreate(DB, req->account->id, post->authorId, post->id));
if (kvFindList(req->queryString, "r")) {
char sbuff[1024];
sprintf(sbuff, "/profile/%d/", post->authorId);
bsDel(idStr);
return responseNewRedirect(sbuff);
}
fail:
bsDel(idStr);
return responseNewRedirect("/dashboard/");
}
static Response *connect(Request *req)
{
ROUTE(req, "/connect/");
if (!req->account) return NULL;
int id = -1;
int idStart = strchr(req->uri + 1, '/') + 1 - req->uri;
char *idStr = bsSubstr(req->uri, idStart, -1);
sscanf(idStr, "%d", &id);
Account *account = accountGetById(DB, id);
if (!account) goto fail;
connectionDel(connectionCreate(DB, req->account->id, account->id));
char sbuff[1024];
sprintf(sbuff, "/profile/%d/", account->id);
bsDel(idStr);
return responseNewRedirect(sbuff);
fail:
bsDel(idStr);
return responseNewRedirect("/dashboard/");
}
static Response *search(Request *req)
{
EXACT_ROUTE(req, "/search/");
if (!req->account)
return responseNewRedirect("/login/");
char *query = kvFindList(req->queryString, "q");
if (!query) return NULL;
char *res = NULL;
char sbuff[1024];
Account *account = NULL;
ListCell *accountPCell = NULL;
ListCell *accountCell = accountSearch(DB, query, 0);
if (accountCell)
res = bsNew("<ul class=\"search-results\">");
while (accountCell) {
account = (Account *)accountCell->value;
sprintf(sbuff,
"<li><a href=\"/profile/%d/\">%s</a> (<span>%s</span>)</li>\n",
account->id, account->name, account->email);
bsLCat(&res, sbuff);
accountDel(account);
accountPCell = accountCell;
accountCell = accountCell->next;
free(accountPCell);
}
if (res)
bsLCat(&res, "</ul>");
Response *response = responseNew();
Template *template = templateNew("templates/search.html");
responseSetStatus(response, OK);
if (!res) {
templateSet(template, "results",
"<h4 class=\"not-found\">There were no results "
"for your query.</h4>");
} else {
templateSet(template, "results", res);
bsDel(res);
}
templateSet(template, "searchQuery", query);
templateSet(template, "active", "search");
templateSet(template, "loggedIn", "t");
templateSet(template, "subtitle", "Search");
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
static Response *login(Request *req)
{
EXACT_ROUTE(req, "/login/");
if (req->account)
return responseNewRedirect("/dashboard/");
Response *response = responseNew();
Template *template = templateNew("templates/login.html");
responseSetStatus(response, OK);
templateSet(template, "active", "login");
templateSet(template, "subtitle", "Login");
if (req->method == POST) {
bool valid = true;
char *username = kvFindList(req->postBody, "username");
char *password = kvFindList(req->postBody, "password");
if (!username) {
invalid("usernameError", "Username missing!");
} else {
templateSet(template, "formUsername", username);
}
if (!password) {
invalid("passwordError", "Password missing!");
}
if (valid) {
Session *session = sessionCreate(DB, username, password);
if (session) {
responseSetStatus(response, FOUND);
responseAddCookie(response, "sid", session->sessionId,
NULL, NULL, 3600 * 24 * 30);
responseAddHeader(response, "Location", "/dashboard/");
templateDel(template);
sessionDel(session);
return response;
} else {
invalid("usernameError", "Invalid username or password.");
}
}
}
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
static Response *logout(Request *req)
{
EXACT_ROUTE(req, "/logout/");
if (!req->account)
return responseNewRedirect("/");
Response *response = responseNewRedirect("/");
responseAddCookie(response, "sid", "", NULL, NULL, -1);
return response;
}
static Response *signup(Request *req)
{
EXACT_ROUTE(req, "/signup/");
if (req->account)
return responseNewRedirect("/dashboard/");
Response *response = responseNew();
Template *template = templateNew("templates/signup.html");
templateSet(template, "active", "signup");
templateSet(template, "subtitle", "Sign Up");
responseSetStatus(response, OK);
if (req->method == POST) {
bool valid = true;
char *name = kvFindList(req->postBody, "name");
char *email = kvFindList(req->postBody, "email");
char *username = kvFindList(req->postBody, "username");
char *password = kvFindList(req->postBody, "password");
char *confirmPassword = kvFindList(req->postBody, "confirm-password");
if (!name) {
invalid("nameError", "You must enter your name!");
} else if (strlen(name) < 5 || strlen(name) > 50) {
invalid("nameError",
"Your name must be between 5 and 50 characters long.");
} else {
templateSet(template, "formName", name);
}
if (!email) {
invalid("emailError", "You must enter an email!");
} else if (strchr(email, '@') == NULL) {
invalid("emailError", "Invalid email.");
} else if (strlen(email) < 3 || strlen(email) > 50) {
invalid("emailError",
"Your email must be between 3 and 50 characters long.");
} else if (!accountCheckEmail(DB, email)) {
invalid("emailError", "This email is taken.");
} else {
templateSet(template, "formEmail", email);
}
if (!username) {
invalid("usernameError", "You must enter a username!");
} else if (strlen(username) < 3 || strlen(username) > 50) {
invalid("usernameError",
"Your username must be between 3 and 50 characters long.");
} else if (!accountCheckUsername(DB, username)) {
invalid("usernameError", "This username is taken.");
} else {
templateSet(template, "formUsername", username);
}
if (!password) {
invalid("passwordError", "You must enter a password!");
} else if (strlen(password) < 8) {
invalid("passwordError",
"Your password must be at least 8 characters long!");
}
if (!confirmPassword) {
invalid("confirmPasswordError", "You must confirm your password.");
} else if (strcmp(password, confirmPassword) != 0) {
invalid("confirmPasswordError",
"The two passwords must be the same.");
}
if (valid) {
Account *account = accountCreate(DB, name,
email, username, password);
if (account) {
responseSetStatus(response, FOUND);
responseAddHeader(response, "Location", "/login/");
templateDel(template);
accountDel(account);
return response;
} else {
invalid("nameError",
"Unexpected error. Please try again later.");
}
}
}
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
static Response *about(Request *req)
{
EXACT_ROUTE(req, "/about/");
Response *response = responseNew();
Template *template = templateNew("templates/about.html");
templateSet(template, "active", "about");
templateSet(template, "loggedIn", req->account ? "t" : "");
templateSet(template, "subtitle", "About");
responseSetStatus(response, OK);
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
static Response *notFound(Request *req)
{
Response *response = responseNew();
Template *template = templateNew("templates/404.html");
templateSet(template, "loggedIn", req->account ? "t" : "");
templateSet(template, "subtitle", "404 Not Found");
responseSetStatus(response, NOT_FOUND);
responseSetBody(response, templateRender(template));
templateDel(template);
return response;
}
| 8,912 |
572 | import time, pytest, inspect
from utils import *
PORT_FROM_CONFIG_FILE = 12345
PORT_FROM_COMMAND_LINE = 12346
def test_running_two_braves_on_different_ports(run_brave, create_config_file):
launch_brave_setting_port_in_config_file(run_brave, create_config_file)
launch_brave_setting_port_in_environment_variable(run_brave)
for port in [PORT_FROM_CONFIG_FILE, PORT_FROM_COMMAND_LINE]:
response = api_get('/api/all', port=port)
assert response.status_code == 200
time.sleep(1)
def launch_brave_setting_port_in_config_file(run_brave, create_config_file):
config = {'api_port': PORT_FROM_CONFIG_FILE}
config_file = create_config_file(config)
run_brave(config_file.name)
check_brave_is_running()
def launch_brave_setting_port_in_environment_variable(run_brave):
run_brave(port=PORT_FROM_COMMAND_LINE)
check_brave_is_running()
| 358 |
1,355 | // Copyright (c) 2018 <NAME>
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <jet/cell_centered_scalar_grid3.h>
#include <jet/grid_forward_euler_diffusion_solver3.h>
#include <gtest/gtest.h>
using namespace jet;
TEST(GridForwardEulerDiffusionSolver3, Solve) {
CellCenteredScalarGrid3 src(3, 3, 3, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0);
CellCenteredScalarGrid3 dst(3, 3, 3, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0);
src(1, 1, 1) = 1.0;
GridForwardEulerDiffusionSolver3 diffusionSolver;
diffusionSolver.solve(src, 1.0 / 12.0, 1.0, &dst);
EXPECT_DOUBLE_EQ(1.0/12.0, dst(1, 1, 0));
EXPECT_DOUBLE_EQ(1.0/12.0, dst(0, 1, 1));
EXPECT_DOUBLE_EQ(1.0/12.0, dst(1, 0, 1));
EXPECT_DOUBLE_EQ(1.0/12.0, dst(2, 1, 1));
EXPECT_DOUBLE_EQ(1.0/12.0, dst(1, 2, 1));
EXPECT_DOUBLE_EQ(1.0/12.0, dst(1, 1, 2));
EXPECT_DOUBLE_EQ(1.0/2.0, dst(1, 1, 1));
}
| 493 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-f684-4cqg-v8mf",
"modified": "2022-05-13T01:35:26Z",
"published": "2022-05-13T01:35:26Z",
"aliases": [
"CVE-2018-0305"
],
"details": "A vulnerability in the Cisco Fabric Services component of Cisco FXOS Software and Cisco NX-OS Software could allow an unauthenticated, remote attacker to cause a denial of service (DoS) condition on the affected device. The vulnerability exists because the affected software insufficiently validates Cisco Fabric Services packets. An attacker could exploit this vulnerability by sending a crafted Cisco Fabric Services packet to an affected device. A successful exploit could allow the attacker to force a NULL pointer dereference and cause a DoS condition. This vulnerability affects the following if configured to use Cisco Fabric Services: Firepower 4100 Series Next-Generation Firewalls, Firepower 9300 Security Appliance, MDS 9000 Series Multilayer Switches, Nexus 2000 Series Fabric Extenders, Nexus 3000 Series Switches, Nexus 3500 Platform Switches, Nexus 5500 Platform Switches, Nexus 5600 Platform Switches, Nexus 6000 Series Switches, Nexus 7000 Series Switches, Nexus 7700 Series Switches, Nexus 9000 Series Switches in standalone NX-OS mode, Nexus 9500 R-Series Line Cards and Fabric Modules, UCS 6100 Series Fabric Interconnects, UCS 6200 Series Fabric Interconnects, UCS 6300 Series Fabric Interconnects. Cisco Bug IDs: CSCvd69966, CSCve02435, CSCve04859, CSCve41590, CSCve41593, CSCve41601.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-0305"
},
{
"type": "WEB",
"url": "https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20180620-fx-os-fabric-dos"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id/1041169"
}
],
"database_specific": {
"cwe_ids": [
"CWE-476"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 739 |
435 | <filename>northbaypython-2017/videos/stumbling-through-django-and-how-not-to.json
{
"description": "If you\u2019re a beginner about to embark on a new Django project adventure, this talk is for you.\n\nWhen I started my first Django project, I took the \u201cSure, I think I can figure that out\u201d approach, which is fun! And also dangerous. But exciting! And also horrible because I caused myself a lot of trouble and barfed on my keyboard. (Metaphorically.) Oops.\n\nMy hope for this talk is to pass along lessons I learned the hard way, and save the world. Or at least prevent some frustration. :)\n\nWe\u2019ll talk about:\n\n- version control\n- structuring your project\n- and how to handle top secret stuff.\n\nWe\u2019ll also talk about:\n\n- throwing house parties without causing anaphylaxis\n- pregnant daddy seahorses\n- velociraptors\n- and friends.\n\nI promise all of that is related to Django.",
"language": "eng",
"recorded": "2017-12-02",
"related_urls": [
{
"label": "Talk schedule",
"url": "https://2017.northbaypython.org/schedule/presentation/16/"
}
],
"speakers": [
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/bxCp3Ciwjm0/hqdefault.jpg",
"title": "Stumbling Through Django and How Not To",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=bxCp3Ciwjm0"
}
]
}
| 480 |
351 | package org.antlr.intellij.plugin.psi;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.antlr.intellij.plugin.ANTLRv4TokenTypes;
import org.antlr.intellij.plugin.parser.ANTLRv4Lexer;
import org.antlr.intellij.plugin.resolve.ImportResolver;
import org.antlr.intellij.plugin.resolve.TokenVocabResolver;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* A reference to a grammar element (parser rule, lexer rule or lexical mode).
*/
public class GrammarElementRef extends PsiReferenceBase<GrammarElementRefNode> {
private final String ruleName;
public GrammarElementRef(GrammarElementRefNode idNode, String ruleName) {
super(idNode, new TextRange(0, ruleName.length()));
this.ruleName = ruleName;
}
/**
* Using for completion. Returns list of rules and tokens; the prefix
* of current element is used as filter by IDEA later.
*/
@NotNull
@Override
public Object[] getVariants() {
RulesNode rules = PsiTreeUtil.getContextOfType(myElement, RulesNode.class);
// find all rule defs (token, parser)
Collection<? extends RuleSpecNode> ruleSpecNodes =
PsiTreeUtil.findChildrenOfAnyType(rules, ParserRuleSpecNode.class, LexerRuleSpecNode.class);
return ruleSpecNodes.toArray();
}
/**
* Called upon jump to def for this rule ref
*/
@Nullable
@Override
public PsiElement resolve() {
PsiFile tokenVocabFile = TokenVocabResolver.resolveTokenVocabFile(getElement());
if ( tokenVocabFile!=null ) {
return tokenVocabFile;
}
PsiFile importedFile = ImportResolver.resolveImportedFile(getElement());
if ( importedFile!=null ) {
return importedFile;
}
GrammarSpecNode grammar = PsiTreeUtil.getContextOfType(getElement(), GrammarSpecNode.class);
PsiElement specNode = MyPsiUtils.findSpecNode(grammar, ruleName);
if ( specNode!=null ) {
return specNode;
}
// Look for a rule defined in an imported grammar
specNode = ImportResolver.resolveInImportedFiles(getElement().getContainingFile(), ruleName);
if ( specNode!=null ) {
return specNode;
}
// Look for a lexer rule in the tokenVocab file if it exists
if ( getElement() instanceof LexerRuleRefNode ) {
return TokenVocabResolver.resolveInTokenVocab(getElement(), ruleName);
}
return null;
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
Project project = getElement().getProject();
myElement.replace(MyPsiUtils.createLeafFromText(project,
myElement.getContext(),
newElementName,
ANTLRv4TokenTypes.TOKEN_ELEMENT_TYPES.get(ANTLRv4Lexer.TOKEN_REF)));
return myElement;
}
}
| 1,014 |
634 | /****************************************************************
* 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.james.transport.mailets;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.james.util.MimeMessageUtil;
import org.apache.mailet.Experimental;
import org.apache.mailet.Mail;
import org.apache.mailet.base.GenericMailet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
/**
* Serialise the email and pass it to an HTTP call
*
* Sample configuration:
*
* <mailet match="All" class="SerialiseToHTTP">
* <name>URL</name> <value>url where serialised message will be posted</value>
* <name>ParameterKey</name> <value>An arbitrary parameter be added to the post</value>
* <name>ParameterValue</name> <value>A value for the arbitrary parameter</value>
* <name>MessageKeyName</name> <value>Field name for the serialised message</value>
* <name>passThrough</name> <value>true or false</value>
* </mailet>
*
*/
@Experimental
public class SerialiseToHTTP extends GenericMailet {
private static final Logger LOGGER = LoggerFactory.getLogger(SerialiseToHTTP.class);
/**
* The name of the header to be added.
*/
private String url;
private String parameterKey = null;
private String parameterValue = null;
private String messageKeyName = "message";
private boolean passThrough = true;
@Override
public void init() throws MessagingException {
passThrough = (getInitParameter("passThrough", "true").compareToIgnoreCase("true") == 0);
String targetUrl = getInitParameter("url");
parameterKey = getInitParameter("parameterKey");
parameterValue = getInitParameter("parameterValue");
String m = getInitParameter("MessageKeyName");
if (m != null) {
messageKeyName = m;
}
// Check if needed config values are used
if (targetUrl == null || targetUrl.equals("")) {
throw new MessagingException(
"Please configure a targetUrl (\"url\")");
} else {
try {
// targetUrl = targetUrl + ( targetUrl.contains("?") ? "&" :
// "?") + parameterKey + "=" + parameterValue;
url = new URL(targetUrl).toExternalForm();
} catch (MalformedURLException e) {
throw new MessagingException(
"Unable to contruct URL object from url");
}
}
// record the result
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("I will attempt to deliver serialised messages to "
+ targetUrl
+ " as "
+ messageKeyName
+ ". "
+ (parameterKey == null || parameterKey.length() < 2 ? "I will not add any fields to the post. " : "I will prepend: " + parameterKey + "=" + parameterValue + ". ")
+ (passThrough ? "Messages will pass through."
: "Messages will be ghosted."));
}
}
/**
* Takes the message, serialises it and sends it to the URL
*
* @param mail
* the mail being processed
*
*/
@Override
public void service(Mail mail) {
MimeMessage message;
try {
message = mail.getMessage();
} catch (MessagingException me) {
LOGGER.error("Messaging exception", me);
addHeader(mail, false, me.getMessage());
return;
}
String messageAsString;
try {
messageAsString = MimeMessageUtil.asString(message);
} catch (Exception e) {
LOGGER.error("Message to string exception", e);
addHeader(mail, false, e.getMessage());
return;
}
String result = httpPost(getNameValuePairs(messageAsString));
if (passThrough) {
addHeader(mail, Strings.isNullOrEmpty(result), result);
} else {
mail.setState(Mail.GHOST);
}
}
private void addHeader(Mail mail, boolean success, String errorMessage) {
try {
MimeMessage message = mail.getMessage();
message.setHeader("X-toHTTP", (success ? "Succeeded" : "Failed"));
if (!success && errorMessage != null && errorMessage.length() > 0) {
message.setHeader("X-toHTTPFailure", errorMessage);
}
message.saveChanges();
} catch (MessagingException me) {
LOGGER.error("Messaging exception", me);
}
}
private String httpPost(NameValuePair[] data) {
RequestBuilder requestBuilder = RequestBuilder.post(url);
for (NameValuePair parameter : data) {
requestBuilder.addParameter(parameter);
LOGGER.debug("{}::{}", parameter.getName(), parameter.getValue());
}
try (CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse clientResponse = client.execute(requestBuilder.build())) {
if (clientResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
LOGGER.debug("POST failed: {}", clientResponse.getStatusLine());
return clientResponse.getStatusLine().toString();
}
return null;
} catch (ClientProtocolException e) {
LOGGER.error("Fatal protocol violation: ", e);
return "Fatal protocol violation: " + e.getMessage();
} catch (IOException e) {
LOGGER.debug("Fatal transport error: ", e);
return "Fatal transport error: " + e.getMessage();
}
}
private NameValuePair[] getNameValuePairs(String message) {
int l = 1;
if (parameterKey != null && parameterKey.length() > 0) {
l = 2;
}
NameValuePair[] data = new BasicNameValuePair[l];
data[0] = new BasicNameValuePair(messageKeyName, message);
if (l == 2) {
data[1] = new BasicNameValuePair(parameterKey, parameterValue);
}
return data;
}
@Override
public String getMailetInfo() {
return "HTTP POST serialised message";
}
}
| 3,244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.