text
stringlengths 2
1.04M
| meta
dict |
---|---|
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class VmfsDatastoreSpec extends DynamicData {
public String diskUuid;
public String getDiskUuid() {
return this.diskUuid;
}
public void setDiskUuid(String diskUuid) {
this.diskUuid=diskUuid;
}
} | {
"content_hash": "c927e0646f76b9fbb0f70be1292127f2",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 52,
"avg_line_length": 16.523809523809526,
"alnum_prop": 0.7089337175792507,
"repo_name": "patrickianwilson/vijava-contrib",
"id": "92b3b87bc0edccc9fe5aa8cbc4b68ed48d00c49f",
"size": "1998",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/vmware/vim25/VmfsDatastoreSpec.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "7967457"
}
],
"symlink_target": ""
} |
# Node.js Core Test Common Modules
This directory contains modules used to test the Node.js implementation.
## Table of Contents
* [ArrayStream module](#arraystream-module)
* [Benchmark module](#benchmark-module)
* [Common module API](#common-module-api)
* [Countdown module](#countdown-module)
* [CPU Profiler module](#cpu-profiler-module)
* [DNS module](#dns-module)
* [Duplex pair helper](#duplex-pair-helper)
* [Environment variables](#environment-variables)
* [Fixtures module](#fixtures-module)
* [Heap dump checker module](#heap-dump-checker-module)
* [hijackstdio module](#hijackstdio-module)
* [HTTP2 module](#http2-module)
* [Internet module](#internet-module)
* [ongc module](#ongc-module)
* [Report module](#report-module)
* [tick module](#tick-module)
* [tmpdir module](#tmpdir-module)
* [WPT module](#wpt-module)
## Benchmark Module
The `benchmark` module is used by tests to run benchmarks.
### `runBenchmark(name, args, env)`
* `name` [<string>][] Name of benchmark suite to be run.
* `args` [<Array>][] Array of environment variable key/value pairs (ex:
`n=1`) to be applied via `--set`.
* `env` [<Object>][] Environment variables to be applied during the run.
## Common Module API
The `common` module is used by tests for consistency across repeated
tasks.
### `allowGlobals(...whitelist)`
* `whitelist` [<Array>][] Array of Globals
* return [<Array>][]
Takes `whitelist` and concats that with predefined `knownGlobals`.
### `canCreateSymLink()`
* return [<boolean>][]
Checks whether the current running process can create symlinks. On Windows, this
returns `false` if the process running doesn't have privileges to create
symlinks
([SeCreateSymbolicLinkPrivilege](https://msdn.microsoft.com/en-us/library/windows/desktop/bb530716(v=vs.85).aspx)).
On non-Windows platforms, this always returns `true`.
### `createZeroFilledFile(filename)`
Creates a 10 MB file of all null characters.
### `disableCrashOnUnhandledRejection()`
Removes the `process.on('unhandledRejection')` handler that crashes the process
after a tick. The handler is useful for tests that use Promises and need to make
sure no unexpected rejections occur, because currently they result in silent
failures. However, it is useful in some rare cases to disable it, for example if
the `unhandledRejection` hook is directly used by the test.
### `enoughTestCpu`
* [<boolean>][]
Indicates if there is more than 1 CPU or that the single CPU has a speed of at
least 1 GHz.
### `enoughTestMem`
* [<boolean>][]
Indicates if there is more than 1gb of total memory.
### expectsError(validator\[, exact\])
* `validator` [<Object>][] | [<RegExp>][] | [<Function>][] |
[<Error>][] The validator behaves identical to
`assert.throws(fn, validator)`.
* `exact` [<number>][] default = 1
* return [<Function>][] A callback function that expects an error.
A function suitable as callback to validate callback based errors. The error is
validated using `assert.throws(() => { throw error; }, validator)`. If the
returned function has not been called exactly `exact` number of times when the
test is complete, then the test will fail.
### `expectWarning(name[, expected[, code]])`
* `name` [<string>][] | [<Object>][]
* `expected` [<string>][] | [<Array>][] | [<Object>][]
* `code` [<string>][]
Tests whether `name`, `expected`, and `code` are part of a raised warning.
The code is required in case the name is set to `'DeprecationWarning'`.
Examples:
```js
const { expectWarning } = require('../common');
expectWarning('Warning', 'Foobar is really bad');
expectWarning('DeprecationWarning', 'Foobar is deprecated', 'DEP0XXX');
expectWarning('DeprecationWarning', [
'Foobar is deprecated', 'DEP0XXX'
]);
expectWarning('DeprecationWarning', [
['Foobar is deprecated', 'DEP0XXX'],
['Baz is also deprecated', 'DEP0XX2']
]);
expectWarning('DeprecationWarning', {
DEP0XXX: 'Foobar is deprecated',
DEP0XX2: 'Baz is also deprecated'
});
expectWarning({
DeprecationWarning: {
DEP0XXX: 'Foobar is deprecated',
DEP0XX1: 'Baz is also deprecated'
},
Warning: [
['Multiple array entries are fine', 'SpecialWarningCode'],
['No code is also fine']
],
SingleEntry: ['This will also work', 'WarningCode'],
SingleString: 'Single string entries without code will also work'
});
```
### `getArrayBufferViews(buf)`
* `buf` [<Buffer>][]
* return [<ArrayBufferView>][]\[\]
Returns an instance of all possible `ArrayBufferView`s of the provided Buffer.
### `getBufferSources(buf)`
* `buf` [<Buffer>][]
* return [<BufferSource>][]\[\]
Returns an instance of all possible `BufferSource`s of the provided Buffer,
consisting of all `ArrayBufferView` and an `ArrayBuffer`.
### `getCallSite(func)`
* `func` [<Function>][]
* return [<string>][]
Returns the file name and line number for the provided Function.
### `getTTYfd()`
Attempts to get a valid TTY file descriptor. Returns `-1` if it fails.
The TTY file descriptor is assumed to be capable of being writable.
### `hasCrypto`
* [<boolean>][]
Indicates whether OpenSSL is available.
### `hasFipsCrypto`
* [<boolean>][]
Indicates that Node.js has been linked with a FIPS compatible OpenSSL library,
and that FIPS as been enabled using `--enable-fips`.
To only detect if the OpenSSL library is FIPS compatible, regardless if it has
been enabled or not, then `process.config.variables.openssl_is_fips` can be
used to determine that situation.
### `hasIntl`
* [<boolean>][]
Indicates if [internationalization][] is supported.
### `hasIPv6`
* [<boolean>][]
Indicates whether `IPv6` is supported on this platform.
### `hasMultiLocalhost`
* [<boolean>][]
Indicates if there are multiple localhosts available.
### `inFreeBSDJail`
* [<boolean>][]
Checks whether free BSD Jail is true or false.
### `isAIX`
* [<boolean>][]
Platform check for Advanced Interactive eXecutive (AIX).
### `isAlive(pid)`
* `pid` [<number>][]
* return [<boolean>][]
Attempts to 'kill' `pid`
### `isDumbTerminal`
* [<boolean>][]
### `isFreeBSD`
* [<boolean>][]
Platform check for Free BSD.
### `isIBMi`
* [<boolean>][]
Platform check for IBMi.
### `isLinux`
* [<boolean>][]
Platform check for Linux.
### `isLinuxPPCBE`
* [<boolean>][]
Platform check for Linux on PowerPC.
### `isOSX`
* [<boolean>][]
Platform check for macOS.
### `isSunOS`
* [<boolean>][]
Platform check for SunOS.
### `isWindows`
* [<boolean>][]
Platform check for Windows.
### `localhostIPv4`
* [<string>][]
IP of `localhost`.
### `localIPv6Hosts`
* [<Array>][]
Array of IPV6 representations for `localhost`.
### `mustCall([fn][, exact])`
* `fn` [<Function>][] default = () => {}
* `exact` [<number>][] default = 1
* return [<Function>][]
Returns a function that calls `fn`. If the returned function has not been called
exactly `exact` number of times when the test is complete, then the test will
fail.
If `fn` is not provided, an empty function will be used.
### `mustCallAtLeast([fn][, minimum])`
* `fn` [<Function>][] default = () => {}
* `minimum` [<number>][] default = 1
* return [<Function>][]
Returns a function that calls `fn`. If the returned function has not been called
at least `minimum` number of times when the test is complete, then the test will
fail.
If `fn` is not provided, an empty function will be used.
### `mustNotCall([msg])`
* `msg` [<string>][] default = 'function should not have been called'
* return [<Function>][]
Returns a function that triggers an `AssertionError` if it is invoked. `msg` is
used as the error message for the `AssertionError`.
### `nodeProcessAborted(exitCode, signal)`
* `exitCode` [<number>][]
* `signal` [<string>][]
* return [<boolean>][]
Returns `true` if the exit code `exitCode` and/or signal name `signal` represent
the exit code and/or signal name of a node process that aborted, `false`
otherwise.
### `opensslCli`
* [<boolean>][]
Indicates whether 'opensslCli' is supported.
### `platformTimeout(ms)`
* `ms` [<number>][] | [<bigint>][]
* return [<number>][] | [<bigint>][]
Returns a timeout value based on detected conditions. For example, a debug build
may need extra time so the returned value will be larger than on a release
build.
### `PIPE`
* [<string>][]
Path to the test socket.
### `PORT`
* [<number>][]
A port number for tests to use if one is needed.
### `printSkipMessage(msg)`
* `msg` [<string>][]
Logs '1..0 # Skipped: ' + `msg`
### `pwdCommand`
* [<array>][] First two argument for the `spawn`/`exec` functions.
Platform normalized `pwd` command options. Usage example:
```js
const common = require('../common');
const { spawn } = require('child_process');
spawn(...common.pwdCommand, { stdio: ['pipe'] });
```
### `rootDir`
* [<string>][]
Path to the 'root' directory. either `/` or `c:\\` (windows)
### `runWithInvalidFD(func)`
* `func` [<Function>][]
Runs `func` with an invalid file descriptor that is an unsigned integer and
can be used to trigger `EBADF` as the first argument. If no such file
descriptor could be generated, a skip message will be printed and the `func`
will not be run.
### `skip(msg)`
* `msg` [<string>][]
Logs '1..0 # Skipped: ' + `msg` and exits with exit code `0`.
### `skipIfDumbTerminal()`
Skip the rest of the tests if the current terminal is a dumb terminal
### `skipIfEslintMissing()`
Skip the rest of the tests in the current file when `ESLint` is not available
at `tools/node_modules/eslint`
### `skipIfInspectorDisabled()`
Skip the rest of the tests in the current file when the Inspector
was disabled at compile time.
### `skipIf32Bits()`
Skip the rest of the tests in the current file when the Node.js executable
was compiled with a pointer size smaller than 64 bits.
### `skipIfWorker()`
Skip the rest of the tests in the current file when not running on a main
thread.
## ArrayStream Module
The `ArrayStream` module provides a simple `Stream` that pushes elements from
a given array.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
const ArrayStream = require('../common/arraystream');
const stream = new ArrayStream();
stream.run(['a', 'b', 'c']);
```
It can be used within tests as a simple mock stream.
## Countdown Module
The `Countdown` module provides a simple countdown mechanism for tests that
require a particular action to be taken after a given number of completed
tasks (for instance, shutting down an HTTP server after a specific number of
requests). The Countdown will fail the test if the remainder did not reach 0.
<!-- eslint-disable strict, node-core/require-common-first, node-core/required-modules -->
```js
const Countdown = require('../common/countdown');
function doSomething() {
console.log('.');
}
const countdown = new Countdown(2, doSomething);
countdown.dec();
countdown.dec();
```
### `new Countdown(limit, callback)`
* `limit` {number}
* `callback` {function}
Creates a new `Countdown` instance.
### `Countdown.prototype.dec()`
Decrements the `Countdown` counter.
### `Countdown.prototype.remaining`
Specifies the remaining number of times `Countdown.prototype.dec()` must be
called before the callback is invoked.
## CPU Profiler module
The `cpu-prof` module provides utilities related to CPU profiling tests.
### `env`
* Default: { ...process.env, NODE_DEBUG_NATIVE: 'INSPECTOR_PROFILER' }
Environment variables used in profiled processes.
### `getCpuProfiles(dir)`
* `dir` {string} The directory containing the CPU profile files.
* return [<string>][]
Returns an array of all `.cpuprofile` files found in `dir`.
### `getFrames(file, suffix)`
* `file` {string} Path to a `.cpuprofile` file.
* `suffix` {string} Suffix of the URL of call frames to retrieve.
* returns { frames: [<Object>][], nodes: [<Object>][] }
Returns an object containing an array of the relevant call frames and an array
of all the profile nodes.
### `kCpuProfInterval`
Sampling interval in microseconds.
### `verifyFrames(output, file, suffix)`
* `output` {string}
* `file` {string}
* `suffix` {string}
Throws an `AssertionError` if there are no call frames with the expected
`suffix` in the profiling data contained in `file`.
## `DNS` Module
The `DNS` module provides utilities related to the `dns` built-in module.
### `errorLookupMock(code, syscall)`
* `code` [<string>][] Defaults to `dns.mockedErrorCode`.
* `syscall` [<string>][] Defaults to `dns.mockedSysCall`.
* return [<Function>][]
A mock for the `lookup` option of `net.connect()` that would result in an error
with the `code` and the `syscall` specified. Returns a function that has the
same signature as `dns.lookup()`.
### `mockedErrorCode`
The default `code` of errors generated by `errorLookupMock`.
### `mockedSysCall`
The default `syscall` of errors generated by `errorLookupMock`.
### `readDomainFromPacket(buffer, offset)`
* `buffer` [<Buffer>][]
* `offset` [<number>][]
* return [<Object>][]
Reads the domain string from a packet and returns an object containing the
number of bytes read and the domain.
### `parseDNSPacket(buffer)`
* `buffer` [<Buffer>][]
* return [<Object>][]
Parses a DNS packet. Returns an object with the values of the various flags of
the packet depending on the type of packet.
### `writeIPv6(ip)`
* `ip` [<string>][]
* return [<Buffer>][]
Reads an IPv6 String and returns a Buffer containing the parts.
### `writeDomainName(domain)`
* `domain` [<string>][]
* return [<Buffer>][]
Reads a Domain String and returns a Buffer containing the domain.
### `writeDNSPacket(parsed)`
* `parsed` [<Object>][]
* return [<Buffer>][]
Takes in a parsed Object and writes its fields to a DNS packet as a Buffer
object.
## Duplex pair helper
The `common/duplexpair` module exports a single function `makeDuplexPair`,
which returns an object `{ clientSide, serverSide }` where each side is a
`Duplex` stream connected to the other side.
There is no difference between client or server side beyond their names.
## Environment variables
The behavior of the Node.js test suite can be altered using the following
environment variables.
### `NODE_COMMON_PORT`
If set, `NODE_COMMON_PORT`'s value overrides the `common.PORT` default value of
12346.
### `NODE_SKIP_FLAG_CHECK`
If set, command line arguments passed to individual tests are not validated.
### `NODE_SKIP_CRYPTO`
If set, crypto tests are skipped.
### `NODE_TEST_KNOWN_GLOBALS`
A comma-separated list of variables names that are appended to the global
variable whitelist. Alternatively, if `NODE_TEST_KNOWN_GLOBALS` is set to `'0'`,
global leak detection is disabled.
## Fixtures Module
The `common/fixtures` module provides convenience methods for working with
files in the `test/fixtures` directory.
### `fixtures.fixturesDir`
* [<string>][]
The absolute path to the `test/fixtures/` directory.
### `fixtures.path(...args)`
* `...args` [<string>][]
Returns the result of `path.join(fixtures.fixturesDir, ...args)`.
### `fixtures.readSync(args[, enc])`
* `args` [<string>][] | [<Array>][]
Returns the result of
`fs.readFileSync(path.join(fixtures.fixturesDir, ...args), 'enc')`.
### `fixtures.readKey(arg[, enc])`
* `arg` [<string>][]
Returns the result of
`fs.readFileSync(path.join(fixtures.fixturesDir, 'keys', arg), 'enc')`.
## Heap dump checker module
This provides utilities for checking the validity of heap dumps.
This requires the usage of `--expose-internals`.
### `heap.recordState()`
Create a heap dump and an embedder graph copy for inspection.
The returned object has a `validateSnapshotNodes` function similar to the
one listed below. (`heap.validateSnapshotNodes(...)` is a shortcut for
`heap.recordState().validateSnapshotNodes(...)`.)
### `heap.validateSnapshotNodes(name, expected, options)`
* `name` [<string>][] Look for this string as the name of heap dump nodes.
* `expected` [<Array>][] A list of objects, possibly with an `children`
property that points to expected other adjacent nodes.
* `options` [<Array>][]
* `loose` [<boolean>][] Do not expect an exact listing of occurrences
of nodes with name `name` in `expected`.
Create a heap dump and an embedder graph copy and validate occurrences.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
validateSnapshotNodes('TLSWRAP', [
{
children: [
{ name: 'enc_out' },
{ name: 'enc_in' },
{ name: 'TLSWrap' }
]
}
]);
```
## hijackstdio Module
The `hijackstdio` module provides utility functions for temporarily redirecting
`stdout` and `stderr` output.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
const { hijackStdout, restoreStdout } = require('../common/hijackstdio');
hijackStdout((data) => {
/* Do something with data */
restoreStdout();
});
console.log('this is sent to the hijacked listener');
```
### `hijackStderr(listener)`
* `listener` [<Function>][]: a listener with a single parameter
called `data`.
Eavesdrop to `process.stderr.write()` calls. Once `process.stderr.write()` is
called, `listener` will also be called and the `data` of `write` function will
be passed to `listener`. What's more, `process.stderr.writeTimes` is a count of
the number of calls.
### `hijackStdout(listener)`
* `listener` [<Function>][]: a listener with a single parameter
called `data`.
Eavesdrop to `process.stdout.write()` calls. Once `process.stdout.write()` is
called, `listener` will also be called and the `data` of `write` function will
be passed to `listener`. What's more, `process.stdout.writeTimes` is a count of
the number of calls.
### restoreStderr()
Restore the original `process.stderr.write()`. Used to restore `stderr` to its
original state after calling [`hijackstdio.hijackStdErr()`][].
### restoreStdout()
Restore the original `process.stdout.write()`. Used to restore `stdout` to its
original state after calling [`hijackstdio.hijackStdOut()`][].
## HTTP/2 Module
The http2.js module provides a handful of utilities for creating mock HTTP/2
frames for testing of HTTP/2 endpoints
<!-- eslint-disable no-unused-vars, node-core/require-common-first, node-core/required-modules -->
```js
const http2 = require('../common/http2');
```
### Class: Frame
The `http2.Frame` is a base class that creates a `Buffer` containing a
serialized HTTP/2 frame header.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
// length is a 24-bit unsigned integer
// type is an 8-bit unsigned integer identifying the frame type
// flags is an 8-bit unsigned integer containing the flag bits
// id is the 32-bit stream identifier, if any.
const frame = new http2.Frame(length, type, flags, id);
// Write the frame data to a socket
socket.write(frame.data);
```
The serialized `Buffer` may be retrieved using the `frame.data` property.
### Class: DataFrame extends Frame
The `http2.DataFrame` is a subclass of `http2.Frame` that serializes a `DATA`
frame.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
// id is the 32-bit stream identifier
// payload is a Buffer containing the DATA payload
// padlen is an 8-bit integer giving the number of padding bytes to include
// final is a boolean indicating whether the End-of-stream flag should be set,
// defaults to false.
const frame = new http2.DataFrame(id, payload, padlen, final);
socket.write(frame.data);
```
### Class: HeadersFrame
The `http2.HeadersFrame` is a subclass of `http2.Frame` that serializes a
`HEADERS` frame.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
// id is the 32-bit stream identifier
// payload is a Buffer containing the HEADERS payload (see either
// http2.kFakeRequestHeaders or http2.kFakeResponseHeaders).
// padlen is an 8-bit integer giving the number of padding bytes to include
// final is a boolean indicating whether the End-of-stream flag should be set,
// defaults to false.
const frame = new http2.HeadersFrame(id, payload, padlen, final);
socket.write(frame.data);
```
### Class: SettingsFrame
The `http2.SettingsFrame` is a subclass of `http2.Frame` that serializes an
empty `SETTINGS` frame.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
// ack is a boolean indicating whether or not to set the ACK flag.
const frame = new http2.SettingsFrame(ack);
socket.write(frame.data);
```
### `http2.kFakeRequestHeaders`
Set to a `Buffer` instance that contains a minimal set of serialized HTTP/2
request headers to be used as the payload of a `http2.HeadersFrame`.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
const frame = new http2.HeadersFrame(1, http2.kFakeRequestHeaders, 0, true);
socket.write(frame.data);
```
### `http2.kFakeResponseHeaders`
Set to a `Buffer` instance that contains a minimal set of serialized HTTP/2
response headers to be used as the payload a `http2.HeadersFrame`.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
const frame = new http2.HeadersFrame(1, http2.kFakeResponseHeaders, 0, true);
socket.write(frame.data);
```
### `http2.kClientMagic`
Set to a `Buffer` containing the preamble bytes an HTTP/2 client must send
upon initial establishment of a connection.
<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules -->
```js
socket.write(http2.kClientMagic);
```
## Internet Module
The `common/internet` module provides utilities for working with
internet-related tests.
### `internet.addresses`
* [<Object>][]
* `INET_HOST` [<string>][] A generic host that has registered common
DNS records, supports both IPv4 and IPv6, and provides basic HTTP/HTTPS
services
* `INET4_HOST` [<string>][] A host that provides IPv4 services
* `INET6_HOST` [<string>][] A host that provides IPv6 services
* `INET4_IP` [<string>][] An accessible IPv4 IP, defaults to the
Google Public DNS IPv4 address
* `INET6_IP` [<string>][] An accessible IPv6 IP, defaults to the
Google Public DNS IPv6 address
* `INVALID_HOST` [<string>][] An invalid host that cannot be resolved
* `MX_HOST` [<string>][] A host with MX records registered
* `SRV_HOST` [<string>][] A host with SRV records registered
* `PTR_HOST` [<string>][] A host with PTR records registered
* `NAPTR_HOST` [<string>][] A host with NAPTR records registered
* `SOA_HOST` [<string>][] A host with SOA records registered
* `CNAME_HOST` [<string>][] A host with CNAME records registered
* `NS_HOST` [<string>][] A host with NS records registered
* `TXT_HOST` [<string>][] A host with TXT records registered
* `DNS4_SERVER` [<string>][] An accessible IPv4 DNS server
* `DNS6_SERVER` [<string>][] An accessible IPv6 DNS server
A set of addresses for internet-related tests. All properties are configurable
via `NODE_TEST_*` environment variables. For example, to configure
`internet.addresses.INET_HOST`, set the environment
variable `NODE_TEST_INET_HOST` to a specified host.
## ongc Module
The `ongc` module allows a garbage collection listener to be installed. The
module exports a single `onGC()` function.
```js
require('../common');
const onGC = require('../common/ongc');
onGC({}, { ongc() { console.log('collected'); } });
```
### `onGC(target, listener)`
* `target` [<Object>][]
* `listener` [<Object>][]
* `ongc` [<Function>][]
Installs a GC listener for the collection of `target`.
This uses `async_hooks` for GC tracking. This means that it enables
`async_hooks` tracking, which may affect the test functionality. It also
means that between a `global.gc()` call and the listener being invoked
a full `setImmediate()` invocation passes.
`listener` is an object to make it easier to use a closure; the target object
should not be in scope when `listener.ongc()` is created.
## Report Module
The `report` module provides helper functions for testing diagnostic reporting
functionality.
### `findReports(pid, dir)`
* `pid` [<number>][] Process ID to retrieve diagnostic report files for.
* `dir` [<string>][] Directory to search for diagnostic report files.
* return [<Array>][]
Returns an array of diagnotic report file names found in `dir`. The files should
have been generated by a process whose PID matches `pid`.
### `validate(filepath)`
* `filepath` [<string>][] Diagnostic report filepath to validate.
Validates the schema of a diagnostic report file whose path is specified in
`filepath`. If the report fails validation, an exception is thrown.
### `validateContent(report)`
* `report` [<Object>][] | [<string>][] JSON contents of a diagnostic
report file, the parsed Object thereof, or the result of
`process.report.getReport()`.
Validates the schema of a diagnostic report whose content is specified in
`report`. If the report fails validation, an exception is thrown.
## tick Module
The `tick` module provides a helper function that can be used to call a callback
after a given number of event loop "ticks".
### `tick(x, cb)`
* `x` [<number>][] Number of event loop "ticks".
* `cb` [<Function>][] A callback function.
## tmpdir Module
The `tmpdir` module supports the use of a temporary directory for testing.
### `path`
* [<string>][]
The realpath of the testing temporary directory.
### `refresh()`
Deletes and recreates the testing temporary directory.
## WPT Module
### `harness`
A legacy port of [Web Platform Tests][] harness.
See the source code for definitions. Please avoid using it in new
code - the current usage of this port in tests is being migrated to
the original WPT harness, see [the WPT tests README][].
### Class: WPTRunner
A driver class for running WPT with the WPT harness in a vm.
See [the WPT tests README][] for details.
[<Array>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
[<ArrayBufferView>]: https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView
[<Buffer>]: https://nodejs.org/api/buffer.html#buffer_class_buffer
[<BufferSource>]: https://developer.mozilla.org/en-US/docs/Web/API/BufferSource
[<Error>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
[<Function>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
[<Object>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
[<RegExp>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
[<bigint>]: https://github.com/tc39/proposal-bigint
[<boolean>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type
[<number>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
[<string>]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type
[Web Platform Tests]: https://github.com/web-platform-tests/wpt
[`hijackstdio.hijackStdErr()`]: #hijackstderrlistener
[`hijackstdio.hijackStdOut()`]: #hijackstdoutlistener
[internationalization]: https://github.com/nodejs/node/wiki/Intl
[the WPT tests README]: ../wpt/README.md
| {
"content_hash": "295c75f2ec25b716f589d0b86bc27c53",
"timestamp": "",
"source": "github",
"line_count": 970,
"max_line_length": 115,
"avg_line_length": 28.454639175257732,
"alnum_prop": 0.7128364914314699,
"repo_name": "enclose-io/compiler",
"id": "5410a8a6c0acf92cf92042edbe28894075a19425",
"size": "27601",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lts/test/common/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "11474"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
<meta charset="utf-8">
{% include seo.html %}
<link href="{% if site.atom_feed.path %}{{ site.atom_feed.path }}{% else %}{{ '/feed.xml' | absolute_url }}{% endif %}" type="application/atom+xml" rel="alternate" title="{{ site.title }} Feed">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js ';
</script>
<!-- For all browsers -->
<link rel="stylesheet" href="{{ '/assets/css/main.css' | absolute_url }}">
<!--[if lte IE 9]>
<style>
/* old IE unsupported flexbox fixes */
.greedy-nav .site-title {
padding-right: 3em;
}
.greedy-nav button {
position: absolute;
top: 0;
right: 0;
height: 100%;
}
</style>
<![endif]-->
<meta http-equiv="cleartype" content="on">
| {
"content_hash": "0f8dc581b4898a2269fdfbfa28957e8e",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 194,
"avg_line_length": 28.705882352941178,
"alnum_prop": 0.6188524590163934,
"repo_name": "EdmondsNAC/edmondsnac.github.io",
"id": "c10461fe782a464db3204e3916305d712955294d",
"size": "976",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "_includes/head.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "71514"
},
{
"name": "HTML",
"bytes": "60039"
},
{
"name": "JavaScript",
"bytes": "53627"
},
{
"name": "Ruby",
"bytes": "3168"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Sat Mar 16 04:11:58 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.undertow.servlet_container.SessionCookieSettingSupplier (BOM: * : All 2.3.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-03-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.undertow.servlet_container.SessionCookieSettingSupplier (BOM: * : All 2.3.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/undertow/servlet_container/SessionCookieSettingSupplier.html" title="interface in org.wildfly.swarm.config.undertow.servlet_container">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/undertow/servlet_container/class-use/SessionCookieSettingSupplier.html" target="_top">Frames</a></li>
<li><a href="SessionCookieSettingSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.undertow.servlet_container.SessionCookieSettingSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.undertow.servlet_container.SessionCookieSettingSupplier</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/undertow/servlet_container/SessionCookieSettingSupplier.html" title="interface in org.wildfly.swarm.config.undertow.servlet_container">SessionCookieSettingSupplier</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.undertow">org.wildfly.swarm.config.undertow</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.undertow">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/undertow/servlet_container/SessionCookieSettingSupplier.html" title="interface in org.wildfly.swarm.config.undertow.servlet_container">SessionCookieSettingSupplier</a> in <a href="../../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/undertow/servlet_container/SessionCookieSettingSupplier.html" title="interface in org.wildfly.swarm.config.undertow.servlet_container">SessionCookieSettingSupplier</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/undertow/ServletContainer.html" title="type parameter in ServletContainer">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">ServletContainer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/undertow/ServletContainer.html#sessionCookieSetting-org.wildfly.swarm.config.undertow.servlet_container.SessionCookieSettingSupplier-">sessionCookieSetting</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/undertow/servlet_container/SessionCookieSettingSupplier.html" title="interface in org.wildfly.swarm.config.undertow.servlet_container">SessionCookieSettingSupplier</a> supplier)</code>
<div class="block">Session cookie configuration</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/undertow/servlet_container/SessionCookieSettingSupplier.html" title="interface in org.wildfly.swarm.config.undertow.servlet_container">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/undertow/servlet_container/class-use/SessionCookieSettingSupplier.html" target="_top">Frames</a></li>
<li><a href="SessionCookieSettingSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "9a47644af7c6be03ea37c8eb1ae0f71b",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 573,
"avg_line_length": 48.26470588235294,
"alnum_prop": 0.6602071907373552,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "d25a31124c96272c2f6301a4443441bee529707c",
"size": "8205",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.3.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/undertow/servlet_container/class-use/SessionCookieSettingSupplier.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
define({
"_widgetLabel": "Controller antet",
"signin": "Conectare",
"signout": "Deconectare",
"about": "Despre",
"signInTo": "Autentificare la",
"cantSignOutTip": "Această funcţie nu este disponibilă în modul de previzualizare.",
"more": "mai mult"
}); | {
"content_hash": "4d51e314353b9e26a7b3d55f019146bd",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 86,
"avg_line_length": 29.555555555555557,
"alnum_prop": 0.6691729323308271,
"repo_name": "cmndrbensisko/LocalLayer",
"id": "24e8e51ac1d52002b504023187a47b45df8f9b1d",
"size": "270",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/flatFileDataSource/themes/FoldableTheme/widgets/HeaderController/nls/ro/strings.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28288"
},
{
"name": "HTML",
"bytes": "170060"
},
{
"name": "JavaScript",
"bytes": "478816"
}
],
"symlink_target": ""
} |
package Brettspiel;
public class Player {
// int turn ; // i added this
String name;
char symbol;
int score;
Player(String name, char symbol) {
this.name = name;
this.symbol = symbol;
// this.turn = turn;
}
}
| {
"content_hash": "2875b6e3774cdd2944b3aad7c7a1da39",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 36,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.5918367346938775,
"repo_name": "tpe-lecture/repo-27",
"id": "dc8fff43de2d9921cf98f6b1195dafd184ae80e7",
"size": "245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BrettpielOOT/src/Brettspiel/Player.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "238684"
}
],
"symlink_target": ""
} |
<?php
namespace Proxies\__CG__\MyIT\BoxBundle\Entity;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class BackOffice extends \MyIT\BoxBundle\Entity\BackOffice implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = array();
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return array('__isInitialized__', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'id', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'tablette', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'mobile', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'vitrine', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'interface', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'photos', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'sons', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'connexion', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'prix');
}
return array('__isInitialized__', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'id', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'tablette', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'mobile', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'vitrine', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'interface', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'photos', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'sons', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'connexion', '' . "\0" . 'MyIT\\BoxBundle\\Entity\\BackOffice' . "\0" . 'prix');
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (BackOffice $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array());
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array());
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getId();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array());
return parent::getId();
}
/**
* {@inheritDoc}
*/
public function setTablette($tablette)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setTablette', array($tablette));
return parent::setTablette($tablette);
}
/**
* {@inheritDoc}
*/
public function getTablette()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getTablette', array());
return parent::getTablette();
}
/**
* {@inheritDoc}
*/
public function setMobile($mobile)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setMobile', array($mobile));
return parent::setMobile($mobile);
}
/**
* {@inheritDoc}
*/
public function getMobile()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getMobile', array());
return parent::getMobile();
}
/**
* {@inheritDoc}
*/
public function setVitrine($vitrine)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setVitrine', array($vitrine));
return parent::setVitrine($vitrine);
}
/**
* {@inheritDoc}
*/
public function getVitrine()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getVitrine', array());
return parent::getVitrine();
}
/**
* {@inheritDoc}
*/
public function setInterface($interface)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setInterface', array($interface));
return parent::setInterface($interface);
}
/**
* {@inheritDoc}
*/
public function getInterface()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getInterface', array());
return parent::getInterface();
}
/**
* {@inheritDoc}
*/
public function setPhotos($photos)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setPhotos', array($photos));
return parent::setPhotos($photos);
}
/**
* {@inheritDoc}
*/
public function getPhotos()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getPhotos', array());
return parent::getPhotos();
}
/**
* {@inheritDoc}
*/
public function setSons($sons)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setSons', array($sons));
return parent::setSons($sons);
}
/**
* {@inheritDoc}
*/
public function getSons()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getSons', array());
return parent::getSons();
}
/**
* {@inheritDoc}
*/
public function setConnexion($connexion)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setConnexion', array($connexion));
return parent::setConnexion($connexion);
}
/**
* {@inheritDoc}
*/
public function getConnexion()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getConnexion', array());
return parent::getConnexion();
}
/**
* {@inheritDoc}
*/
public function setPrix($prix)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setPrix', array($prix));
return parent::setPrix($prix);
}
/**
* {@inheritDoc}
*/
public function getPrix()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getPrix', array());
return parent::getPrix();
}
}
| {
"content_hash": "5ef3eb0cac993f8d1c7f4e9ca4fe5e8a",
"timestamp": "",
"source": "github",
"line_count": 367,
"max_line_length": 668,
"avg_line_length": 26.64032697547684,
"alnum_prop": 0.5460775288943439,
"repo_name": "SkyzoFahira/myitbox",
"id": "ffaacef05ad6251159a51d1b35f70f1ae4765870",
"size": "9777",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/cache/dev_old/doctrine/orm/Proxies/__CG__MyITBoxBundleEntityBackOffice.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "143169"
},
{
"name": "HTML",
"bytes": "43228"
},
{
"name": "JavaScript",
"bytes": "7369"
},
{
"name": "PHP",
"bytes": "74739"
}
],
"symlink_target": ""
} |
package com.azure.spring.cloud.resourcemanager.implementation.connectionstring;
import com.azure.core.http.HttpResponse;
import com.azure.core.management.exception.ManagementException;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.spring.cloud.core.properties.resource.AzureResourceMetadata;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
abstract class AbstractArmConnectionStringProviderTests<T> {
protected AzureResourceManager resourceManager;
protected AzureResourceMetadata resourceMetadata;
protected ArmConnectionStringProvider<T> provider;
abstract ArmConnectionStringProvider<T> getArmConnectionStringProvider();
@BeforeEach
void beforeEach() {
resourceManager = mock(AzureResourceManager.class);
resourceMetadata = mock(AzureResourceMetadata.class);
provider = getArmConnectionStringProvider();
}
@Test
void failedWhenGettingConnectionStringNamespaceDoesNotExist() {
HttpResponse response = mock(HttpResponse.class);
when(response.getStatusCode()).thenReturn(403);
ManagementException exception = new ManagementException("AuthorizationFailed", response);
when(resourceManager.eventHubNamespaces()).thenThrow(exception);
assertThrows(RuntimeException.class, () -> provider.getConnectionString());
}
}
| {
"content_hash": "a103b5ca32f4d06034e6517be7cc1b5f",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 97,
"avg_line_length": 42.138888888888886,
"alnum_prop": 0.7897165458141068,
"repo_name": "Azure/azure-sdk-for-java",
"id": "e4fe6c75001a2adb0596c7a590b4fff9c3cc758c",
"size": "1614",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/spring/spring-cloud-azure-resourcemanager/src/test/java/com/azure/spring/cloud/resourcemanager/implementation/connectionstring/AbstractArmConnectionStringProviderTests.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\RequestContextAwareInterface;
/**
* UrlGeneratorInterface is the interface that all URL generator classes must implements.
*
* @author Fabien Potencier <[email protected]>
*/
interface UrlGeneratorInterface extends RequestContextAwareInterface
{
/**
* Generates a URL from the given parameters.
*
* @param string $name The name of the route
* @param array $parameters An array of parameters
* @param Boolean $absolute Whether to generate an absolute URL
*
* @return string The generated URL
*/
function generate($name, array $parameters = array(), $absolute = false);
}
| {
"content_hash": "1c759752afa932aa146d65623894b787",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 89,
"avg_line_length": 27.76923076923077,
"alnum_prop": 0.7077562326869806,
"repo_name": "DerekRoth/symfony",
"id": "bc66f95998f27efd71171acfdacd5489ed85c119",
"size": "951",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "src/Symfony/Component/Routing/Generator/UrlGeneratorInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "DOT",
"bytes": "3215"
},
{
"name": "JavaScript",
"bytes": "34"
},
{
"name": "PHP",
"bytes": "5030531"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package execution;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class provide partial implementation for managing collection of tasks.
* @author Ivan Straka
*/
public abstract class Feeder extends TaskManager {
private static final Logger logger = Logger.getLogger(Feeder.class.getName());
protected final LinkedBlockingQueue<String> todo;
protected final Object lock;
protected volatile int tasksDoneCounter;
protected volatile long startTime;
protected volatile int allTasksCounter;
public Feeder(Collection<String> files){
todo = new LinkedBlockingQueue<>();
if(files != null) {
todo.addAll(files);
}
lock = new Object();
allTasksCounter= todo.size();
}
@Override
public boolean removeFile(String file){
synchronized(lock){
if(todo.remove(file)){
allTasksCounter--;
return true;
}
return false;
}
}
/**
* Put task into queue.
* @param f file
*/
@Override
public void addFile(String f){
synchronized(lock){
allTasksCounter++;
todo.add(f);
}
}
/**
* Return the head of queue if not empty or null.
* @return Task
*/
@Override
public String getFile(){
synchronized(lock){
String result = todo.poll();
if(result != null){
allTasksCounter--;
}
return result;
}
}
@Override
public void taskDone(){
synchronized(lock){
tasksDoneCounter++;
}
}
@Override
public double getEstimatedFinishTimeSec(){
synchronized(lock){
double result = (tasksDoneCounter / (double) allTasksCounter < TaskManager.TASK_DONE_VALID_RATIO)? TaskManager.NOTHING_DONE : getTheoreticalEstimatedFinishTimeSec(0);
logger.log(Level.INFO, "Estimated finish time: {0}, done: {1}, all: {2}, done/all ratio to cumpute time: {3}", new Object[]{result, tasksDoneCounter, allTasksCounter, TASK_DONE_VALID_RATIO});
return result;
}
}
@Override
public boolean finished(){
synchronized(lock){
return allTasksCounter - tasksDoneCounter <= 0;
}
}
/**
* Get theoretical estimated finish time after changing numbers of files in queue.
*/
@Override
public double getTheoreticalEstimatedFinishTimeSec(int fileNumberChange){
synchronized(lock){
int remain = allTasksCounter + fileNumberChange - tasksDoneCounter;
if(remain <= 0){
return 0;
}
else if(tasksDoneCounter == 0){
return TaskManager.NOTHING_DONE;
}
else{
return (remain * ((System.currentTimeMillis() - startTime) / (double)tasksDoneCounter))/1000;
}
}
}
protected void start(){
startTime = System.currentTimeMillis();
}
public String obtainTask() throws InterruptedException{
return todo.take();
}
}
| {
"content_hash": "c42a90e84ac5f7686a04e56b11573ddd",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 203,
"avg_line_length": 28.096774193548388,
"alnum_prop": 0.5895522388059702,
"repo_name": "strakai/pd_corp",
"id": "81d7de8578f3aefffb022f5e539c1ab4caaf8604",
"size": "3484",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/execution/Feeder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "274045"
},
{
"name": "Python",
"bytes": "2489"
}
],
"symlink_target": ""
} |
layout: post
title: Goldschmidt · Evolution of the Water Cycle since the Archean
type: poster
---
Kurokawa H, Foriel J & Laneuville M, Evolution of the Water Cycle Since the
Archean as Constrained by Hydrogen Isotopes.
[Abstract](https://goldschmidt.info/2017/abstracts/abstractView?id=2017004813)
Manuscript now submitted to EPSL.
| {
"content_hash": "6e099e94b608986869e772f51c2df2a9",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 78,
"avg_line_length": 34.2,
"alnum_prop": 0.7923976608187134,
"repo_name": "mlaneuville/mlaneuville.github.io",
"id": "3883cc721b4ec3a9d5a7d68a3c583ed4204bf266",
"size": "346",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2017-08-13-Goldschmidt-hydrogen-cycling.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12650"
},
{
"name": "HTML",
"bytes": "9238"
},
{
"name": "JavaScript",
"bytes": "2698"
},
{
"name": "Ruby",
"bytes": "3526"
}
],
"symlink_target": ""
} |
from django.contrib import admin
from .models import Link
class LinkAdmin(admin.ModelAdmin):
search_fields = ['title__icontains', 'description']
list_display = ['title', 'user', 'domain', 'active']
list_filter = ['user', 'active']
date_hierarchy = 'created_on'
admin.site.register(Link, LinkAdmin)
| {
"content_hash": "ba9f24a0442584af4fa70e6113c40e2b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 56,
"avg_line_length": 24.53846153846154,
"alnum_prop": 0.6833855799373041,
"repo_name": "moshthepitt/product.co.ke",
"id": "094d7f606e62915e065e725b89fc3afc6e0caa57",
"size": "319",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "links/admin.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "54411"
},
{
"name": "HTML",
"bytes": "39651"
},
{
"name": "JavaScript",
"bytes": "849"
},
{
"name": "Python",
"bytes": "26102"
}
],
"symlink_target": ""
} |
<?php
namespace Exceptions\IO\Filesystem;
use Exceptions\Tag\AbortedTag;
/**
* Use this exception when your code realizes that there is no more space available on the device to write to.
*
* @author Mathieu Dumoulin <[email protected]>
* @license MIT
*/
class NoMoreSpaceException extends FilesystemException implements AbortedTag
{
const MESSAGE = 'Specified target location has run out of disk space';
const CODE = 0;
}
| {
"content_hash": "7f15c3ae63af0403abdf0a579ead891b",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 110,
"avg_line_length": 26.235294117647058,
"alnum_prop": 0.7488789237668162,
"repo_name": "crazycodr/standard-exceptions",
"id": "12f3d3312c1398e7959650c42ce407ba075af1de",
"size": "446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Exceptions/IO/Filesystem/NoMoreSpaceException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "131388"
}
],
"symlink_target": ""
} |
package com.softwaremill.macwire
class CompileTests extends CompileTestsSupport {
runTestsWith(
expectedFailures = List(
"methodWithTaggedParamsNotFound" -> List(valueNotFound("com.softwaremill.macwire.tagging.@@[Berry,Blue]")),
"methodWithTaggedParamsAmbiguous" -> List(ambiguousResMsg("com.softwaremill.macwire.tagging.@@[Berry,Blue]"), "blueberryArg1", "blueberryArg2"),
"moduleAmbiguousWithParent" -> List(ambiguousResMsg("A"), "module.a", "parentA"),
"taggedNoValueWithTag" -> List(valueNotFound("com.softwaremill.macwire.tagging.@@[Berry,Blue]")))
)
}
| {
"content_hash": "100430dc5e9e4656ee1e53d391210a23",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 150,
"avg_line_length": 49.333333333333336,
"alnum_prop": 0.7381756756756757,
"repo_name": "guersam/macwire",
"id": "ea25fe386d888df866df002ef734d5f376a76d3a",
"size": "592",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "util-tests/src/test/scala/com/softwaremill/macwire/CompileTests.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1889"
},
{
"name": "Scala",
"bytes": "62246"
}
],
"symlink_target": ""
} |
/**
* Контроллер панели notebody.
*
* @author [email protected] <Suvorov Andrey M.>
*/
Ext.define(
'FBEditor.view.panel.main.props.body.editor.notebody.EditorController',
{
extend: 'FBEditor.view.panel.main.props.body.editor.AbstractEditorController',
alias: 'controller.panel.props.body.editor.notebody',
onChange: function ()
{
var me = this,
view = me.getView(),
notesCmp;
me.callParent(arguments);
// обновляем кнопки на сноски
notesCmp = view.getNotesCmp();
notesCmp.updateView();
}
}
); | {
"content_hash": "9ce64ed2d84882d820990101f3a96ad7",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 80,
"avg_line_length": 21.14814814814815,
"alnum_prop": 0.6409807355516638,
"repo_name": "Litres/FB3Editor",
"id": "a3a242ca2f0e8da86a22a403d7bfa32b69725ed1",
"size": "610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Frontend/app/view/panel/main/props/body/editor/notebody/EditorController.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "1726929"
},
{
"name": "HTML",
"bytes": "84407"
},
{
"name": "Java",
"bytes": "2770"
},
{
"name": "JavaScript",
"bytes": "75213255"
},
{
"name": "Perl",
"bytes": "13"
},
{
"name": "Ruby",
"bytes": "7620"
}
],
"symlink_target": ""
} |
module Azure::Redis::Mgmt::V2016_04_01
module Models
#
# Parameters for Redis export operation.
#
class ExportRDBParameters
include MsRestAzure
# @return [String] File format.
attr_accessor :format
# @return [String] Prefix to use for exported files.
attr_accessor :prefix
# @return [String] Container name to export to.
attr_accessor :container
#
# Mapper for ExportRDBParameters class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ExportRDBParameters',
type: {
name: 'Composite',
class_name: 'ExportRDBParameters',
model_properties: {
format: {
client_side_validation: true,
required: false,
serialized_name: 'format',
type: {
name: 'String'
}
},
prefix: {
client_side_validation: true,
required: true,
serialized_name: 'prefix',
type: {
name: 'String'
}
},
container: {
client_side_validation: true,
required: true,
serialized_name: 'container',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| {
"content_hash": "d4ce391aba888e368bb861289523b6cf",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 60,
"avg_line_length": 25.523809523809526,
"alnum_prop": 0.46455223880597013,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "9b8bb6b45d2ce03f3205098610052877645ea7a3",
"size": "1772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_redis/lib/2016-04-01/generated/azure_mgmt_redis/models/export_rdbparameters.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
namespace ft {
int Library::initialized = 0;
Library::Library()
{
if (!initialized)
{
const auto error = FT_Init_FreeType(&library);
if (error)
throw Exception("Couldn't init FreeType engine", error);
}
++initialized;
}
Library::~Library()
{
if (initialized)
{
if (--initialized == 0)
{
FT_Done_FreeType(library);
library = nullptr;
}
}
}
std::string Library::getVersionString() const
{
if (!library)
return "";
FT_Int major;
FT_Int minor;
FT_Int patch;
FT_Library_Version(library, &major, &minor, &patch);
return StringMaker() << major << "." << minor << "." << patch;
}
}
| {
"content_hash": "98641d9d28d7ab66f740a0abe29fe909",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 68,
"avg_line_length": 18.095238095238095,
"alnum_prop": 0.506578947368421,
"repo_name": "vladimirgamalian/fontbm",
"id": "ceeb643e919fdef4cc66577d76116e7150f45860",
"size": "845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/freeType/FtLibrary.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5502"
},
{
"name": "C++",
"bytes": "896368"
},
{
"name": "CMake",
"bytes": "2374"
},
{
"name": "Python",
"bytes": "3276"
}
],
"symlink_target": ""
} |
package output
import (
"fmt"
"github.com/mcuadros/harvester/src/intf"
)
type DummyConfig struct {
Print bool
}
type Dummy struct {
printInfo bool
}
func NewDummy(config *DummyConfig) *Dummy {
output := new(Dummy)
output.SetConfig(config)
return output
}
func (o *Dummy) SetConfig(config *DummyConfig) {
o.printInfo = config.Print
}
func (o *Dummy) PutRecord(record intf.Record) bool {
if o.printInfo {
fmt.Println(record)
}
return true
}
| {
"content_hash": "76aebc7afb385df529635378d1cb2a9a",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 52,
"avg_line_length": 13.93939393939394,
"alnum_prop": 0.7130434782608696,
"repo_name": "mcuadros/harvester",
"id": "e8d25020b64ccf5d1fc9853c8103460be29a4118",
"size": "460",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/output/dummy.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "110378"
},
{
"name": "Makefile",
"bytes": "1588"
},
{
"name": "Shell",
"bytes": "1164"
}
],
"symlink_target": ""
} |
package org.wso2.developerstudio.eclipse.gmf.esb;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Rule Source Type</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getRuleSourceType()
* @model
* @generated
*/
public enum RuleSourceType implements Enumerator {
/**
* The '<em><b>Inline</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #INLINE_VALUE
* @generated
* @ordered
*/
INLINE(0, "inline", "INLINE"),
/**
* The '<em><b>Registry</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #REGISTRY_VALUE
* @generated
* @ordered
*/
REGISTRY(1, "registry", "REGISTRY_REFERENCE"), /**
* The '<em><b>Url</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #URL_VALUE
* @generated
* @ordered
*/
URL(2, "url", "URL");
/**
* The '<em><b>Inline</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>INLINE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #INLINE
* @model name="inline" literal="INLINE"
* @generated
* @ordered
*/
public static final int INLINE_VALUE = 0;
/**
* The '<em><b>Registry</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Registry</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #REGISTRY
* @model name="registry" literal="REGISTRY_REFERENCE"
* @generated
* @ordered
*/
public static final int REGISTRY_VALUE = 1;
/**
* The '<em><b>Url</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>URL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #URL
* @model name="url" literal="URL"
* @generated
* @ordered
*/
public static final int URL_VALUE = 2;
/**
* An array of all the '<em><b>Rule Source Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final RuleSourceType[] VALUES_ARRAY =
new RuleSourceType[] {
INLINE,
REGISTRY,
URL,
};
/**
* A public read-only list of all the '<em><b>Rule Source Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<RuleSourceType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Rule Source Type</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static RuleSourceType get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
RuleSourceType result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Rule Source Type</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static RuleSourceType getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
RuleSourceType result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Rule Source Type</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static RuleSourceType get(int value) {
switch (value) {
case INLINE_VALUE: return INLINE;
case REGISTRY_VALUE: return REGISTRY;
case URL_VALUE: return URL;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private RuleSourceType(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //RuleSourceType
| {
"content_hash": "dd2c4973c09bc20425be957f43222171",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 109,
"avg_line_length": 23.06694560669456,
"alnum_prop": 0.5924179212769817,
"repo_name": "nwnpallewela/devstudio-tooling-esb",
"id": "50b6f61522a801ba841e0e7dbb0dcd5bf3424c70",
"size": "5562",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "plugins/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/RuleSourceType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "41190583"
},
{
"name": "Shell",
"bytes": "6640"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/AppMarket.iml" filepath="$PROJECT_DIR$/AppMarket.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project> | {
"content_hash": "cc4696ecf57e50f6a952f532519441bc",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 100,
"avg_line_length": 39.44444444444444,
"alnum_prop": 0.6591549295774648,
"repo_name": "FreyHerbert/AppMarket",
"id": "10d7df86f53be07942f909fda174ec9215734e93",
"size": "355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "730947"
}
],
"symlink_target": ""
} |
namespace Google.Cloud.VpcAccess.V1.Snippets
{
// [START vpcaccess_v1_generated_VpcAccessService_CreateConnector_sync_flattened_resourceNames]
using Google.Api.Gax.ResourceNames;
using Google.Cloud.VpcAccess.V1;
using Google.LongRunning;
public sealed partial class GeneratedVpcAccessServiceClientSnippets
{
/// <summary>Snippet for CreateConnector</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateConnectorResourceNames()
{
// Create client
VpcAccessServiceClient vpcAccessServiceClient = VpcAccessServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
string connectorId = "";
Connector connector = new Connector();
// Make the request
Operation<Connector, OperationMetadata> response = vpcAccessServiceClient.CreateConnector(parent, connectorId, connector);
// Poll until the returned long-running operation is complete
Operation<Connector, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Connector result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Connector, OperationMetadata> retrievedResponse = vpcAccessServiceClient.PollOnceCreateConnector(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Connector retrievedResult = retrievedResponse.Result;
}
}
}
// [END vpcaccess_v1_generated_VpcAccessService_CreateConnector_sync_flattened_resourceNames]
}
| {
"content_hash": "66d1469fc1b0e89bc46eb39a460eb63f",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 134,
"avg_line_length": 49.65909090909091,
"alnum_prop": 0.6764302059496567,
"repo_name": "jskeet/google-cloud-dotnet",
"id": "eed22b6c83b7f461ada032df3a63e71663dc9b15",
"size": "2807",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "apis/Google.Cloud.VpcAccess.V1/Google.Cloud.VpcAccess.V1.GeneratedSnippets/VpcAccessServiceClient.CreateConnectorResourceNamesSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "767"
},
{
"name": "C#",
"bytes": "268415427"
},
{
"name": "CSS",
"bytes": "1346"
},
{
"name": "Dockerfile",
"bytes": "3173"
},
{
"name": "HTML",
"bytes": "3823"
},
{
"name": "JavaScript",
"bytes": "226"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "2744"
},
{
"name": "Shell",
"bytes": "65260"
},
{
"name": "sed",
"bytes": "1030"
}
],
"symlink_target": ""
} |
package org.apache.arrow.vector;
import static io.netty.util.internal.PlatformDependent.getByte;
import static io.netty.util.internal.PlatformDependent.getInt;
import static io.netty.util.internal.PlatformDependent.getLong;
import static org.apache.arrow.memory.util.LargeMemoryUtil.checkedCastToInt;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BoundsChecking;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.ipc.message.ArrowFieldNode;
import org.apache.arrow.vector.util.DataSizeRoundingUtil;
import io.netty.util.internal.PlatformDependent;
/**
* Helper class for performing generic operations on a bit vector buffer.
* External use of this class is not recommended.
*/
public class BitVectorHelper {
private BitVectorHelper() {}
/**
* Get the index of byte corresponding to bit index in validity buffer.
*/
public static long byteIndex(long absoluteBitIndex) {
return absoluteBitIndex >> 3;
}
/**
* Get the relative index of bit within the byte in validity buffer.
*/
public static int bitIndex(long absoluteBitIndex) {
return checkedCastToInt(absoluteBitIndex & 7);
}
/**
* Get the index of byte corresponding to bit index in validity buffer.
*/
public static int byteIndex(int absoluteBitIndex) {
return absoluteBitIndex >> 3;
}
/**
* Get the relative index of bit within the byte in validity buffer.
*/
public static int bitIndex(int absoluteBitIndex) {
return absoluteBitIndex & 7;
}
/**
* Set the bit at provided index to 1.
*
* @param validityBuffer validity buffer of the vector
* @param index index to be set
*/
public static void setBit(ArrowBuf validityBuffer, long index) {
// it can be observed that some logic is duplicate of the logic in setValidityBit.
// this is because JIT cannot always remove the if branch in setValidityBit,
// so we give a dedicated implementation for setting bits.
final long byteIndex = byteIndex(index);
final int bitIndex = bitIndex(index);
// the byte is promoted to an int, because according to Java specification,
// bytes will be promoted to ints automatically, upon expression evaluation.
// by promoting it manually, we avoid the unnecessary conversions.
int currentByte = validityBuffer.getByte(byteIndex);
final int bitMask = 1 << bitIndex;
currentByte |= bitMask;
validityBuffer.setByte(byteIndex, currentByte);
}
/**
* Set the bit at provided index to 1.
*
* @deprecated Please use {@link BitVectorHelper#setBit(ArrowBuf, long)} instead..
*/
@Deprecated
public static void setValidityBitToOne(ArrowBuf validityBuffer, int index) {
setBit(validityBuffer, index);
}
/**
* Set the bit at provided index to 0.
*
* @param validityBuffer validity buffer of the vector
* @param index index to be set
*/
public static void unsetBit(ArrowBuf validityBuffer, int index) {
// it can be observed that some logic is duplicate of the logic in setValidityBit.
// this is because JIT cannot always remove the if branch in setValidityBit,
// so we give a dedicated implementation for unsetting bits.
final int byteIndex = byteIndex(index);
final int bitIndex = bitIndex(index);
// the byte is promoted to an int, because according to Java specification,
// bytes will be promoted to ints automatically, upon expression evaluation.
// by promoting it manually, we avoid the unnecessary conversions.
int currentByte = validityBuffer.getByte(byteIndex);
final int bitMask = 1 << bitIndex;
currentByte &= ~bitMask;
validityBuffer.setByte(byteIndex, currentByte);
}
/**
* Set the bit at a given index to provided value (1 or 0).
*
* @param validityBuffer validity buffer of the vector
* @param index index to be set
* @param value value to set
*/
public static void setValidityBit(ArrowBuf validityBuffer, int index, int value) {
final int byteIndex = byteIndex(index);
final int bitIndex = bitIndex(index);
// the byte is promoted to an int, because according to Java specification,
// bytes will be promoted to ints automatically, upon expression evaluation.
// by promoting it manually, we avoid the unnecessary conversions.
int currentByte = validityBuffer.getByte(byteIndex);
final int bitMask = 1 << bitIndex;
if (value != 0) {
currentByte |= bitMask;
} else {
currentByte &= ~bitMask;
}
validityBuffer.setByte(byteIndex, currentByte);
}
/**
* Set the bit at a given index to provided value (1 or 0). Internally
* takes care of allocating the buffer if the caller didn't do so.
*
* @param validityBuffer validity buffer of the vector
* @param allocator allocator for the buffer
* @param valueCount number of values to allocate/set
* @param index index to be set
* @param value value to set
* @return ArrowBuf
*/
public static ArrowBuf setValidityBit(ArrowBuf validityBuffer, BufferAllocator allocator,
int valueCount, int index, int value) {
if (validityBuffer == null) {
validityBuffer = allocator.buffer(getValidityBufferSize(valueCount));
}
setValidityBit(validityBuffer, index, value);
if (index == (valueCount - 1)) {
validityBuffer.writerIndex(getValidityBufferSize(valueCount));
}
return validityBuffer;
}
/**
* Check if a bit at a given index is set or not.
*
* @param buffer buffer to check
* @param index index of the buffer
* @return 1 if bit is set, 0 otherwise.
*/
public static int get(final ArrowBuf buffer, int index) {
final int byteIndex = index >> 3;
final byte b = buffer.getByte(byteIndex);
final int bitIndex = index & 7;
return (b >> bitIndex) & 0x01;
}
/**
* Compute the size of validity buffer required to manage a given number
* of elements in a vector.
*
* @param valueCount number of elements in the vector
* @return buffer size
*/
public static int getValidityBufferSize(int valueCount) {
return DataSizeRoundingUtil.divideBy8Ceil(valueCount);
}
/**
* Given a validity buffer, find the number of bits that are not set.
* This is used to compute the number of null elements in a nullable vector.
*
* @param validityBuffer validity buffer of the vector
* @param valueCount number of values in the vector
* @return number of bits not set.
*/
public static int getNullCount(final ArrowBuf validityBuffer, final int valueCount) {
if (valueCount == 0) {
return 0;
}
int count = 0;
final int sizeInBytes = getValidityBufferSize(valueCount);
// If value count is not a multiple of 8, then calculate number of used bits in the last byte
final int remainder = valueCount % 8;
final int fullBytesCount = remainder == 0 ? sizeInBytes : sizeInBytes - 1;
int index = 0;
while (index + 8 <= fullBytesCount) {
long longValue = validityBuffer.getLong(index);
count += Long.bitCount(longValue);
index += 8;
}
if (index + 4 <= fullBytesCount) {
int intValue = validityBuffer.getInt(index);
count += Integer.bitCount(intValue);
index += 4;
}
while (index < fullBytesCount) {
byte byteValue = validityBuffer.getByte(index);
count += Integer.bitCount(byteValue & 0xFF);
index += 1;
}
// handling with the last bits
if (remainder != 0) {
byte byteValue = validityBuffer.getByte(sizeInBytes - 1);
// making the remaining bits all 1s if it is not fully filled
byte mask = (byte) (0xFF << remainder);
byteValue = (byte) (byteValue | mask);
count += Integer.bitCount(byteValue & 0xFF);
}
return 8 * sizeInBytes - count;
}
/**
* Tests if all bits in a validity buffer are equal 0 or 1, according to the specified parameter.
* @param validityBuffer the validity buffer.
* @param valueCount the bit count.
* @param checkOneBits if set to true, the method checks if all bits are equal to 1;
* otherwise, it checks if all bits are equal to 0.
* @return true if all bits are 0 or 1 according to the parameter, and false otherwise.
*/
public static boolean checkAllBitsEqualTo(
final ArrowBuf validityBuffer, final int valueCount, final boolean checkOneBits) {
if (valueCount == 0) {
return true;
}
final int sizeInBytes = getValidityBufferSize(valueCount);
// boundary check
validityBuffer.checkBytes(0, sizeInBytes);
// If value count is not a multiple of 8, then calculate number of used bits in the last byte
final int remainder = valueCount % 8;
final int fullBytesCount = remainder == 0 ? sizeInBytes : sizeInBytes - 1;
// the integer number to compare against
final int intToCompare = checkOneBits ? -1 : 0;
int index = 0;
while (index + 8 <= fullBytesCount) {
long longValue = getLong(validityBuffer.memoryAddress() + index);
if (longValue != (long) intToCompare) {
return false;
}
index += 8;
}
if (index + 4 <= fullBytesCount) {
int intValue = getInt(validityBuffer.memoryAddress() + index);
if (intValue != intToCompare) {
return false;
}
index += 4;
}
while (index < fullBytesCount) {
byte byteValue = getByte(validityBuffer.memoryAddress() + index);
if (byteValue != (byte) intToCompare) {
return false;
}
index += 1;
}
// handling with the last bits
if (remainder != 0) {
byte byteValue = getByte(validityBuffer.memoryAddress() + sizeInBytes - 1);
byte mask = (byte) ((1 << remainder) - 1);
byteValue = (byte) (byteValue & mask);
if (checkOneBits) {
if ((mask & byteValue) != mask) {
return false;
}
} else {
if (byteValue != (byte) 0) {
return false;
}
}
}
return true;
}
/** Returns the byte at index from data right-shifted by offset. */
public static byte getBitsFromCurrentByte(final ArrowBuf data, final int index, final int offset) {
return (byte) ((data.getByte(index) & 0xFF) >>> offset);
}
/**
* Returns the byte at <code>index</code> from left-shifted by (8 - <code>offset</code>).
*/
public static byte getBitsFromNextByte(ArrowBuf data, int index, int offset) {
return (byte) ((data.getByte(index) << (8 - offset)));
}
/**
* Returns a new buffer if the source validity buffer is either all null or all
* not-null, otherwise returns a buffer pointing to the same memory as source.
*
* @param fieldNode The fieldNode containing the null count
* @param sourceValidityBuffer The source validity buffer that will have its
* position copied if there is a mix of null and non-null values
* @param allocator The allocator to use for creating a new buffer if necessary.
* @return A new buffer that is either allocated or points to the same memory as sourceValidityBuffer.
*/
public static ArrowBuf loadValidityBuffer(final ArrowFieldNode fieldNode,
final ArrowBuf sourceValidityBuffer,
final BufferAllocator allocator) {
final int valueCount = fieldNode.getLength();
ArrowBuf newBuffer = null;
/* either all NULLs or all non-NULLs */
if (fieldNode.getNullCount() == 0 || fieldNode.getNullCount() == valueCount) {
newBuffer = allocator.buffer(getValidityBufferSize(valueCount));
newBuffer.setZero(0, newBuffer.capacity());
if (fieldNode.getNullCount() != 0) {
/* all NULLs */
return newBuffer;
}
/* all non-NULLs */
int fullBytesCount = valueCount / 8;
newBuffer.setOne(0, fullBytesCount);
int remainder = valueCount % 8;
if (remainder > 0) {
byte bitMask = (byte) (0xFFL >>> ((8 - remainder) & 7));
newBuffer.setByte(fullBytesCount, bitMask);
}
} else {
/* mixed byte pattern -- create another ArrowBuf associated with the
* target allocator
*/
newBuffer = sourceValidityBuffer.getReferenceManager().retain(sourceValidityBuffer, allocator);
}
return newBuffer;
}
/**
* Set the byte of the given index in the data buffer by applying a bit mask to
* the current byte at that index.
*
* @param data buffer to set
* @param byteIndex byteIndex within the buffer
* @param bitMask bit mask to be set
*/
static void setBitMaskedByte(ArrowBuf data, int byteIndex, byte bitMask) {
byte currentByte = data.getByte(byteIndex);
currentByte |= bitMask;
data.setByte(byteIndex, currentByte);
}
/**
* Concat two validity buffers.
* @param input1 the first validity buffer.
* @param numBits1 the number of bits in the first validity buffer.
* @param input2 the second validity buffer.
* @param numBits2 the number of bits in the second validity buffer.
* @param output the output validity buffer. It can be the same one as the first input.
* The caller must make sure the output buffer has enough capacity.
*/
public static void concatBits(ArrowBuf input1, int numBits1, ArrowBuf input2, int numBits2, ArrowBuf output) {
int numBytes1 = DataSizeRoundingUtil.divideBy8Ceil(numBits1);
int numBytes2 = DataSizeRoundingUtil.divideBy8Ceil(numBits2);
int numBytesOut = DataSizeRoundingUtil.divideBy8Ceil(numBits1 + numBits2);
if (BoundsChecking.BOUNDS_CHECKING_ENABLED) {
output.checkBytes(0, numBytesOut);
}
// copy the first bit set
if (input1 != output) {
PlatformDependent.copyMemory(input1.memoryAddress(), output.memoryAddress(), numBytes1);
}
if (bitIndex(numBits1) == 0) {
// The number of bits for the first bit set is a multiple of 8, so the boundary is at byte boundary.
// For this case, we have a shortcut to copy all bytes from the second set after the byte boundary.
PlatformDependent.copyMemory(input2.memoryAddress(), output.memoryAddress() + numBytes1, numBytes2);
return;
}
// the number of bits to fill a full byte after the first input is processed
int numBitsToFill = 8 - bitIndex(numBits1);
// mask to clear high bits
int mask = (1 << (8 - numBitsToFill)) - 1;
int numFullBytes = numBits2 / 8;
int prevByte = output.getByte(numBytes1 - 1) & mask;
for (int i = 0; i < numFullBytes; i++) {
int curByte = input2.getByte(i) & 0xff;
// first fill the bits to a full byte
int byteToFill = (curByte << (8 - numBitsToFill)) & 0xff;
output.setByte(numBytes1 + i - 1, byteToFill | prevByte);
// fill remaining bits in the current byte
// note that it is also the previous byte for the next iteration
prevByte = curByte >>> numBitsToFill;
}
int lastOutputByte = prevByte;
// the number of extra bits for the second input, relative to full bytes
int numTrailingBits = bitIndex(numBits2);
if (numTrailingBits == 0) {
output.setByte(numBytes1 + numFullBytes - 1, lastOutputByte);
return;
}
// process remaining bits from input2
int remByte = input2.getByte(numBytes2 - 1) & 0xff;
int byteToFill = remByte << (8 - numBitsToFill);
lastOutputByte |= byteToFill;
output.setByte(numBytes1 + numFullBytes - 1, lastOutputByte);
if (numTrailingBits > numBitsToFill) {
// clear all bits for the last byte before writing
output.setByte(numBytes1 + numFullBytes, 0);
// some remaining bits cannot be filled in the previous byte
int leftByte = remByte >>> numBitsToFill;
output.setByte(numBytes1 + numFullBytes, leftByte);
}
}
}
| {
"content_hash": "e0deb5ce6c0ddf0b25eed1b7f82c364d",
"timestamp": "",
"source": "github",
"line_count": 444,
"max_line_length": 112,
"avg_line_length": 35.58108108108108,
"alnum_prop": 0.6739460691226737,
"repo_name": "cpcloud/arrow",
"id": "ec73382a0ef33206f7d07ea2c9b68888086004fb",
"size": "16598",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "java/vector/src/main/java/org/apache/arrow/vector/BitVectorHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "486660"
},
{
"name": "Awk",
"bytes": "3709"
},
{
"name": "Batchfile",
"bytes": "29705"
},
{
"name": "C",
"bytes": "1078695"
},
{
"name": "C#",
"bytes": "911504"
},
{
"name": "C++",
"bytes": "18880401"
},
{
"name": "CMake",
"bytes": "588081"
},
{
"name": "Cython",
"bytes": "1156054"
},
{
"name": "Dockerfile",
"bytes": "108671"
},
{
"name": "Emacs Lisp",
"bytes": "1916"
},
{
"name": "FreeMarker",
"bytes": "2312"
},
{
"name": "Go",
"bytes": "1794213"
},
{
"name": "HTML",
"bytes": "3430"
},
{
"name": "Java",
"bytes": "5134538"
},
{
"name": "JavaScript",
"bytes": "110059"
},
{
"name": "Jinja",
"bytes": "9101"
},
{
"name": "Julia",
"bytes": "241544"
},
{
"name": "Lua",
"bytes": "8771"
},
{
"name": "MATLAB",
"bytes": "36260"
},
{
"name": "Makefile",
"bytes": "19262"
},
{
"name": "Meson",
"bytes": "55180"
},
{
"name": "Objective-C++",
"bytes": "12128"
},
{
"name": "PLpgSQL",
"bytes": "56995"
},
{
"name": "Perl",
"bytes": "3803"
},
{
"name": "Python",
"bytes": "2417779"
},
{
"name": "R",
"bytes": "864022"
},
{
"name": "Ruby",
"bytes": "1366715"
},
{
"name": "Shell",
"bytes": "312029"
},
{
"name": "Thrift",
"bytes": "142245"
},
{
"name": "TypeScript",
"bytes": "1183174"
}
],
"symlink_target": ""
} |
<?xml version="1.0" ?>
<xmcda:XMCDA xmlns:xmcda="http://www.decision-deck.org/2017/XMCDA-3.0.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.decision-deck.org/2017/XMCDA-3.0.2 http://www.decision-deck.org/xmcda/_downloads/XMCDA-3.0.2.xsd">
<performanceTable>
<alternativePerformances>
<alternativeID>b1</alternativeID>
<performance>
<criterionID>cr1</criterionID>
<values>
<value>
<real>10.0</real>
</value>
</values>
</performance>
<performance>
<criterionID>cr2</criterionID>
<values>
<value>
<real>50.0</real>
</value>
</values>
</performance>
</alternativePerformances>
<alternativePerformances>
<alternativeID>b2</alternativeID>
<performance>
<criterionID>cr1</criterionID>
<values>
<value>
<real>20.0</real>
</value>
</values>
</performance>
<performance>
<criterionID>cr2</criterionID>
<values>
<value>
<real>40.0</real>
</value>
</values>
</performance>
</alternativePerformances>
<alternativePerformances>
<alternativeID>b3</alternativeID>
<performance>
<criterionID>cr1</criterionID>
<values>
<value>
<real>30.0</real>
</value>
</values>
</performance>
<performance>
<criterionID>cr2</criterionID>
<values>
<value>
<real>30.0</real>
</value>
</values>
</performance>
</alternativePerformances>
<alternativePerformances>
<alternativeID>b4</alternativeID>
<performance>
<criterionID>cr1</criterionID>
<values>
<value>
<real>40.0</real>
</value>
</values>
</performance>
<performance>
<criterionID>cr2</criterionID>
<values>
<value>
<real>20.0</real>
</value>
</values>
</performance>
</alternativePerformances>
<alternativePerformances>
<alternativeID>b5</alternativeID>
<performance>
<criterionID>cr1</criterionID>
<values>
<value>
<real>50.0</real>
</value>
</values>
</performance>
<performance>
<criterionID>cr2</criterionID>
<values>
<value>
<real>10.0</real>
</value>
</values>
</performance>
</alternativePerformances>
</performanceTable>
</xmcda:XMCDA> | {
"content_hash": "32f82030e3193b5f7d61c08618d0c687",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 142,
"avg_line_length": 33.745098039215684,
"alnum_prop": 0.41167925624636836,
"repo_name": "sbigaret/PrometheeDiviz-maciej7777",
"id": "3d5d7b7022cf02c122149f9192ae8cb0335acccf",
"size": "3442",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "PROMETHEE-I-FlowSort_assignments/tests/in2.v3/performance_table.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "399479"
},
{
"name": "Shell",
"bytes": "15447"
},
{
"name": "TeX",
"bytes": "5088"
}
],
"symlink_target": ""
} |
typedef NS_ENUM(NSUInteger, DDBottomShowComponent)
{
DDInputViewUp = 1,
DDShowKeyboard = 1 << 1,
DDShowEmotion = 1 << 2,
DDShowUtility = 1 << 3
};
typedef NS_ENUM(NSUInteger, DDBottomHiddComponent)
{
DDInputViewDown = 14,
DDHideKeyboard = 13,
DDHideEmotion = 11,
DDHideUtility = 7
};
//
typedef NS_ENUM(NSUInteger, DDInputType)
{
DDVoiceInput,
DDTextInput
};
typedef NS_ENUM(NSUInteger, PanelStatus)
{
VoiceStatus,
TextInputStatus,
EmotionStatus,
ImageStatus
};
#define DDINPUT_MIN_HEIGHT 44.0f
#define DDINPUT_HEIGHT self.chatInputView.size.height
#define DDINPUT_BOTTOM_FRAME CGRectMake(0, CONTENT_HEIGHT - self.chatInputView.height + NAVBAR_HEIGHT,FULL_WIDTH,self.chatInputView.height)
#define DDINPUT_TOP_FRAME CGRectMake(0, CONTENT_HEIGHT - self.chatInputView.height + NAVBAR_HEIGHT - 216, 320, self.chatInputView.height)
#define DDUTILITY_FRAME CGRectMake(0, CONTENT_HEIGHT + NAVBAR_HEIGHT -216, 320, 216)
#define DDEMOTION_FRAME CGRectMake(0, CONTENT_HEIGHT + NAVBAR_HEIGHT-216, 320, 216)
#define DDCOMPONENT_BOTTOM CGRectMake(0, CONTENT_HEIGHT + NAVBAR_HEIGHT, 320, 216)
@interface ChattingMainViewController ()<UIGestureRecognizerDelegate>
@property(nonatomic,assign)CGPoint inputViewCenter;
@property(nonatomic,strong)UIActivityIndicatorView *activity;
@property(assign)PanelStatus panelStatus;
@property(strong)NSString *chatObjectID;
@property(strong)QuickReplyView *replyView;
- (void)recentViewController;
- (UITableViewCell*)p_textCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDMessageEntity*)message;
- (UITableViewCell*)p_voiceCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDMessageEntity*)message;
- (UITableViewCell*)p_promptCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDPromptEntity*)prompt;
- (UITableViewCell*)p_commodityCell_tableView:(UITableView* )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDMessageEntity*)commodity;
- (void)n_receiveMessage:(NSNotification*)notification;
- (void)n_receiveUnreadMessageUpdateNotification:(NSNotification*)notification;
- (void)n_receiveStartLoginNotification:(NSNotification*)notification;
- (void)n_receiveLoginSuccessNotification:(NSNotification*)notification;
- (void)n_receiveLoginFailureNotification:(NSNotification*)notification;
- (void)n_receiveUserKickoffNotification:(NSNotification*)notification;
- (void)p_clickThRecordButton:(UIButton*)button;
- (void)p_record:(UIButton*)button;
- (void)p_willCancelRecord:(UIButton*)button;
- (void)p_cancelRecord:(UIButton*)button;
- (void)p_sendRecord:(UIButton*)button;
- (void)p_endCancelRecord:(UIButton*)button;
- (void)p_tapOnTableView:(UIGestureRecognizer*)sender;
- (void)p_hideBottomComponent;
- (void)p_enableChatFunction;
- (void)p_unableChatFunction;
@end
@implementation ChattingMainViewController
{
TouchDownGestureRecognizer* _touchDownGestureRecognizer;
NSString* _currentInputContent;
UIButton *_recordButton;
DDBottomShowComponent _bottomShowComponent;
float _inputViewY;
NSString* _goodID;
NSString* _shopID;
int _type;
}
+(instancetype )shareInstance
{
static dispatch_once_t onceToken;
static ChattingMainViewController *_sharedManager = nil;
dispatch_once(&onceToken, ^{
_sharedManager = [ChattingMainViewController new];
});
return _sharedManager;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
CGPoint location = [gestureRecognizer locationInView:self.view];
if (CGRectContainsPoint(DDINPUT_BOTTOM_FRAME, location))
{
return NO;
}
return YES;
}
-(void)sendImageMessage:(Photo *)photo
{
NSDictionary* messageContentDic = @{DD_IMAGE_LOCAL_KEY:photo.localPath};
NSString* messageContent = [messageContentDic jsonString];
DDMessageEntity *message = [DDMessageEntity makeMessage:messageContent Module:self.module MsgType:DDMessageTypeImage];
[self.chatInputView.textView setText:nil];
[self.tableView reloadData];
[[DDDatabaseUtil instance] insertMessages:@[message] success:^{
DDLog(@"消息插入DB成功");
} failure:^(NSString *errorDescripe) {
DDLog(@"消息插入DB失败");
}];
[[DDSendPhotoMessageAPI sharedPhotoCache] uploadImage:photo.localPath success:^(NSString *imageURL) {
NSDictionary* tempMessageContent = [NSDictionary initWithJsonString:message.msgContent];
NSMutableDictionary* mutalMessageContent = [[NSMutableDictionary alloc] initWithDictionary:tempMessageContent];
[mutalMessageContent setValue:imageURL forKey:DD_IMAGE_URL_KEY];
NSString* messageContent = [mutalMessageContent jsonString];
message.msgContent = messageContent;
[self sendMessage:imageURL messageEntity:message];
} failure:^(id error) {
message.state = DDMessageSendFailure;
//刷新DB
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
if (result)
{
[self.tableView reloadData];
}
}];
}];
}
- (void)textViewEnterSend
{
//发送消息
NSString* text = [self.chatInputView.textView text];
if ([text length] == 0)
{
return;
}
DDMessageType msgtype = self.module.sessionEntity.sessionType == SESSIONTYPE_SINGLE?DDMessageTypeText:DDGroup_Message_TypeText;
DDMessageEntity *message = [DDMessageEntity makeMessage:text Module:self.module MsgType:msgtype];
[self.chatInputView.textView setText:nil];
[[DDDatabaseUtil instance] insertMessages:@[message] success:^{
DDLog(@"消息插入DB成功");
} failure:^(NSString *errorDescripe) {
DDLog(@"消息插入DB失败");
}];
[self sendMessage:text messageEntity:message];
}
-(void)sendMessage:(NSString *)msg messageEntity:(DDMessageEntity *)message
{
BOOL isGroup = self.module.sessionEntity.sessionType == SESSIONTYPE_SINGLE?NO:YES;
[[DDMessageSendManager instance] sendMessage:msg isGroup:isGroup forSessionID:self.module.sessionEntity.sessionID completion:^(DDMessageEntity* theMessage,NSError *error) {
if (error)
{
DDLog(@"发送消息失败");
//刷新消息所在行
message.state = DDMessageSendFailure;
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
if (result)
{
[self.tableView reloadData];
[self scrollToBottomAnimated:YES];
}
}];
}
else
{
//刷新消息所在行
message.state = DDmessageSendSuccess;
//刷新DB
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
if (result)
{
[self.tableView reloadData];
[self scrollToBottomAnimated:YES];
}
}];
}
}];
}
//--------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark RecordingDelegate
- (void)recordingFinishedWithFileName:(NSString *)filePath time:(NSTimeInterval)interval
{
NSMutableData* muData = [[NSMutableData alloc] init];
NSData* data = [NSData dataWithContentsOfFile:filePath];
int length = [RecorderManager sharedManager].recordedTimeInterval;
if (length < 1 )
{
DDLog(@"录音时间太短");
dispatch_async(dispatch_get_main_queue(), ^{
[_recordingView setHidden:NO];
[_recordingView setRecordingState:DDShowRecordTimeTooShort];
});
return;
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[_recordingView setHidden:YES];
});
}
int8_t ch[4];
for(int32_t i = 0;i<4;i++){
ch[i] = ((length >> ((3 - i)*8)) & 0x0ff);
}
[muData appendBytes:ch length:4];
[muData appendData:data];
DDMessageType msgtype = self.module.sessionEntity.sessionType == SESSIONTYPE_SINGLE?DDMessageTypeVoice:DDGroup_MessageTypeVoice;
DDMessageEntity* message = [DDMessageEntity makeMessage:filePath Module:self.module MsgType:msgtype];
[message.info setObject:@(length) forKey:VOICE_LENGTH];
[message.info setObject:@(1) forKey:DDVOICE_PLAYED];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[[DDDatabaseUtil instance] insertMessages:@[message] success:^{
NSLog(@"消息插入DB成功");
} failure:^(NSString *errorDescripe) {
NSLog(@"消息插入DB失败");
}];
});
[[DDMessageSendManager instance] sendVoiceMessage:muData filePath:filePath forSessionID:self.module.sessionEntity.sessionID completion:^(DDMessageEntity *theMessage, NSError *error) {
if (!error)
{
DDLog(@"发送语音消息成功");
[[PlayerManager sharedManager] playAudioWithFileName:@"msg.caf" playerType:DDSpeaker delegate:self];
message.state = DDmessageSendSuccess;
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
if (result)
{
[self.tableView reloadData];
}
}];
}
else
{
DDLog(@"发送语音消息失败");
message.state = DDMessageSendFailure;
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
if (result)
{
[self.tableView reloadData];
}
}];
}
}];
}
- (void)playingStoped
{
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)notificationCenter
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(n_receiveMessage:)
name:DDNotificationReceiveMessage
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(n_receiveUnreadMessageUpdateNotification:)
name:DDNotificationUpdateUnReadMessage
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(n_receiveStartLoginNotification:) name:DDNotificationStartLogin object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(n_receiveLoginSuccessNotification:)
name:DDNotificationUserLoginSuccess
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(n_receiveLoginFailureNotification:)
name:DDNotificationUserLoginFailure
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(n_receiveUserKickoffNotification:) name:DDNotificationUserKickouted object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleWillShowKeyboard:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleWillHideKeyboard:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self notificationCenter];
[self initialInput];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(p_tapOnTableView:)];
[self.tableView addGestureRecognizer:tap];
UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(p_tapOnTableView:)];
pan.delegate = self;
[self.tableView addGestureRecognizer:pan];
self.tableView.delegate=self;
self.tableView.dataSource=self;
[self scrollToBottomAnimated:NO];
_originalTableViewContentInset = self.tableView.contentInset;
self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.activity.frame=CGRectMake(self.view.frame.size.width/2, 70, 20, 20);
[self.view addSubview:self.activity];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(Edit:)];
self.navigationItem.rightBarButtonItem=item;
[self.module addObserver:self forKeyPath:@"showingMessages" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:NULL];
[self.module addObserver:self forKeyPath:@"sessionEntity.sessionID" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
self.replyView = [QuickReplyView new];
[self.view addSubview:self.replyView];
}
-(IBAction)Edit:(id)sender
{
DDChattingEditViewController *chattingedit = [DDChattingEditViewController new];
chattingedit.session=self.module.sessionEntity;
[self.navigationController pushViewController:chattingedit animated:YES];
}
- (void)back
{
[self.chatInputView.textView resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)scrollToBottomAnimated:(BOOL)animated
{
NSInteger rows = [self.tableView numberOfRowsInSection:0];
if(rows > 0) {
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom
animated:animated];
if(self.tableView.contentOffset.y < -10)
{
//[self.tableView setContentOffset:CGPointMake(0, -10)];
}
}
}
- (ChattingModule*)module
{
if (!_module)
{
_module = [[ChattingModule alloc] init];
}
return _module;
}
#pragma mark -
#pragma mark ActionMethods 发送sendAction 音频 voiceChange 显示表情 disFaceKeyboard
-(IBAction)sendAction:(id)sender{
if (self.chatInputView.textView.text.length>0) {
NSLog(@"点击发送");
[self.chatInputView.textView setText:@""];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
[self.chatInputView.textView setText:nil];
[self.tabBarController.tabBar setHidden:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.chatInputView.textView resignFirstResponder];
[self p_hideBottomComponent];
[self.tabBarController.tabBar setHidden:NO];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
#pragma mark -
#pragma mark UIGesture Delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
if ([gestureRecognizer.view isEqual:_tableView])
{
return YES;
}
return NO;
}
#pragma mark - EmojiFace Funcation
-(void)insertEmojiFace:(NSString *)string
{
NSMutableString* content = [NSMutableString stringWithString:self.chatInputView.textView.text];
[content appendString:string];
[self.chatInputView.textView setText:content];
}
-(void)deleteEmojiFace
{
EmotionsModule* emotionModule = [EmotionsModule shareInstance];
NSString* toDeleteString = nil;
if (self.chatInputView.textView.text.length == 0)
{
return;
}
if (self.chatInputView.textView.text.length == 1)
{
self.chatInputView.textView.text = @"";
}
else
{
toDeleteString = [self.chatInputView.textView.text substringFromIndex:self.chatInputView.textView.text.length - 1];
int length = [emotionModule.emotionLength[toDeleteString] intValue];
if (length == 0)
{
toDeleteString = [self.chatInputView.textView.text substringFromIndex:self.chatInputView.textView.text.length - 2];
length = [emotionModule.emotionLength[toDeleteString] intValue];
}
length = length == 0 ? 1 : length;
self.chatInputView.textView.text = [self.chatInputView.textView.text substringToIndex:self.chatInputView.textView.text.length - length];
}
}
#pragma mark - UITableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.module.showingMessages count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float height = 0;
id object = self.module.showingMessages[indexPath.row];
if ([object isKindOfClass:[DDMessageEntity class]])
{
DDMessageEntity* message = object;
height = [self.module messageHeight:message];
}
else if([object isKindOfClass:[DDPromptEntity class]])
{
height = 30;
}
return height+10;
// return 84;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
id object = self.module.showingMessages[indexPath.row];
UITableViewCell* cell = nil;
if ([object isKindOfClass:[DDMessageEntity class]])
{
DDMessageEntity* message = (DDMessageEntity*)object;
if (message.msgType == DDMessageTypeText || message.msgType == DDGroup_Message_TypeText ) {
cell = [self p_textCell_tableView:tableView cellForRowAtIndexPath:indexPath message:message];
}else if (message.msgType == DDMessageTypeVoice || message.msgType == DDGroup_MessageTypeVoice)
{
cell = [self p_voiceCell_tableView:tableView cellForRowAtIndexPath:indexPath message:message];
}
else if(message.msgType == DDMessageTypeImage)
{
cell = [self p_imageCell_tableView:tableView cellForRowAtIndexPath:indexPath message:message];
}
else
{
cell = [self p_textCell_tableView:tableView cellForRowAtIndexPath:indexPath message:message];
}
}
else if ([object isKindOfClass:[DDPromptEntity class]])
{
DDPromptEntity* prompt = (DDPromptEntity*)object;
cell = [self p_promptCell_tableView:tableView cellForRowAtIndexPath:indexPath message:prompt];
}
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
static BOOL loadingHistory = NO;
if (scrollView.contentOffset.y < -100 && [self.module.showingMessages count] > 0 && !loadingHistory)
{
loadingHistory = YES;
[self.activity startAnimating];
NSString* sessionID = self.module.sessionEntity.sessionID;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.module loadMoreHistoryCompletion:^(NSUInteger addCount,NSError *error) {
loadingHistory = NO;
if ([sessionID isEqualToString:self.module.sessionEntity.sessionID])
{
[_tableView reloadData];
[self.activity stopAnimating];
if ([self.module.showingMessages count] > addCount)
{
[_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:addCount inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
}
}];
});
}
}
#pragma mark PublicAPI
- (void)showChattingContentForSession:(DDSessionEntity*)session
{
self.title = @"正在联系用户";
[self.module.showingMessages removeAllObjects];
self.module.sessionEntity = nil;
[self p_unableChatFunction];
[self p_enableChatFunction];
[self.activity startAnimating];
if (![session.sessionID isEqualToString:self.module.sessionEntity.sessionID])
{
[self.module.showingMessages removeAllObjects];
self.module.sessionEntity = session;
}
[self setTitle:session.name];
NSUInteger unreadMessageCount = [[DDMessageModule shareInstance] getUnreadMessageCountForSessionID:session.sessionID];
if (unreadMessageCount > 0)
{
NSArray* unreadMessages = [[DDMessageModule shareInstance]popAllUnreadMessagesForSessionID:session.sessionID];
[[DDDatabaseUtil instance] insertMessages:unreadMessages success:^{
DDSendMessageReadACKAPI* sendMessageReadACKAPI = [[DDSendMessageReadACKAPI alloc] init];
[sendMessageReadACKAPI requestWithObject:session.sessionID Completion:nil];
} failure:^(NSString *errorDescripe) {
}];
[self.module addShowMessages:unreadMessages];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
[self scrollToBottomAnimated:NO];
});
}
else
{
[self.module loadMoreHistoryCompletion:^(NSUInteger addCount,NSError *error) {
[_tableView reloadData];
if (addCount < DD_PAGE_ITEM_COUNT)
{
[self.activity stopAnimating];
}
else
{
[self scrollToBottomAnimated:NO];
}
}];
}
}
#pragma mark - Text view delegatef
- (void)viewheightChanged:(float)height
{
[self setValue:@(self.chatInputView.origin.y) forKeyPath:@"_inputViewY"];
}
#pragma mark PrivateAPI
- (UITableViewCell*)p_textCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDMessageEntity*)message
{
static NSString* identifier = @"DDChatTextCellIdentifier";
DDChatBaseCell* cell = (DDChatBaseCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell)
{
cell = [[DDChatTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSString* myUserID = [RuntimeStatus instance].user.userId;
if ([message.senderId isEqualToString:myUserID])
{
[cell setLocation:DDBubbleRight];
}
else
{
[cell setLocation:DDBubbleLeft];
}
[cell setContent:message];
__weak DDChatTextCell* weakCell = (DDChatTextCell*)cell;
cell.sendAgain = ^{
[weakCell showSending];
[weakCell sendTextAgain:message];
};
return cell;
}
- (UITableViewCell*)p_voiceCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDMessageEntity*)message
{
static NSString* identifier = @"DDVoiceCellIdentifier";
DDChatBaseCell* cell = (DDChatBaseCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell)
{
cell = [[DDChatVoiceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSString* myUserID = [RuntimeStatus instance].user.userId;
if ([message.senderId isEqualToString:myUserID])
{
[cell setLocation:DDBubbleRight];
}
else
{
[cell setLocation:DDBubbleLeft];
}
[cell setContent:message];
__weak DDChatVoiceCell* weakCell = (DDChatVoiceCell*)cell;
[(DDChatVoiceCell*)cell setTapInBubble:^{
//播放语音
NSString* fileName = message.msgContent;
[[PlayerManager sharedManager] playAudioWithFileName:fileName delegate:self];
[message.info setObject:@(1) forKey:DDVOICE_PLAYED];
[weakCell showVoicePlayed];
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
}];
}];
[(DDChatVoiceCell*)cell setEarphonePlay:^{
//听筒播放
NSString* fileName = message.msgContent;
[[PlayerManager sharedManager] playAudioWithFileName:fileName playerType:DDEarPhone delegate:self];
[message.info setObject:@(1) forKey:DDVOICE_PLAYED];
[weakCell showVoicePlayed];
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
}];
}];
[(DDChatVoiceCell*)cell setSpeakerPlay:^{
//扬声器播放
NSString* fileName = message.msgContent;
[[PlayerManager sharedManager] playAudioWithFileName:fileName playerType:DDSpeaker delegate:self];
[message.info setObject:@(1) forKey:DDVOICE_PLAYED];
[weakCell showVoicePlayed];
[[DDDatabaseUtil instance] updateMessageForMessage:message completion:^(BOOL result) {
}];
}];
[(DDChatVoiceCell *)cell setSendAgain:^{
//重发
[weakCell showSending];
[weakCell sendVoiceAgain:message];
}];
return cell;
}
- (UITableViewCell*)p_promptCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDPromptEntity*)prompt
{
static NSString* identifier = @"DDPromptCellIdentifier";
DDPromptCell* cell = (DDPromptCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell)
{
cell = [[DDPromptCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSString* promptMessage = prompt.message;
[cell setprompt:promptMessage];
return cell;
}
- (UITableViewCell*)p_imageCell_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath message:(DDMessageEntity*)message
{
static NSString* identifier = @"DDImageCellIdentifier";
DDChatImageCell* cell = (DDChatImageCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell)
{
cell = [[DDChatImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSString* myUserID =[RuntimeStatus instance].user.userId;
if ([message.senderId isEqualToString:myUserID])
{
[cell setLocation:DDBubbleRight];
}
else
{
[cell setLocation:DDBubbleLeft];
}
[cell setContent:message];
__weak DDChatImageCell* weakCell = cell;
[cell setSendAgain:^{
[weakCell sendImageAgain:message];
}];
[cell setTapInBubble:^{
[weakCell showPreview];
}];
[cell setPreview:cell.tapInBubble];
return cell;
}
- (void)n_receiveMessage:(NSNotification*)notification
{
if (![self.navigationController.topViewController isEqual:self])
{
//当前不是聊天界面直接返回
return;
}
DDMessageEntity* message = [notification object];
[AnalysisImage analysisImage:message Block:^(NSMutableArray *array) {
for (DDMessageEntity *msg in array) {
NSString *msgID= nil;
if (message.msgType <5) {
msgID = msg.sessionId;
}else
{
msgID =msg.toUserID;
}
if ([msgID isEqualToString:self.module.sessionEntity.sessionID])
{
//显示消息
[[DDSundriesCenter instance] pushTaskToParallelQueue:^{
msg.state=DDmessageSendSuccess;
[self.module addShowMessage:msg];
[self.module updateSessionUpdateTime:msg.msgTime];
[[DDDatabaseUtil instance] updateMessageForMessage:msg completion:^(BOOL result) {
}];
[[DDMessageModule shareInstance] clearUnreadMessagesForSessionID:self.module.sessionEntity.sessionID];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[self scrollToBottomAnimated:YES];
});
if (message.msgType >5) {
DDGroupMsgReadACKAPI *groupACK = [[DDGroupMsgReadACKAPI alloc] init];
[groupACK requestWithObject:self.module.sessionEntity.sessionID Completion:^(id response, NSError *error) {
}];
}else
{
DDSendMessageReadACKAPI* readACKAPI = [[DDSendMessageReadACKAPI alloc] init];
[readACKAPI requestWithObject:self.module.sessionEntity.sessionID Completion:^(id response, NSError *error) {
}];
}
}];
}
else
{
[self.replyView setDescriptionInfo:msg];
// UIImage* image = [UIImage imageNamed:@"dd_has_unread_message"];
// [_recentButton setImage:image forState:UIControlStateNormal];
// //TODO:右上角显示有未读消息
}
}
}];
}
- (void)n_receiveUnreadMessageUpdateNotification:(NSNotification*)notification
{
if (![self.navigationController.topViewController isEqual:self])
{
//当前不是聊天界面直接返回
return;
}
NSString* userID = [notification object];
NSUInteger oldMessageCount = [self.module.showingMessages count];
NSArray* unreadMessage = [[DDMessageModule shareInstance] popAllUnreadMessagesForSessionID:userID];
[self.module.showingMessages addObjectsFromArray:unreadMessage];
NSMutableArray* addIndexpaths = [[NSMutableArray alloc] init];
for (NSUInteger index = 0; index < [unreadMessage count]; index ++)
{
[addIndexpaths addObject:[NSIndexPath indexPathForRow:oldMessageCount + index inSection:0]];
}
[self.tableView insertRowsAtIndexPaths:addIndexpaths withRowAnimation:UITableViewRowAnimationAutomatic];
if (self.module.sessionEntity.sessionType == SESSIONTYPE_SINGLE) {
DDSendMessageReadACKAPI* readACKAPI = [[DDSendMessageReadACKAPI alloc] init];
[readACKAPI requestWithObject:self.module.sessionEntity.sessionID Completion:^(id response, NSError *error) {
}];
}else
{
DDGroupMsgReadACKAPI *groupReadACK = [[DDGroupMsgReadACKAPI alloc] init];
[groupReadACK requestWithObject:self.module.sessionEntity.sessionID Completion:^(id response, NSError *error) {
}];
}
}
- (void)n_receiveStartLoginNotification:(NSNotification*)notification
{
self.title = @"正在连接...";
}
- (void)n_receiveLoginSuccessNotification:(NSNotification*)notification
{
if (self.module.sessionEntity)
self.title = self.module.sessionEntity.name;
}
- (void)n_receiveLoginFailureNotification:(NSNotification*)notification
{
self.title = @"未连接";
}
- (void)n_receiveUserKickoffNotification:(NSNotification*)notification
{
if ([self.navigationController.topViewController isEqual:self])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您的帐号在别处登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"重连", nil];
[alert show];
}
}
- (void)p_clickThRecordButton:(UIButton*)button
{
switch (button.tag) {
case DDVoiceInput:
//开始录音
[self p_hideBottomComponent];
[button setImage:[UIImage imageNamed:@"dd_input_normal"] forState:UIControlStateNormal];
button.tag = DDTextInput;
[self.chatInputView willBeginRecord];
[self.chatInputView.textView resignFirstResponder];
_currentInputContent = self.chatInputView.textView.text;
if ([_currentInputContent length] > 0)
{
[self.chatInputView.textView setText:nil];
}
break;
case DDTextInput:
//开始输入文字
[button setImage:[UIImage imageNamed:@"dd_record_normal"] forState:UIControlStateNormal];
button.tag = DDVoiceInput;
[self.chatInputView willBeginInput];
if ([_currentInputContent length] > 0)
{
[self.chatInputView.textView setText:_currentInputContent];
}
[self.chatInputView.textView becomeFirstResponder];
break;
}
}
- (void)p_record:(UIButton*)button
{
[self.chatInputView.recordButton setHighlighted:YES];
if (![[self.view subviews] containsObject:_recordingView])
{
[self.view addSubview:_recordingView];
}
[_recordingView setHidden:NO];
[_recordingView setRecordingState:DDShowVolumnState];
[[RecorderManager sharedManager] setDelegate:self];
[[RecorderManager sharedManager] startRecording];
DDLog(@"record");
}
- (void)p_willCancelRecord:(UIButton*)button
{
[_recordingView setHidden:NO];
[_recordingView setRecordingState:DDShowCancelSendState];
DDLog(@"will cancel record");
}
- (void)p_cancelRecord:(UIButton*)button
{
[self.chatInputView.recordButton setHighlighted:NO];
[_recordingView setHidden:YES];
[[RecorderManager sharedManager] cancelRecording];
DDLog(@"cancel record");
}
- (void)p_sendRecord:(UIButton*)button
{
[self.chatInputView.recordButton setHighlighted:NO];
[[RecorderManager sharedManager] stopRecording];
DDLog(@"send record");
}
- (void)p_endCancelRecord:(UIButton*)button
{
[_recordingView setHidden:NO];
[_recordingView setRecordingState:DDShowVolumnState];
}
- (void)p_tapOnTableView:(UIGestureRecognizer*)sender
{
if (_bottomShowComponent)
{
[self p_hideBottomComponent];
}
}
- (void)p_hideBottomComponent
{
_bottomShowComponent = _bottomShowComponent & 0;
//隐藏所有
[self.chatInputView.textView resignFirstResponder];
[UIView animateWithDuration:0.25 animations:^{
[self.ddUtility.view setFrame:DDCOMPONENT_BOTTOM];
[self.emotions.view setFrame:DDCOMPONENT_BOTTOM];
[self.chatInputView setFrame:DDINPUT_BOTTOM_FRAME];
}];
DDLog(@"%@",NSStringFromCGRect(DDINPUT_BOTTOM_FRAME));
[self setValue:@(self.chatInputView.origin.y) forKeyPath:@"_inputViewY"];
}
- (void)p_enableChatFunction
{
[self.chatInputView setUserInteractionEnabled:YES];
}
- (void)p_unableChatFunction
{
[self.chatInputView setUserInteractionEnabled:NO];
}
#pragma mark -
#pragma mark DDEmotionViewCOntroller Delegate
- (void)emotionViewClickSendButton
{
[self textViewEnterSend];
}
- (void)recordingTimeout
{
}
- (void)recordingStopped //录音机停止采集声音
{
}
- (void)recordingFailed:(NSString *)failureInfoString
{
}
- (void)levelMeterChanged:(float)levelMeter
{
[_recordingView setVolume:levelMeter];
}
#pragma mark -
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"sessionEntity.sessionID"]) {
if ([change objectForKey:@"new"] !=nil) {
self.title=self.module.sessionEntity.name;
}
}
if ([keyPath isEqualToString:@"showingMessages"]) {
[self.tableView reloadData];
}
if ([keyPath isEqualToString:@"_inputViewY"])
{
if (![change[@"new"] isEqualToNumber:change[@"old"]]) {
float maxY = self.view.height - DDINPUT_MIN_HEIGHT;
float gap = maxY - _inputViewY;
[UIView animateWithDuration:0.25 animations:^{
_tableView.contentInset = UIEdgeInsetsMake(_tableView.contentInset.top, 0, gap, 0);
_tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, gap, 0);
}];
[self scrollToBottomAnimated:YES];
}
}
}
@end
@implementation ChattingMainViewController(ChattingInput)
- (void)initialInput
{
CGRect inputFrame = CGRectMake(0, CONTENT_HEIGHT - DDINPUT_MIN_HEIGHT + NAVBAR_HEIGHT,FULL_WIDTH,DDINPUT_MIN_HEIGHT);
self.chatInputView = [[JSMessageInputView alloc] initWithFrame:inputFrame delegate:self];
[self.chatInputView setBackgroundColor:RGB(249, 249, 249)];
[self.view addSubview:self.chatInputView];
[self.chatInputView.emotionbutton addTarget:self
action:@selector(showEmotions:)
forControlEvents:UIControlEventTouchUpInside];
[self.chatInputView.showUtilitysbutton addTarget:self
action:@selector(showUtilitys:)
forControlEvents:UIControlEventTouchDown];
[self.chatInputView.voiceButton addTarget:self
action:@selector(p_clickThRecordButton:)
forControlEvents:UIControlEventTouchUpInside];
_touchDownGestureRecognizer = [[TouchDownGestureRecognizer alloc] initWithTarget:self action:nil];
__weak ChattingMainViewController* weakSelf = self;
_touchDownGestureRecognizer.touchDown = ^{
[weakSelf p_record:nil];
};
_touchDownGestureRecognizer.moveInside = ^{
[weakSelf p_endCancelRecord:nil];
};
_touchDownGestureRecognizer.moveOutside = ^{
[weakSelf p_willCancelRecord:nil];
};
_touchDownGestureRecognizer.touchEnd = ^(BOOL inside){
if (inside)
{
[weakSelf p_sendRecord:nil];
}
else
{
[weakSelf p_cancelRecord:nil];
}
};
[self.chatInputView.recordButton addGestureRecognizer:_touchDownGestureRecognizer];
_recordingView = [[RecordingView alloc] initWithState:DDShowVolumnState];
[_recordingView setHidden:YES];
[_recordingView setCenter:CGPointMake(self.view.centerX, self.view.centerY)];
[self addObserver:self forKeyPath:@"_inputViewY" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
-(IBAction)showUtilitys:(id)sender
{
[_recordButton setImage:[UIImage imageNamed:@"dd_record_normal"] forState:UIControlStateNormal];
_recordButton.tag = DDVoiceInput;
[self.chatInputView willBeginInput];
if ([_currentInputContent length] > 0)
{
[self.chatInputView.textView setText:_currentInputContent];
}
if (self.ddUtility == nil)
{
self.ddUtility = [ChatUtilityViewController new];
[self addChildViewController:self.ddUtility];
self.ddUtility.view.frame=CGRectMake(0, self.view.size.height,320 , 280);
[self.view addSubview:self.ddUtility.view];
}
if (_bottomShowComponent & DDShowKeyboard)
{
//显示的是键盘,这是需要隐藏键盘,显示插件,不需要动画
_bottomShowComponent = (_bottomShowComponent & 0) | DDShowUtility;
[self.chatInputView.textView resignFirstResponder];
[self.ddUtility.view setFrame:DDUTILITY_FRAME];
[self.emotions.view setFrame:DDCOMPONENT_BOTTOM];
}
else if (_bottomShowComponent & DDShowUtility)
{
//插件面板本来就是显示的,这时需要隐藏所有底部界面
[self p_hideBottomComponent];
_bottomShowComponent = _bottomShowComponent & DDHideUtility;
}
else if (_bottomShowComponent & DDShowEmotion)
{
//显示的是表情,这时需要隐藏表情,显示插件
[self.emotions.view setFrame:DDCOMPONENT_BOTTOM];
[self.ddUtility.view setFrame:DDUTILITY_FRAME];
_bottomShowComponent = (_bottomShowComponent & DDHideEmotion) | DDShowUtility;
}
else
{
//这是什么都没有显示,需用动画显示插件
_bottomShowComponent = _bottomShowComponent | DDShowUtility;
[UIView animateWithDuration:0.25 animations:^{
[self.ddUtility.view setFrame:DDUTILITY_FRAME];
[self.chatInputView setFrame:DDINPUT_TOP_FRAME];
}];
[self setValue:@(DDINPUT_TOP_FRAME.origin.y) forKeyPath:@"_inputViewY"];
}
}
-(IBAction)showEmotions:(id)sender
{
[_recordButton setImage:[UIImage imageNamed:@"dd_record_normal"] forState:UIControlStateNormal];
_recordButton.tag = DDVoiceInput;
[self.chatInputView willBeginInput];
if ([_currentInputContent length] > 0)
{
[self.chatInputView.textView setText:_currentInputContent];
}
if (self.emotions == nil) {
self.emotions = [EmotionsViewController new];
[self.emotions.view setBackgroundColor:[UIColor darkGrayColor]];
self.emotions.view.frame=DDCOMPONENT_BOTTOM;
self.emotions.delegate = self;
[self.view addSubview:self.emotions.view];
}
if (_bottomShowComponent & DDShowKeyboard)
{
//显示的是键盘,这是需要隐藏键盘,显示表情,不需要动画
_bottomShowComponent = (_bottomShowComponent & 0) | DDShowEmotion;
[self.chatInputView.textView resignFirstResponder];
[self.emotions.view setFrame:DDEMOTION_FRAME];
[self.ddUtility.view setFrame:DDCOMPONENT_BOTTOM];
}
else if (_bottomShowComponent & DDShowUtility)
{
//显示的是插件,这时需要隐藏插件,显示表情
[self.ddUtility.view setFrame:DDCOMPONENT_BOTTOM];
[self.emotions.view setFrame:DDEMOTION_FRAME];
_bottomShowComponent = (_bottomShowComponent & DDHideUtility) | DDShowEmotion;
}
else
{
//这是什么都没有显示,需用动画显示表情
_bottomShowComponent = _bottomShowComponent | DDShowEmotion;
[UIView animateWithDuration:0.25 animations:^{
[self.emotions.view setFrame:DDEMOTION_FRAME];
[self.chatInputView setFrame:DDINPUT_TOP_FRAME];
}];
[self setValue:@(DDINPUT_TOP_FRAME.origin.y) forKeyPath:@"_inputViewY"];
}
}
#pragma mark - KeyBoardNotification
- (void)handleWillShowKeyboard:(NSNotification *)notification
{
CGRect keyboardRect;
keyboardRect = [(notification.userInfo)[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
_bottomShowComponent = _bottomShowComponent | DDShowKeyboard;
//什么都没有显示
[UIView animateWithDuration:0.25 animations:^{
[self.chatInputView setFrame:CGRectMake(0, keyboardRect.origin.y - DDINPUT_HEIGHT, self.view.size.width, DDINPUT_HEIGHT)];
}];
[self setValue:@(keyboardRect.origin.y - DDINPUT_HEIGHT) forKeyPath:@"_inputViewY"];
}
- (void)handleWillHideKeyboard:(NSNotification *)notification
{
CGRect keyboardRect;
keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
_bottomShowComponent = _bottomShowComponent & DDHideKeyboard;
if (_bottomShowComponent & DDShowUtility)
{
//显示的是插件
[UIView animateWithDuration:0.25 animations:^{
[self.chatInputView setFrame:DDINPUT_TOP_FRAME];
}];
[self setValue:@(self.chatInputView.origin.y) forKeyPath:@"_inputViewY"];
}
else if (_bottomShowComponent & DDShowEmotion)
{
//显示的是表情
[UIView animateWithDuration:0.25 animations:^{
[self.chatInputView setFrame:DDINPUT_TOP_FRAME];
}];
[self setValue:@(self.chatInputView.origin.y) forKeyPath:@"_inputViewY"];
}
else
{
[self p_hideBottomComponent];
}
}
@end
| {
"content_hash": "c4a9793f89b9e5f514aff2a7c7917939",
"timestamp": "",
"source": "github",
"line_count": 1219,
"max_line_length": 187,
"avg_line_length": 35.96390484003281,
"alnum_prop": 0.6521441605839416,
"repo_name": "zhaiqingchao/TTiOSClient",
"id": "01f176bc02d69071c7dad571a9b293fca7f32a80",
"size": "45410",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "TeamTalk/IOSDuoduo/VC/Chatting/ChattingMainViewController.m",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.5.4.11_A1_T11;
* @section: 15.5.4.11;
* @assertion: String.prototype.replace (searchValue, replaceValue);
* @description: Call replace (searchValue, replaceValue) function with objects arguments of string object. Objects have overrided toString function, that throw exception;
*/
var __obj = {toString:function(){throw "insearchValue";}};
var __obj2 = {toString:function(){throw "inreplaceValue";}};
var __str = {str__:"ABB\u0041BABAB"};
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
with(__str){
with(str__){
try {
var x = replace(__obj,__obj2);
$FAIL('#1: "var x = replace(__obj,__obj2)" lead to throwing exception');
} catch (e) {
if (e!=="insearchValue") {
$ERROR('#1.1: Exception === "insearchValue". Actual: '+e);
}
}
}
}
//
//////////////////////////////////////////////////////////////////////////////
| {
"content_hash": "4383e2fa65e56d1d2fc8f91cc6cb5060",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 170,
"avg_line_length": 36.3,
"alnum_prop": 0.527089072543618,
"repo_name": "seraum/nectarjs",
"id": "1520b02fb11c909aaaa45258f3163e5f9e347bbd",
"size": "1089",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.5_String_Objects/15.5.4_Properties_of_the_String_Prototype_Object/15.5.4.11_String.prototype.replace/S15.5.4.11_A1_T11.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "122"
},
{
"name": "CSS",
"bytes": "28166"
},
{
"name": "HTML",
"bytes": "43809"
},
{
"name": "JavaScript",
"bytes": "55917"
},
{
"name": "Python",
"bytes": "35"
},
{
"name": "TypeScript",
"bytes": "45"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="PalindromeTest" default="default" basedir=".">
<description>Builds, tests, and runs the project PalindromeTest.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="PalindromeTest-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>
| {
"content_hash": "126e5220d97a8aa579a947eff126e723",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 86,
"avg_line_length": 49.68493150684932,
"alnum_prop": 0.6421284808381582,
"repo_name": "JmoIST331Repo/EX-5.3",
"id": "10be89deaf9ea42c247435ef7acb4bce9bc8d647",
"size": "3627",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PalindromeTest/build.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "6839"
}
],
"symlink_target": ""
} |
package de.techdev.springtest;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.springframework.test.web.servlet.ResultActions;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Matchers to be used in {@link de.techdev.springtest.AbstractResourceTest}.
*
* @author Moritz Schulze
*/
public class DomainResourceTestMatchers {
private DomainResourceTestMatchers() {
}
/**
* Functional interface for a consumer that can throw an exception.
* @param <T> The type to consume.
*/
@FunctionalInterface
private static interface ConsumerWithException<T> {
public void accept(T item) throws Exception;
}
private static class ResultActionsMatcher extends TypeSafeMatcher<ResultActions> {
private String description;
private ConsumerWithException<ResultActions> test;
protected ResultActionsMatcher(String description, ConsumerWithException<ResultActions> test) {
this.description = description;
this.test = test;
}
@Override
protected boolean matchesSafely(ResultActions item) {
try {
test.accept(item);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText(this.description);
}
}
/**
* @return Matcher that checks if the HTTP status is 200.
*/
public static Matcher<? super ResultActions> isAccessible() {
return new ResultActionsMatcher("accessible", resultActions -> {
resultActions
.andExpect(status().isOk());
});
}
/**
* @return Matcher that checks if the HTTP status is 201 and the "id" field in the returned JSON is not null.
*/
public static Matcher<? super ResultActions> isCreated() {
return new ResultActionsMatcher("created", resultActions -> {
resultActions
.andExpect(status().isCreated());
});
}
/**
* @return Matcher that checks if the HTTP status is 403.
*/
public static Matcher<? super ResultActions> isForbidden() {
return new ResultActionsMatcher("forbidden", resultActions -> {
resultActions.andExpect(status().isForbidden());
});
}
/**
* @return Matcher that checks if the HTTP status is 200 and the "id" field in the returned JSON is not null.
*/
public static Matcher<? super ResultActions> isUpdated() {
return new ResultActionsMatcher("updated", resultActions -> {
resultActions
.andExpect(status().isOk());
});
}
/**
* @return Matcher that checks if the HTTP status is 204.
*/
public static Matcher<? super ResultActions> isNoContent() {
return new ResultActionsMatcher("no content", resultActions -> {
resultActions
.andExpect(status().isNoContent());
});
}
/**
* @return Matcher that checks if the HTTP status is 405.
*/
public static Matcher<? super ResultActions> isMethodNotAllowed() {
return new ResultActionsMatcher("method not allowed", resultActions -> {
resultActions
.andExpect(status().isMethodNotAllowed());
});
}
}
| {
"content_hash": "58cf7156df4397df3f6468128144c9a6",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 113,
"avg_line_length": 31.339285714285715,
"alnum_prop": 0.621937321937322,
"repo_name": "techdev-solutions/spring-test-example",
"id": "cc25d2af2e628fb3dcb24c0e60d62e71be0f173a",
"size": "3510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/de/techdev/springtest/DomainResourceTestMatchers.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "1388"
},
{
"name": "Java",
"bytes": "33016"
},
{
"name": "Shell",
"bytes": "7394"
}
],
"symlink_target": ""
} |
@implementation M3uContainer
#pragma mark - ORMGContainer
+ (NSArray *)fileTypes {
return @[@"m3u"];
}
+ (NSArray *)urlsForContainerURL:(NSURL*)url {
NSStringEncoding encoding;
NSError *error = nil;
NSString *contents = [NSString stringWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
if (error) {
error = nil;
contents = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
}
if (error) {
error = nil;
contents = [NSString stringWithContentsOfURL:url
encoding:NSWindowsCP1251StringEncoding
error:&error];
}
if (error) {
error = nil;
contents = [NSString stringWithContentsOfURL:url
encoding:NSISOLatin1StringEncoding
error:&error];
}
if (error || !contents) {
return nil;
}
NSMutableArray *entries = [NSMutableArray array];
NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for (NSString *line in [contents componentsSeparatedByString:@"\n"]) {
NSString *entry = [line stringByTrimmingCharactersInSet:charSet];
if ([entry hasPrefix:@"#"] || [entry isEqualToString:@""])
continue;
[entries addObject:[self urlForPath:entry relativeTo:url]];
}
return entries;
}
#pragma mark - private
+ (NSURL *)urlForPath:(NSString *)path relativeTo:(NSURL *)baseFileUrl {
NSRange protocolRange = [path rangeOfString:@"://"];
if (protocolRange.location != NSNotFound) {
return [NSURL URLWithString:path];
}
NSURL *baseUrl = baseFileUrl.URLByDeletingLastPathComponent;
return [baseUrl URLByAppendingPathComponent:path];
}
@end
| {
"content_hash": "761205e8b587907f36983421ef397c1f",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 82,
"avg_line_length": 33.74576271186441,
"alnum_prop": 0.5715720743345053,
"repo_name": "ardenfire/SonanEngine",
"id": "b483bdd116b1eeac06198dd54d691e6061b284ec",
"size": "3160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SonanEngine/Plugins/M3uContainer.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "216958"
},
{
"name": "Ruby",
"bytes": "3183"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>io.grpc:grpc-testing</name>
<description>gRPC: Testing</description>
<url>https://github.com/grpc/grpc-java</url>
<licenses>
<license>
<name>BSD 3-Clause</name>
<url>http://opensource.org/licenses/BSD-3-Clause</url>
</license>
</licenses>
<developers>
<developer>
<id>grpc.io</id>
<name>gRPC Contributors</name>
<email>[email protected]</email>
<url>http://grpc.io/</url>
<organization>Google, Inc.</organization>
<organizationUrl>https://www.google.com</organizationUrl>
</developer>
</developers>
<scm>
<connection>scm:svn:https://github.com/grpc/grpc-java.git</connection>
<developerConnection>scm:svn:[email protected]:grpc/grpc-java.git</developerConnection>
<url>https://github.com/grpc/grpc-java</url>
</scm>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-core</artifactId>
<version>0.1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "616cf982f97bf2196002b90e82374ca0",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 149,
"avg_line_length": 34,
"alnum_prop": 0.6578054298642534,
"repo_name": "dhwanishah9/Lab2",
"id": "c53f8951d23f2aa153e799fe714b361947b88daf",
"size": "1768",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "testing/build/poms/pom-default.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "27373"
},
{
"name": "Java",
"bytes": "958813"
},
{
"name": "Protocol Buffer",
"bytes": "20358"
},
{
"name": "Shell",
"bytes": "1396"
}
],
"symlink_target": ""
} |
Installation
============
1. Using Composer (recommended)
-------------------------------
To install JMSPaymentCoreBundle with Composer just add the following to your
`composer.json` file:
.. code-block :: js
// composer.json
{
// ...
require: {
// ...
"jms/payment-core-bundle": "master-dev"
}
}
.. note ::
Please replace `master-dev` in the snippet above with the latest stable
branch, for example ``1.0.*``.
Then, you can install the new dependencies by running Composer's ``update``
command from the directory where your ``composer.json`` file is located:
.. code-block :: bash
$ php composer.phar update
Now, Composer will automatically download all required files, and install them
for you. All that is left to do is to update your ``AppKernel.php`` file, and
register the new bundle:
.. code-block :: php
<?php
// in AppKernel::registerBundles()
$bundles = array(
// ...
new JMS\Payment\CoreBundle\JMSPaymentCoreBundle(),
// ...
);
2. Using the ``deps`` file (Symfony 2.0.x)
------------------------------------------
First, checkout a copy of the code. Just add the following to the ``deps``
file of your Symfony Standard Distribution:
.. code-block :: ini
[JMSPaymentCoreBundle]
git=git://github.com/schmittjoh/JMSPaymentCoreBundle.git
target=bundles/JMS/Payment/CoreBundle
Then register the bundle with your kernel:
.. code-block :: php
<?php
// in AppKernel::registerBundles()
$bundles = array(
// ...
new JMS\PaymentCoreBundle\JMSPaymentCoreBundle(),
// ...
);
Make sure that you also register the namespace with the autoloader:
.. code-block :: php
<?php
// app/autoload.php
$loader->registerNamespaces(array(
// ...
'JMS' => __DIR__.'/../vendor/bundles',
// ...
));
Now use the ``vendors`` script to clone the newly added repositories
into your project:
.. code-block :: bash
$ php bin/vendors install
| {
"content_hash": "2f9fe071e72bee081fd4dd3e18d6d4e2",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 78,
"avg_line_length": 22.978021978021978,
"alnum_prop": 0.5949306551889049,
"repo_name": "wolfoux/soleil",
"id": "bc3a5374ae87c744a29dc157cb5ac7cfc5ea7f0b",
"size": "2091",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/jms/payment-core-bundle/JMS/Payment/CoreBundle/Resources/doc/installation.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "371512"
},
{
"name": "Java",
"bytes": "147372"
},
{
"name": "JavaScript",
"bytes": "263161"
},
{
"name": "PHP",
"bytes": "3178100"
},
{
"name": "Perl",
"bytes": "9844"
},
{
"name": "Python",
"bytes": "3299"
},
{
"name": "Shell",
"bytes": "139949"
},
{
"name": "Slash",
"bytes": "309072"
},
{
"name": "XSLT",
"bytes": "221100"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2015 The Android Open Source Project
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.
-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="together" >
<objectAnimator
android:duration="@android:integer/config_longAnimTime"
android:propertyName="translationX"
android:valueFrom="@dimen/lb_guidedstep_slide_start_distance"
android:valueTo="0.0"
android:valueType="floatType" />
<objectAnimator
android:duration="@android:integer/config_longAnimTime"
android:propertyName="alpha"
android:valueFrom="0.0"
android:valueTo="1.0"
android:valueType="floatType" />
</set>
| {
"content_hash": "95d6d162cb2513d7a3ae445ef0f755b3",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 77,
"avg_line_length": 37.529411764705884,
"alnum_prop": 0.6927899686520376,
"repo_name": "ycdev-aosp/sdk-support",
"id": "3c01324f9a08c812dc7386a9ba2043dacb4dcb77",
"size": "1276",
"binary": false,
"copies": "3",
"ref": "refs/heads/demo-build",
"path": "v17/leanback/res/animator/lb_guidedstep_slide_in_from_start.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2380"
},
{
"name": "Java",
"bytes": "3044972"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE supplementalData SYSTEM "../../common/dtd/ldmlSupplemental.dtd">
<!--
Copyright © 1991-2013 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<supplementalData>
<version number="$Revision: 8242 $"/>
<generation date="$Date: 2013-02-24 21:06:02 -0600 (Sun, 24 Feb 2013) $"/>
<transforms>
<transform source="Malayalam" target="Kannada" direction="forward">
<tRule>::[ം-ഃഅ-ഌഎ-ഐഒ-നപ-ഹാ-ൃെ-ൈൊ-്ൗൠ-ൡ൦-൯];</tRule>
<tRule>::NFD;</tRule>
<tRule>::Malayalam-InterIndic;</tRule>
<tRule>::InterIndic-Kannada;</tRule>
<tRule>::NFC;</tRule>
</transform>
</transforms>
</supplementalData>
| {
"content_hash": "65e003914a1ec10d18ec40b1ffe7dfc8",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 102,
"avg_line_length": 37.142857142857146,
"alnum_prop": 0.676923076923077,
"repo_name": "haakonsk/O2-Framework",
"id": "dad5258bf72321372ad028c01ca20f9099391f82",
"size": "823",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "var/resources/cldr/common/transforms/Malayalam-Kannada.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "321037"
},
{
"name": "CSS",
"bytes": "83670"
},
{
"name": "Emacs Lisp",
"bytes": "140999"
},
{
"name": "JavaScript",
"bytes": "1127586"
},
{
"name": "PHP",
"bytes": "1316824"
},
{
"name": "Perl",
"bytes": "1879776"
},
{
"name": "Prolog",
"bytes": "1284"
},
{
"name": "Rebol",
"bytes": "350"
},
{
"name": "Shell",
"bytes": "1220"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "5071052c06647e6b365d9a02f023d5ae",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "6b62ff384b1cd30bf07249b7869179f75608c3df",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Jonthlaspi/Jonthlaspi cyclodonteum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.carbondata.core.util;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.carbondata.core.datastore.block.SegmentProperties;
import org.apache.carbondata.core.datastore.page.EncodedTablePage;
import org.apache.carbondata.core.datastore.page.encoding.ColumnPageEncoderMeta;
import org.apache.carbondata.core.datastore.page.encoding.EncodedColumnPage;
import org.apache.carbondata.core.datastore.page.key.TablePageKey;
import org.apache.carbondata.core.datastore.page.statistics.PrimitivePageStatsCollector;
import org.apache.carbondata.core.metadata.ValueEncoderMeta;
import org.apache.carbondata.core.metadata.index.BlockIndexInfo;
import org.apache.carbondata.format.BlockIndex;
import org.apache.carbondata.format.BlockletIndex;
import org.apache.carbondata.format.BlockletInfo;
import org.apache.carbondata.format.BlockletInfo3;
import org.apache.carbondata.format.BlockletMinMaxIndex;
import org.apache.carbondata.format.ColumnSchema;
import org.apache.carbondata.format.DataChunk;
import org.apache.carbondata.format.DataChunk2;
import org.apache.carbondata.format.DataType;
import org.apache.carbondata.format.Encoding;
import org.apache.carbondata.format.FileFooter3;
import org.apache.carbondata.format.IndexHeader;
import org.apache.carbondata.format.SegmentInfo;
import mockit.Mock;
import mockit.MockUp;
import org.junit.BeforeClass;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.convertFileFooterVersion3;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getBlockIndexInfo;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getBlockletIndex;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getIndexHeader;
public class CarbonMetadataUtilTest {
static List<ByteBuffer> byteBufferList;
static byte[] byteArr;
static List<ColumnSchema> columnSchemas;
static List<BlockletInfo> blockletInfoList;
static List<ColumnSchema> columnSchemaList;
static Long[] objMaxArr;
static Long[] objMinArr;
static int[] objDecimal;
@BeforeClass public static void setUp() {
objMaxArr = new Long[6];
objMaxArr[0] = new Long("111111");
objMaxArr[1] = new Long("121111");
objMaxArr[2] = new Long("131111");
objMaxArr[3] = new Long("141111");
objMaxArr[4] = new Long("151111");
objMaxArr[5] = new Long("161111");
objMinArr = new Long[6];
objMinArr[0] = new Long("119");
objMinArr[1] = new Long("121");
objMinArr[2] = new Long("131");
objMinArr[3] = new Long("141");
objMinArr[4] = new Long("151");
objMinArr[5] = new Long("161");
objDecimal = new int[] { 0, 0, 0, 0, 0, 0 };
columnSchemaList = new ArrayList<>();
List<Encoding> encodingList = new ArrayList<>();
encodingList.add(Encoding.BIT_PACKED);
encodingList.add(Encoding.DELTA);
encodingList.add(Encoding.INVERTED_INDEX);
encodingList.add(Encoding.DIRECT_DICTIONARY);
byteArr = "412111".getBytes();
byte[] byteArr1 = "321".getBytes();
byte[] byteArr2 = "356".getBytes();
byteBufferList = new ArrayList<>();
ByteBuffer bb = ByteBuffer.allocate(byteArr.length);
bb.put(byteArr);
ByteBuffer bb1 = ByteBuffer.allocate(byteArr1.length);
bb1.put(byteArr1);
ByteBuffer bb2 = ByteBuffer.allocate(byteArr2.length);
bb2.put(byteArr2);
byteBufferList.add(bb);
byteBufferList.add(bb1);
byteBufferList.add(bb2);
DataChunk dataChunk = new DataChunk();
dataChunk.setEncoders(encodingList);
dataChunk.setEncoder_meta(byteBufferList);
List<DataChunk> dataChunkList = new ArrayList<>();
dataChunkList.add(dataChunk);
dataChunkList.add(dataChunk);
BlockletInfo blockletInfo = new BlockletInfo();
blockletInfo.setColumn_data_chunks(dataChunkList);
blockletInfoList = new ArrayList<>();
blockletInfoList.add(blockletInfo);
blockletInfoList.add(blockletInfo);
ValueEncoderMeta meta = CarbonTestUtil.createValueEncoderMeta();
meta.setDecimal(5);
meta.setMinValue(objMinArr);
meta.setMaxValue(objMaxArr);
meta.setType(ColumnPageEncoderMeta.DOUBLE_MEASURE);
List<Encoding> encoders = new ArrayList<>();
encoders.add(Encoding.INVERTED_INDEX);
encoders.add(Encoding.BIT_PACKED);
encoders.add(Encoding.DELTA);
encoders.add(Encoding.DICTIONARY);
encoders.add(Encoding.DIRECT_DICTIONARY);
encoders.add(Encoding.RLE);
ColumnSchema columnSchema = new ColumnSchema(DataType.INT, "column", "3", true, encoders, true);
ColumnSchema columnSchema1 =
new ColumnSchema(DataType.ARRAY, "column", "3", true, encoders, true);
ColumnSchema columnSchema2 =
new ColumnSchema(DataType.DECIMAL, "column", "3", true, encoders, true);
ColumnSchema columnSchema3 =
new ColumnSchema(DataType.DOUBLE, "column", "3", true, encoders, true);
ColumnSchema columnSchema4 =
new ColumnSchema(DataType.LONG, "column", "3", true, encoders, true);
ColumnSchema columnSchema5 =
new ColumnSchema(DataType.SHORT, "column", "3", true, encoders, true);
ColumnSchema columnSchema6 =
new ColumnSchema(DataType.STRUCT, "column", "3", true, encoders, true);
ColumnSchema columnSchema7 =
new ColumnSchema(DataType.STRING, "column", "3", true, encoders, true);
columnSchemas = new ArrayList<>();
columnSchemas.add(columnSchema);
columnSchemas.add(columnSchema1);
columnSchemas.add(columnSchema2);
columnSchemas.add(columnSchema3);
columnSchemas.add(columnSchema4);
columnSchemas.add(columnSchema5);
columnSchemas.add(columnSchema6);
columnSchemas.add(columnSchema7);
}
@Test public void testGetIndexHeader() {
int[] columnCardinality = { 1, 2, 3, 4 };
SegmentInfo segmentInfo = new SegmentInfo();
segmentInfo.setNum_cols(0);
segmentInfo.setColumn_cardinalities(CarbonUtil.convertToIntegerList(columnCardinality));
IndexHeader indexHeader = new IndexHeader();
indexHeader.setVersion(3);
indexHeader.setSegment_info(segmentInfo);
indexHeader.setTable_columns(columnSchemaList);
indexHeader.setBucket_id(0);
IndexHeader indexheaderResult = getIndexHeader(columnCardinality, columnSchemaList, 0);
assertEquals(indexHeader, indexheaderResult);
}
@Test public void testConvertFileFooter() throws Exception {
int[] cardinality = { 1, 2, 3, 4, 5 };
org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema colSchema =
new org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema();
org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema colSchema1 =
new org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema();
List<org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema>
columnSchemaList = new ArrayList<>();
columnSchemaList.add(colSchema);
columnSchemaList.add(colSchema1);
SegmentProperties segmentProperties = new SegmentProperties(columnSchemaList, cardinality);
final EncodedColumnPage measure = new EncodedColumnPage(new DataChunk2(), new byte[]{0,1},
PrimitivePageStatsCollector.newInstance(
org.apache.carbondata.core.metadata.datatype.DataType.BYTE, 0, 0));
new MockUp<EncodedTablePage>() {
@SuppressWarnings("unused") @Mock
public EncodedColumnPage getMeasure(int measureIndex) {
return measure;
}
};
new MockUp<TablePageKey>() {
@SuppressWarnings("unused") @Mock
public byte[] serializeStartKey() {
return new byte[]{1, 2};
}
@SuppressWarnings("unused") @Mock
public byte[] serializeEndKey() {
return new byte[]{1, 2};
}
};
TablePageKey key = new TablePageKey(3, null, segmentProperties, false);
EncodedTablePage encodedTablePage = EncodedTablePage.newInstance(3, new EncodedColumnPage[0], new EncodedColumnPage[0],
key);
List<EncodedTablePage> encodedTablePageList = new ArrayList<>();
encodedTablePageList.add(encodedTablePage);
BlockletInfo3 blockletInfoColumnar1 = new BlockletInfo3();
List<BlockletInfo3> blockletInfoColumnarList = new ArrayList<>();
blockletInfoColumnarList.add(blockletInfoColumnar1);
byte[] byteMaxArr = "1".getBytes();
byte[] byteMinArr = "2".getBytes();
BlockletIndex index = getBlockletIndex(encodedTablePageList, segmentProperties.getMeasures());
List<BlockletIndex> indexList = new ArrayList<>();
indexList.add(index);
BlockletMinMaxIndex blockletMinMaxIndex = new BlockletMinMaxIndex();
blockletMinMaxIndex.addToMax_values(ByteBuffer.wrap(byteMaxArr));
blockletMinMaxIndex.addToMin_values(ByteBuffer.wrap(byteMinArr));
FileFooter3 footer = convertFileFooterVersion3(blockletInfoColumnarList,
indexList,
cardinality, 2);
assertEquals(footer.getBlocklet_index_list(), indexList);
}
@Test public void testGetBlockIndexInfo() throws Exception {
byte[] startKey = { 1, 2, 3, 4, 5 };
byte[] endKey = { 9, 3, 5, 5, 5 };
byte[] byteArr = { 1, 2, 3, 4, 5 };
List<ByteBuffer> minList = new ArrayList<>();
minList.add(ByteBuffer.wrap(byteArr));
byte[] byteArr1 = { 9, 9, 8, 6, 7 };
List<ByteBuffer> maxList = new ArrayList<>();
maxList.add(ByteBuffer.wrap(byteArr1));
org.apache.carbondata.core.metadata.blocklet.index.BlockletMinMaxIndex
blockletMinMaxIndex =
new org.apache.carbondata.core.metadata.blocklet.index.BlockletMinMaxIndex(minList,
maxList);
org.apache.carbondata.core.metadata.blocklet.index.BlockletBTreeIndex
blockletBTreeIndex =
new org.apache.carbondata.core.metadata.blocklet.index.BlockletBTreeIndex(startKey,
endKey);
org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex blockletIndex =
new org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex(
blockletBTreeIndex, blockletMinMaxIndex);
BlockIndexInfo blockIndexInfo = new BlockIndexInfo(1, "file", 1, blockletIndex);
List<BlockIndexInfo> blockIndexInfoList = new ArrayList<>();
blockIndexInfoList.add(blockIndexInfo);
List<BlockIndex> result = getBlockIndexInfo(blockIndexInfoList);
String expected = "file";
assertEquals(result.get(0).file_name, expected);
}
}
| {
"content_hash": "bfec64c203f623142e47bb393d26b2e0",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 123,
"avg_line_length": 40.298449612403104,
"alnum_prop": 0.7340579013176878,
"repo_name": "aniketadnaik/carbondataStreamIngest",
"id": "35b45ca483a9657be57e79dd023aa7bc4a196f00",
"size": "11197",
"binary": false,
"copies": "1",
"ref": "refs/heads/streaming_ingest",
"path": "core/src/test/java/org/apache/carbondata/core/util/CarbonMetadataUtilTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4889080"
},
{
"name": "Python",
"bytes": "19915"
},
{
"name": "Scala",
"bytes": "6633539"
},
{
"name": "Shell",
"bytes": "3008"
},
{
"name": "Smalltalk",
"bytes": "86"
},
{
"name": "Thrift",
"bytes": "21635"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Proc. Amer. Acad. Arts & Sci. 5: 399 (1862)
#### Original name
Physcidia Tuck.
### Remarks
null | {
"content_hash": "69da3ba4593a5095f34c5bf07c73a81e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 14.153846153846153,
"alnum_prop": 0.6793478260869565,
"repo_name": "mdoering/backbone",
"id": "00d97af1f69bc3db11b93f42c9d971f33073665a",
"size": "221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Physcidia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import Immutable from "immutable";
import alt from "alt-instance";
import GatewayActions from "actions/GatewayActions";
import ls from "common/localStorage";
const STORAGE_KEY = "__graphene__";
let ss = new ls(STORAGE_KEY);
class GatewayStore {
constructor() {
this.backedCoins = Immutable.Map(ss.get("backedCoins", {}));
this.bridgeCoins = Immutable.Map(
Immutable.fromJS(ss.get("bridgeCoins", {}))
);
/**
* bridgeInputs limits the available depositable coins through blocktrades
* when using the "Buy" functionaility.
*
* While the application still makes sure the asset is possible to deposit,
* this is to limit the app to display internal assets like bit-assets that
* BlockTrades accept within their platform.
*/
this.bridgeInputs = [
"btc",
"dash",
"eth",
"steem",
"sbd",
"doge",
"bch",
"ppy",
"ltc"
];
this.down = Immutable.Map({});
this.bindListeners({
onFetchCoins: GatewayActions.fetchCoins,
onFetchCoinsSimple: GatewayActions.fetchCoinsSimple,
onFetchPairs: GatewayActions.fetchPairs
});
}
onFetchCoins({backer, coins, backedCoins, down} = {}) {
if (backer && coins) {
this.backedCoins = this.backedCoins.set(backer, backedCoins);
ss.set("backedCoins", this.backedCoins.toJS());
this.down = this.down.set(backer, false);
}
if (down) {
this.down = this.down.set(down, true);
}
}
onFetchCoinsSimple({backer, coins, down} = {}) {
if (backer && coins) {
this.backedCoins = this.backedCoins.set(backer, coins);
ss.set("backedCoins", this.backedCoins.toJS());
this.down = this.down.set(backer, false);
}
if (down) {
this.down = this.down.set(down, true);
}
}
onFetchPairs({coins, bridgeCoins, wallets, down} = {}) {
if (coins && bridgeCoins && wallets) {
let coins_by_type = {};
coins.forEach(
coin_type => (coins_by_type[coin_type.coinType] = coin_type)
);
bridgeCoins = bridgeCoins
.filter(a => {
return (
a &&
coins_by_type[a.outputCoinType] &&
(coins_by_type[a.outputCoinType].walletType ===
"bitshares2" && // Only use bitshares2 wallet types
this.bridgeInputs.indexOf(a.inputCoinType) !== -1) // Only use coin types defined in bridgeInputs
);
})
.forEach(coin => {
coin.isAvailable =
wallets.indexOf(
coins_by_type[coin.outputCoinType].walletType
) !== -1;
this.bridgeCoins = this.bridgeCoins.setIn(
[
coins_by_type[coin.outputCoinType].walletSymbol,
coin.inputCoinType
],
Immutable.fromJS(coin)
);
});
ss.set("bridgeCoins", this.bridgeCoins.toJS());
}
if (down) {
this.down = this.down.set(down, true);
}
}
}
export default alt.createStore(GatewayStore, "GatewayStore");
| {
"content_hash": "767f617a9fc87a41e6feccc8cd102cdf",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 125,
"avg_line_length": 33.2962962962963,
"alnum_prop": 0.49860956618464963,
"repo_name": "BitSharesEurope/graphene-ui-testnet",
"id": "84f016dcb6a337fe881cd34b9d5645cd8e3cb95d",
"size": "3596",
"binary": false,
"copies": "3",
"ref": "refs/heads/testnet",
"path": "app/stores/GatewayStore.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "63946"
},
{
"name": "CoffeeScript",
"bytes": "2701"
},
{
"name": "GCC Machine Description",
"bytes": "1327"
},
{
"name": "HTML",
"bytes": "3263"
},
{
"name": "JavaScript",
"bytes": "1814194"
},
{
"name": "NSIS",
"bytes": "3767"
},
{
"name": "Objective-C",
"bytes": "2789"
},
{
"name": "Python",
"bytes": "1188"
},
{
"name": "Shell",
"bytes": "187"
}
],
"symlink_target": ""
} |
namespace LINQSamples
{
using System;
using System.Collections.Generic;
public partial class Employee
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Employee()
{
this.EmployeeDepartmentHistories = new HashSet<EmployeeDepartmentHistory>();
this.EmployeePayHistories = new HashSet<EmployeePayHistory>();
this.JobCandidates = new HashSet<JobCandidate>();
this.PurchaseOrderHeaders = new HashSet<PurchaseOrderHeader>();
}
public int BusinessEntityID { get; set; }
public string NationalIDNumber { get; set; }
public string LoginID { get; set; }
public Nullable<short> OrganizationLevel { get; set; }
public string JobTitle { get; set; }
public System.DateTime BirthDate { get; set; }
public string MaritalStatus { get; set; }
public string Gender { get; set; }
public System.DateTime HireDate { get; set; }
public bool SalariedFlag { get; set; }
public short VacationHours { get; set; }
public short SickLeaveHours { get; set; }
public bool CurrentFlag { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Person Person { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EmployeePayHistory> EmployeePayHistories { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<JobCandidate> JobCandidates { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; }
public virtual SalesPerson SalesPerson { get; set; }
}
}
| {
"content_hash": "b79d6404da3ebd21e0b30399866a4ca3",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 128,
"avg_line_length": 53.31818181818182,
"alnum_prop": 0.6930946291560103,
"repo_name": "SudhersonV/DotNetRoot",
"id": "659c1381fa41e364ad2893ce09ce211c52eb0194",
"size": "2770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SampleCode/LINQSamples/Employee.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "2638"
},
{
"name": "Batchfile",
"bytes": "17"
},
{
"name": "C#",
"bytes": "2181546"
},
{
"name": "CSS",
"bytes": "310234"
},
{
"name": "HTML",
"bytes": "508222"
},
{
"name": "JavaScript",
"bytes": "594509"
},
{
"name": "Pascal",
"bytes": "109532"
},
{
"name": "PowerShell",
"bytes": "451694"
},
{
"name": "Puppet",
"bytes": "25968"
}
],
"symlink_target": ""
} |
( function() {
if ( !jQuery.fn.offset ) {
return;
}
var supportsScroll, supportsFixedPosition,
forceScroll = jQuery( "<div/>" ).css( { width: 2000, height: 2000 } ),
checkSupport = function() {
// Only run once
checkSupport = false;
var checkFixed = jQuery( "<div/>" ).css( { position: "fixed", top: "20px" } ).appendTo( "#qunit-fixture" );
// Must append to body because #qunit-fixture is hidden and elements inside it don't have a scrollTop
forceScroll.appendTo( "body" );
window.scrollTo( 200, 200 );
supportsScroll = document.documentElement.scrollTop || document.body.scrollTop;
forceScroll.detach();
supportsFixedPosition = checkFixed[ 0 ].offsetTop === 20;
checkFixed.remove();
};
QUnit.module( "offset", { setup: function() {
if ( typeof checkSupport === "function" ) {
checkSupport();
}
// Force a scroll value on the main window to ensure incorrect results
// if offset is using the scroll offset of the parent window
forceScroll.appendTo( "body" );
window.scrollTo( 1, 1 );
forceScroll.detach();
}, teardown: moduleTeardown } );
/*
Closure-compiler will roll static methods off of the jQuery object and so they will
not be passed with the jQuery object across the windows. To differentiate this, the
testIframe callbacks use the "$" symbol to refer to the jQuery object passed from
the iframe window and the "jQuery" symbol is used to access any static methods.
*/
QUnit.test( "empty set", function( assert ) {
assert.expect( 2 );
assert.strictEqual( jQuery().offset(), undefined, "offset() returns undefined for empty set (#11962)" );
assert.strictEqual( jQuery().position(), undefined, "position() returns undefined for empty set (#11962)" );
} );
QUnit.test( "object without getBoundingClientRect", function( assert ) {
assert.expect( 2 );
// Simulates a browser without gBCR on elements, we just want to return 0,0
var result = jQuery( { ownerDocument: document } ).offset();
assert.equal( result.top, 0, "Check top" );
assert.equal( result.left, 0, "Check left" );
} );
QUnit.test( "disconnected node", function( assert ) {
assert.expect( 2 );
var result = jQuery( document.createElement( "div" ) ).offset();
// These tests are solely for 2.x/1.x consistency
// Retrieving offset on disconnected/hidden elements is not officially
// valid input, but will return zeros for back-compat
assert.equal( result.top, 0, "Check top" );
assert.equal( result.left, 0, "Check left" );
} );
QUnit.test( "hidden (display: none) element", function( assert ) {
assert.expect( 2 );
var node = jQuery( "<div style='display: none' />" ).appendTo( "#qunit-fixture" ),
result = node.offset();
node.remove();
// These tests are solely for 2.x/1.x consistency
// Retrieving offset on disconnected/hidden elements is not officially
// valid input, but will return zeros for back-compat
assert.equal( result.top, 0, "Retrieving offset on hidden elements returns zeros (gh-2310)" );
assert.equal( result.left, 0, "Retrieving offset on hidden elements returns zeros (gh-2310)" );
} );
testIframe( "offset/absolute", "absolute", function( $, iframe, document, assert ) {
assert.expect( 4 );
var doc = iframe.document,
tests;
// get offset
tests = [
{ "id": "#absolute-1", "top": 1, "left": 1 }
];
jQuery.each( tests, function() {
assert.equal( jQuery( this[ "id" ], doc ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset().top" );
assert.equal( jQuery( this[ "id" ], doc ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset().left" );
} );
// get position
tests = [
{ "id": "#absolute-1", "top": 0, "left": 0 }
];
jQuery.each( tests, function() {
assert.equal( jQuery( this[ "id" ], doc ).position().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').position().top" );
assert.equal( jQuery( this[ "id" ], doc ).position().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').position().left" );
} );
} );
testIframe( "offset/absolute", "absolute", function( $, window, document, assert ) {
assert.expect( 178 );
var tests, offset;
// get offset tests
tests = [
{ "id": "#absolute-1", "top": 1, "left": 1 },
{ "id": "#absolute-1-1", "top": 5, "left": 5 },
{ "id": "#absolute-1-1-1", "top": 9, "left": 9 },
{ "id": "#absolute-2", "top": 20, "left": 20 }
];
jQuery.each( tests, function() {
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset().top" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset().left" );
} );
// get position
tests = [
{ "id": "#absolute-1", "top": 0, "left": 0 },
{ "id": "#absolute-1-1", "top": 1, "left": 1 },
{ "id": "#absolute-1-1-1", "top": 1, "left": 1 },
{ "id": "#absolute-2", "top": 19, "left": 19 }
];
jQuery.each( tests, function() {
assert.equal( $( this[ "id" ] ).position().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').position().top" );
assert.equal( $( this[ "id" ] ).position().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').position().left" );
} );
// test #5781
offset = $( "#positionTest" ).offset( { "top": 10, "left": 10 } ).offset();
assert.equal( offset.top, 10, "Setting offset on element with position absolute but 'auto' values." );
assert.equal( offset.left, 10, "Setting offset on element with position absolute but 'auto' values." );
// set offset
tests = [
{ "id": "#absolute-2", "top": 30, "left": 30 },
{ "id": "#absolute-2", "top": 10, "left": 10 },
{ "id": "#absolute-2", "top": -1, "left": -1 },
{ "id": "#absolute-2", "top": 19, "left": 19 },
{ "id": "#absolute-1-1-1", "top": 15, "left": 15 },
{ "id": "#absolute-1-1-1", "top": 5, "left": 5 },
{ "id": "#absolute-1-1-1", "top": -1, "left": -1 },
{ "id": "#absolute-1-1-1", "top": 9, "left": 9 },
{ "id": "#absolute-1-1", "top": 10, "left": 10 },
{ "id": "#absolute-1-1", "top": 0, "left": 0 },
{ "id": "#absolute-1-1", "top": -1, "left": -1 },
{ "id": "#absolute-1-1", "top": 5, "left": 5 },
{ "id": "#absolute-1", "top": 2, "left": 2 },
{ "id": "#absolute-1", "top": 0, "left": 0 },
{ "id": "#absolute-1", "top": -1, "left": -1 },
{ "id": "#absolute-1", "top": 1, "left": 1 }
];
jQuery.each( tests, function() {
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ] } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset({ top: " + this[ "top" ] + " })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset({ left: " + this[ "left" ] + " })" );
var top = this[ "top" ], left = this[ "left" ];
$( this[ "id" ] ).offset( function( i, val ) {
assert.equal( val.top, top, "Verify incoming top position." );
assert.equal( val.left, left, "Verify incoming top position." );
return { "top": top + 1, "left": left + 1 };
} );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ top: " + ( this[ "top" ] + 1 ) + " })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ left: " + ( this[ "left" ] + 1 ) + " })" );
$( this[ "id" ] )
.offset( { "left": this[ "left" ] + 2 } )
.offset( { "top": this[ "top" ] + 2 } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ] + 2, "Setting one property at a time." );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ] + 2, "Setting one property at a time." );
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ], "using": function( props ) {
$( this ).css( {
"top": props.top + 1,
"left": props.left + 1
} );
} } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ top: " + ( this[ "top" ] + 1 ) + ", using: fn })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ left: " + ( this[ "left" ] + 1 ) + ", using: fn })" );
} );
} );
testIframe( "offset/relative", "relative", function( $, window, document, assert ) {
assert.expect( 64 );
// get offset
var tests = [
{ "id": "#relative-1", "top": 7, "left": 7 },
{ "id": "#relative-1-1", "top": 15, "left": 15 },
{ "id": "#relative-2", "top": 142, "left": 27 },
{ "id": "#relative-2-1", "top": 149, "left": 52 }
];
jQuery.each( tests, function() {
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset().top" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset().left" );
} );
// get position
tests = [
{ "id": "#relative-1", "top": 6, "left": 6 },
{ "id": "#relative-1-1", "top": 5, "left": 5 },
{ "id": "#relative-2", "top": 141, "left": 26 },
{ "id": "#relative-2-1", "top": 5, "left": 5 }
];
jQuery.each( tests, function() {
assert.equal( $( this[ "id" ] ).position().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').position().top" );
assert.equal( $( this[ "id" ] ).position().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').position().left" );
} );
// set offset
tests = [
{ "id": "#relative-2", "top": 200, "left": 50 },
{ "id": "#relative-2", "top": 100, "left": 10 },
{ "id": "#relative-2", "top": -5, "left": -5 },
{ "id": "#relative-2", "top": 142, "left": 27 },
{ "id": "#relative-1-1", "top": 100, "left": 100 },
{ "id": "#relative-1-1", "top": 5, "left": 5 },
{ "id": "#relative-1-1", "top": -1, "left": -1 },
{ "id": "#relative-1-1", "top": 15, "left": 15 },
{ "id": "#relative-1", "top": 100, "left": 100 },
{ "id": "#relative-1", "top": 0, "left": 0 },
{ "id": "#relative-1", "top": -1, "left": -1 },
{ "id": "#relative-1", "top": 7, "left": 7 }
];
jQuery.each( tests, function() {
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ] } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset({ top: " + this[ "top" ] + " })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset({ left: " + this[ "left" ] + " })" );
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ], "using": function( props ) {
$( this ).css( {
"top": props.top + 1,
"left": props.left + 1
} );
} } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ top: " + ( this[ "top" ] + 1 ) + ", using: fn })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ left: " + ( this[ "left" ] + 1 ) + ", using: fn })" );
} );
} );
testIframe( "offset/static", "static", function( $, window, document, assert ) {
assert.expect( 80 );
// get offset
var tests = [
{ "id": "#static-1", "top": 7, "left": 7 },
{ "id": "#static-1-1", "top": 15, "left": 15 },
{ "id": "#static-1-1-1", "top": 23, "left": 23 },
{ "id": "#static-2", "top": 122, left: 7 }
];
jQuery.each( tests, function() {
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset().top" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset().left" );
} );
// get position
tests = [
{ "id": "#static-1", "top": 6, "left": 6 },
{ "id": "#static-1-1", "top": 14, "left": 14 },
{ "id": "#static-1-1-1", "top": 22, "left": 22 },
{ "id": "#static-2", "top": 121, "left": 6 }
];
jQuery.each( tests, function() {
assert.equal( $( this[ "id" ] ).position().top, this[ "top" ], "jQuery('" + this[ "top" ] + "').position().top" );
assert.equal( $( this[ "id" ] ).position().left, this[ "left" ], "jQuery('" + this[ "left" ] + "').position().left" );
} );
// set offset
tests = [
{ "id": "#static-2", "top": 200, "left": 200 },
{ "id": "#static-2", "top": 100, "left": 100 },
{ "id": "#static-2", "top": -2, "left": -2 },
{ "id": "#static-2", "top": 121, "left": 6 },
{ "id": "#static-1-1-1", "top": 50, "left": 50 },
{ "id": "#static-1-1-1", "top": 10, "left": 10 },
{ "id": "#static-1-1-1", "top": -1, "left": -1 },
{ "id": "#static-1-1-1", "top": 22, "left": 22 },
{ "id": "#static-1-1", "top": 25, "left": 25 },
{ "id": "#static-1-1", "top": 10, "left": 10 },
{ "id": "#static-1-1", "top": -3, "left": -3 },
{ "id": "#static-1-1", "top": 14, "left": 14 },
{ "id": "#static-1", "top": 30, "left": 30 },
{ "id": "#static-1", "top": 2, "left": 2 },
{ "id": "#static-1", "top": -2, "left": -2 },
{ "id": "#static-1", "top": 7, "left": 7 }
];
jQuery.each( tests, function() {
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ] } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset({ top: " + this[ "top" ] + " })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset({ left: " + this[ "left" ] + " })" );
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ], "using": function( props ) {
$( this ).css( {
"top": props.top + 1,
"left": props.left + 1
} );
} } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ top: " + ( this[ "top" ] + 1 ) + ", using: fn })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ left: " + ( this[ "left" ] + 1 ) + ", using: fn })" );
} );
} );
testIframe( "offset/fixed", "fixed", function( $, window, document, assert ) {
assert.expect( 34 );
var tests, $noTopLeft;
tests = [
{
"id": "#fixed-1",
"offsetTop": 1001,
"offsetLeft": 1001,
"positionTop": 0,
"positionLeft": 0
},
{
"id": "#fixed-2",
"offsetTop": 1021,
"offsetLeft": 1021,
"positionTop": 20,
"positionLeft": 20
}
];
jQuery.each( tests, function() {
if ( !window.supportsScroll ) {
assert.ok( true, "Browser doesn't support scroll position." );
assert.ok( true, "Browser doesn't support scroll position." );
assert.ok( true, "Browser doesn't support scroll position." );
assert.ok( true, "Browser doesn't support scroll position." );
} else if ( window.supportsFixedPosition ) {
assert.equal( $( this[ "id" ] ).offset().top, this[ "offsetTop" ], "jQuery('" + this[ "id" ] + "').offset().top" );
assert.equal( $( this[ "id" ] ).position().top, this[ "positionTop" ], "jQuery('" + this[ "id" ] + "').position().top" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "offsetLeft" ], "jQuery('" + this[ "id" ] + "').offset().left" );
assert.equal( $( this[ "id" ] ).position().left, this[ "positionLeft" ], "jQuery('" + this[ "id" ] + "').position().left" );
} else {
// need to have same number of assertions
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
}
} );
tests = [
{ "id": "#fixed-1", "top": 100, "left": 100 },
{ "id": "#fixed-1", "top": 0, "left": 0 },
{ "id": "#fixed-1", "top": -4, "left": -4 },
{ "id": "#fixed-2", "top": 200, "left": 200 },
{ "id": "#fixed-2", "top": 0, "left": 0 },
{ "id": "#fixed-2", "top": -5, "left": -5 }
];
jQuery.each( tests, function() {
if ( window.supportsFixedPosition ) {
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ] } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ], "jQuery('" + this[ "id" ] + "').offset({ top: " + this[ "top" ] + " })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ], "jQuery('" + this[ "id" ] + "').offset({ left: " + this[ "left" ] + " })" );
$( this[ "id" ] ).offset( { "top": this[ "top" ], "left": this[ "left" ], "using": function( props ) {
$( this ).css( {
"top": props.top + 1,
"left": props.left + 1
} );
} } );
assert.equal( $( this[ "id" ] ).offset().top, this[ "top" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ top: " + ( this[ "top" ] + 1 ) + ", using: fn })" );
assert.equal( $( this[ "id" ] ).offset().left, this[ "left" ] + 1, "jQuery('" + this[ "id" ] + "').offset({ left: " + ( this[ "left" ] + 1 ) + ", using: fn })" );
} else {
// need to have same number of assertions
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
}
} );
// Bug 8316
$noTopLeft = $( "#fixed-no-top-left" );
if ( window.supportsFixedPosition ) {
assert.equal( $noTopLeft.offset().top, 1007, "Check offset top for fixed element with no top set" );
assert.equal( $noTopLeft.offset().left, 1007, "Check offset left for fixed element with no left set" );
} else {
// need to have same number of assertions
assert.ok( true, "Fixed position is not supported" );
assert.ok( true, "Fixed position is not supported" );
}
} );
testIframe( "offset/table", "table", function( $, window, document, assert ) {
assert.expect( 4 );
assert.equal( $( "#table-1" ).offset().top, 6, "jQuery('#table-1').offset().top" );
assert.equal( $( "#table-1" ).offset().left, 6, "jQuery('#table-1').offset().left" );
assert.equal( $( "#th-1" ).offset().top, 10, "jQuery('#th-1').offset().top" );
assert.equal( $( "#th-1" ).offset().left, 10, "jQuery('#th-1').offset().left" );
} );
testIframe( "offset/scroll", "scroll", function( $, win, doc, assert ) {
assert.expect( 24 );
assert.equal( $( "#scroll-1" ).offset().top, 7, "jQuery('#scroll-1').offset().top" );
assert.equal( $( "#scroll-1" ).offset().left, 7, "jQuery('#scroll-1').offset().left" );
assert.equal( $( "#scroll-1-1" ).offset().top, 11, "jQuery('#scroll-1-1').offset().top" );
assert.equal( $( "#scroll-1-1" ).offset().left, 11, "jQuery('#scroll-1-1').offset().left" );
// These tests are solely for 2.x/1.x consistency
// Retrieving offset on disconnected/hidden elements is not officially
// valid input, but will return zeros for back-compat
// assert.equal( $( "#hidden" ).offset().top, 0, "Hidden elements do not subtract scroll" );
// assert.equal( $( "#hidden" ).offset().left, 0, "Hidden elements do not subtract scroll" );
// scroll offset tests .scrollTop/Left
assert.equal( $( "#scroll-1" ).scrollTop(), 5, "jQuery('#scroll-1').scrollTop()" );
assert.equal( $( "#scroll-1" ).scrollLeft(), 5, "jQuery('#scroll-1').scrollLeft()" );
assert.equal( $( "#scroll-1-1" ).scrollTop(), 0, "jQuery('#scroll-1-1').scrollTop()" );
assert.equal( $( "#scroll-1-1" ).scrollLeft(), 0, "jQuery('#scroll-1-1').scrollLeft()" );
// scroll method chaining
assert.equal( $( "#scroll-1" ).scrollTop( undefined ).scrollTop(), 5, ".scrollTop(undefined) is chainable (#5571)" );
assert.equal( $( "#scroll-1" ).scrollLeft( undefined ).scrollLeft(), 5, ".scrollLeft(undefined) is chainable (#5571)" );
win.name = "test";
if ( !window.supportsScroll ) {
assert.ok( true, "Browser doesn't support scroll position." );
assert.ok( true, "Browser doesn't support scroll position." );
assert.ok( true, "Browser doesn't support scroll position." );
assert.ok( true, "Browser doesn't support scroll position." );
} else {
assert.equal( $( win ).scrollTop(), 1000, "jQuery(window).scrollTop()" );
assert.equal( $( win ).scrollLeft(), 1000, "jQuery(window).scrollLeft()" );
assert.equal( $( win.document ).scrollTop(), 1000, "jQuery(document).scrollTop()" );
assert.equal( $( win.document ).scrollLeft(), 1000, "jQuery(document).scrollLeft()" );
}
// test jQuery using parent window/document
// jQuery reference here is in the iframe
// Support: Android 2.3 only
// Android 2.3 is sometimes off by a few pixels.
window.scrollTo( 0, 0 );
if ( /android 2\.3/i.test( navigator.userAgent ) ) {
assert.ok(
Math.abs( $( window ).scrollTop() ) < 5,
"jQuery(window).scrollTop() other window"
);
} else {
assert.equal( $( window ).scrollTop(), 0, "jQuery(window).scrollTop() other window" );
}
assert.equal( $( window ).scrollLeft(), 0, "jQuery(window).scrollLeft() other window" );
if ( /android 2\.3/i.test( navigator.userAgent ) ) {
assert.ok(
Math.abs( $( window ).scrollTop() ) < 5,
"jQuery(window).scrollTop() other document"
);
} else {
assert.equal( $( document ).scrollTop(), 0, "jQuery(window).scrollTop() other document" );
}
assert.equal( $( document ).scrollLeft(), 0, "jQuery(window).scrollLeft() other document" );
// Tests scrollTop/Left with empty jquery objects
assert.notEqual( $().scrollTop( 100 ), null, "jQuery().scrollTop(100) testing setter on empty jquery object" );
assert.notEqual( $().scrollLeft( 100 ), null, "jQuery().scrollLeft(100) testing setter on empty jquery object" );
assert.notEqual( $().scrollTop( null ), null, "jQuery().scrollTop(null) testing setter on empty jquery object" );
assert.notEqual( $().scrollLeft( null ), null, "jQuery().scrollLeft(null) testing setter on empty jquery object" );
assert.strictEqual( $().scrollTop(), undefined, "jQuery().scrollTop() testing getter on empty jquery object" );
assert.strictEqual( $().scrollLeft(), undefined, "jQuery().scrollLeft() testing getter on empty jquery object" );
} );
testIframe( "offset/body", "body", function( $, window, document, assert ) {
assert.expect( 4 );
assert.equal( $( "body" ).offset().top, 1, "jQuery('#body').offset().top" );
assert.equal( $( "body" ).offset().left, 1, "jQuery('#body').offset().left" );
assert.equal( $( "#firstElement" ).position().left, 5, "$('#firstElement').position().left" );
assert.equal( $( "#firstElement" ).position().top, 5, "$('#firstElement').position().top" );
} );
QUnit.test( "chaining", function( assert ) {
assert.expect( 3 );
var coords = { "top": 1, "left": 1 };
assert.equal( jQuery("#absolute-1").offset(coords).selector, "#absolute-1", "offset(coords) returns jQuery object" );
assert.equal( jQuery("#non-existent").offset(coords).selector, "#non-existent", "offset(coords) with empty jQuery set returns jQuery object" );
assert.equal( jQuery("#absolute-1").offset(undefined).selector, "#absolute-1", "offset(undefined) returns jQuery object (#5571)" );
});
QUnit.test( "offsetParent", function( assert ) {
assert.expect( 13 );
var body, header, div, area;
body = jQuery( "body" ).offsetParent();
assert.equal( body.length, 1, "Only one offsetParent found." );
assert.equal( body[ 0 ], document.documentElement, "The html element is the offsetParent of the body." );
header = jQuery( "#qunit" ).offsetParent();
assert.equal( header.length, 1, "Only one offsetParent found." );
assert.equal( header[ 0 ], document.documentElement, "The html element is the offsetParent of #qunit." );
div = jQuery( "#nothiddendivchild" ).offsetParent();
assert.equal( div.length, 1, "Only one offsetParent found." );
assert.equal( div[ 0 ], document.getElementById( "qunit-fixture" ), "The #qunit-fixture is the offsetParent of #nothiddendivchild." );
jQuery( "#nothiddendiv" ).css( "position", "relative" );
div = jQuery( "#nothiddendivchild" ).offsetParent();
assert.equal( div.length, 1, "Only one offsetParent found." );
assert.equal( div[ 0 ], jQuery( "#nothiddendiv" )[ 0 ], "The div is the offsetParent." );
div = jQuery( "body, #nothiddendivchild" ).offsetParent();
assert.equal( div.length, 2, "Two offsetParent found." );
assert.equal( div[ 0 ], document.documentElement, "The html element is the offsetParent of the body." );
assert.equal( div[ 1 ], jQuery( "#nothiddendiv" )[ 0 ], "The div is the offsetParent." );
area = jQuery( "#imgmap area" ).offsetParent();
assert.equal( area[ 0 ], document.documentElement, "The html element is the offsetParent of the body." );
div = jQuery( "<div>" ).css( { "position": "absolute" } ).appendTo( "body" );
assert.equal( div.offsetParent()[ 0 ], document.documentElement, "Absolutely positioned div returns html as offset parent, see #12139" );
div.remove();
} );
QUnit.test( "fractions (see #7730 and #7885)", function( assert ) {
assert.expect( 2 );
jQuery( "body" ).append( "<div id='fractions'/>" );
var result,
expected = { "top": 1000, "left": 1000 },
div = jQuery( "#fractions" );
div.css( {
"position": "absolute",
"left": "1000.7432222px",
"top": "1000.532325px",
"width": 100,
"height": 100
} );
div.offset( expected );
result = div.offset();
// Support: Chrome 45-46+
// In recent Chrome these values differ a little.
assert.ok( Math.abs( result.top - expected.top ) < 0.25, "Check top within 0.25 of expected" );
assert.equal( result.left, expected.left, "Check left" );
div.remove();
} );
QUnit.test( "iframe scrollTop/Left (see gh-1945)", function( assert ) {
assert.expect( 2 );
var ifDoc = jQuery( "#iframe" )[ 0 ].contentDocument;
// Mobile Safari and Android 2.3 resize the iframe by its content
// meaning it's not possible to scroll the iframe only its parent element.
// It seems (not confirmed) in android 4.0 it's not possible to scroll iframes from the code.
// Opera 12.1x also has problems with this test.
if ( /iphone os/i.test( navigator.userAgent ) ||
/android 2\.3/i.test( navigator.userAgent ) ||
/android 4\.0/i.test( navigator.userAgent ) ||
/opera.*version\/12\.1/i.test( navigator.userAgent ) ) {
assert.equal( true, true, "Can't scroll iframes in this environment" );
assert.equal( true, true, "Can't scroll iframes in this environment" );
} else {
// Tests scrollTop/Left with iframes
jQuery( "#iframe" ).css( "width", "50px" ).css( "height", "50px" );
ifDoc.write( "<div style='width: 1000px; height: 1000px;'></div>" );
jQuery( ifDoc ).scrollTop( 200 );
jQuery( ifDoc ).scrollLeft( 500 );
assert.equal( jQuery( ifDoc ).scrollTop(), 200, "$($('#iframe')[0].contentDocument).scrollTop()" );
assert.equal( jQuery( ifDoc ).scrollLeft(), 500, "$($('#iframe')[0].contentDocument).scrollLeft()" );
}
} );
} )();
| {
"content_hash": "4c8468f60496ce696471f021fe417473",
"timestamp": "",
"source": "github",
"line_count": 606,
"max_line_length": 165,
"avg_line_length": 43.693069306930695,
"alnum_prop": 0.567792129314903,
"repo_name": "jacobSingh/allbackgammongroup",
"id": "cacfe675035067fe30c5334e28e95149a2c7475d",
"size": "26478",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "bower_components/jquery/test/unit/offset.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "13908"
},
{
"name": "HTML",
"bytes": "288401"
},
{
"name": "JavaScript",
"bytes": "639042"
},
{
"name": "Jupyter Notebook",
"bytes": "61352"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "86884"
},
{
"name": "Shell",
"bytes": "1043"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Ann. Sci. Nat. , Bot. sér. 2, 16:91, t. 7. 1841
#### Original name
null
### Remarks
null | {
"content_hash": "214adc9f7181a381a5b0e7465c5530a0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 13,
"alnum_prop": 0.6568047337278107,
"repo_name": "mdoering/backbone",
"id": "b71661dd98079c7620ef1bb03ae939e05212fc6f",
"size": "219",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Monoporus/Monoporus paludosus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
const { dest, src } = require('gulp')
const browserSync = require('browser-sync')
const changed = require('gulp-changed')
const config = require('../config').images
const handleErrors = require('../utilities/handle-errors')
const plumber = require('gulp-plumber')
// Task
function images () {
browserSync.notify('Rebuilding Images…')
return src(config.src)
.pipe(plumber({ errorHandler: handleErrors }))
.pipe(changed(config.dest))
.pipe(dest(config.dest))
}
module.exports = images
| {
"content_hash": "47a5b89ead112af904c54f95be49311e",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 58,
"avg_line_length": 28.27777777777778,
"alnum_prop": 0.7072691552062869,
"repo_name": "cbracco/rapid-website-boilerplate",
"id": "de0001b0d4e90183468858ac60d276461606369a",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gulpfile.js/tasks/images.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "109"
},
{
"name": "JavaScript",
"bytes": "11304"
}
],
"symlink_target": ""
} |
const int default_font_width = 8;
const int default_font_height = 12;
const uint8_t default_font[][default_font_height] = {
#include "generated/default-font-data.txt"
};
| {
"content_hash": "14296095402fe6ec73143151d3a4d807",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 53,
"avg_line_length": 34.2,
"alnum_prop": 0.7309941520467836,
"repo_name": "satgo1546/frogimine",
"id": "5ce4da1ee021f21de8291cba3d78d8a25c6bf482",
"size": "1359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/default-font.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "8740"
},
{
"name": "Awk",
"bytes": "2314"
},
{
"name": "C++",
"bytes": "45395"
},
{
"name": "Makefile",
"bytes": "3168"
},
{
"name": "PHP",
"bytes": "3434"
}
],
"symlink_target": ""
} |
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.stdole;
import com.wilutions.com.*;
/**
* OLE_YPOS_CONTAINER.
*
*/
@SuppressWarnings("all")
public class OLE_YPOS_CONTAINER {
static boolean __typelib__loaded = __TypeLib.load();
private Float value;
public OLE_YPOS_CONTAINER() {}
public OLE_YPOS_CONTAINER(Float v) { this.value = value; }
public Float getValue() { return value; }
public void setValue(Float v) { value = v;}
}
| {
"content_hash": "0f3f4db1ce308dbf8c9c699aed61fa6b",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 60,
"avg_line_length": 28.470588235294116,
"alnum_prop": 0.6528925619834711,
"repo_name": "wolfgangimig/joa",
"id": "0cd5474aa26d36905cb611efb06c06f2f834b7b6",
"size": "484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/joa/src-gen/com/wilutions/mslib/stdole/OLE_YPOS_CONTAINER.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1296"
},
{
"name": "CSS",
"bytes": "792"
},
{
"name": "HTML",
"bytes": "1337"
},
{
"name": "Java",
"bytes": "9952275"
},
{
"name": "VBScript",
"bytes": "338"
}
],
"symlink_target": ""
} |
(function() {
var ownerDocument = document.currentScript.ownerDocument;
var eventCard = Object.create(HTMLElement.prototype);
/**
* The element has been attached to the DOM, update the structure.
*
* Kris: This probably wouldn't even be necessary if we configured the
* attributeChangedCallback correctly.
*
* @return {[type]} [description]
*/
eventCard.attachedCallback = function() {
var model = {
eventName: this.getAttribute("name"),
eventSourceId: this.getAttribute("sourceId"),
eventDuration: this.getAttribute("duration"),
eventType: this.getAttribute("type") === "APPLICATION" ? "APP" : "CMP",
eventCaller: this.getAttribute("caller"),
parameters: this.getAttribute("parameters")//,
// handledBy: this.getAttribute("handledBy"),
// handledByTree: this.getAttribute("handledByTree")
};
// remove markup:// from the event name if present
if(model.eventName.startsWith("markup://")) {
model.eventName = model.eventName.substr(9);
}
// I'm still working on what the best pattern is here
// This seems sloppy
this.shadowRoot.querySelector("h1").textContent = model.eventName;
this.shadowRoot.querySelector("h6").textContent = model.eventType;
this.shadowRoot.querySelector(".caller").textContent = model.eventCaller;
this.shadowRoot.querySelector("#eventDuration").textContent = model.eventDuration+"ms";
this.shadowRoot.querySelector(".parameters").textContent = model.parameters;
var collapsed = this.getAttribute("collapsed");
if(collapsed === "true" || collapsed === "collapsed") {
var section = this.shadowRoot.querySelector("section");
section.classList.add("hidden");
}
var source = this.shadowRoot.querySelector("#eventSource");
if(model.eventSourceId) {
var auracomponent = document.createElement("aurainspector-auracomponent");
auracomponent.setAttribute("globalId", model.eventSourceId);
source.appendChild(auracomponent);
} else {
source.classList.add("hidden");
}
};
/*
New Action Card created, update it's body
*/
eventCard.createdCallback = function(){
var template = ownerDocument.querySelector("template");
var clone = document.importNode(template.content, true);
var shadowRoot = this.createShadowRoot();
shadowRoot.appendChild(clone);
var toggleButton = shadowRoot.querySelector("#gridToggle");
toggleButton.addEventListener("click", ToggleButton_OnClick.bind(this));
};
eventCard.attributeChangedCallback = function(attr, oldValue, newValue) {
if(attr === "collapsed") {
var section = this.shadowRoot.querySelector("section");
var isCollapsed = this.isCollapsed();
if(newValue === "true" || newValue === "collapsed" && !isCollapsed) {
section.classList.add("hidden");
} else if(newValue !== "true" && newValue !== "collapsed" && isCollapsed) {
section.classList.remove("hidden");
renderHandledBy(this);
if(this.getAttribute("showGrid") === "true") {
renderHandledByTree(this);
}
}
}
if(attr === "showgrid" || attr === "showGrid") {
if(newValue === "true") {
renderHandledByTree(this);
} else {
this.shadowRoot.querySelector("#eventHandledByGrid").classList.add("hidden");
}
}
};
eventCard.isCollapsed = function() {
return this.shadowRoot.querySelector("section").classList.contains("hidden");
};
var eventCardConstructor = document.registerElement('aurainspector-eventCard', {
prototype: eventCard
});
function renderHandledBy(element) {
var data = getData(element.getAttribute("handledBy"));
var handledContainer = element.shadowRoot.querySelector("#eventHandledBy");
handledContainer.removeChildren();
if(!data || data.length === 0) {
var span = document.createElement("span");
span.textContent = "None";
handledContainer.appendChild(span);
return;
}
var dl = document.createElement("dl");
var dt;
var auracomponent;
var dd;
for(var c=0;c<data.length;c++) {
if(data[c].scope) {
auracomponent = document.createElement("aurainspector-auracomponent");
auracomponent.setAttribute("globalId", data[c].scope);
dt = document.createElement("dt");
dt.appendChild(auracomponent);
dd = document.createElement("dd");
dd.textContent = "c." + data[c].name;
dl.appendChild(dt);
dl.appendChild(dd);
} else {
dt = document.createElement("dt");
dt.appendChild(document.createTextNode("{Bubbled Event}"));
dd = document.createElement("dd");
dd.textContent = data[c].name;
dl.appendChild(dt);
dl.appendChild(dd);
}
}
// build the handled collection
handledContainer.appendChild(dl);
// Show Toggle Button
var gridToggle = element.shadowRoot.querySelector("#gridToggle");
gridToggle.classList.remove("hidden");
}
function renderHandledByTree(element) {
var handledByTree = getData(element.getAttribute("handledByTree")) || [];
// Empty, or just itself? Don't draw
if(handledByTree.length < 2) {
return;
}
var gridContainer = element.shadowRoot.querySelector("#eventHandledByGrid");
gridContainer.removeChildren();
gridContainer.classList.remove("hidden");
var eventId = element.id;
var rawEdges = [];
var rawNodes = [];
for(var c = 0; c < handledByTree.length;c++) {
var handled = handledByTree[c];
if(handled.type === "action") {
rawNodes.push({ "id": handled.id, "label": `{${handled.data.scope}} c.${handled.data.name}`, "color": "maroon" });
} else {
var label = handled.data.sourceId ? `{${handled.data.sourceId}} ${handled.data.name}` : handled.data.name;
var data = { "id": handled.id, "label": label, "color": "steelblue" };
if(handled.id === eventId) {
data.size = 60;
data.color = "#333";
}
rawNodes.push(data);
}
if(handled.parent) {
rawEdges.push( { "from": handled.id, "to": handled.parent, arrows: "from" } );
}
}
var nodes = new vis.DataSet(rawNodes);
var edges = new vis.DataSet(rawEdges);
var options = {
nodes: {
borderWidth: 1,
shape: "box",
size: 50,
font: {
color: "#fff"
},
color: {
border: "#222"
}
},
layout: {
hierarchical: {
enabled: true,
//levelSeparation: 70,
direction: 'DU', // UD, DU, LR, RL
sortMethod: 'directed' // hubsize, directed
}
},
interaction: {
dragNodes: true
}
};
var network = new vis.Network(gridContainer, { "nodes": nodes, "edges": edges }, options);
}
function getData(data) {
if(!data) { return data; }
if(data.length === 0) { return data; }
if(typeof data === "string") {
return JSON.parse(data);
}
return data;
}
function ToggleButton_OnClick(event) {
var showGrid = this.getAttribute("showGrid");
this.setAttribute("showGrid", (!showGrid || showGrid !== "true") ? "true" : "false");
}
})();
| {
"content_hash": "5ed5115ce31331453ccda80bb8f7016b",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 120,
"avg_line_length": 30.323144104803493,
"alnum_prop": 0.6553859447004609,
"repo_name": "SalesforceSFDC/aura",
"id": "561991420fbff4e3a176d539e9893bf75b81e64d",
"size": "6944",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aura-devtools/aura-inspector/devtoolsPanel/components/eventCard/eventCard.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "884345"
},
{
"name": "GAP",
"bytes": "10087"
},
{
"name": "HTML",
"bytes": "2899877"
},
{
"name": "Java",
"bytes": "7839910"
},
{
"name": "JavaScript",
"bytes": "16275112"
},
{
"name": "PHP",
"bytes": "3345441"
},
{
"name": "Python",
"bytes": "9744"
},
{
"name": "Shell",
"bytes": "19650"
},
{
"name": "XSLT",
"bytes": "2725"
}
],
"symlink_target": ""
} |
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_H_
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/mojom/speech/speech_recognizer.mojom-blink.h"
#include "third_party/blink/public/platform/web_private_ptr.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/page/page_visibility_observer.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/speech/speech_grammar_list.h"
#include "third_party/blink/renderer/modules/speech/speech_recognition_result.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_receiver.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
class ExceptionState;
class ExecutionContext;
class LocalDOMWindow;
class SpeechRecognitionController;
class MODULES_EXPORT SpeechRecognition final
: public EventTargetWithInlineData,
public ActiveScriptWrappable<SpeechRecognition>,
public ExecutionContextLifecycleObserver,
public mojom::blink::SpeechRecognitionSessionClient,
public PageVisibilityObserver {
DEFINE_WRAPPERTYPEINFO();
public:
static SpeechRecognition* Create(ExecutionContext*);
SpeechRecognition(LocalDOMWindow*);
~SpeechRecognition() override;
// SpeechRecognition.idl implemementation.
// Attributes.
SpeechGrammarList* grammars() { return grammars_; }
void setGrammars(SpeechGrammarList* grammars) { grammars_ = grammars; }
String lang() { return lang_; }
void setLang(const String& lang) { lang_ = lang; }
bool continuous() { return continuous_; }
void setContinuous(bool continuous) { continuous_ = continuous; }
bool interimResults() { return interim_results_; }
void setInterimResults(bool interim_results) {
interim_results_ = interim_results;
}
unsigned maxAlternatives() { return max_alternatives_; }
void setMaxAlternatives(unsigned max_alternatives) {
max_alternatives_ = max_alternatives;
}
// Callable by the user.
void start(ExceptionState&);
void stopFunction();
void abort();
// mojom::blink::SpeechRecognitionSessionClient
void ResultRetrieved(
WTF::Vector<mojom::blink::SpeechRecognitionResultPtr> results) override;
void ErrorOccurred(mojom::blink::SpeechRecognitionErrorPtr error) override;
void Started() override;
void AudioStarted() override;
void SoundStarted() override;
void SoundEnded() override;
void AudioEnded() override;
void Ended() override;
// EventTarget
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
// ScriptWrappable
bool HasPendingActivity() const final;
// ExecutionContextLifecycleObserver
void ContextDestroyed() override;
// PageVisibilityObserver
void PageVisibilityChanged() override;
DEFINE_ATTRIBUTE_EVENT_LISTENER(audiostart, kAudiostart)
DEFINE_ATTRIBUTE_EVENT_LISTENER(soundstart, kSoundstart)
DEFINE_ATTRIBUTE_EVENT_LISTENER(speechstart, kSpeechstart)
DEFINE_ATTRIBUTE_EVENT_LISTENER(speechend, kSpeechend)
DEFINE_ATTRIBUTE_EVENT_LISTENER(soundend, kSoundend)
DEFINE_ATTRIBUTE_EVENT_LISTENER(audioend, kAudioend)
DEFINE_ATTRIBUTE_EVENT_LISTENER(result, kResult)
DEFINE_ATTRIBUTE_EVENT_LISTENER(nomatch, kNomatch)
DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError)
DEFINE_ATTRIBUTE_EVENT_LISTENER(start, kStart)
DEFINE_ATTRIBUTE_EVENT_LISTENER(end, kEnd)
void Trace(Visitor*) const override;
private:
void OnConnectionError();
void StartInternal(ExceptionState* exception_state);
Member<SpeechGrammarList> grammars_;
String lang_;
bool continuous_;
bool interim_results_;
uint32_t max_alternatives_;
Member<SpeechRecognitionController> controller_;
bool started_;
bool stopping_;
HeapVector<Member<SpeechRecognitionResult>> final_results_;
HeapMojoReceiver<mojom::blink::SpeechRecognitionSessionClient,
SpeechRecognition>
receiver_;
HeapMojoRemote<mojom::blink::SpeechRecognitionSession> session_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_SPEECH_SPEECH_RECOGNITION_H_
| {
"content_hash": "140a811145f6f9a2565602e3f04bbf43",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 99,
"avg_line_length": 36.992,
"alnum_prop": 0.7770328719723183,
"repo_name": "chromium/chromium",
"id": "683e5d340214b0d4b513628f3398b4fc1ef5d286",
"size": "5975",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "third_party/blink/renderer/modules/speech/speech_recognition.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<HTML>
<BODY BGCOLOR="white">
<PRE>
<FONT color="green">001</FONT> /* Generated By:JavaCC: Do not edit this line. Token.java Version 5.0 */<a name="line.1"></a>
<FONT color="green">002</FONT> /* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */<a name="line.2"></a>
<FONT color="green">003</FONT> package org.apache.commons.jexl2.parser;<a name="line.3"></a>
<FONT color="green">004</FONT> <a name="line.4"></a>
<FONT color="green">005</FONT> /**<a name="line.5"></a>
<FONT color="green">006</FONT> * Describes the input token stream.<a name="line.6"></a>
<FONT color="green">007</FONT> */<a name="line.7"></a>
<FONT color="green">008</FONT> <a name="line.8"></a>
<FONT color="green">009</FONT> public class Token implements java.io.Serializable {<a name="line.9"></a>
<FONT color="green">010</FONT> <a name="line.10"></a>
<FONT color="green">011</FONT> /**<a name="line.11"></a>
<FONT color="green">012</FONT> * The version identifier for this Serializable class.<a name="line.12"></a>
<FONT color="green">013</FONT> * Increment only if the <i>serialized</i> form of the<a name="line.13"></a>
<FONT color="green">014</FONT> * class changes.<a name="line.14"></a>
<FONT color="green">015</FONT> */<a name="line.15"></a>
<FONT color="green">016</FONT> private static final long serialVersionUID = 1L;<a name="line.16"></a>
<FONT color="green">017</FONT> <a name="line.17"></a>
<FONT color="green">018</FONT> /**<a name="line.18"></a>
<FONT color="green">019</FONT> * An integer that describes the kind of this token. This numbering<a name="line.19"></a>
<FONT color="green">020</FONT> * system is determined by JavaCCParser, and a table of these numbers is<a name="line.20"></a>
<FONT color="green">021</FONT> * stored in the file ...Constants.java.<a name="line.21"></a>
<FONT color="green">022</FONT> */<a name="line.22"></a>
<FONT color="green">023</FONT> public int kind;<a name="line.23"></a>
<FONT color="green">024</FONT> <a name="line.24"></a>
<FONT color="green">025</FONT> /** The line number of the first character of this Token. */<a name="line.25"></a>
<FONT color="green">026</FONT> public int beginLine;<a name="line.26"></a>
<FONT color="green">027</FONT> /** The column number of the first character of this Token. */<a name="line.27"></a>
<FONT color="green">028</FONT> public int beginColumn;<a name="line.28"></a>
<FONT color="green">029</FONT> /** The line number of the last character of this Token. */<a name="line.29"></a>
<FONT color="green">030</FONT> public int endLine;<a name="line.30"></a>
<FONT color="green">031</FONT> /** The column number of the last character of this Token. */<a name="line.31"></a>
<FONT color="green">032</FONT> public int endColumn;<a name="line.32"></a>
<FONT color="green">033</FONT> <a name="line.33"></a>
<FONT color="green">034</FONT> /**<a name="line.34"></a>
<FONT color="green">035</FONT> * The string image of the token.<a name="line.35"></a>
<FONT color="green">036</FONT> */<a name="line.36"></a>
<FONT color="green">037</FONT> public String image;<a name="line.37"></a>
<FONT color="green">038</FONT> <a name="line.38"></a>
<FONT color="green">039</FONT> /**<a name="line.39"></a>
<FONT color="green">040</FONT> * A reference to the next regular (non-special) token from the input<a name="line.40"></a>
<FONT color="green">041</FONT> * stream. If this is the last token from the input stream, or if the<a name="line.41"></a>
<FONT color="green">042</FONT> * token manager has not read tokens beyond this one, this field is<a name="line.42"></a>
<FONT color="green">043</FONT> * set to null. This is true only if this token is also a regular<a name="line.43"></a>
<FONT color="green">044</FONT> * token. Otherwise, see below for a description of the contents of<a name="line.44"></a>
<FONT color="green">045</FONT> * this field.<a name="line.45"></a>
<FONT color="green">046</FONT> */<a name="line.46"></a>
<FONT color="green">047</FONT> public Token next;<a name="line.47"></a>
<FONT color="green">048</FONT> <a name="line.48"></a>
<FONT color="green">049</FONT> /**<a name="line.49"></a>
<FONT color="green">050</FONT> * This field is used to access special tokens that occur prior to this<a name="line.50"></a>
<FONT color="green">051</FONT> * token, but after the immediately preceding regular (non-special) token.<a name="line.51"></a>
<FONT color="green">052</FONT> * If there are no such special tokens, this field is set to null.<a name="line.52"></a>
<FONT color="green">053</FONT> * When there are more than one such special token, this field refers<a name="line.53"></a>
<FONT color="green">054</FONT> * to the last of these special tokens, which in turn refers to the next<a name="line.54"></a>
<FONT color="green">055</FONT> * previous special token through its specialToken field, and so on<a name="line.55"></a>
<FONT color="green">056</FONT> * until the first special token (whose specialToken field is null).<a name="line.56"></a>
<FONT color="green">057</FONT> * The next fields of special tokens refer to other special tokens that<a name="line.57"></a>
<FONT color="green">058</FONT> * immediately follow it (without an intervening regular token). If there<a name="line.58"></a>
<FONT color="green">059</FONT> * is no such token, this field is null.<a name="line.59"></a>
<FONT color="green">060</FONT> */<a name="line.60"></a>
<FONT color="green">061</FONT> public Token specialToken;<a name="line.61"></a>
<FONT color="green">062</FONT> <a name="line.62"></a>
<FONT color="green">063</FONT> /**<a name="line.63"></a>
<FONT color="green">064</FONT> * An optional attribute value of the Token.<a name="line.64"></a>
<FONT color="green">065</FONT> * Tokens which are not used as syntactic sugar will often contain<a name="line.65"></a>
<FONT color="green">066</FONT> * meaningful values that will be used later on by the compiler or<a name="line.66"></a>
<FONT color="green">067</FONT> * interpreter. This attribute value is often different from the image.<a name="line.67"></a>
<FONT color="green">068</FONT> * Any subclass of Token that actually wants to return a non-null value can<a name="line.68"></a>
<FONT color="green">069</FONT> * override this method as appropriate.<a name="line.69"></a>
<FONT color="green">070</FONT> */<a name="line.70"></a>
<FONT color="green">071</FONT> public Object getValue() {<a name="line.71"></a>
<FONT color="green">072</FONT> return null;<a name="line.72"></a>
<FONT color="green">073</FONT> }<a name="line.73"></a>
<FONT color="green">074</FONT> <a name="line.74"></a>
<FONT color="green">075</FONT> /**<a name="line.75"></a>
<FONT color="green">076</FONT> * No-argument constructor<a name="line.76"></a>
<FONT color="green">077</FONT> */<a name="line.77"></a>
<FONT color="green">078</FONT> public Token() {}<a name="line.78"></a>
<FONT color="green">079</FONT> <a name="line.79"></a>
<FONT color="green">080</FONT> /**<a name="line.80"></a>
<FONT color="green">081</FONT> * Constructs a new token for the specified Image.<a name="line.81"></a>
<FONT color="green">082</FONT> */<a name="line.82"></a>
<FONT color="green">083</FONT> public Token(int kind)<a name="line.83"></a>
<FONT color="green">084</FONT> {<a name="line.84"></a>
<FONT color="green">085</FONT> this(kind, null);<a name="line.85"></a>
<FONT color="green">086</FONT> }<a name="line.86"></a>
<FONT color="green">087</FONT> <a name="line.87"></a>
<FONT color="green">088</FONT> /**<a name="line.88"></a>
<FONT color="green">089</FONT> * Constructs a new token for the specified Image and Kind.<a name="line.89"></a>
<FONT color="green">090</FONT> */<a name="line.90"></a>
<FONT color="green">091</FONT> public Token(int kind, String image)<a name="line.91"></a>
<FONT color="green">092</FONT> {<a name="line.92"></a>
<FONT color="green">093</FONT> this.kind = kind;<a name="line.93"></a>
<FONT color="green">094</FONT> this.image = image;<a name="line.94"></a>
<FONT color="green">095</FONT> }<a name="line.95"></a>
<FONT color="green">096</FONT> <a name="line.96"></a>
<FONT color="green">097</FONT> /**<a name="line.97"></a>
<FONT color="green">098</FONT> * Returns the image.<a name="line.98"></a>
<FONT color="green">099</FONT> */<a name="line.99"></a>
<FONT color="green">100</FONT> public String toString()<a name="line.100"></a>
<FONT color="green">101</FONT> {<a name="line.101"></a>
<FONT color="green">102</FONT> return image;<a name="line.102"></a>
<FONT color="green">103</FONT> }<a name="line.103"></a>
<FONT color="green">104</FONT> <a name="line.104"></a>
<FONT color="green">105</FONT> /**<a name="line.105"></a>
<FONT color="green">106</FONT> * Returns a new Token object, by default. However, if you want, you<a name="line.106"></a>
<FONT color="green">107</FONT> * can create and return subclass objects based on the value of ofKind.<a name="line.107"></a>
<FONT color="green">108</FONT> * Simply add the cases to the switch for all those special cases.<a name="line.108"></a>
<FONT color="green">109</FONT> * For example, if you have a subclass of Token called IDToken that<a name="line.109"></a>
<FONT color="green">110</FONT> * you want to create if ofKind is ID, simply add something like :<a name="line.110"></a>
<FONT color="green">111</FONT> *<a name="line.111"></a>
<FONT color="green">112</FONT> * case MyParserConstants.ID : return new IDToken(ofKind, image);<a name="line.112"></a>
<FONT color="green">113</FONT> *<a name="line.113"></a>
<FONT color="green">114</FONT> * to the following switch statement. Then you can cast matchedToken<a name="line.114"></a>
<FONT color="green">115</FONT> * variable to the appropriate type and use sit in your lexical actions.<a name="line.115"></a>
<FONT color="green">116</FONT> */<a name="line.116"></a>
<FONT color="green">117</FONT> public static Token newToken(int ofKind, String image)<a name="line.117"></a>
<FONT color="green">118</FONT> {<a name="line.118"></a>
<FONT color="green">119</FONT> switch(ofKind)<a name="line.119"></a>
<FONT color="green">120</FONT> {<a name="line.120"></a>
<FONT color="green">121</FONT> default : return new Token(ofKind, image);<a name="line.121"></a>
<FONT color="green">122</FONT> }<a name="line.122"></a>
<FONT color="green">123</FONT> }<a name="line.123"></a>
<FONT color="green">124</FONT> <a name="line.124"></a>
<FONT color="green">125</FONT> public static Token newToken(int ofKind)<a name="line.125"></a>
<FONT color="green">126</FONT> {<a name="line.126"></a>
<FONT color="green">127</FONT> return newToken(ofKind, null);<a name="line.127"></a>
<FONT color="green">128</FONT> }<a name="line.128"></a>
<FONT color="green">129</FONT> <a name="line.129"></a>
<FONT color="green">130</FONT> }<a name="line.130"></a>
<FONT color="green">131</FONT> /* JavaCC - OriginalChecksum=28f3293a1d27d70edea279be2f20585e (do not edit this line) */<a name="line.131"></a>
</PRE>
</BODY>
</HTML>
| {
"content_hash": "7f434a56f8969026e98955241563131d",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 145,
"avg_line_length": 58.81725888324873,
"alnum_prop": 0.6229395011650988,
"repo_name": "vasukiarunachalam/Android-Projects",
"id": "c0cc2b77f119c1b7fcac94dd7bce4e500936001f",
"size": "11587",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ApparelDesigner/app/libs/commons-jexl-2.1.1/apidocs/src-html/org/apache/commons/jexl2/parser/Token.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1391"
},
{
"name": "HTML",
"bytes": "10207595"
},
{
"name": "Java",
"bytes": "310776"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sphp\Config\ErrorHandling;
use Throwable;
use Zend\Mail\Message;
use Zend\Mail\Transport\Sendmail;
/**
* Sends a thrown exception as a email
*
* @author Sami Holck <[email protected]>
* @license https://opensource.org/licenses/MIT The MIT License
* @filesource
*/
class ExceptionMailer implements ExceptionListener {
/**
* @var string
*/
private $sender;
/**
* @var string
*/
private $receiver;
/**
* Constructor
*
* @param string $from senders email address
* @param string $to receivers email address
*/
public function __construct(string $from, string $to) {
$this->sender = $from;
$this->receiver = $to;
}
/**
* Returns senders email address or null if not set
*
* @return string|null senders email address or null if not set
*/
public function getSender(): string {
return $this->sender;
}
/**
* Returns receivers email address
*
* @return string receivers email address
*/
public function getReceiver(): string {
return $this->receiver;
}
/**
*
* @param Throwable $t the throwable to mail
* @return $this for a fluent interface
*/
public function send(Throwable $t) {
$mail = new Message();
$mail->setFrom($this->getSender());
$mail->addTo($this->getReceiver());
$mail->setSubject(get_class($t));
$mail->setBody($this->createMailBody($t));
$mail->setEncoding('UTF-8');
$transport = new Sendmail();
$transport->send($mail);
return $this;
}
/**
*
* @param Throwable $t the throwable to mail
* @return string mail body as a string
*/
protected function parseThrowable(Throwable $t): string {
$output .= "Type: " . get_class($t) . "\n";
$output = get_class($t) . ": " . $t->getMessage() . ", (code " . $t->getCode() . ")\n";
$output .= "----------------------\n";
$output .= "on line " . $t->getLine() . " of file '" . $t->getFile() . "'\n";
$output .= "----------------------\n";
$output .= "Trace:\n" . $t->getTraceAsString() . "\n";
if ($t->getPrevious() !== null) {
$output .= "----------------------\n";
$output .= "Previous exception:\n" . $this->parseThrowable($t->getPrevious()) . "\n";
}
$output .= "----------------------\n";
return $output;
}
/**
*
* @param Throwable $t the throwable to mail
* @return string mail body as a string
*/
protected function createMailBody(Throwable $t): string {
$mailBody = "An exception was thrown:\n";
$mailBody .= $this->parseThrowable($t);
return $mailBody;
}
public function onException(Throwable $e): void {
$this->send($e);
}
}
| {
"content_hash": "8ca79c3ccb8c5082f10b77ed18372527",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 91,
"avg_line_length": 24,
"alnum_prop": 0.575589970501475,
"repo_name": "samhol/SPHP-framework",
"id": "449b24609fb44e6bc07c72dabcb1dd86c05f5f1c",
"size": "3003",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sphp/php/Sphp/Config/ErrorHandling/ExceptionMailer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Hack",
"bytes": "19"
},
{
"name": "JavaScript",
"bytes": "22252"
},
{
"name": "PHP",
"bytes": "3138045"
},
{
"name": "SCSS",
"bytes": "34618"
}
],
"symlink_target": ""
} |
@implementation NSMutableDictionary (RangeOutRunTime)
+ (void)load{
// 交换方法
//Check:addObj
Method addObjCheck = class_getClassMethod(self, @selector(setValueCheck:forKey:));
Method addObj = class_getClassMethod(self, @selector(setValue:forKey:));
;
method_exchangeImplementations(addObjCheck, addObj);
}
- (void)setValueCheck:(id)value forKey:(NSString *)key{
if (self&&value&&key) {
[self setValue:value forKey:key];
}else{
NSLog(@"————————Dic_Obj为空———————");
}
}
@end
| {
"content_hash": "2ef0a0a89cfc5c956d60803283d32169",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 86,
"avg_line_length": 25.238095238095237,
"alnum_prop": 0.6452830188679245,
"repo_name": "1457792186/JWOCLibertyDemoWithPHP",
"id": "5b44197c9f776bcaa2b2e6d839e59c03ff7f3e40",
"size": "826",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LibertyDemoWithPHP/NxhTest/VC/BBSRunTime/CommonCrashCheck/NSMutableDictionary+RangeOutRunTime.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1172"
},
{
"name": "Objective-C",
"bytes": "815768"
},
{
"name": "Swift",
"bytes": "898398"
}
],
"symlink_target": ""
} |
<?php
namespace DBScribe;
use Exception;
/**
* This class holds all information concerning a database table and methods to operate
* on the table and it's columns and rows
*
* @author Ezra Obiwale <[email protected]>
*/
class Table {
const ORDER_ASC = 'ASC';
const ORDER_DESC = 'DESC';
const INDEX_REGULAR = 'INDEX';
const INDEX_UNIQUE = 'UNIQUE';
const INDEX_FULLTEXT = 'FULLTEXT';
const OP_SELECT = 'select';
const OP_INSERT = 'insert';
const OP_UPDATE = 'update';
const OP_DELETE = 'delete';
const RETURN_DEFAULT = 0;
const RETURN_MODEL = 1;
const RETURN_JSON = 2;
/**
* Table name
* @var string
*/
protected $name;
/**
* Connection object
* @var Connection
*/
protected $connection;
/**
* Table Description
* @var string
*/
protected $description;
/**
* New Table Description
* @var string
*/
protected $newDescription;
/**
* Array of columns and some of their properties
* @var array
*/
protected $columns;
/**
* Array of new columns and their definitions
* @var array
*/
protected $newColumns;
/**
* Array of references from this table to other tables
* @var array
*/
protected $references;
/**
* Array of references from other tables to this table
* @var array
*/
protected $backReferences;
/**
* Array of indexes
* @var string
*/
protected $indexes;
/**
* Array of new references from this table to others
* @var array
*/
protected $newReferences;
/**
* The primary key of the table
* @var string
*/
protected $primaryKey;
/**
* Indicates whether to remove the primary key
* @var boolean
*/
protected $dropPrimaryKey;
/**
* The new primary key to replace the old
* @var string
*/
protected $newPrimaryKey;
/**
* Array of columns to remove from the table
* @var array
*/
protected $dropColumns;
/**
* Array of existing columns with new definitions
* @var array
*/
protected $alterColumns;
/**
* Array of columns whose references should be dropped
* @var array
*/
protected $dropReferences;
/**
* Array of columns whose references need be changed
* @var array
*/
protected $alterReferences;
/**
* Array of columns to add indexes to
* @var array
*/
protected $newIndexes;
/**
* Array of columns whose indexes should be dropped
* @var array
*/
protected $dropIndexes;
/**
* The query string to be executed
* @var string
*/
protected $query;
/**
* The last query executed
* @var string
*/
protected $lastQuery;
/**
* Columns to target the query
* @var Array|String
*/
protected $targetColumns;
/**
* The query that serves to join results with referenced tables' rows
* @var string
*/
protected $joinQuery;
/**
* Array of prepared values to be saved to the database
* @var array
*/
protected $values;
/**
* Array of referenced tables from which to draw more rows
* @var array
*/
protected $joins;
/**
* Indicates whether multiple values are prepared for the query
* @var boolean
*/
protected $multiple;
/**
* Indicates whether to return results with a class model
* @var boolean
*/
protected $withModel;
/**
* The class that extends \DBScribe\Row which to map results to
* @var Row
*/
protected $rowModel;
/**
* Holds the current model the class is working with
* @var Row
*/
protected $rowModelInUse;
/**
* Array of columns and options to order the result by
* @var array
*/
protected $orderBy;
/**
* The limit part of the query
* @var string
*/
protected $limit;
/**
* Indicates whether to delay the execution of the query until @method execute() is called
* @var boolean
*/
protected $delayExecute;
/**
* Indicates whether to run the postSave method of the Row after operating the query
* @var boolean
*/
protected $doPost;
/**
* Currenct operation: one of the OP_ constants of this class
* @var string
*/
protected $current;
/**
* Additional conditions to attach to the query
* @var string
*/
protected $customWhere;
/**
* Conditions to attach to the query
* @var string
*/
protected $where;
/**
* Array of columns to group query results by
* @var array
*/
protected $groups;
/**
* The having portion of the query
* @var string
*/
protected $having;
/**
* Array holding the relationship information with all other tables
* @var array
*/
protected $relationshipData;
/**
* Used with customWhere(). No relationship with join()
* @var string AND|OR
*/
protected $customWhereJoin;
/**
* Indicates the type of results expected
* @var int One of the RETURN_* constants of this class
*/
protected $expected;
/**
* Indicates whether to retrieve data from cache or not
* @var bool
*/
protected $fromCache;
/**
* Indicates whether the query has been generated
* @var boolean
*/
protected $genQry;
/**
* Indicates whether to preserve queries that change the table or not
* @var boolean
*/
protected $preserveQueries;
/**
* Allows reuse of parameters
* @var boolean
*/
protected $reuseParams;
/**
* Class contructor
* @param string $name Name of the table, without the prefix if already
* supplied in the connection object
* @param Connection $connection
* @param Row $rowModel
*/
public function __construct($name, Connection $connection = null,
Row $rowModel = null) {
$this->name = $connection->getTablePrefix() . strtolower(Util::camelTo_($name));
$this->connection = $connection;
$this->rowModel = ($rowModel) ? $rowModel : new Row();
$this->multiple = false;
$this->doPost = false;
$this->delayExecute = false;
$this->where = null;
$this->groups = array();
$this->orderBy = array();
$this->joins = array();
$this->fromCache = true;
$this->genQry = false;
$this->columns = array();
$this->references = array();
$this->backReferences = array();
$this->indexes = array();
$this->foreignKeys = array();
$this->newColumns = array();
$this->newReferences = array();
$this->alterColumns = array();
$this->dropColumns = array();
$this->dropReferences = array();
$this->dropIndexes = array();
$this->alterReferences = array();
$this->init();
$this->checkDATA();
}
/**
* Checks if the DATA constant is declared and declares it if not
* @return Table
*/
public function checkDATA() {
if (!defined(DATA))
define(DATA,
__DIR__ . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR);
if (!is_dir(DATA)) mkdir(DATA, 0777, true);
return $this;
}
/**
* Indicates whether to preserve queries that change the table or not
* @param bool $bool
* @return \DBScribe\Table
*/
public function preserveQueries($bool = true) {
$this->preserveQueries = $bool;
return $this;
}
protected function doPreserveQueries() {
$path = DATA . md5('queries') . DIRECTORY_SEPARATOR;
if (!is_dir($path)) mkdir($path, 0777, true);
$today = Util::createTimestamp(time(), 'Y-m-d');
$save = array();
if (is_readable($path . $today)) {
$save = include $path . $today;
}
$save[] = array(
'q' => $this->query,
'v' => $this->values,
);
Util::updateConfig($path . $today, $save);
}
/**
* Sets the model to use with fetched rows
* @param Row $model
* @return Table
*/
public function setRowModel(Row $model) {
$this->rowModel = $model;
return $this;
}
/**
* Fetches the model attached to the table
* @return Row $model
*/
public function getRowModel() {
return $this->rowModel;
}
/**
* Fetches the connection used in the table
* @return Connection
*/
public function getConnection() {
return $this->connection;
}
/**
* Initialiazes the table
*/
public function init() {
if ($this->connection) $this->defineRelationships();
}
/**
* Fetches the name of the table
* @return string
*/
public function getName() {
return $this->name;
}
/**
* Set the table description
* @param string $tableDescription
* @return Table
*/
public function setDescription($tableDescription = 'ENGINE=InnoDB') {
if (!$this->description) $this->description = $tableDescription;
return $this;
}
/**
* Change the table description
* @param string $tableDescription
* @return Table
*/
public function changeDescription($tableDescription = 'ENGINE=InnoDB') {
$this->newDescription = $tableDescription;
return $this;
}
/**
* Fetches the description of the table
* @return string|null
*/
public function getDescription() {
return $this->description;
}
/**
* Fetches the new description for the table
* @return string|null
*/
public function getNewDescription($reset = false) {
$return = $this->newDescription;
if ($reset) $this->newDescription = null;
return $return;
}
/**
* Sets the primary key
* @param string $pk
* @return Table
*/
public function setPrimaryKey($pk) {
if ($this->primaryKey === $pk) return $this;
if ($this->primaryKey) {
$this->dropPrimaryKey();
}
$this->newPrimaryKey = $pk;
return $this;
}
/**
* Fetches the primary key
* @return string|null
*/
public function getPrimaryKey() {
return $this->primaryKey;
}
/**
* Removes the primary key
* @return Table
*/
public function dropPrimaryKey() {
$this->dropPrimaryKey = true;
return $this;
}
/**
* Checks if to drop the primary key
* @return boolean|null
*/
public function shouldDropPrimaryKey($reset = false) {
$return = $this->dropPrimaryKey;
if ($reset) $this->dropPrimaryKey = false;
return $return;
}
/**
* Fetches the new primary key
* @return string|null
*/
public function getNewPrimarykey($reset = false) {
$return = $this->newPrimaryKey;
if ($reset) $this->newPrimaryKey = null;
return $return;
}
/**
* Fetches the indexes
* @param string $columnName Name of column to return the index
* @return array
*/
public function getIndexes($columnName = null) {
if (!$this->indexes) {
$this->indexes = array();
}
return ($columnName) ? $this->indexes[$columnName] : $this->indexes;
}
/**
* Adds an index to a column
* @param string $columnName
* @param string $type Should be one of \DBScribe\Table::INDEX_REGULAR, \DBScribe\Table::INDEX_UNIQUE,
* or \DBScribe\Table::INDEX_FULLTEXT
* @return Table
*/
public function addIndex($columnName, $type = Table::INDEX_REGULAR) {
if (!array_key_exists($columnName, $this->getIndexes()) && !array_key_exists($columnName,
$this->newIndexes))
$this->newIndexes[$columnName] = $type;
return $this;
}
/**
* Fetches the indexes to create
* @return array
*/
public function getNewIndexes($reset = false) {
$return = $this->newIndexes;
if ($reset) $this->newIndexes = array();
return $return;
}
/**
* Removes index from a column
* @param string $columnName
* @return Table
*/
public function dropIndex($columnName) {
if (!in_array($columnName, $this->dropIndexes))
$this->dropIndexes[] = $columnName;
if (array_key_exists($columnName, $this->getReferences()))
$this->dropReference($columnName);
return $this;
}
/**
* Fetches the indexes to remove
* @param bool $reset Reset the indexes
* @return array
*/
public function getDropIndexes($reset = false) {
$return = $this->dropIndexes;
if ($reset) $this->dropIndexes = array();
return $return;
}
/**
* Add a column to the table
* @param string $columnName
* @param string $columnDescription
* @return Table
*/
public function addColumn($columnName, $columnDescription) {
$this->newColumns[$columnName] = $columnDescription;
return $this;
}
/**
* Gets available columns in table
* @return array
*/
public function getColumns($justNames = false) {
return ($justNames) ? array_keys($this->columns) : $this->columns;
}
/**
* Removes a column
* @param string $columnName
* @return Table
*/
public function dropColumn($columnName) {
$this->dropColumns[] = $columnName;
if (array_key_exists($columnName, $this->references)) {
$this->dropReference($columnName);
}
return $this;
}
/**
* Fetches columns to remove
* @param bool $reset Reset the columns
* @return array
*/
public function getDropColumns($reset = false) {
$return = $this->dropColumns;
if ($reset) $this->dropColumns = array();
return $return;
}
/**
* Fetches columns to add
* @param bool $reset Reset the columns
* @return array
*/
public function getNewColumns($reset = false) {
$return = $this->newColumns;
if ($reset) $this->newColumns = array();
return $return;
}
/**
* Alter column description
* @param string $columnName
* @param string $columnDescription
* @return Table
*/
public function alterColumn($columnName, $columnDescription) {
$this->alterColumns[$columnName] = $columnDescription;
return $this;
}
/**
* Fetches the columns to change
* @return array
*/
public function getAlterColumns($reset = false) {
$return = $this->alterColumns;
if ($reset) $this->alterColumns = array();
return $return;
}
/**
* Fetches the references in the table
* @return array
*/
public function getReferences() {
return $this->references;
}
/**
* Fetches the tables and columns that reference this table
* @return array
*/
public function getBackReferences() {
return $this->backReferences;
}
/**
* Removes a reference from a column
* @param string $columnName
* @return Table
*/
public function dropReference($columnName) {
$this->dropReferences[] = $columnName;
return $this;
}
/**
* Fetches all columns from which references should be dropped
* @return array
*/
public function getDropReferences($reset = false) {
$return = array_unique($this->dropReferences);
if ($reset) $this->dropReferences = array();
return $return;
}
/**
* Add reference to a column
* @param string $columnName
* @param string $refTable
* @param string $refColumn
* @return Table
*/
public function addReference($columnName, $refTable, $refColumn,
$onDelete = 'RESTRICT', $onUpdate = 'RESTRICT') {
$this->addIndex($columnName);
$this->newReferences[$columnName] = array(
'table' => $refTable,
'column' => $refColumn,
'onDelete' => $onDelete,
'onUpdate' => $onUpdate,
);
return $this;
}
/**
* Fetches all new references
* @return array
*/
public function getNewReferences($reset = false) {
$return = $this->newReferences;
if ($reset) $this->newReferences = array();
return $return;
}
/**
* Alter references of the table column
* @param string $columnName
* @param string $refTable
* @param string $refColumn
* @return Table
*/
public function alterReference($columnName, $refTable, $refColumn,
$onDelete = 'RESTRICT', $onUpdate = 'RESTRICT') {
$this->dropReference($columnName);
$this->addReference($columnName, $refTable, $refColumn, $onDelete,
$onUpdate);
return $this;
}
/**
* Sets the model to map the table to
* @param Row $model
* @return Table
*/
public function setModel(Row $model) {
$this->rowModel = $model;
return $this;
}
/**
* Fetches the model set for the table
* @return Row
*/
public function getModel() {
return $this->rowModel;
}
/**
* Defines the relationships of the table
* @return void
*/
private function defineRelationships() {
$this->fetchColumns();
$this->fetchReferences();
$this->fetchBackReferences();
}
/**
* Fetches the tables that reference this table, and their columns
*/
private function fetchBackReferences() {
$qry = "SELECT k.COLUMN_NAME as refColumn, k.TABLE_SCHEMA as refDB, k.TABLE_NAME as refTable,
k.REFERENCED_COLUMN_NAME as columnName" .
" FROM information_schema.KEY_COLUMN_USAGE k" .
" WHERE k.TABLE_SCHEMA = '" . $this->connection->getDBName() .
"' AND k.REFERENCED_TABLE_NAME = '" . $this->name . "'";
$backRef = $this->connection->doPrepare($qry);
if (is_bool($backRef)) return;
foreach ($backRef as &$info) {
$name = $info['columnName'];
unset($info['columnName']);
$this->backReferences[$name][] = $info;
}
}
/**
* Fetches all tables and columns that this table references
*/
private function fetchReferences() {
$qry = "SELECT i.CONSTRAINT_NAME as constraintName, i.CONSTRAINT_TYPE as constraintType,
j.COLUMN_NAME as columnName, j.REFERENCED_TABLE_SCHEMA as refDB, j.REFERENCED_TABLE_NAME as refTable,
j.REFERENCED_COLUMN_NAME as refColumn, k.UPDATE_RULE as onUpdate, k.DELETE_RULE as onDelete" .
" FROM information_schema.TABLE_CONSTRAINTS i" .
" LEFT JOIN information_schema.KEY_COLUMN_USAGE j
ON i.CONSTRAINT_NAME = j.CONSTRAINT_NAME AND j.TABLE_SCHEMA = '" . $this->connection->getDBName() . "'
AND j.TABLE_NAME = '" . $this->name . "'" .
" LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS k
ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME AND j.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA
AND k.TABLE_NAME = '" . $this->name . "'" .
" WHERE i.TABLE_SCHEMA = '" . $this->connection->getDBName() . "'
AND i.TABLE_NAME = '" . $this->name . "'";
$define = $this->connection->doPrepare($qry);
if (is_bool($define)) return;
foreach ($define as $info) {
if (isset($info['constraintType']) && $info['constraintType'] === 'PRIMARY KEY') {
if (isset($info['columnName']))
$this->primaryKey = $info['columnName'];
} else if ($info['refTable']) {
if (isset($info['constraintType']))
unset($info['constraintType']);
if (isset($info['columnName'])) {
$name = $info['columnName'];
unset($info['columnName']);
}
$this->references[$name] = $info;
}
}
}
/**
* Fetches all columns of the table and their information
*/
private function fetchColumns() {
$qry = 'SELECT c.column_name as colName, c.column_default as colDefault,
c.is_nullable as nullable, c.column_type as colType, c.extra, c.column_key as colKey,
c.character_set_name as charset, c.collation_name as collation';
$qry .= ', d.index_name as indexName';
$qry .=' FROM INFORMATION_SCHEMA.COLUMNS c ' .
'LEFT JOIN INFORMATION_SCHEMA.STATISTICS d'
. ' ON c.column_name = d.column_name AND d.table_schema="' . $this->connection->getDBName() . '" AND d.table_name="' . $this->name . '" ' .
'WHERE c.table_schema="' . $this->connection->getDBName() . '" AND c.table_name="' . $this->name . '"';
$columns = $this->connection->doPrepare($qry);
if (is_bool($columns)) return;
foreach ($columns as $column) {
$this->columns[$column['colName']] = $column;
if (in_array($column['colKey'],
array('MUL', 'UNI', 'PRI', 'SPA', 'FUL'))) {
$this->indexes[$column['colName']] = $column['indexName'];
}
}
}
public function getConstraintName($column) {
if (array_key_exists($column, $this->references)) {
return $this->references[$column]['constraintName'];
}
return null;
}
/**
* Checks if the table exists
* @return boolean
*/
public function exists() {
return (count($this->columns));
}
/**
* Checks if a connection and table exist
* @return boolean
* @throws Exception
*/
private function checkExists() {
if (!$this->connection)
throw new Exception('Invalid action. No connection found');
return $this->exists();
}
/**
* Inserts the given row(s) into the table<br />
* Many rows can be inserted at once.
* @param array $values Array with values \DBScribe\Row or array of [column => value]
* @return Table
*/
public function insert(array $values) {
if (!$this->checkExists()) return false;
$this->current = self::OP_INSERT;
$this->query = 'INSERT INTO `' . $this->name . '` (';
$columns = array();
$noOfColumns = 0;
foreach (array_values($values) as $ky => $row) {
$rowArray = $this->checkModel($row, true);
if ($ky === 0) $noOfColumns = count($rowArray);
if (count($rowArray) !== $noOfColumns) {
throw new Exception('All rows must have the same number of columns in table "' . $this->name .
'". Set others as null');
}
if (count($rowArray) === 0)
throw new Exception('You cannot insert an empty row into table "' . $this->name . '"');
foreach ($rowArray as $column => &$value) {
if (empty($value) && $value != 0) continue;
$column = Util::camelTo_($column);
if (!in_array($column, $columns)) $columns[] = $column;
$this->values[$ky][':' . $column] = $value;
}
}
$this->query .= '`' . join('`, `', $columns) . '`';
$this->query .= ') VALUES (';
$this->query .= ':' . join(', :', $columns);
$this->query .= ')';
$this->multiple = true;
$this->doPost = self::OP_INSERT;
if ($this->delayExecute) {
return $this;
}
return $this->execute();
}
/**
* Fetches the relationships between the columns in this table and the
* give table
* @param string $table
* @return array
*/
public function getTableRelationships($table) {
$table = $this->connection->getTablePrefix() . Util::camelTo_($table);
$relationships = array();
foreach ($this->references as $columnName => $info) {
if ($info['constraintName'] == 'PRIMARY' || $info['refTable'] != $table)
continue;
$this->setupRelationship($columnName, $info['refColumn'],
$info['refTable'], $relationships, false);
}
foreach ($this->backReferences as $columnName => $infoArray) {
foreach ($infoArray as $info) {
if ($info['refTable'] != $table) continue;
$this->setupRelationship($columnName, $info['refColumn'],
$info['refTable'], $relationships, true);
}
}
return $relationships[$table];
}
/**
* Fetches the relationships between the specified column and other columns
* (in other tables)
* @param string $columnName
* @return array
*/
public function getColumnRelationships($columnName) {
$columnName = Util::camelTo_($columnName);
$relationships = array();
if ($info = $this->references[$columnName]) {
if ($info['constraintName'] != 'PRIMARY' && !empty($info['refTable'])) {
$this->setupRelationship($columnName, $info['refColumn'],
$info['refTable'], $relationships, false);
}
}
if ($info = $this->backReferences[$columnName]) {
if (!empty($info['refTable'])) {
$this->setupRelationship($columnName, $info['refColumn'],
$info['refTable'], $relationships, true);
}
}
return $relationships;
}
private function setupRelationship($columnName, $refColumn, $refTable,
array &$relationships, $push = true) {
return $relationships[$refTable][] = array(
'column' => $columnName,
'refColumn' => $refColumn,
'push' => $push
);
}
private function prepareColumns(Table $table = null, $alias = null) {
$ignoreJoins = false;
if (!$table) {
$table = $this;
$ignoreJoins = true;
}
$return = '';
if (!$table->hasTargetColumns() && $table->getModel() !== null && count($table->getModel()->toArray())) {
$table->targetColumns(array_keys($table->getRowModel()->toArray(true)));
}
else if (!$table->hasTargetColumns()) {
$table->targetColumns($table->getColumns(true));
}
foreach ($table->targetColumns as &$column) {
$column = Util::camelTo_(trim($column));
if ($return) $return .= ', ';
$return .= '`' . (($alias) ? $alias : $table->getName()) . '`.`' . $column . '`';
if ($this->joins && !$ignoreJoins) {
$return .= ' as ' . Util::_toCamel($table->getName()) . '_' . Util::_toCamel($column);
}
else if ($ignoreJoins) {
$return .= ' as ' . Util::_toCamel($column);
}
}
return $return;
}
/**
* This targets the query at the given columns
* @param array|string $columns Array or comma-separated string of columns
* @return Table
*/
public function targetColumns($columns) {
$this->targetColumns = is_array($columns) ? $columns : explode(',',
$columns);
return $this;
}
public function hasTargetColumns() {
return !is_null($this->targetColumns);
}
/**
* Selects the given columns from rows with the given criteria
* Many rows can be passed in as criteria
* @param array|string $columns Array or comma-separated string of columns
* @param array $criteria Array with values \DBScribe\Row or array of [column => value]
* @param int $return Indicates the type of result expected
* @return Table|ArrayCollection
*/
public function selectColumns($columns, array $criteria = array(),
$return = Table::RETURN_MODEL) {
$this->targetColumns($columns);
return $this->select($criteria, $return);
}
/**
* Selects rows from database
* Many rows can be passed in as criteria
* @param array $criteria Array with values \DBScribe\Row or array of [column => value]
* @param int $return Indicates the type of result expected
* @return Table|ArrayCollection
*/
public function select(array $criteria = array(),
$return = Table::RETURN_MODEL) {
if (!$this->checkExists()) {
return ($this->delayExecute) ? $this : new ArrayCollection();
}
$this->current = self::OP_SELECT;
$this->query = 'SELECT ' . $this->prepareColumns();
$this->query .= ' FROM `' . $this->name . '`' . $this->processJoins();
$this->where($criteria);
$this->setExpectedResult($return, true);
if ($this->delayExecute) {
return $this;
}
return $this->execute();
}
/**
* Fetches the results from cache if available
* @return array|nul
*/
private function getCached() {
if (isset($_GET['noCache'])) return null;
$cacheDir = DATA . 'select' . DIRECTORY_SEPARATOR;
if (!is_dir($cacheDir)) mkdir($cacheDir, 0777, true);
$cache = $cacheDir . base64_encode($this->getName()) . '.php';
if (!is_readable($cache)) return null;
$cached = include $cache;
return $this->decode($cached[$this->encode($this->query . serialize($this->values))]);
}
/**
* Saves the given result, if valid, to cache for future uses
* @param array $result
* @return boolean
*/
private function saveCache($result) {
if (!$result) return false;
$cache = DATA . 'select' . DIRECTORY_SEPARATOR . $this->encode($this->getName()) . '.php';
return Util::updateConfig($cache,
array($this->encode($this->query . serialize($this->values)) => $this->encode(serialize($result))));
}
/**
* Determines whether to retrieve data from cache or not.
* @param bool $bool
* @return \DBScribe\Table
*/
public function fromCache($bool = true) {
$this->fromCache = $bool;
return $this;
}
/**
* Checks whether the returned data is gotten from cache or not
* @return bool
*/
public function isCached() {
return $this->fromCache;
}
/**
* Removes cached result because the table has been updated
* @return bool
*/
private function removeCache() {
return unlink(DATA . 'select' . DIRECTORY_SEPARATOR . $this->encode($this->getName()) . '.php');
}
/**
* Encodes the given data
* @param string $data
* @return string
*/
private function encode($data) {
return base64_encode($data);
}
/**
* Decodes the given data and unserializes it
* @param string $data
* @return array|bool False if not unserializable. Array otherwise
*/
private function decode($data) {
return unserialize(base64_decode($data));
}
/**
* Sets the type of result expected
* @param int $expected One of \DBScribe\Table::RETURN_DEFAULT,
* \DBScribe\Table::RETURN_MODEL or \DBScribe\Table::RETURN_JSON
* @param bool $checkNotSet Only set if not already
* @return Table
*/
public function setExpectedResult($expected = Table::RETURN_MODEL,
$checkNotSet = false) {
if (!$checkNotSet || ($checkNotSet && is_null($this->expected)))
$this->expected = $expected;
return $this;
}
/**
* Create the where part of the query
* @param array $criteria Array of row column array
* @param bool $joinWithAnd Indicates whether to join the query with the
* previous one with the logical AND
* @param bool $notEqual Indicates whether not to equate the giveM value to actual
* column value
* @param boolean $valuesAreColumns Indicates whether the criteria values are columnNames
* @return Table
*/
public function where(array $criteria, $joinWithAnd = true,
$notEqual = false, $valuesAreColumns = false) {
if (count($criteria)) {
if (!$this->where) {
$this->where = ' WHERE (';
$opened = true;
}
// else if ($this->where && substr($this->where,
// strlen($this->where) - 1) === ')')
// $this->where = substr($this->where, 0,
// strlen($this->where) - 1);
if (substr($this->where, strlen($this->where) - 1) != '(') {
$this->where .= $joinWithAnd ? ' AND ' : ' OR ';
}
foreach ($criteria as $ky => $row) {
if ($ky) $this->where .= ' OR (';
$rowArray = $this->checkModel($row);
$cnt = 1;
foreach ($rowArray as $column => $value) {
if (!is_array($value)) {
$this->where .= '`' . $this->name . '`.`' . Util::camelTo_($column) . '` ';
$this->where .= ($notEqual) ? '!=' : '=';
if ($valuesAreColumns)
$this->where .= '`' . $this->name . '`.`' . Util::camelTo_($value) . '` ';
else {
$this->where .= ' ?';
$this->values[] = $value;
}
if (count($rowArray) > $cnt) $this->where .= ' AND ';
}
else {
$this->where .= '`' . $this->name . '`.`' . Util::camelTo_($column) . '` ';
$this->where .= ($notEqual) ? 'NOT IN' : 'IN';
$this->where .= ' (';
if ($valuesAreColumns) {
$n = 0;
foreach ($value as $val) {
if ($n) $this->where .= ', ';
$this->where .= '`' . $this->name . '`.`' .
Util::camelTo_($val) . '`';
$n++;
}
}
else {
$this->where .= '?' . str_repeat(',?',
count($value) - 1);
$this->values = $this->values ? array_merge($this->values,
$value) : $value;
}
$this->where .= ')';
}
$cnt++;
}
if ($opened) $this->where .= ')';
}
}
return $this;
}
/**
* Check if the intending query has conditions to go with it
* @return boolean
*/
public function hasCondition() {
return ($this->where || $this->customWhere);
}
/**
* Sets a column as the key to hold each result. Default is ID. This is only
* valid if return type IS NOT MODEL
* @param string $column
* @return \DBScribe\Table
*/
public function setResultKey($column) {
$this->resultKey = $column;
return $this;
}
private function returnSelect($return) {
if (!is_array($return)) {
$return = array();
}
$forThis = $this->relationshipData = array();
foreach ($return as &$ret) {
$imm = array();
foreach ($this->targetColumns as $col) {
$imm[Util::_toCamel($col)] = @$ret[Util::_toCamel($col)];
unset($ret[Util::_toCamel($col)]);
}
if ($this->resultKey && !empty($imm[Util::_toCamel($this->resultKey)])) {
$forThis[$imm[Util::_toCamel($this->resultKey)]] = $imm;
}
else if ($this->getPrimaryKey() && !empty($imm[Util::_toCamel($this->getPrimaryKey())])) {
$forThis[$imm[Util::_toCamel($this->getPrimaryKey())]] = $imm;
}
else $forThis[] = $imm;
if (!empty($ret)) {
$this->relationshipData[] = $ret;
}
}
switch ($this->expected) {
case self::RETURN_JSON:
$return = json_encode($forThis);
break;
case self::RETURN_MODEL:
$return = $this->createReturnModels($forThis);
break;
case self::RETURN_DEFAULT:
$return = $forThis;
break;
}
return $return;
}
private function createReturnModels(array $forThis) {
$rows = new ArrayCollection();
foreach ($forThis as $valueArray) {
$row = clone $this->rowModel;
foreach ($valueArray as $name => $value) {
if (method_exists($row, 'set' . $name))
$row->{'set' . $name}($value);
else $row->{$name} = $value;
}
$row->postFetch();
$row->setTable($this);
$rows->append($row);
}
return $rows;
}
/**
* Select a column where it is LIKE the value, i.e. it contains the given
* value *
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function like($column, $value, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` LIKE "' . $value . '"',
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where it is NOT LIKE the value, i.e. it does not contain
* the given value
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function notLike($column, $value, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` NOT LIKE "' . $value . '"',
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where it is less than the given value
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @param boolean $valueIsColumn Indicates whether the value is another columnName
* @return Table
*/
public function lessThan($column, $value, $logicalAnd = true,
$valueIsColumn = false) {
$value = $valueIsColumn ? '`:TBL:`.`' . \Util::camelTo_($value) . '`' :
'"' . $value . '"';
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` < ' . $value,
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where it is less than or equal to the given value
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @param boolean $valueIsColumn Indicates whether the value is another columnName
* @return Table
*/
public function lessThanOrEqualTo($column, $value, $logicalAnd = true,
$valueIsColumn = false) {
$value = $valueIsColumn ? '`:TBL:`.`' . \Util::camelTo_($value) . '`' :
'"' . $value . '"';
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` <= ' . $value,
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where it is greater than the given value
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @param boolean $valueIsColumn Indicates whether the value is another columnName
* @return Table
*/
public function greaterThan($column, $value, $logicalAnd = true,
$valueIsColumn = false) {
$value = $valueIsColumn ? '`:TBL:`.`' . \Util::camelTo_($value) . '`' :
'"' . $value . '"';
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` > ' . $value,
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where it is greater than or equal to the given value
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @param boolean $valueIsColumn Indicates whether the value is another columnName
* @return Table
*/
public function greaterThanOrEqualTo($column, $value, $logicalAnd = true,
$valueIsColumn = false) {
$value = $valueIsColumn ? '`:TBL:`.`' . \Util::camelTo_($value) . '`' :
'"' . $value . '"';
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` >= ' . $value,
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Finds rows that matches the given range of values in the required column
* @param string $column
* @param mixed $value1
* @param mixed $value2
* @param boolean $logicalAnd Indicates whether to use the logical AND [TRUE] or OR [FALSE]
*/
public function between($column, $value1, $value2, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` BETWEEN "'
. $value1 . '" AND "' . $value2 . '" ',
$logicalAnd ? 'AND' : 'OR');
}
/**
* Query the table where the given values are equal to the corresponding
* column value in the table
* @param array $criteria
* @param boolean $joinWithAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @param boolean $valuesAreColumns Indicates whether the values are columnNames
* @return Table
*/
public function equal(array $criteria, $joinWithAnd = true,
$valuesAreColumns = false) {
$this->where($criteria, $joinWithAnd, false, $valuesAreColumns);
return $this;
}
/**
* Query the table where the given values are not equal to the corresponding
* column value in the table
* @param array $criteria
* @param boolean $joinWithAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @param boolean $valuesAreColumns Indicates whether the values are columnNames
* @return Table
*/
public function notEqual(array $criteria, $joinWithAnd = true,
$valuesAreColumns = false) {
$this->where($criteria, $joinWithAnd, true, $valuesAreColumns);
return $this;
}
/**
* Select a column where the value matches the regular expression
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function regExp($column, $value, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` REGEXP "' . $value . '"',
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where the value does not match the regular expression
* @param string $column
* @param mixed $value
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function notRegExp($column, $value, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` NOT REGEXP "' . $value . '"',
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where the value is null
* @param string $column
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function isNull($column, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` IS NULL',
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where the value is not null
* @param string $column
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function isNotNull($column, $logicalAnd = true) {
$this->customWhere('`:TBL:`.`' . Util::camelTo_($column) . '` IS NOT NULL',
$logicalAnd ? 'AND' : 'OR');
return $this;
}
/**
* Select a column where the values of the given columns are null
* @param string $columns
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function areNull(array $columns, $logicalAnd = true) {
foreach ($columns as $column) {
$this->isNull($column, $logicalAnd);
}
return $this;
}
/**
* Select a column where the values of the given columns are not null
* @param string $columns
* @param boolean $logicalAnd Indicates whether to use logical AND (TRUE) or OR (FALSE)
* @return Table
*/
public function areNotNull(array $columns, $logicalAnd = true) {
foreach ($columns as $column) {
$this->isNotNull($column, $logicalAnd);
}
return $this;
}
/**
* Start grouping criteria with a parenthesis
* @param boolean $logicalAnd
* @return \DBScribe\Table
*/
public function startGroup($logicalAnd = true) {
if ($this->where)
$this->where .= ' ' . ($logicalAnd ? 'AND' : 'OR') . ' (';
else $this->where = ' WHERE (';
return $this;
}
/**
* Ends the parenthesis group
* @return \DBScribe\Table
*/
public function endGroup() {
if ($this->where) $this->where .= ')';
return $this;
}
/**
* Adds a custom query to the existing query. If no query exists, it serves as
* the query.
* @param string $custom
* @param string $logicalConnector Logical operator to link the <i><b>custom where</b></i>
* with the <i><b>regular where</b></i> if available
* @param string $tablePlaceholder A string within the custom where to be
* replaced with the table name. Useful when a table prefix might have been
* used
* @return Table
*/
public function customWhere($custom, $logicalConnector = 'AND',
$tablePlaceholder = ':TBL:') {
if ($this->where && substr($this->where, strlen($this->where) - 1) != '(')
$this->where .= ' ' . $logicalConnector;
else if (!$this->where) $this->where = ' WHERE ';
$this->where .= trim(str_replace($tablePlaceholder, $this->name, $custom));
return $this;
}
/**
* Group result by data in given column
* @param string $columnName
* @return Table
*/
public function groupBy($columnName) {
$this->groups[] = $columnName;
return $this;
}
/**
* Fetch rows that fulfill the given condition
* @param string $condition Ready-made query e.g `:TBL:`.`id` > 2
* @return Table
*/
public function having($condition, $tablePlaceholder = ':TBL:') {
$this->having = trim(str_replace($tablePlaceholder, $this->name,
$condition));
return $this;
}
/**
* Fetch results whose data in the given column is in the given array
* of values
* @param string $column
* @param array $values
* @param boolean $logicalAnd Indicates whether to join the in query to the
* rest of the query with an AND (TRUE) or an OR (FALSE)
* @param boolean $valuesAreColumns Indicates whether the values are columnNames
* @return Table
*/
public function in($column, array $values, $logicalAnd = true,
$valuesAreColumns = false) {
$this->where(array(array($column => $values)), $logicalAnd, false,
$valuesAreColumns);
return $this;
}
/**
* Fetch results whose data in the given column are in the given array
* of values
* @param string $column
* @param array $values
* @param boolean $logicalAnd Indicates whether to join the in query to the
* rest of the query with an AND (TRUE) or an OR (FALSE)
* @param boolean $valuesAreColumns Indicates whether the values are columnNames
* @return Table
*/
public function notIn($column, array $values, $logicalAnd = true,
$valuesAreColumns = false) {
$this->where(array(array($column => $values)), $logicalAnd, true,
$valuesAreColumns);
return $this;
}
/**
* Joins with the given table
* @param string|Table $table
* @param array $options Keys include [rowModel]
*/
public function join($table, array $options = array()) {
$this->joins[$table] = $options;
return $this;
}
private function processJoins() {
$this->joinQuery = '';
$superStart = false;
foreach ($this->joins as $table => $options) {
$relationships = $this->getTableRelationships($table);
if (!count($relationships)) continue;
if (!is_object($table)) {
$table = new Table($table, $this->connection);
}
$alias = substr($table->getName(), 0, 1) .
substr($table->getName(), count($table->getName()) - 1, 1);
$this->query .= ', ' .
$this->prepareColumns($table,
($table->getName() == $this->name) ?
$alias : null);
$this->joinQuery .= ' LEFT OUTER JOIN `' . $table->getName() . '`' .
(($table->getName() == $this->name) ? ' ' . $alias : null);
$started = false;
foreach ($relationships as $ky => $rel) {
if (($rel['push'] && isset($options['pull']) && @$options['push']) ||
(!$rel['push'] && isset($options['pull']) && !$options['pull']))
continue;
if ($ky && $started) $this->joinQuery .= 'OR ';
if (!$started) $this->joinQuery .= ' ON ';
$started = true;
$superStart = true;
$this->joinQuery .= '`' . $this->name . '`.`' . $rel['column'] .
'` = ' . (($table->getName() == $this->name) ?
$alias : '`' . $table->getName() . '`') . '.`' .
$rel['refColumn'] . '` ';
if (isset($options['where'])) {
foreach ($options['where'] as $column => $value) {
$this->joinQuery .= 'AND `' . $table->getName() . '`.`' . Util::camelTo_($column) . '` = ? ';
$this->values[] = $value;
}
}
}
}
if ($this->joinQuery && !$superStart)
throw new Exception('Joined table(s) must have something in common with the current table "' . $this->name . '"');
$this->joins = array();
return $this->joinQuery;
}
/**
* Checks the joined data for rows that have the value needed in a column
* @param string $tableName
* @param array $columns Key to value of column to value
* @param Row $object
* @param array $options
* @return ArrayCollection
*/
final public function seekJoin($tableName, array $columns,
Row $object = null, array $options = array()) {
if (!$this->joinQuery) return false;
$prefix = $this->connection->getTablePrefix() . $tableName . '_';
if (!$object) {
$object = new Row();
}
$array = array();
foreach ($this->relationshipData as $data) {
foreach ($columns as $column => $value) {
$compare = $prefix . $column;
if ($data[$compare] === null) continue;
$found = true;
if ((!is_array($value) && @$data[$compare] != $value) || (is_array($value) &&
!in_array(@$data[$compare], $value))) {
$found = false;
}
if (!$found) break;
}
if ($found) {
$d = array();
foreach ($data as $col => $val) {
$d[str_replace($prefix, '', $col)] = $val;
}
$ob = clone $object;
$array[] = $ob->populate($d);
}
}
$this->parseWithOptions($array, $options);
return count($array) ? new ArrayCollection($array) : false;
}
private function parseWithOptions(array &$array, array $options) {
if (isset($options[0]['orderBy'])) {
usort($array,
function($a, $b) use($options) {
if (is_array($options[0]['orderBy'])) {
foreach ($options[0]['orderBy'] as $order) {
$comp = is_array($order) ?
$this->compareOrder($order['position'], $a, $b) :
$this->compareOrder($order, $a, $b);
if ($comp) {
return $comp;
}
}
}
else {
return $this->compareOrder($options[0]['orderBy'], $a, $b);
}
});
}
$array = array_values($array);
if (isset($options[0]['limit'])) {
if (!isset($options[0]['limit']['start'])) {
$options[0]['limit']['start'] = 0;
}
if (!isset($options[0]['limit']['count'])) {
$options[0]['limit']['count'] = count($array) - (int) $options['0']['limit']['start'];
}
$array = array_slice($array, $options[0]['limit']['start'],
$options[0]['limit']['count']);
}
return $array;
}
private function compareOrder($order, $a, $b) {
$method = 'get' . ucfirst($order);
if (method_exists($a, $method)) {
$value1 = $a->$method();
$value2 = $b->$method();
}
else {
$value1 = $a->$order;
$value2 = $b->$order;
}
return strcmp($value1, $value2);
}
/**
* Checks if the row is a valid \DBScribe\Row row
* @param array|object $row
* @param boolean $preSave Indicates whether to call the presave function of the row
* @throws Exception
* @return array|boolean
*/
private function checkModel($row, $preSave = false) {
if (!is_array($row) && !is_object($row))
throw new Exception('Each element of param $where must be an object of, or one that extends, "DBScribe\Row", or an array of [column => value]: ' . print_r($row,
true));
if (empty($this->columns)) return array();
if (is_array($row)) {
return $row;
}
elseif (is_object($row) && get_class($row) === 'DBScribe\Row' || in_array('DBScribe\Row',
class_parents($row))) {
if ($preSave) $row->preSave();
$this->rowModelInUse = $row;
return $row->toArray(($this->current !== self::OP_SELECT));
}
}
/**
* Orders the returned rows
* @param string $column
* @param string $direction One of \DBScribe\Table::ORDER_ASC or \DBScribe\Table::ORDER_DESC
* @return Table
*/
public function orderBy($column, $direction = Table::ORDER_ASC) {
$this->orderBy[] = '`' . Util::camelTo_($column) . '` ' . $direction;
return $this;
}
/**
* Limits the number of rows to return
* @param int $count No of rows to return
* @param int $start Row no to start from
* @return Table
*/
public function limit($count, $start = 0) {
$this->limit = 'LIMIT ' . $start . ', ' . $count;
return $this;
}
/**
* Counts the number of rows in the table based on a column
* @param string $column The column to count
* @return Int
*/
public function count($column = '*', $criteria = array(),
$return = Table::RETURN_DEFAULT) {
$this->query = 'SELECT COUNT(' . Util::camelTo_($column) . ') as rows FROM `' . $this->name . '`';
$this->where($criteria);
$this->setExpectedResult($return, true);
if ($ret = $this->execute()) {
return ($ret) ? $ret[0]['rows'] : 0;
}
return 0;
}
/**
* Gets the distinct values of a column
* @param string $column
* @param array $criteria Array with values \DBScribe\Row or array of [column => value]
* @return ArrayCollection
*/
public function distinct($column, array $criteria = array(),
$return = Table::RETURN_MODEL) {
$this->current = self::OP_SELECT;
$this->setExpectedResult($return, true);
$this->targetColumns($column);
$this->query = 'SELECT DISTINCT `' . $this->name . '`.`' . Util::camelTo_($column) . '` as ' . Util::_toCamel($column) . ' FROM `' . $this->name . '` ' . $this->joinQuery;
$this->where($criteria);
return $this->execute();
}
/**
* Updates the given row(s) in the table<br />
* Many rows can be updated at once.
* @param array $values Array with values \DBScribe\Row or array of [column => value]
* @param string $whereColumn Column name to check. Default is the id column
* @todo Allow multiple columns as criteria where
* @return Table
*/
public function update(array $values, $whereColumn = 'id') {
if (!$this->checkExists()) return false;
$this->current = self::OP_UPDATE;
$this->query = 'UPDATE `' . $this->name . '` SET ';
if (!is_array($whereColumn)) $whereColumn = array($whereColumn);
foreach ($whereColumn as &$col) {
$col = Util::camelTo_($col);
}
$nColumns = 0;
$columns = array();
foreach (array_values($values) as $ky => $row) {
$rowArray = $this->checkModel($row, true);
if ($ky == 0) $nColumns = array_keys($rowArray);
if (count(array_keys($rowArray)) !== count($nColumns))
throw new Exception('All rows must have the same number of columns in table "' . $this->name .
'". Set others as null');
if (count($rowArray) === 0)
throw new Exception('You cannot insert an empty row into table "' . $this->name . '"');
$cnt = 1;
foreach ($rowArray as $column => &$value) {
if (empty($value) && $value != 0) continue;
if ($cnt > 1 && !in_array($column, $nColumns)) {
throw new Exception('All rows must have the same column names.');
}
$column = Util::camelTo_($column);
if ($this->getPrimaryKey() == $column) {
if (in_array($this->getPrimaryKey(), $whereColumn)) {
$this->values[$ky][':' . $column] = $value;
}
continue;
}
$this->values[$ky][':' . $column] = $value;
if (in_array($column, array_merge($columns, $whereColumn))) {
$cnt++;
continue;
}
$this->query .= '`' . $column . '` = :' . $column;
if (count($rowArray) > $cnt) $this->query .= ', ';
$columns[] = $column;
$cnt++;
}
foreach ($whereColumn as $column) {
$column = Util::camelTo_($column);
$this->value[$ky][':' . $column] = $rowArray[$column];
}
}
$this->query = (substr($this->query, strlen($this->query) - 2) === ', ')
?
substr($this->query, 0, strlen($this->query) - 2) : $this->query;
$this->query .= ' WHERE ';
foreach ($whereColumn as $key => $where) {
$where = Util::camelTo_($where);
if ($key) $this->query .= ' AND ';
$this->query .= '`' . $where . '`=:' . $where;
}
$this->multiple = true;
$this->doPost = self::OP_UPDATE;
if ($this->delayExecute) {
return $this;
}
return $this->execute();
}
/**
* Updates rows that exist and creates those that don't
* @param array $values
* @param string|integer|array $whereColumn
* @param string|bool $generateIds If string, indicates a YES and the primary column name.
* If bool TRUE, it indicates YES and primay column name 'id'
* If bool FALSE, it indicates NO.
* @return boolean
* @todo Refactor to accomodate large bulk of data
*/
public function upsert(array $values, $whereColumn = 'id',
$generateIds = true) {
if (!is_array($whereColumn)) $whereColumn = array($whereColumn);
if (!$this->checkExists()) return false;
$this->current = self::OP_INSERT;
$this->query = 'INSERT INTO `' . $this->name . '` (';
$columns = array();
$noOfColumns = 0;
$update = '';
foreach (array_values($values) as $ky => $row) {
$rowArray = $this->checkModel($row, true);
if ($ky === 0) $noOfColumns = count($rowArray);
if (count($rowArray) === 0)
throw new Exception('You cannot insert an empty row into table "' . $this->name . '"');
if ($generateIds) {
$id = is_string($generateIds) ? $generateIds : 'id';
if (!array_key_exists($id, $rowArray))
$rowArray[$id] = Util::createGUID();
}
if ($generateIds) {
$id = is_string($generateIds) ? $generateIds : 'id';
if (!array_key_exists($id, $rowArray))
$rowArray[$id] = Util::createGUID();
}
foreach ($rowArray as $column => &$value) {
if (empty($value) && $value != 0) continue;
$column = Util::camelTo_($column);
if (!$ky && !in_array($column, $whereColumn)) {
if ($update) $update .= ', ';
$update .= '`' . $column . '`=VALUES(' . $column . ')';
}
if (!in_array($column, $columns)) $columns[] = $column;
$this->values[$ky][':' . $column] = $value;
}
}
$this->query .= '`' . join('`, `', $columns) . '`';
$this->query .= ') VALUES (';
$this->query .= ':' . join(', :', $columns);
$this->query .= ') ON DUPLICATE KEY UPDATE ';
$this->query .= $update;
$this->multiple = true;
$this->doPost = self::OP_INSERT;
if ($this->delayExecute) {
return $this;
}
return $this->execute();
}
/**
* Deletes the given row(s) in the table<br />
* Many rows can be deleted at once.
* @param array $criteria Array with values \DBScribe\Row or values of [column => value]
* @return Table
*/
public function delete(array $criteria = array()) {
if (!$this->checkExists()) return false;
$this->current = self::OP_DELETE;
$this->query = 'DELETE FROM `' . $this->name . '`';
if (!empty($criteria)) $this->query .= ' WHERE ';
foreach ($criteria as $ky => $row) {
$rowArray = $this->checkModel($row, false);
$cnt = 0;
foreach ($rowArray as $column => $value) {
if (!is_object($value) && $value === null) {
continue;
}
$column = Util::camelTo_($column);
if ($cnt) $this->query .= ' AND ';
$this->query .= '`' . $column . '` = ?';
$this->values[] = $value;
$cnt++;
}
if ($ky < (count($criteria) - 1)) $this->query .= ' OR ';
}
if ($this->delayExecute) {
return $this;
}
return $this->execute();
}
/**
* Indicates whether to delay database operation until method execute() is called
* @param boolean $delay
* @return Table
*/
public function delayExecute($delay = true) {
$this->delayExecute = $delay;
return $this;
}
/**
* Allows reuse of parameters
* @param boolean $bool
* @return \DBScribe\Table
*/
public function reuseParams($bool = true) {
$this->reuseParams = $bool;
return $this;
}
/**
* Executes the delayed database operation
* @return mixed
*/
public function execute() {
if (!$this->checkExists()) {
if ($this->current === self::OP_SELECT) {
return new ArrayCollection();
}
return false;
}
$this->createQuery();
$model = ($this->expected) ? $this->getRowModel() : null;
if ($this->current === self::OP_SELECT && $this->isCached()) {
$result = $this->getCached();
}
if (!$result) {
if ($this->preserveQueries && $this->current !== self::OP_SELECT) // keep all queries except selects
$this->doPreserveQueries();
$result = $this->connection->doPrepare($this->query, $this->values,
array(
'multipleRows' => $this->multiple,
'model' => $model
));
if ($this->current === self::OP_SELECT) $this->saveCache($result);
else $this->removeCache();
}
if ($this->current === self::OP_SELECT)
$result = $this->returnSelect($result);
$this->lastQuery = $this->query . '<pre><code>' . print_r($this->values,
true) . '</code></pre>';
$this->resetQuery();
return $result;
}
/**
* Fetches the last query executed
* @return string
*/
public function getLastQuery() {
return $this->lastQuery;
}
private function createQuery() {
if ($this->genQry) return $this->query;
if (!empty($this->customWhere)) {
if ($this->where) {
$this->where .= ' ' . $this->customWhereJoin . ' ' . $this->customWhere;
}
else {
$this->where = ' WHERE ' . $this->customWhere;
}
}
if ($this->current === self::OP_SELECT) {
if ($this->groups) {
$this->where .= ' GROUP BY ';
foreach ($this->groups as $ky => $column) {
if ($ky) $this->where .= ', ';
$this->where .= '`' . $this->name . '`.`' . $column . '`';
}
}
if ($this->having) {
$this->where .= ' HAVING ' . $this->having;
}
}
if (!empty($this->orderBy)) {
$this->where .= ' ORDER BY ';
foreach ($this->orderBy as $ky => $order) {
$this->where .= $order;
if ($ky < (count($this->orderBy) - 1)) $this->where .= ', ';
}
}
$this->where .= ' ' . $this->limit;
if (($this->current === self::OP_SELECT || !empty($this->customWhere)) &&
!stristr($this->query, ' from')) {
$this->query .= ' FROM `' . $this->name . '`';
}
$this->query .= $this->where;
$this->genQry = true;
return $this->query;
}
/**
* Fetches the query to execute
* @param bool $withValues
* @return string
*/
public function getQuery($withValues = false) {
return $withValues ? $this->createQuery() . '<pre><code>' . print_r($this->getQueryValues(),
true) . '</code></pre>' : $this->createQuery();
}
/**
* Fetches the values to pass in to the query
* @return array
*/
public function getQueryValues() {
return $this->values;
}
private function resetQuery() {
$this->query = null;
$this->genQry = false;
$this->targetColumns = null;
$this->orderBy = array();
$this->limit = null;
$this->customWhere = null;
if (!$this->reuseParams) {
$this->where = null;
$this->values = null;
}
$this->having = null;
$this->groups = array();
$this->current = null;
$this->multiple = false;
$this->expected = null;
}
/**
* Fetches the autogenerated id of the last insert statement, if primary key is autogenerated
* @return mixed
*/
public function lastInsertId() {
return $this->connection->lastInsertId();
}
}
| {
"content_hash": "53451894a261e04d7831691c91c1fcce",
"timestamp": "",
"source": "github",
"line_count": 2189,
"max_line_length": 179,
"avg_line_length": 31.886706258565557,
"alnum_prop": 0.5209312320916906,
"repo_name": "ezra-obiwale/DBScribe",
"id": "11c0d0ce070180a986cb1b9a9968478281db8b38",
"size": "69800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "8"
},
{
"name": "PHP",
"bytes": "180086"
}
],
"symlink_target": ""
} |
var path = require('path'),
globalConfigs = require(path.resolve(__dirname, './globalConfigs'));
// Dir Paths
var LIB_DIR = globalConfigs.paths.LIB_DIR;
UTIL_DIR = globalConfigs.paths.UTIL_DIR;
// Export Configs
module.exports = {
modules : {
'regexDict' : require(LIB_DIR + 'regexDict'),
'enExceptions' : require(LIB_DIR + 'enExceptions'),
// 'stemRuleMapper' : require(LIB_DIR + 'stemRules')
},
languageStemRules : {
'en' : require(UTIL_DIR + 'enStemRules')
}
};
| {
"content_hash": "24048651e991e732e0b8e848be2b2c07",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 72,
"avg_line_length": 28.166666666666668,
"alnum_prop": 0.6370808678500987,
"repo_name": "sramzan/bo-sr-stem",
"id": "0a5305cde8447a45f85819fe608ba61958f29e35",
"size": "571",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/server/common/configs/stemmerConfigs.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "503"
},
{
"name": "HTML",
"bytes": "4442"
},
{
"name": "JavaScript",
"bytes": "34530"
}
],
"symlink_target": ""
} |
A self-hosted chat app for small teams built by [Security Compass][seccom].
## Features and Stuff
* BYOS (bring your own server)
* Persistent messages
* Multiple rooms
* Private and password-protected rooms
* New message alerts / notifications
* Mentions (hey @you/@all)
* Image embeds / Giphy search
* Code pasting
* File uploads (Local / [Amazon S3][s3] / [Azure][azure])
* Transcripts / chat history
* XMPP Multi-user chat (MUC)
* 1-to-1 chat between XMPP users
* Local / [Kerberos][kerberos] / [LDAP][ldap] authentication
* [Hubot Adapter][hubot]
* REST-like API
* Basic i18n support
* MIT Licensed
## Deployment
For installation instructions, please use the following links:
* [Local installation][install-local]
* [Docker][install-docker]
* [Heroku][install-heroku]
* [Vagrant][install-vagrant]
## Support & Problems
We have a [troubleshooting document][troubleshooting], otherwise please use our
[mailing list][mailing-list] for support issues and questions.
## Bugs and feature requests
Have a bug or a feature request? Please first read the [issue
guidelines][contributing] and search for existing and closed issues. If your
problem or idea is not addressed yet, [please open a new issue][new-issue].
## Documentation
Let's Chat documentation is hosted in the [wiki]. If there is an inaccuracy in
the documentation, [please open a new issue][new-issue].
## Contributing
Please read through our [contributing guidelines][contributing]. Included are
directions for opening issues, coding standards, and notes on development.
Editor preferences are available in the [editor config][editorconfig] for easy
use in common text editors. Read more and download plugins at
<http://editorconfig.org>.
## License
Released under [the MIT license][license].
[wiki]: https://github.com/sdelements/lets-chat/wiki
[troubleshooting]: https://github.com/sdelements/lets-chat/blob/master/TROUBLESHOOTING.md
[mailing-list]: https://groups.google.com/forum/#!forum/lets-chat-app
[tracker]: https://github.com/sdelements/lets-chat/issues
[contributing]: https://github.com/sdelements/lets-chat/blob/master/CONTRIBUTING.md
[new-issue]: https://github.com/sdelements/lets-chat/issues/new
[editorconfig]: https://github.com/sdelements/lets-chat/blob/master/.editorconfig
[license]: https://github.com/sdelements/lets-chat/blob/master/LICENSE
[ldap]: https://github.com/sdelements/lets-chat-ldap
[kerberos]: https://github.com/sdelements/lets-chat-kerberos
[s3]: https://github.com/sdelements/lets-chat-s3
[seccom]: http://securitycompass.com/
[hubot]: https://github.com/sdelements/hubot-lets-chat
[azure]: https://github.com/maximilian-krauss/lets-chat-azure
[install-local]: https://github.com/sdelements/lets-chat/wiki/Installation
[install-docker]: https://registry.hub.docker.com/u/sdelements/lets-chat/
[install-heroku]: https://github.com/sdelements/lets-chat/wiki/Heroku
[install-vagrant]: https://github.com/sdelements/lets-chat/wiki/Vagrant
| {
"content_hash": "733a9ef7232c2c41f0b1b2c8caed3c6f",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 89,
"avg_line_length": 35.214285714285715,
"alnum_prop": 0.7647058823529411,
"repo_name": "8bitjeremy/velochat",
"id": "d3761c20a2396d7aeb1f782c04d653196abad37a",
"size": "3027",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24551"
},
{
"name": "HTML",
"bytes": "46148"
},
{
"name": "JavaScript",
"bytes": "252926"
}
],
"symlink_target": ""
} |
package brown.tracingplane.atomlayer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.junit.Test;
import brown.tracingplane.atomlayer.AtomLayerSerialization;
public class TestSerialization {
@Test
public void testSerializeNulls() {
assertNotNull(AtomLayerSerialization.serialize(null));
assertNotNull(AtomLayerSerialization.serialize(new ArrayList<ByteBuffer>()));
assertEquals(0, AtomLayerSerialization.serialize(null).length);
assertEquals(0, AtomLayerSerialization.serialize(new ArrayList<ByteBuffer>()).length);
}
}
| {
"content_hash": "d5f5eea72274defc37bbd3bcad905425",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 94,
"avg_line_length": 29.956521739130434,
"alnum_prop": 0.7663280116110305,
"repo_name": "JonathanMace/tracingplane",
"id": "4f47c00f983d6269fa60626659975fc392bb7d8a",
"size": "689",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "atomlayer/core/src/test/java/brown/tracingplane/atomlayer/TestSerialization.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "BlitzBasic",
"bytes": "1721"
},
{
"name": "CSS",
"bytes": "12981"
},
{
"name": "Java",
"bytes": "620169"
},
{
"name": "Scala",
"bytes": "53570"
}
],
"symlink_target": ""
} |
<?php
namespace Dudulina\CodeGeneration\Event;
use Dudulina\CodeGeneration\Command\AggregateCommandValidatorDetector;
use Dudulina\CodeGeneration\Command\ReadModelEventHandlerDetector;
use Dudulina\CodeGeneration\Command\WriteSideEventHandlerDetector;
use Gica\CodeAnalysis\MethodListenerDiscovery;
use Gica\CodeAnalysis\MethodListenerDiscovery\ListenerClassValidator\AnyPhpClassIsAccepted;
use Gica\CodeAnalysis\MethodListenerDiscovery\MapCodeGenerator;
use Gica\CodeAnalysis\MethodListenerDiscovery\MapCodeGenerator\GroupedByEventMapCodeGenerator;
class SagaEventProcessorsMapCodeGenerator implements \Dudulina\CodeGeneration\CodeGenerator
{
public function generateClass(string $template, \Iterator $filesToSearchForHandlers): string
{
$map = $this->getListenerDiscovery()->discoverListeners($filesToSearchForHandlers);
return $this->getCodeGenerator()->generateAndGetFileContents($map, $template);
}
private function getListenerDiscovery(): MethodListenerDiscovery
{
return new MethodListenerDiscovery(
new WriteSideEventHandlerDetector(),
new AnyPhpClassIsAccepted);
}
private function getCodeGenerator(): MapCodeGenerator
{
return new GroupedByEventMapCodeGenerator();
}
} | {
"content_hash": "bdb87073d31416a7b485ed3aef53704f",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 96,
"avg_line_length": 38.666666666666664,
"alnum_prop": 0.8040752351097179,
"repo_name": "xprt64/cqrs-es",
"id": "e0317fc5f4d56f3055be8bc74f95f327a16502fa",
"size": "1343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Dudulina/CodeGeneration/Event/SagaEventProcessorsMapCodeGenerator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "286245"
},
{
"name": "Shell",
"bytes": "489"
}
],
"symlink_target": ""
} |
require 'prawn/literal_string'
require 'prawn/reference'
module Prawn
module NameTree #:nodoc:
class Node #:nodoc:
attr_reader :children
attr_reader :limit
attr_reader :document
attr_accessor :parent
attr_accessor :ref
def initialize(document, limit, parent=nil)
@document = document
@children = []
@limit = limit
@parent = parent
@ref = nil
end
def empty?
children.empty?
end
def size
leaf? ? children.size : children.inject(0) { |sum, child| sum + child.size }
end
def leaf?
children.empty? || children.first.is_a?(Value)
end
def add(name, value)
self << Value.new(name, value)
end
def to_hash
hash = {}
hash[:Limits] = [least, greatest] if parent
if leaf?
hash[:Names] = children if leaf?
else
hash[:Kids] = children.map { |child| child.ref }
end
return hash
end
def least
if leaf?
children.first.name
else
children.first.least
end
end
def greatest
if leaf?
children.last.name
else
children.last.greatest
end
end
def <<(value)
if children.empty?
children << value
elsif leaf?
children.insert(insertion_point(value), value)
split! if children.length > limit
else
fit = children.detect { |child| child >= value }
fit = children.last unless fit
fit << value
end
value
end
def >=(value)
children.empty? || children.last >= value
end
def split!
if parent
parent.split(self)
else
left, right = new_node(self), new_node(self)
split_children(self, left, right)
children.replace([left, right])
end
end
protected
def split(node)
new_child = new_node(self)
split_children(node, node, new_child)
index = children.index(node)
children.insert(index+1, new_child)
split! if children.length > limit
end
private
def new_node(parent=nil)
node = Node.new(document, limit, parent)
node.ref = document.ref!(node)
return node
end
def split_children(node, left, right)
half = (node.limit+1)/2
left_children, right_children = node.children[0...half], node.children[half..-1]
left.children.replace(left_children)
right.children.replace(right_children)
unless node.leaf?
left_children.each { |child| child.parent = left }
right_children.each { |child| child.parent = right }
end
end
def insertion_point(value)
children.each_with_index do |child, index|
return index if child >= value
end
return children.length
end
end
class Value #:nodoc:
include Comparable
attr_reader :name
attr_reader :value
def initialize(name, value)
@name, @value = Prawn::LiteralString.new(name), value
end
def <=>(leaf)
name <=> leaf.name
end
def inspect
"#<Value: #{name.inspect} : #{value.inspect}>"
end
def to_s
"#{name} : #{value}"
end
end
end
end
| {
"content_hash": "194b6af9c99c46a74451978fe8bab677",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 90,
"avg_line_length": 22.132911392405063,
"alnum_prop": 0.5295967972547898,
"repo_name": "Santhoshonet/ticketingSystem",
"id": "c7d20c881359fc0c895641c7f7a9b2991641e458",
"size": "3706",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "vendor/gems/prawn-layout-0.3.2/vendor/prawn-core/lib/prawn/name_tree.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "99868"
},
{
"name": "Ruby",
"bytes": "89580"
}
],
"symlink_target": ""
} |
export DEBIAN_FRONTEND=noninteractive
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 && echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
curl -sL https://deb.nodesource.com/setup | bash -
apt-get update && apt-get install --no-install-recommends -y nodejs git vim mongodb-org
# change global node module directory
echo prefix = /home/vagrant/.node >> /home/vagrant/.npmrc
echo "export PATH=\$PATH:/home/vagrant/.node/bin" >> /home/vagrant/.bashrc
echo "export NODE_PATH=\$NODE_PATH:/home/vagrant/.node/lib/node_modules" >> /home/vagrant/.bashrc
source /home/vagrant/.bashrc
# install yo grunt bower generator-meanjs as non-root user
su -c "npm install -g yo grunt-cli bower generator-meanjs" vagrant
| {
"content_hash": "3d763b619f462f270680b1872c00acdd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 198,
"avg_line_length": 61.69230769230769,
"alnum_prop": 0.7556109725685786,
"repo_name": "LarngearTech/codelinks",
"id": "b11367b4dd05467e9941826cb13b5418db1f00fc",
"size": "827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vagrant/bootstrap.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "110"
},
{
"name": "JavaScript",
"bytes": "6144"
},
{
"name": "Ruby",
"bytes": "2845"
},
{
"name": "Shell",
"bytes": "976"
}
],
"symlink_target": ""
} |
package co.cask.cdap.data2.transaction.stream;
import co.cask.cdap.proto.Id;
import java.io.IOException;
/**
* Factory for creating {@link StreamConsumerStateStore} instance for different streams.
*/
public interface StreamConsumerStateStoreFactory {
/**
* Creates a {@link StreamConsumerStateStore} for the given stream.
*
* @param streamConfig Configuration of the stream.
* @return a new state store instance.
*/
StreamConsumerStateStore create(StreamConfig streamConfig) throws IOException;
/**
* Deletes all consumer state stores.
*/
void dropAllInNamespace(Id.Namespace namespace) throws IOException;
}
| {
"content_hash": "0a62333e5dfeb71c284e7f7ea6193752",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 88,
"avg_line_length": 25.84,
"alnum_prop": 0.7507739938080495,
"repo_name": "anthcp/cdap",
"id": "244c1c403bed66e4b098d9ef807b6f6f9199f12f",
"size": "1243",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "cdap-data-fabric/src/main/java/co/cask/cdap/data2/transaction/stream/StreamConsumerStateStoreFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "33104"
},
{
"name": "CSS",
"bytes": "202988"
},
{
"name": "HTML",
"bytes": "421224"
},
{
"name": "Java",
"bytes": "14928080"
},
{
"name": "JavaScript",
"bytes": "1065462"
},
{
"name": "Python",
"bytes": "97949"
},
{
"name": "Scala",
"bytes": "24273"
},
{
"name": "Shell",
"bytes": "184239"
}
],
"symlink_target": ""
} |
package com.datatorrent.common.util;
/**
* <p>ScheduledExecutorService interface.</p>
*
* @since 0.3.2
*/
public interface ScheduledExecutorService extends java.util.concurrent.ScheduledExecutorService
{
/**
*
* @return long
*/
public long getCurrentTimeMillis();
}
| {
"content_hash": "c73fb1d2003a0a6e46867e8dd8995909",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 95,
"avg_line_length": 18.375,
"alnum_prop": 0.6870748299319728,
"repo_name": "PramodSSImmaneni/apex-core",
"id": "0e2aff0f9c5286dfa6a329c03a19ae888afab02e",
"size": "1102",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "common/src/main/java/com/datatorrent/common/util/ScheduledExecutorService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "843"
},
{
"name": "Java",
"bytes": "3337721"
},
{
"name": "Shell",
"bytes": "3865"
},
{
"name": "XSLT",
"bytes": "1758"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
class Publicacion(models.Model):
titulo = models.CharField(max_length=50)
contenido = models.TextField()
autor = models.ForeignKey(User, on_delete=models.CASCADE, editable=False)
publicado = models.DateField(auto_now_add=True)
slug = models.SlugField(editable=False)
def __str__(self):
return self.titulo.encode('utf-8', errors='strict')
class Meta:
ordering = ('titulo',)
verbose_name = "Publicacion"
verbose_name_plural = "Publicaciones"
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.titulo)
super(Publicacion, self).save(*args, **kwargs)
| {
"content_hash": "e0fee448a556fd9f0879b1dd1d47f002",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 77,
"avg_line_length": 33.24,
"alnum_prop": 0.677496991576414,
"repo_name": "edwar/repositio.com",
"id": "bc81897d11ad5c1defae5f723a544ab0ed87a44b",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apps/blog/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "723976"
},
{
"name": "HTML",
"bytes": "2199227"
},
{
"name": "JavaScript",
"bytes": "3359735"
},
{
"name": "PHP",
"bytes": "3916"
},
{
"name": "Python",
"bytes": "140232"
}
],
"symlink_target": ""
} |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var auth_service_1 = require('../user/auth.service');
var index_1 = require('../events/index');
var NavBarComponent = (function () {
function NavBarComponent(auth, eventService) {
this.auth = auth;
this.eventService = eventService;
this.searchTerm = "";
}
NavBarComponent.prototype.searchSessions = function (searchTerm) {
var _this = this;
this.eventService.searchSessions(searchTerm).subscribe(function (sessions) {
_this.foundSessions = sessions;
});
};
NavBarComponent = __decorate([
core_1.Component({
selector: 'nav-bar',
templateUrl: 'app/nav/navbar.component.html',
styles: ["\n .nav.navbar-nav {font-size:15px} \n #searchForm {margin-right:100px; } \n @media (max-width: 1200px) {#searchForm {display:none}}\n li > a.active { color: #F97924; }\n "],
}),
__metadata('design:paramtypes', [auth_service_1.AuthService, index_1.EventService])
], NavBarComponent);
return NavBarComponent;
}());
exports.NavBarComponent = NavBarComponent;
//# sourceMappingURL=navbar.component.js.map | {
"content_hash": "86eb2ae36c8ac60506192c309927be00",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 209,
"avg_line_length": 52.67567567567568,
"alnum_prop": 0.6218573627501283,
"repo_name": "mbrown6944/LilSass",
"id": "cdafa294be7228b87948cd5db40c8157076a5785",
"size": "1949",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/nav/navbar.component.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "80"
},
{
"name": "HTML",
"bytes": "3283"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "TypeScript",
"bytes": "7200"
}
],
"symlink_target": ""
} |
<program xmlns="http://ci.uchicago.edu/swift/2009/02/swiftscript"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<variable name="a" type="int" xsi:nil="true"/>
<variable name="b" type="int" xsi:nil="true"/>
<variable name="c" type="int" xsi:nil="true"/>
</program>
| {
"content_hash": "68f2d685fd333ccf8662d2542309e742",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 65,
"avg_line_length": 50.42857142857143,
"alnum_prop": 0.6260623229461756,
"repo_name": "ya7lelkom/swift-k",
"id": "ea25699ab35ea3d8c1c44412355bb3e8e26f2eac",
"size": "353",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/language/working-base/049-many-nested-statements.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3839"
},
{
"name": "C",
"bytes": "32702"
},
{
"name": "C++",
"bytes": "199455"
},
{
"name": "CSS",
"bytes": "66734"
},
{
"name": "GAP",
"bytes": "32217"
},
{
"name": "Gnuplot",
"bytes": "9817"
},
{
"name": "HTML",
"bytes": "86466"
},
{
"name": "Java",
"bytes": "6090207"
},
{
"name": "JavaScript",
"bytes": "736447"
},
{
"name": "Makefile",
"bytes": "13707"
},
{
"name": "Perl",
"bytes": "159196"
},
{
"name": "Perl6",
"bytes": "29608"
},
{
"name": "Python",
"bytes": "48695"
},
{
"name": "Shell",
"bytes": "338545"
},
{
"name": "Swift",
"bytes": "145446"
},
{
"name": "Tcl",
"bytes": "10821"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>Core Network</title>
<link rel="stylesheet" type="text/css" href="styles/app.css">
</head>
<body>
<div id="menu">
<button id="table">TABLE</button>
<button id="sphere">SPHERE</button>
</div>
<script src="bundle.js"></script>
<script defer="true">
Scene = CoreNetwork.core.Scene
TableLayout = CoreNetwork.layouts.TableLayout
SphereLayout = CoreNetwork.layouts.SphereLayout
IsomorphicLayout = CoreNetwork.layouts.IsomorphicLayout
D3 = CoreNetwork.adaptors.D3
scene = new Scene({
layouts: [
new IsomorphicLayout({
layouts: [
new TableLayout,
new SphereLayout
]
})
]
})
D3.create()
.then(function(source) {
return source.fetch({
// url: 'http://d3js.org/d3/talk/20110921/miserables.json'
url: 'https://cdn.rawgit.com/d3/d3-plugins/d238d9448758f2a2a8a33c4b3a50b809fdcf614b/graph/data/miserables.json'
})
})
.then(function(sphere) {
scene.setData(sphere)
return scene.animate()
})
</script>
</body>
</html>
| {
"content_hash": "5ba81ef170649ef0c5ca474293ab7bc3",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 121,
"avg_line_length": 27.387755102040817,
"alnum_prop": 0.5886736214605067,
"repo_name": "core-network/client-threejs",
"id": "1bf86fba1d396af682bd69f7cb636a37cb456d11",
"size": "1342",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/d3.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7445"
},
{
"name": "CoffeeScript",
"bytes": "18607"
},
{
"name": "HTML",
"bytes": "20050"
},
{
"name": "JavaScript",
"bytes": "4325982"
}
],
"symlink_target": ""
} |
"""Google Cloud Platform library - Cloud Storage Functionality."""
from __future__ import absolute_import
from ._bucket import Bucket, Buckets
from ._object import Object, Objects
__all__ = ['Bucket', 'Buckets', 'Object', 'Objects']
| {
"content_hash": "f1424519cda80e0c38cf8669467c1467",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 66,
"avg_line_length": 33.57142857142857,
"alnum_prop": 0.7148936170212766,
"repo_name": "supriyagarg/pydatalab",
"id": "f68f853b415b5f99fae1de77581b07a69cabc29d",
"size": "824",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "google/datalab/storage/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3798"
},
{
"name": "Python",
"bytes": "767068"
},
{
"name": "Shell",
"bytes": "2456"
},
{
"name": "TypeScript",
"bytes": "50852"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/rds-data/RDSDataService_EXPORTS.h>
#include <aws/rds-data/RDSDataServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/rds-data/model/ResultSetOptions.h>
#include <aws/rds-data/model/SqlParameter.h>
#include <utility>
namespace Aws
{
namespace RDSDataService
{
namespace Model
{
/**
* <p>The request parameters represent the input of a request to run a SQL
* statement against a database.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/rds-data-2018-08-01/ExecuteStatementRequest">AWS
* API Reference</a></p>
*/
class AWS_RDSDATASERVICE_API ExecuteStatementRequest : public RDSDataServiceRequest
{
public:
ExecuteStatementRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "ExecuteStatement"; }
Aws::String SerializePayload() const override;
/**
* <p>A value that indicates whether to continue running the statement after the
* call times out. By default, the statement stops running when the call times
* out.</p> <p>For DDL statements, we recommend continuing to run the
* statement after the call times out. When a DDL statement terminates before it is
* finished running, it can result in errors and possibly corrupted data
* structures.</p>
*/
inline bool GetContinueAfterTimeout() const{ return m_continueAfterTimeout; }
/**
* <p>A value that indicates whether to continue running the statement after the
* call times out. By default, the statement stops running when the call times
* out.</p> <p>For DDL statements, we recommend continuing to run the
* statement after the call times out. When a DDL statement terminates before it is
* finished running, it can result in errors and possibly corrupted data
* structures.</p>
*/
inline bool ContinueAfterTimeoutHasBeenSet() const { return m_continueAfterTimeoutHasBeenSet; }
/**
* <p>A value that indicates whether to continue running the statement after the
* call times out. By default, the statement stops running when the call times
* out.</p> <p>For DDL statements, we recommend continuing to run the
* statement after the call times out. When a DDL statement terminates before it is
* finished running, it can result in errors and possibly corrupted data
* structures.</p>
*/
inline void SetContinueAfterTimeout(bool value) { m_continueAfterTimeoutHasBeenSet = true; m_continueAfterTimeout = value; }
/**
* <p>A value that indicates whether to continue running the statement after the
* call times out. By default, the statement stops running when the call times
* out.</p> <p>For DDL statements, we recommend continuing to run the
* statement after the call times out. When a DDL statement terminates before it is
* finished running, it can result in errors and possibly corrupted data
* structures.</p>
*/
inline ExecuteStatementRequest& WithContinueAfterTimeout(bool value) { SetContinueAfterTimeout(value); return *this;}
/**
* <p>The name of the database.</p>
*/
inline const Aws::String& GetDatabase() const{ return m_database; }
/**
* <p>The name of the database.</p>
*/
inline bool DatabaseHasBeenSet() const { return m_databaseHasBeenSet; }
/**
* <p>The name of the database.</p>
*/
inline void SetDatabase(const Aws::String& value) { m_databaseHasBeenSet = true; m_database = value; }
/**
* <p>The name of the database.</p>
*/
inline void SetDatabase(Aws::String&& value) { m_databaseHasBeenSet = true; m_database = std::move(value); }
/**
* <p>The name of the database.</p>
*/
inline void SetDatabase(const char* value) { m_databaseHasBeenSet = true; m_database.assign(value); }
/**
* <p>The name of the database.</p>
*/
inline ExecuteStatementRequest& WithDatabase(const Aws::String& value) { SetDatabase(value); return *this;}
/**
* <p>The name of the database.</p>
*/
inline ExecuteStatementRequest& WithDatabase(Aws::String&& value) { SetDatabase(std::move(value)); return *this;}
/**
* <p>The name of the database.</p>
*/
inline ExecuteStatementRequest& WithDatabase(const char* value) { SetDatabase(value); return *this;}
/**
* <p>A value that indicates whether to include metadata in the results.</p>
*/
inline bool GetIncludeResultMetadata() const{ return m_includeResultMetadata; }
/**
* <p>A value that indicates whether to include metadata in the results.</p>
*/
inline bool IncludeResultMetadataHasBeenSet() const { return m_includeResultMetadataHasBeenSet; }
/**
* <p>A value that indicates whether to include metadata in the results.</p>
*/
inline void SetIncludeResultMetadata(bool value) { m_includeResultMetadataHasBeenSet = true; m_includeResultMetadata = value; }
/**
* <p>A value that indicates whether to include metadata in the results.</p>
*/
inline ExecuteStatementRequest& WithIncludeResultMetadata(bool value) { SetIncludeResultMetadata(value); return *this;}
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline const Aws::Vector<SqlParameter>& GetParameters() const{ return m_parameters; }
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline bool ParametersHasBeenSet() const { return m_parametersHasBeenSet; }
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline void SetParameters(const Aws::Vector<SqlParameter>& value) { m_parametersHasBeenSet = true; m_parameters = value; }
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline void SetParameters(Aws::Vector<SqlParameter>&& value) { m_parametersHasBeenSet = true; m_parameters = std::move(value); }
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline ExecuteStatementRequest& WithParameters(const Aws::Vector<SqlParameter>& value) { SetParameters(value); return *this;}
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline ExecuteStatementRequest& WithParameters(Aws::Vector<SqlParameter>&& value) { SetParameters(std::move(value)); return *this;}
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline ExecuteStatementRequest& AddParameters(const SqlParameter& value) { m_parametersHasBeenSet = true; m_parameters.push_back(value); return *this; }
/**
* <p>The parameters for the SQL statement.</p> <p>Array parameters are not
* supported.</p>
*/
inline ExecuteStatementRequest& AddParameters(SqlParameter&& value) { m_parametersHasBeenSet = true; m_parameters.push_back(std::move(value)); return *this; }
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline const Aws::String& GetResourceArn() const{ return m_resourceArn; }
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline ExecuteStatementRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline ExecuteStatementRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster.</p>
*/
inline ExecuteStatementRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;}
/**
* <p>Options that control how the result set is returned.</p>
*/
inline const ResultSetOptions& GetResultSetOptions() const{ return m_resultSetOptions; }
/**
* <p>Options that control how the result set is returned.</p>
*/
inline bool ResultSetOptionsHasBeenSet() const { return m_resultSetOptionsHasBeenSet; }
/**
* <p>Options that control how the result set is returned.</p>
*/
inline void SetResultSetOptions(const ResultSetOptions& value) { m_resultSetOptionsHasBeenSet = true; m_resultSetOptions = value; }
/**
* <p>Options that control how the result set is returned.</p>
*/
inline void SetResultSetOptions(ResultSetOptions&& value) { m_resultSetOptionsHasBeenSet = true; m_resultSetOptions = std::move(value); }
/**
* <p>Options that control how the result set is returned.</p>
*/
inline ExecuteStatementRequest& WithResultSetOptions(const ResultSetOptions& value) { SetResultSetOptions(value); return *this;}
/**
* <p>Options that control how the result set is returned.</p>
*/
inline ExecuteStatementRequest& WithResultSetOptions(ResultSetOptions&& value) { SetResultSetOptions(std::move(value)); return *this;}
/**
* <p>The name of the database schema.</p>
*/
inline const Aws::String& GetSchema() const{ return m_schema; }
/**
* <p>The name of the database schema.</p>
*/
inline bool SchemaHasBeenSet() const { return m_schemaHasBeenSet; }
/**
* <p>The name of the database schema.</p>
*/
inline void SetSchema(const Aws::String& value) { m_schemaHasBeenSet = true; m_schema = value; }
/**
* <p>The name of the database schema.</p>
*/
inline void SetSchema(Aws::String&& value) { m_schemaHasBeenSet = true; m_schema = std::move(value); }
/**
* <p>The name of the database schema.</p>
*/
inline void SetSchema(const char* value) { m_schemaHasBeenSet = true; m_schema.assign(value); }
/**
* <p>The name of the database schema.</p>
*/
inline ExecuteStatementRequest& WithSchema(const Aws::String& value) { SetSchema(value); return *this;}
/**
* <p>The name of the database schema.</p>
*/
inline ExecuteStatementRequest& WithSchema(Aws::String&& value) { SetSchema(std::move(value)); return *this;}
/**
* <p>The name of the database schema.</p>
*/
inline ExecuteStatementRequest& WithSchema(const char* value) { SetSchema(value); return *this;}
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline const Aws::String& GetSecretArn() const{ return m_secretArn; }
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline bool SecretArnHasBeenSet() const { return m_secretArnHasBeenSet; }
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline void SetSecretArn(const Aws::String& value) { m_secretArnHasBeenSet = true; m_secretArn = value; }
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline void SetSecretArn(Aws::String&& value) { m_secretArnHasBeenSet = true; m_secretArn = std::move(value); }
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline void SetSecretArn(const char* value) { m_secretArnHasBeenSet = true; m_secretArn.assign(value); }
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline ExecuteStatementRequest& WithSecretArn(const Aws::String& value) { SetSecretArn(value); return *this;}
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline ExecuteStatementRequest& WithSecretArn(Aws::String&& value) { SetSecretArn(std::move(value)); return *this;}
/**
* <p>The name or ARN of the secret that enables access to the DB cluster.</p>
*/
inline ExecuteStatementRequest& WithSecretArn(const char* value) { SetSecretArn(value); return *this;}
/**
* <p>The SQL statement to run.</p>
*/
inline const Aws::String& GetSql() const{ return m_sql; }
/**
* <p>The SQL statement to run.</p>
*/
inline bool SqlHasBeenSet() const { return m_sqlHasBeenSet; }
/**
* <p>The SQL statement to run.</p>
*/
inline void SetSql(const Aws::String& value) { m_sqlHasBeenSet = true; m_sql = value; }
/**
* <p>The SQL statement to run.</p>
*/
inline void SetSql(Aws::String&& value) { m_sqlHasBeenSet = true; m_sql = std::move(value); }
/**
* <p>The SQL statement to run.</p>
*/
inline void SetSql(const char* value) { m_sqlHasBeenSet = true; m_sql.assign(value); }
/**
* <p>The SQL statement to run.</p>
*/
inline ExecuteStatementRequest& WithSql(const Aws::String& value) { SetSql(value); return *this;}
/**
* <p>The SQL statement to run.</p>
*/
inline ExecuteStatementRequest& WithSql(Aws::String&& value) { SetSql(std::move(value)); return *this;}
/**
* <p>The SQL statement to run.</p>
*/
inline ExecuteStatementRequest& WithSql(const char* value) { SetSql(value); return *this;}
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline const Aws::String& GetTransactionId() const{ return m_transactionId; }
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline bool TransactionIdHasBeenSet() const { return m_transactionIdHasBeenSet; }
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline void SetTransactionId(const Aws::String& value) { m_transactionIdHasBeenSet = true; m_transactionId = value; }
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline void SetTransactionId(Aws::String&& value) { m_transactionIdHasBeenSet = true; m_transactionId = std::move(value); }
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline void SetTransactionId(const char* value) { m_transactionIdHasBeenSet = true; m_transactionId.assign(value); }
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline ExecuteStatementRequest& WithTransactionId(const Aws::String& value) { SetTransactionId(value); return *this;}
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline ExecuteStatementRequest& WithTransactionId(Aws::String&& value) { SetTransactionId(std::move(value)); return *this;}
/**
* <p>The identifier of a transaction that was started by using the
* <code>BeginTransaction</code> operation. Specify the transaction ID of the
* transaction that you want to include the SQL statement in.</p> <p>If the SQL
* statement is not part of a transaction, don't set this parameter.</p>
*/
inline ExecuteStatementRequest& WithTransactionId(const char* value) { SetTransactionId(value); return *this;}
private:
bool m_continueAfterTimeout;
bool m_continueAfterTimeoutHasBeenSet;
Aws::String m_database;
bool m_databaseHasBeenSet;
bool m_includeResultMetadata;
bool m_includeResultMetadataHasBeenSet;
Aws::Vector<SqlParameter> m_parameters;
bool m_parametersHasBeenSet;
Aws::String m_resourceArn;
bool m_resourceArnHasBeenSet;
ResultSetOptions m_resultSetOptions;
bool m_resultSetOptionsHasBeenSet;
Aws::String m_schema;
bool m_schemaHasBeenSet;
Aws::String m_secretArn;
bool m_secretArnHasBeenSet;
Aws::String m_sql;
bool m_sqlHasBeenSet;
Aws::String m_transactionId;
bool m_transactionIdHasBeenSet;
};
} // namespace Model
} // namespace RDSDataService
} // namespace Aws
| {
"content_hash": "032bd66192777662251c7a0f5f5543dc",
"timestamp": "",
"source": "github",
"line_count": 485,
"max_line_length": 162,
"avg_line_length": 39.02268041237114,
"alnum_prop": 0.6725668392687308,
"repo_name": "jt70471/aws-sdk-cpp",
"id": "b2255e1ddecbb7c0b2c47c8068fcf8e05ae61bad",
"size": "19045",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-rds-data/include/aws/rds-data/model/ExecuteStatementRequest.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "13452"
},
{
"name": "C++",
"bytes": "278594037"
},
{
"name": "CMake",
"bytes": "653931"
},
{
"name": "Dockerfile",
"bytes": "5555"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "302182"
},
{
"name": "Python",
"bytes": "110380"
},
{
"name": "Shell",
"bytes": "4674"
}
],
"symlink_target": ""
} |
'use strict';
const models = require('./index');
/**
* Defines a video object that is relevant to the query.
*
* @extends models['MediaObject']
*/
class VideoObject extends models['MediaObject'] {
/**
* Create a VideoObject.
* @property {string} [motionThumbnailUrl]
* @property {string} [motionThumbnailId]
* @property {string} [embedHtml]
* @property {boolean} [allowHttpsEmbed]
* @property {number} [viewCount]
* @property {object} [thumbnail]
* @property {object} [thumbnail.thumbnail] The URL to a thumbnail of the
* image
* @property {string} [videoId]
* @property {boolean} [allowMobileEmbed]
* @property {boolean} [isSuperfresh]
*/
constructor() {
super();
}
/**
* Defines the metadata of VideoObject
*
* @returns {object} metadata of VideoObject
*
*/
mapper() {
return {
required: false,
serializedName: 'VideoObject',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'VideoObject',
modelProperties: {
_type: {
required: true,
serializedName: '_type',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
webSearchUrl: {
required: false,
readOnly: true,
serializedName: 'webSearchUrl',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
url: {
required: false,
readOnly: true,
serializedName: 'url',
type: {
name: 'String'
}
},
image: {
required: false,
readOnly: true,
serializedName: 'image',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'ImageObject'
}
},
description: {
required: false,
readOnly: true,
serializedName: 'description',
type: {
name: 'String'
}
},
bingId: {
required: false,
readOnly: true,
serializedName: 'bingId',
type: {
name: 'String'
}
},
thumbnailUrl: {
required: false,
readOnly: true,
serializedName: 'thumbnailUrl',
type: {
name: 'String'
}
},
provider: {
required: false,
readOnly: true,
serializedName: 'provider',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ThingElementType',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'Thing'
}
}
}
},
text: {
required: false,
readOnly: true,
serializedName: 'text',
type: {
name: 'String'
}
},
contentUrl: {
required: false,
readOnly: true,
serializedName: 'contentUrl',
type: {
name: 'String'
}
},
hostPageUrl: {
required: false,
readOnly: true,
serializedName: 'hostPageUrl',
type: {
name: 'String'
}
},
width: {
required: false,
readOnly: true,
serializedName: 'width',
type: {
name: 'Number'
}
},
height: {
required: false,
readOnly: true,
serializedName: 'height',
type: {
name: 'Number'
}
},
motionThumbnailUrl: {
required: false,
readOnly: true,
serializedName: 'motionThumbnailUrl',
type: {
name: 'String'
}
},
motionThumbnailId: {
required: false,
readOnly: true,
serializedName: 'motionThumbnailId',
type: {
name: 'String'
}
},
embedHtml: {
required: false,
readOnly: true,
serializedName: 'embedHtml',
type: {
name: 'String'
}
},
allowHttpsEmbed: {
required: false,
readOnly: true,
serializedName: 'allowHttpsEmbed',
type: {
name: 'Boolean'
}
},
viewCount: {
required: false,
readOnly: true,
serializedName: 'viewCount',
type: {
name: 'Number'
}
},
thumbnail: {
required: false,
readOnly: true,
serializedName: 'thumbnail',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'ImageObject'
}
},
videoId: {
required: false,
readOnly: true,
serializedName: 'videoId',
type: {
name: 'String'
}
},
allowMobileEmbed: {
required: false,
readOnly: true,
serializedName: 'allowMobileEmbed',
type: {
name: 'Boolean'
}
},
isSuperfresh: {
required: false,
readOnly: true,
serializedName: 'isSuperfresh',
type: {
name: 'Boolean'
}
}
}
}
};
}
}
module.exports = VideoObject;
| {
"content_hash": "0cd00b3138401cd2109f0494a8a82d5d",
"timestamp": "",
"source": "github",
"line_count": 273,
"max_line_length": 75,
"avg_line_length": 25.227106227106226,
"alnum_prop": 0.4106287207782779,
"repo_name": "xingwu1/azure-sdk-for-node",
"id": "7dbe069ca77be3408f66ac03b026862e8f76f793",
"size": "7204",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/services/cognitiveServicesWebSearch/lib/models/videoObject.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "122792600"
},
{
"name": "Shell",
"bytes": "437"
},
{
"name": "TypeScript",
"bytes": "2558"
}
],
"symlink_target": ""
} |
class AddLandingToPages < ActiveRecord::Migration[6.1]
def change
add_column :pages, :landing, :boolean, default: false, null: false
end
end
| {
"content_hash": "df9607cd93487952c574e2dc3df6e753",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 70,
"avg_line_length": 29.8,
"alnum_prop": 0.7315436241610739,
"repo_name": "rubycentral/cfp-app",
"id": "319e400c7adda83445973678cdd57f499fa58fc6",
"size": "149",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "db/migrate/20220415014232_add_landing_to_pages.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "18355"
},
{
"name": "Haml",
"bytes": "213114"
},
{
"name": "JavaScript",
"bytes": "168727"
},
{
"name": "Procfile",
"bytes": "122"
},
{
"name": "Ruby",
"bytes": "595785"
},
{
"name": "SCSS",
"bytes": "116900"
}
],
"symlink_target": ""
} |
package org.apache.myfaces.trinidadbuild.plugin.javascript.uixtools;
import java.io.IOException;
/**
* A buffer to hold Token objects. Tokens can be read from and written to this
* buffer as if it were a queue. it is thread safe. Best if a single thread is
* reading and a single thread is writing.
* @version $Name: $ ($Revision: 518820 $) $Date: 2007-03-15 22:02:36 -0300 (qui, 15 mar 2007) $
*/
public class TokenBuffer extends Queue implements TokenReader
{
/**
* @param bufferSize the maximum size of this buffer.
*/
public TokenBuffer(int bufferSize)
{
super(bufferSize);
}
public TokenBuffer()
{
this(100);
}
/**
* reads a Token from this buffer. This method blocks until data is available
* @return null if there is no more data and this buffer has been closed.
* @see TokenReader
*/
public synchronized Token read() throws IOException, InterruptedException
{
Token tok;
try
{
tok = (Token) super.remove();
}
catch (IllegalStateException e)
{
tok = null;
}
if (tok==_EXCEPTION_TOKEN)
{
throw _getException();
}
return tok;
}
/**
* This method blocks if the buffer is full.
* @param tok the token to write to this buffer
*/
public synchronized void write(Token tok) throws InterruptedException
{
super.add(tok);
}
public synchronized void write(IOException e) throws InterruptedException
{
_setException(e);
write(_EXCEPTION_TOKEN);
close();
}
private synchronized void _setException(IOException e)
{
_exception = e;
}
private synchronized IOException _getException()
{
return _exception;
}
private IOException _exception = null;
private static final Token _EXCEPTION_TOKEN = new Token(-1, 0);
} | {
"content_hash": "a3f79ee836b6ccd943b13fdfaae64479",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 97,
"avg_line_length": 22.14814814814815,
"alnum_prop": 0.664994425863991,
"repo_name": "alessandroleite/maven-jdev-plugin",
"id": "8606d81b9937a1e5fefb946fea061a78cf6d87c2",
"size": "2615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "maven-javascript-plugin/src/main/java/org/apache/myfaces/trinidadbuild/plugin/javascript/uixtools/TokenBuffer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1671575"
}
],
"symlink_target": ""
} |
import os
import django
# Calculated paths for django and the site
# Used as starting points for various other paths
# Thanks to Gareth Rushgrove:
# http://www.morethanseven.net/2009/02/11/django-settings-tip-setting-relative-paths/
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
# Django settings for omfraf project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'u@31@@7+*9xer#n3=3!@4bqct^j=2$t4jty)_@*@2*7zrsli_!'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'omfraf.middleware.logging_middleware.LoggingMiddleware',
'omfraf.middleware.django-crossdomainxhr-middleware.XsSharing',
)
ROOT_URLCONF = 'omfraf.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'omfraf.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'omfraf.main',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'simple': {
'format': '[%(asctime)s] %(message)s',
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console':{
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'logfile': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': SITE_ROOT + "/log/debug.log",
'maxBytes': 1000000,
'backupCount': 2,
'formatter': 'simple',
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'': {
'handlers': ['null', 'console', 'logfile'],
'propagate': True,
'level': 'DEBUG',
},
'django': {
'handlers': ['null', 'console'],
'propagate': True,
'level': 'INFO',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| {
"content_hash": "fd450fd2b93547a9cf33711471aa8379",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 101,
"avg_line_length": 33.53658536585366,
"alnum_prop": 0.645090909090909,
"repo_name": "jimivdw/OMFraF",
"id": "90631633a66c286b0a9292f741f3c816bb7f1484",
"size": "6875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/omfraf/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "29610"
}
],
"symlink_target": ""
} |
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function creatureSayCallback(cid, type, msg)
local player = Player(cid)
-- GREET
if(msg == "DJANNI'HAH") and (not npcHandler:isFocused(cid)) then
if player:getStorageValue(Factions) > 0 then
npcHandler:addFocus(cid)
if player:getStorageValue(BlueDjinn.MissionStart) < 1 or not BlueOrGreen then
npcHandler:say("You know the code human! Very well then... What do you want, " .. player:getName() .. "?", cid)
npcHandler:addFocus(cid)
end
end
end
-- GREET
if(not npcHandler:isFocused(cid)) then
return false
end
-- Mission 1 - The Supply Thief
if(msgcontains(msg, "mission")) then
if player:getStorageValue(GreenDjinn.MissionStart) == 1 and player:getStorageValue(GreenDjinn.MissionStart+1) < 1 then
npcHandler:say({"Each mission and operation is a crucial step towards our victory! ...", "Now that we speak of it ...", "Since you are no djinn, there is something you could help us with. Are you interested, human?"}, cid, 0, 1, 3000)
npcHandler.topic[cid] = 1
elseif player:getStorageValue(GreenDjinn.MissionStart+1) == 3 then
npcHandler:say("Did you find the thief of our supplies?", cid)
npcHandler.topic[cid] = 2
end
elseif(msgcontains(msg, "partos")) then
if(npcHandler.topic[cid] == 3) then
npcHandler:say({"You found the thief! Excellent work, soldier! You are doing well - for a human, that is. Here - take this as a reward. ...", "Since you have proven to be a capable soldier, we have another mission for you. ...", "If you are interested go to Alesar and ask him about it."}, cid, 0, 1, 3000)
npcHandler.topic[cid] = 4
end
elseif(msgcontains(msg, "hail malor")) then
if(npcHandler.topic[cid] == 4) then
npcHandler:say("Hail to our great leader!", cid)
player:setStorageValue(GreenDjinn.MissionStart+1, 4)
npcHandler.topic[cid] = 0
end
-- Mission 1 - The Supply Thief
elseif(msgcontains(msg, "yes")) then
if(npcHandler.topic[cid] == 1) then
npcHandler:say({"Well ... All right. You may only be a human, but you do seem to have the right spirit. ...", "Listen! Since our base of operations is set in this isolated spot we depend on supplies from outside. These supplies are crucial for us to win the war. ...", "Unfortunately, it has happened that some of our supplies have disappeared on their way to this fortress. At first we thought it was the Marid, but intelligence reports suggest a different explanation. ...", "We now believe that a human was behind the theft! ...", "His identity is still unknown but we have been told that the thief fled to the human settlement called Carlin. I want you to find him and report back to me. Nobody messes with the Efreet and lives to tell the tale! ...", "Now go! Travel to the northern city Carlin! Keep your eyes open and look around for something that might give you a clue!"}, cid, 0, 1, 4500)
npcHandler.topic[cid] = 0
player:setStorageValue(GreenDjinn.MissionStart+1, 1)
elseif(npcHandler.topic[cid] == 2) then
npcHandler:say("Finally! What is his name then?", cid)
npcHandler.topic[cid] = 3
end
end
if (msgcontains(msg, "bye") or msgcontains(msg, "farewell")) then
npcHandler:say("Stand down, soldier!", cid)
npcHandler.topic[cid] = 0
npcHandler:releaseFocus(cid)
npcHandler:resetNpc(cid)
end
return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| {
"content_hash": "90f0fe4c57efe35dbb542ef49c275644",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 901,
"avg_line_length": 56.088235294117645,
"alnum_prop": 0.7338751966439434,
"repo_name": "victorperin/tibia-server",
"id": "a714be92f2e067c7d1248f8bbfe98bb1f2ff7103",
"size": "3814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/npc/scripts/Baa'leal.lua",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Lua",
"bytes": "2465786"
}
],
"symlink_target": ""
} |
package com.dennisxu.sample.common.ui;
import android.os.Bundle;
/**
* fragment与activity通信接口
*
* @author: xuyang
* @date: 2014-8-24 上午9:59:24
*/
public interface IFragmentNotification {
public void beforeFragmentView();
public void afterFragmentView();
/**
* fragment与Activity通信回调
*
* @param tag 通讯的类型
* @param simpleParam 简单参数
* @param extra 额外参数
*/
public void onFragmentNotificated(String tag, String simpleParam, Bundle extra);
}
| {
"content_hash": "5f2df4679e44904dab1101f2a9ce07a9",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 84,
"avg_line_length": 20.16,
"alnum_prop": 0.6567460317460317,
"repo_name": "dennisxu1014/dennisxu-sample-android",
"id": "6cfaf51f15b5ade86c1df72b22edbb77939e7d3f",
"size": "554",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/dennisxu/sample/common/ui/IFragmentNotification.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "119794"
},
{
"name": "Prolog",
"bytes": "37"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Registrado(models.Model):
nombre = models.CharField(max_length=120, blank=True, null=True)
email = models.EmailField()
codigo_postal = models.IntegerField(blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
actualizado = models.DateTimeField(auto_now_add=False, auto_now=True)
media = models.FileField(upload_to='myfolder/', blank=True, null=True) #barra despues NO antes
def __unicode__(self): #Python 3 __str__
return self.email | {
"content_hash": "6cd9560ba36ffee118779a0cb8d5af0e",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 95,
"avg_line_length": 34.411764705882355,
"alnum_prop": 0.7521367521367521,
"repo_name": "probardjango/Probar-Django-1.9",
"id": "adf9ea91782a8b2ecc810927eef58a04a149cd81",
"size": "585",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/boletin/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "45809"
},
{
"name": "HTML",
"bytes": "917"
},
{
"name": "JavaScript",
"bytes": "88987"
},
{
"name": "Python",
"bytes": "12473"
}
],
"symlink_target": ""
} |
// Copyright 2015 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.
package org.chromium.mojo.shell;
import org.chromium.base.ApplicationStatus;
import org.chromium.mojo.application.ServiceFactoryBinder;
import org.chromium.mojo.bindings.InterfaceRequest;
import org.chromium.mojo.keyboard.KeyboardServiceImpl;
import org.chromium.mojom.keyboard.KeyboardService;
/**
* A ServiceFactoryBinder for the keyboard service.
*/
final class KeyboardFactory implements ServiceFactoryBinder<KeyboardService> {
@Override
public void bind(InterfaceRequest<KeyboardService> request) {
KeyboardService.MANAGER.bind(
new KeyboardServiceImpl(ApplicationStatus.getApplicationContext()), request);
}
@Override
public String getInterfaceName() {
return KeyboardService.MANAGER.getName();
}
}
| {
"content_hash": "c74b88139a54ddf5cabcdf2c7c508089",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 93,
"avg_line_length": 34.51851851851852,
"alnum_prop": 0.7682403433476395,
"repo_name": "afandria/mojo",
"id": "0136b7dec105fc53e76d20a88676dc33062df88d",
"size": "932",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "shell/android/apk/src/org/chromium/mojo/shell/KeyboardFactory.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2031492"
},
{
"name": "C++",
"bytes": "24525248"
},
{
"name": "Dart",
"bytes": "354436"
},
{
"name": "Go",
"bytes": "183671"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "Java",
"bytes": "1244656"
},
{
"name": "JavaScript",
"bytes": "208100"
},
{
"name": "Makefile",
"bytes": "402"
},
{
"name": "Objective-C",
"bytes": "82678"
},
{
"name": "Objective-C++",
"bytes": "389484"
},
{
"name": "Protocol Buffer",
"bytes": "1048"
},
{
"name": "Python",
"bytes": "3524970"
},
{
"name": "Shell",
"bytes": "148167"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
package com.netflix.spinnaker.clouddriver.alicloud.cache;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class KeysTest {
static final String ACCOUNT = "test-account";
static final String REGION = "cn-test";
@Test
public void testGetLoadBalancerKey() {
String key = "alicloud:loadBalancers:test-account:cn-test:test-loadBalancer";
String loadBalancerKey = Keys.getLoadBalancerKey("test-loadBalancer", ACCOUNT, REGION, null);
assertTrue(key.equals(loadBalancerKey));
}
@Test
public void testGetSubnetKey() {
String key = "alicloud:subnets:test-account:cn-test:test-vswitchId";
String subnetKey = Keys.getSubnetKey("test-vswitchId", REGION, ACCOUNT);
assertTrue(key.equals(subnetKey));
}
@Test
public void testGetImageKey() {
String key = "alicloud:images:test-account:cn-test:test-imageId";
String imageKey = Keys.getImageKey("test-imageId", ACCOUNT, REGION);
assertTrue(key.equals(imageKey));
}
@Test
public void testGetNamedImageKey() {
String key = "alicloud:namedImages:test-account:test-imageName";
String namedImageKey = Keys.getNamedImageKey(ACCOUNT, "test-imageName");
assertTrue(key.equals(namedImageKey));
}
@Test
public void testGetInstanceTypeKey() {
String key = "alicloud:instanceTypes:test-account:cn-test:test-zoneId";
String instanceTypeKey = Keys.getInstanceTypeKey(ACCOUNT, REGION, "test-zoneId");
assertTrue(key.equals(instanceTypeKey));
}
@Test
public void testGetSecurityGroupKey() {
String key =
"alicloud:securityGroups:test-account:cn-test:test-SecurityGroupName:test-SecurityGroupId";
String securityGroupKey =
Keys.getSecurityGroupKey(
"test-SecurityGroupName", "test-SecurityGroupId", REGION, ACCOUNT, null);
assertTrue(key.equals(securityGroupKey));
}
@Test
public void testGetKeyPairKey() {
String key = "alicloud:aliCloudKeyPairs:test-KeyPair:test-account:cn-test";
String keyPairKey = Keys.getKeyPairKey("test-KeyPair", REGION, ACCOUNT);
assertTrue(key.equals(keyPairKey));
}
@Test
public void testGetServerGroupKey() {
String key = "alicloud:serverGroups:Spin63-test-ali:test-account:cn-test:Spin63-test-ali";
String serverGroupKey = Keys.getServerGroupKey("Spin63-test-ali", ACCOUNT, REGION);
assertTrue(key.equals(serverGroupKey));
}
@Test
public void testGetApplicationKey() {
String key = "alicloud:applications:test-application";
String applicationKey = Keys.getApplicationKey("test-Application");
assertTrue(key.equals(applicationKey));
}
@Test
public void testGetClusterKey() {
String key = "alicloud:clusters:test-application:test-account:test-Cluster";
String clusterKey = Keys.getClusterKey("test-Cluster", "test-Application", ACCOUNT);
assertTrue(key.equals(clusterKey));
}
@Test
public void testGetLaunchConfigKey() {
String key = "alicloud:launchConfigs:test-account:cn-test:test-LaunchConfigName";
String launchConfigKey = Keys.getLaunchConfigKey("test-LaunchConfigName", ACCOUNT, REGION);
assertTrue(key.equals(launchConfigKey));
}
@Test
public void testGetInstanceKey() {
String key = "alicloud:instances:test-account:cn-test:test-instanceId";
String instanceKey = Keys.getInstanceKey("test-instanceId", ACCOUNT, REGION);
assertTrue(key.equals(instanceKey));
}
}
| {
"content_hash": "285cadbc30c570e4c4845e3aa969a505",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 99,
"avg_line_length": 34.36363636363637,
"alnum_prop": 0.7325102880658436,
"repo_name": "spinnaker/clouddriver",
"id": "0ff7dab080dd640c8370f34ff12ab0607a7a5d3d",
"size": "3996",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "clouddriver-alicloud/src/test/java/com/netflix/spinnaker/clouddriver/alicloud/cache/KeysTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "7641380"
},
{
"name": "Java",
"bytes": "7248003"
},
{
"name": "Kotlin",
"bytes": "282069"
},
{
"name": "Shell",
"bytes": "3066"
},
{
"name": "Slim",
"bytes": "2423"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.7: http://docutils.sourceforge.net/" />
<title>The MPL Reference Manual: unique</title>
<link rel="stylesheet" href="../style.css" type="text/css" />
</head>
<body class="docframe refmanual">
<table class="header"><tr class="header"><td class="header-group navigation-bar"><span class="navigation-group"><a href="./remove-if.html" class="navigation-link">Prev</a> <a href="./partition.html" class="navigation-link">Next</a></span><span class="navigation-group-separator"> | </span><span class="navigation-group"><a href="./remove-if.html" class="navigation-link">Back</a> <a href="./partition.html" class="navigation-link">Along</a></span><span class="navigation-group-separator"> | </span><span class="navigation-group"><a href="./transformation-algorithms.html" class="navigation-link">Up</a> <a href="../refmanual.html" class="navigation-link">Home</a></span><span class="navigation-group-separator"> | </span><span class="navigation-group"><a href="./refmanual_toc.html" class="navigation-link">Full TOC</a></span></td>
<td class="header-group page-location"><a href="../refmanual.html" class="navigation-link">Front Page</a> / <a href="./algorithms.html" class="navigation-link">Algorithms</a> / <a href="./transformation-algorithms.html" class="navigation-link">Transformation Algorithms</a> / <a href="./unique.html" class="navigation-link">unique</a></td>
</tr></table><div class="header-separator"></div>
<div class="section" id="unique">
<h1><a class="toc-backref" href="./transformation-algorithms.html#id1493">unique</a></h1>
<div class="section" id="id678">
<h3><a class="subsection-title" href="#synopsis" name="synopsis">Synopsis</a></h3>
<pre class="literal-block">
template<
typename Seq
, typename Pred
, typename In = <em>unspecified</em>
>
struct <a href="./unique.html" class="identifier">unique</a>
{
typedef <em>unspecified</em> type;
};
</pre>
</div>
<div class="section" id="id679">
<h3><a class="subsection-title" href="#description" name="description">Description</a></h3>
<p>Returns a sequence of the initial elements of every subrange of the
original sequence <tt class="literal"><span class="pre">Seq</span></tt> whose elements are all the same.</p>
<p>[<em>Note:</em> This wording applies to a no-inserter version(s) of the algorithm. See the
<cite>Expression semantics</cite> subsection for a precise specification of the algorithm's
details in all cases — <em>end note</em>]</p>
</div>
<div class="section" id="id680">
<h3><a class="subsection-title" href="#header" name="header">Header</a></h3>
<pre class="literal-block">
#include <<a href="../../../../boost/mpl/unique.hpp" class="header">boost/mpl/unique.hpp</a>>
</pre>
</div>
<div class="section" id="id681">
<h3><a class="subsection-title" href="#model-of" name="model-of">Model of</a></h3>
<p><a class="reference internal" href="./reversible-algorithm.html">Reversible Algorithm</a></p>
</div>
<div class="section" id="id682">
<h3><a class="subsection-title" href="#parameters" name="parameters">Parameters</a></h3>
<table border="1" class="docutils table">
<colgroup>
<col width="19%" />
<col width="43%" />
<col width="38%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Parameter</th>
<th class="head">Requirement</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="literal"><span class="pre">Sequence</span></tt></td>
<td><a class="reference internal" href="./forward-sequence.html">Forward Sequence</a></td>
<td>An original sequence.</td>
</tr>
<tr><td><tt class="literal"><span class="pre">Pred</span></tt></td>
<td>Binary <a class="reference internal" href="./lambda-expression.html">Lambda Expression</a></td>
<td>An equivalence relation.</td>
</tr>
<tr><td><tt class="literal"><span class="pre">In</span></tt></td>
<td><a class="reference internal" href="./inserter.html">Inserter</a></td>
<td>An inserter.</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="id683">
<h3><a class="subsection-title" href="#expression-semantics" name="expression-semantics">Expression semantics</a></h3>
<p>The semantics of an expression are defined only
where they differ from, or are not defined in <a class="reference internal" href="./reversible-algorithm.html">Reversible Algorithm</a>.</p>
<p>For any <a class="reference internal" href="./forward-sequence.html">Forward Sequence</a> <tt class="literal"><span class="pre">s</span></tt>, a binary <a class="reference internal" href="./lambda-expression.html">Lambda Expression</a> <tt class="literal"><span class="pre">pred</span></tt>,
and an <a class="reference internal" href="./inserter.html">Inserter</a> <tt class="literal"><span class="pre">in</span></tt>:</p>
<pre class="literal-block">
typedef <a href="./unique.html" class="identifier">unique</a><s,pred,in>::type r;
</pre>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Return type:</th><td class="field-body"><p class="first">A type.</p>
</td>
</tr>
<tr class="field"><th class="field-name">Semantics:</th><td class="field-body"><p class="first">If <tt class="literal"><span class="pre"><a href="./size.html" class="identifier">size</a><s>::value</span> <span class="pre"><=</span> <span class="pre">1</span></tt>, then equivalent to</p>
<pre class="literal-block">
typedef <a href="./copy.html" class="identifier">copy</a><s,in>::type r;
</pre>
<p>otherwise equivalent to</p>
<pre class="last literal-block">
typedef <a href="./lambda.html" class="identifier">lambda</a><pred>::type p;
typedef <a href="./lambda.html" class="identifier">lambda</a><in::operation>::type in_op;
typedef <a href="./apply-wrap.html" class="identifier">apply_wrap</a><tt class="literal"><span class="pre">2</span></tt><
in_op
, in::state
, <a href="./front.html" class="identifier">front</a><types>::type
>::type in_state;
typedef <a href="./fold.html" class="identifier">fold</a><
s
, <a href="./pair.html" class="identifier">pair</a>< in_state, <a href="./front.html" class="identifier">front</a><s>::type >
, <a href="./eval-if.html" class="identifier">eval_if</a><
<a href="./apply-wrap.html" class="identifier">apply_wrap</a><tt class="literal"><span class="pre">2</span></tt><p, second<<a href="./placeholders.html" class="identifier">_1</a>>, <a href="./placeholders.html" class="identifier">_2</a>>
, <a href="./identity.html" class="identifier">identity</a>< first<<a href="./placeholders.html" class="identifier">_1</a>> >
, <a href="./apply-wrap.html" class="identifier">apply_wrap</a><tt class="literal"><span class="pre">2</span></tt><in_op, first<<a href="./placeholders.html" class="identifier">_1</a>>, <a href="./placeholders.html" class="identifier">_2</a>>
>
>::type::first r;
</pre>
</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="id684">
<h3><a class="subsection-title" href="#complexity" name="complexity">Complexity</a></h3>
<p>Linear. Performs exactly <tt class="literal"><span class="pre"><a href="./size.html" class="identifier">size</a><s>::value</span> <span class="pre">-</span> <span class="pre">1</span></tt> applications of <tt class="literal"><span class="pre">pred</span></tt>, and at
most <tt class="literal"><span class="pre"><a href="./size.html" class="identifier">size</a><s>::value</span></tt> insertions.</p>
</div>
<div class="section" id="id685">
<h3><a class="subsection-title" href="#example" name="example">Example</a></h3>
<pre class="literal-block">
typedef <a href="./vector.html" class="identifier">vector</a><int,float,float,char,int,int,int,double> types;
typedef <a href="./vector.html" class="identifier">vector</a><int,float,char,int,double> expected;
typedef <a href="./unique.html" class="identifier">unique</a>< types, is_same<<a href="./placeholders.html" class="identifier">_1</a>,<a href="./placeholders.html" class="identifier">_2</a>> >::type result;
<a href="./assert.html" class="identifier">BOOST_MPL_ASSERT</a>(( <a href="./equal.html" class="identifier">equal</a>< result,expected > ));
</pre>
</div>
<div class="section" id="id686">
<h3><a class="subsection-title" href="#see-also" name="see-also">See also</a></h3>
<p><a class="reference internal" href="./transformation-algorithms.html">Transformation Algorithms</a>, <a class="reference internal" href="./reversible-algorithm.html">Reversible Algorithm</a>, <a class="reference internal" href="./reverse-unique.html">reverse_unique</a>, <a class="reference internal" href="./remove.html">remove</a>, <a class="reference internal" href="./copy-if.html">copy_if</a>, <a class="reference internal" href="./replace-if.html">replace_if</a></p>
<!-- Algorithms/Transformation Algorithms//partition |85 -->
</div>
</div>
<div class="footer-separator"></div>
<table class="footer"><tr class="footer"><td class="header-group navigation-bar"><span class="navigation-group"><a href="./remove-if.html" class="navigation-link">Prev</a> <a href="./partition.html" class="navigation-link">Next</a></span><span class="navigation-group-separator"> | </span><span class="navigation-group"><a href="./remove-if.html" class="navigation-link">Back</a> <a href="./partition.html" class="navigation-link">Along</a></span><span class="navigation-group-separator"> | </span><span class="navigation-group"><a href="./transformation-algorithms.html" class="navigation-link">Up</a> <a href="../refmanual.html" class="navigation-link">Home</a></span><span class="navigation-group-separator"> | </span><span class="navigation-group"><a href="./refmanual_toc.html" class="navigation-link">Full TOC</a></span></td>
<td><div class="copyright-footer"><div class="copyright">Copyright © 2001-2009 Aleksey Gurtovoy and David Abrahams</div>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a class="reference external" href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</div></td></tr></table></body>
</html>
| {
"content_hash": "eb043f05fc21019616a7e647cda4b462",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 876,
"avg_line_length": 72.22,
"alnum_prop": 0.6775593095172159,
"repo_name": "cpascal/af-cpp",
"id": "bd5a091bde9b758ec54f52dc36989bdcd3cd3f15",
"size": "10836",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "apdos/exts/boost_1_53_0/libs/mpl/doc/refmanual/unique.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "142321"
},
{
"name": "Batchfile",
"bytes": "45292"
},
{
"name": "C",
"bytes": "2380742"
},
{
"name": "C#",
"bytes": "41850"
},
{
"name": "C++",
"bytes": "141733840"
},
{
"name": "CMake",
"bytes": "1784"
},
{
"name": "CSS",
"bytes": "303526"
},
{
"name": "Cuda",
"bytes": "27558"
},
{
"name": "FORTRAN",
"bytes": "1440"
},
{
"name": "Groff",
"bytes": "8174"
},
{
"name": "HTML",
"bytes": "80494592"
},
{
"name": "IDL",
"bytes": "15"
},
{
"name": "JavaScript",
"bytes": "134468"
},
{
"name": "Lex",
"bytes": "1318"
},
{
"name": "Makefile",
"bytes": "1028949"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "4297"
},
{
"name": "PHP",
"bytes": "60249"
},
{
"name": "Perl",
"bytes": "30505"
},
{
"name": "Perl6",
"bytes": "2130"
},
{
"name": "Python",
"bytes": "1751993"
},
{
"name": "QML",
"bytes": "613"
},
{
"name": "Rebol",
"bytes": "372"
},
{
"name": "Shell",
"bytes": "374946"
},
{
"name": "Tcl",
"bytes": "1205"
},
{
"name": "TeX",
"bytes": "13819"
},
{
"name": "XSLT",
"bytes": "780775"
},
{
"name": "Yacc",
"bytes": "19612"
}
],
"symlink_target": ""
} |
@class JavaIoBufferedReader;
@class JavaUtilArrayList;
@class JavaUtilHashMap;
@protocol JavaUtilCollection;
#import "JreEmulation.h"
@interface FFTCsvReader : NSObject {
@public
JavaUtilArrayList *attributes_;
JavaUtilArrayList *rows_;
}
- (id)initWithJavaIoBufferedReader:(JavaIoBufferedReader *)inArg
withChar:(unichar)sep;
- (id)initWithJavaIoBufferedReader:(JavaIoBufferedReader *)inArg
withChar:(unichar)sep
withInt:(int)headerRows;
- (BOOL)containsAttributeWithNSString:(NSString *)s;
- (JavaUtilArrayList *)getAttributes;
- (JavaUtilArrayList *)getRows;
- (JavaUtilArrayList *)tokenizeWithNSString:(NSString *)line
withChar:(unichar)sep;
- (void)copyAllFieldsTo:(FFTCsvReader *)other;
@end
__attribute__((always_inline)) inline void FFTCsvReader_init() {}
J2OBJC_FIELD_SETTER(FFTCsvReader, attributes_, JavaUtilArrayList *)
J2OBJC_FIELD_SETTER(FFTCsvReader, rows_, JavaUtilArrayList *)
typedef FFTCsvReader ComSponbergFluidUtilCsvReader;
@interface FFTCsvReader_Attribute : NSObject {
@public
int index_;
NSString *name_;
}
- (id)initWithInt:(int)index
withNSString:(NSString *)name;
- (int)getIndex;
- (NSString *)getName;
- (void)copyAllFieldsTo:(FFTCsvReader_Attribute *)other;
@end
__attribute__((always_inline)) inline void FFTCsvReader_Attribute_init() {}
J2OBJC_FIELD_SETTER(FFTCsvReader_Attribute, name_, NSString *)
@interface FFTCsvReader_Row : NSObject {
@public
JavaUtilHashMap *map_;
}
- (NSString *)getWithNSString:(NSString *)key;
- (id<JavaUtilCollection>)getAllValues;
- (id)init;
- (void)copyAllFieldsTo:(FFTCsvReader_Row *)other;
@end
__attribute__((always_inline)) inline void FFTCsvReader_Row_init() {}
J2OBJC_FIELD_SETTER(FFTCsvReader_Row, map_, JavaUtilHashMap *)
#endif // _FFTCsvReader_H_
| {
"content_hash": "922df8cecb286fb386faffd5c45e5468",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 75,
"avg_line_length": 23.25925925925926,
"alnum_prop": 0.7117834394904459,
"repo_name": "joey1087/fluid-framework",
"id": "79a8c06d385543b502b8a92ed21cb5ac0399bf54",
"size": "2062",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "FluidFrameworkIOS/FluidFrameworkIOS/FluidFramework/src/com/sponberg/fluid/util/CsvReader.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5544"
},
{
"name": "HTML",
"bytes": "35295"
},
{
"name": "Java",
"bytes": "815306"
},
{
"name": "JavaScript",
"bytes": "73299"
},
{
"name": "Objective-C",
"bytes": "2081323"
},
{
"name": "Python",
"bytes": "5470"
}
],
"symlink_target": ""
} |
This is a live editor for Riot tag.
## Have a play
[Open this example on Plunker](http://riotjs.com/examples/plunker/?app=live-editor)
## Run locally
Install superstatic if you don't have.
```bash
$ npm install -g superstatic
```
Download or clone this repo, then run the command.
```bash
$ cd to/this/dir
$ ss
```
Open the URL shown in your browser.
| {
"content_hash": "1b27cfc3d6375f52f226d596990a6b3a",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 83,
"avg_line_length": 16.318181818181817,
"alnum_prop": 0.7047353760445683,
"repo_name": "dp-lewis/examples",
"id": "153d7d3543bd1e8ddb0c60d6f3ce8992df2ddc7e",
"size": "374",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "live-editor/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1972"
},
{
"name": "HTML",
"bytes": "6224"
},
{
"name": "JavaScript",
"bytes": "914"
}
],
"symlink_target": ""
} |
A simple starter project demonstrating the basic concepts of Angular 2.
### Usage
- Clone or fork this repository
- Make sure you have [node.js](https://nodejs.org/) installed version 5+
- Make sure you have NPM installed version 3+
- `WINDOWS ONLY` run `npm install -g webpack webpack-dev-server typescript` to install global dependencies
- run `npm install` to install dependencies
- run `npm start` to fire up dev server
- open browser to [`http://localhost:3000`](http://localhost:3000)
| {
"content_hash": "6885c9725e5b92ba535dfa9e27b1232d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 106,
"avg_line_length": 44.81818181818182,
"alnum_prop": 0.7525354969574036,
"repo_name": "ogix/angular2-seed",
"id": "4f8db873877b0cf088788783fd1d238878e8dfab",
"size": "511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1289"
},
{
"name": "JavaScript",
"bytes": "1438"
},
{
"name": "TypeScript",
"bytes": "6419"
}
],
"symlink_target": ""
} |
package com.connectsdk.smarthomesampler;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.connectsdk.smarthomesampler.adapter.BeaconAdapter;
public class BluetoothService extends Service implements BeaconAdapter.BeaconUpdate {
public static final String ACTION_NEW_BEACON = "com.connectsdk.com.connectsdk.smarthomesampler.BluetoothService.action_new_beacon";
public static final String ACTION_PAUSE_SCANNING = "com.connectsdk.com.connectsdk.smarthomesampler.BluetoothService.action_pause_scanning";
BeaconAdapter beaconAdapter;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
beaconAdapter = new BeaconAdapter(getApplicationContext());
beaconAdapter.setListener(this);
beaconAdapter.startScan();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_PAUSE_SCANNING.equals(intent.getAction())) {
beaconAdapter.stopScanForPeriod(1000);
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
beaconAdapter.stopScan();
}
@Override
public void onClosestBeacon(BeaconAdapter.ScannedBleDevice ble) {
if (ble != null) {
Intent intent = new Intent();
intent.setAction(ACTION_NEW_BEACON);
intent.putExtra("beacon", ble.macAddress);
intent.putExtra("distance", ble.distance);
sendBroadcast(intent);
}
}
@Override
public void onDetectBeacon(BeaconAdapter.ScannedBleDevice ble) {
}
}
| {
"content_hash": "d32d8b3a71ca5cc6b5bed03fa0e5dcd0",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 143,
"avg_line_length": 30.17543859649123,
"alnum_prop": 0.6831395348837209,
"repo_name": "ConnectSDK/SmartHomeSamplerAndroid",
"id": "618e3b70e7154cfcef7b8948ae85ae1f19cc7d04",
"size": "2416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/connectsdk/smarthomesampler/BluetoothService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "143653"
}
],
"symlink_target": ""
} |
angular.module('thirdi.system').factory("Global", [
function() {
var _this = this;
_this._data = {
user: window.user,
authenticated: !! window.user
};
return _this._data;
}
]);
| {
"content_hash": "882d11183b7ac1299ef9aed4b25de027",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 51,
"avg_line_length": 22,
"alnum_prop": 0.4793388429752066,
"repo_name": "abhinavzspace/node-express-mysql-angular-boilerplate",
"id": "65208a740105c6ab0494e691cc54dc8ed2dbd86d",
"size": "280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/services/global.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "110"
},
{
"name": "JavaScript",
"bytes": "6767"
}
],
"symlink_target": ""
} |
<?php
/**
* Contains methods for matching API requests with endpoint routes.
*
* @package NamelessMC\Endpoints
* @author Aberdeener
* @version 2.0.0-pr13
* @license MIT
*/
trait MatchesRoutes {
/**
* Determine if an Endpoint matches a route.
* If it does, return an array of variables to pass to the endpoint.
*
* @param EndpointBase $endpoint Endpoint to attempt to match.
* @param string $route Route to match.
* @return array|false Array of variables to pass to the endpoint, or false if the route does not match.
*/
private function matchRoute(EndpointBase $endpoint, string $route) {
$endpoint_parts = explode('/', $endpoint->getRoute());
$endpoint_vars = [];
$route_parts = explode('/', $route);
$route_vars = [];
// first, find any variables (e.g. {user}) in the endpoint's route
// we save them to an array with their index, so we can reference them later
foreach ($endpoint_parts as $i => $part) {
if ($this->isVariable($part)) {
$endpoint_vars[$i] = $this->stripVariable($part);
}
}
if (count($endpoint_parts) !== count($route_parts)) {
return false;
}
// now we go over the route and, if each piece is a variable (according to its index), add it to the returned variable array
// otherwise, if it's not supposed to be a variable, we check if it matches the endpoint's respective route fragment and exit if it doesn't
foreach ($route_parts as $i => $part) {
if (array_key_exists($i, $endpoint_vars)) {
$route_vars[$endpoint_vars[$i]] = $part;
} else if ($endpoint_parts[$i] !== $part) {
return false;
}
}
return $route_vars;
}
private function isVariable(string $type) : bool {
return str_starts_with($type, '{') && str_ends_with($type, '}');
}
private function stripVariable(string $type) : string {
return substr($type, 1, -1);
}
}
| {
"content_hash": "01335cf9c5e484a1ba5c737455f798f0",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 147,
"avg_line_length": 35.220338983050844,
"alnum_prop": 0.5871029836381135,
"repo_name": "NamelessMC/Nameless",
"id": "84526b48f7ae0316b642ca588ee7bfa5c37fdfdb",
"size": "2078",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "core/classes/Endpoints/MatchesRoutes.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52115"
},
{
"name": "HTML",
"bytes": "2462"
},
{
"name": "JavaScript",
"bytes": "27159"
},
{
"name": "PHP",
"bytes": "1953744"
},
{
"name": "Python",
"bytes": "765"
},
{
"name": "Smarty",
"bytes": "878148"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The OEmbed Spec — djangoembed v0.1 documentation</title>
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '0.1',
COLLAPSE_MODINDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="top" title="djangoembed v0.1 documentation" href="../index.html" />
<link rel="prev" title="Providing Resources" href="providing_resources.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="providing_resources.html" title="Providing Resources"
accesskey="P">previous</a> |</li>
<li><a href="../index.html">djangoembed v0.1 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="the-oembed-spec">
<h1>The OEmbed Spec<a class="headerlink" href="#the-oembed-spec" title="Permalink to this headline">¶</a></h1>
<p>The full spec is available at <a class="reference external" href="http://www.oembed.com">http://www.oembed.com</a> - this overview will touch
on everything without going into too much detail to get you up and running with
OEmbed quickly!</p>
<div class="section" id="what-is-oembed">
<h2>What is OEmbed?<a class="headerlink" href="#what-is-oembed" title="Permalink to this headline">¶</a></h2>
<blockquote>
“oEmbed is a format for allowing an embedded representation of a URL on
third party sites. The simple API allows a website to display embedded
content (such as photos or videos) when a user posts a link to that
resource, without having to parse the resource directly.”</blockquote>
</div>
<div class="section" id="what-problem-does-it-solve">
<h2>What problem does it solve?<a class="headerlink" href="#what-problem-does-it-solve" title="Permalink to this headline">¶</a></h2>
<p>One of the tasks we as web developers run into a lot is the need to integrate
rich third-party content into our own sites. Numerous REST APIs exist for this
purpose, but suppose we are only concerned with metadata?</p>
<dl class="docutils">
<dt>REST APIs make it difficult to extract metadata in a generic way:</dt>
<dd><ul class="first last simple">
<li>URL structures vary (/statuses/update.json, /users/show.json)</li>
<li>attribute names are not standardized</li>
<li>metadata provided is content-dependant (twitter returns tweets, flickr photos)</li>
<li>authentication can be a pain</li>
<li>response formats vary</li>
</ul>
</dd>
<dt>OEmbed aims at solving these problems by:</dt>
<dd><ul class="first last simple">
<li>Endpoint lives at one place, like /oembed/json/</li>
<li>attribute names are standard, including ‘title’, ‘author’, ‘thumbnail_url’</li>
<li>resource types are standard, being ‘video’, ‘photo’, ‘link’, ‘rich’</li>
<li>response format must be JSON or XML</li>
</ul>
</dd>
</dl>
<p>OEmbed is not a REST API. It is a <em>READ</em> API. It allows you to retrieve
metadata about the objects you’re interested in, using a single endpoint.</p>
<p>The best part? <strong>All you need to provide the endpoint is the URL you want
metadata about</strong>.</p>
</div>
<div class="section" id="an-example">
<h2>An Example<a class="headerlink" href="#an-example" title="Permalink to this headline">¶</a></h2>
<div class="highlight-python"><pre>curl http://www.flickr.com/services/oembed/?url=http%3A//www.flickr.com/photos/bees/2341623661/
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<oembed>
<version>1.0</version>
<type>photo</type>
<title>ZB8T0193</title>
<author_name>bees</author_name>
<author_url>http://www.flickr.com/photos/bees/</author_url>
<cache_age>3600</cache_age>
<provider_name>Flickr</provider_name>
<provider_url>http://www.flickr.com/</provider_url>
<width>500</width>
<height>333</height>
<url>http://farm4.static.flickr.com/3123/2341623661_7c99f48bbf.jpg</url>
</oembed></pre>
</div>
<p>In the example above, we pass a flickr photo-detail URL to their OEmbed endpoint.
Flickr then returns a wealth of metadata about the object, including the image’s
URL, width and height.</p>
<p>OEmbed endpoints also can accept other arguments, like a <strong>maxwidth</strong>, or <strong>format</strong>:</p>
<div class="highlight-python"><pre>curl http://www.flickr.com/services/oembed/?url=http%3A//www.flickr.com/photos/bees/2341623661/\&maxwidth=300\&format=json
{
"version":"1.0",
"type":"photo",
"title":"ZB8T0193",
"author_name":"\u202e\u202d\u202cbees\u202c",
"author_url":"http:\/\/www.flickr.com\/photos\/bees\/",
"cache_age":3600,
"provider_name":"Flickr",
"provider_url":"http:\/\/www.flickr.com\/",
"width":"240",
"height":"160",
"url":"http:\/\/farm4.static.flickr.com\/3123\/2341623661_7c99f48bbf_m.jpg"
}</pre>
</div>
<p>As you can see from the response, the returned image width is now 240. If a
maximum width (or height) is specified, the provider must respect that.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference external" href="#">The OEmbed Spec</a><ul>
<li><a class="reference external" href="#what-is-oembed">What is OEmbed?</a></li>
<li><a class="reference external" href="#what-problem-does-it-solve">What problem does it solve?</a></li>
<li><a class="reference external" href="#an-example">An Example</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="providing_resources.html"
title="previous chapter">Providing Resources</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/djangoembed/spec.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" size="18" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="providing_resources.html" title="Providing Resources"
>previous</a> |</li>
<li><a href="../index.html">djangoembed v0.1 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2010, The World Company.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.4.
</div>
</body>
</html> | {
"content_hash": "f99ecec61f61463a4059a07eb516b26a",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 165,
"avg_line_length": 45.005319148936174,
"alnum_prop": 0.6317220186739156,
"repo_name": "0101/djangoembed",
"id": "5535b6373566cca694d92f94065f6fae4a14d9aa",
"size": "8473",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "doc/_build/html/djangoembed/spec.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13295"
},
{
"name": "JavaScript",
"bytes": "19227"
},
{
"name": "Python",
"bytes": "146905"
}
],
"symlink_target": ""
} |
package org.apache.logging.log4j.core.net.server;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.AppenderLoggingException;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.SocketAppender;
import org.apache.logging.log4j.core.layout.JsonLayout;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.layout.XmlLayout;
import org.apache.logging.log4j.core.net.Protocol;
import org.apache.logging.log4j.test.AvailablePortFinder;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
*/
public abstract class AbstractSocketServerTest {
protected static Thread thread;
private static final String MESSAGE = "This is test message";
private static final String MESSAGE_2 = "This is test message 2";
private static final String MESSAGE_WITH_SPECIAL_CHARS = "{This}\n[is]\"n\"a\"\r\ntrue:\n\ttest,\nmessage";
static final int PORT_NUM = AvailablePortFinder.getNextAvailable();
static final int PORT = PORT_NUM;
private final LoggerContext ctx = LoggerContext.getContext(false);
private final boolean expectLengthException;
protected final int port;
protected final Protocol protocol;
private final Logger rootLogger = ctx.getLogger(AbstractSocketServerTest.class.getSimpleName());
protected AbstractSocketServerTest(final Protocol protocol, final int port, final boolean expectLengthException) {
this.protocol = protocol;
this.port = port;
this.expectLengthException = expectLengthException;
}
protected Layout<String> createJsonLayout() {
return JsonLayout.createLayout(null, true, true, false, false, false, null, null, null);
}
protected abstract Layout<? extends Serializable> createLayout();
protected Layout<? extends Serializable> createSerializedLayout() {
return null;
}
protected Layout<String> createXmlLayout() {
return XmlLayout.createLayout(true, true, false, false, null);
}
@After
public void tearDown() {
final Map<String, Appender> map = rootLogger.getAppenders();
for (final Map.Entry<String, Appender> entry : map.entrySet()) {
final Appender appender = entry.getValue();
rootLogger.removeAppender(appender);
appender.stop();
}
}
@Test
@Ignore("Broken test?")
public void test1000ShortMessages() throws Exception {
testServer(1000);
}
@Test
@Ignore("Broken test?")
public void test100ShortMessages() throws Exception {
testServer(100);
}
@Test
public void test10ShortMessages() throws Exception {
testServer(10);
}
@Test
public void test1ShortMessages() throws Exception {
testServer(1);
}
@Test
public void test2ShortMessages() throws Exception {
testServer(2);
}
@Test
public void test64KBMessages() throws Exception {
final char[] a64K = new char[1024 * 64];
Arrays.fill(a64K, 'a');
final String m1 = new String(a64K);
final String m2 = MESSAGE_2 + m1;
if (expectLengthException) {
try {
testServer(m1, m2);
} catch (final AppenderLoggingException are) {
assertTrue("", are.getCause() != null && are.getCause() instanceof IOException);
// Failure expected.
}
} else {
testServer(m1, m2);
}
}
@Test
public void testMessagesWithSpecialChars() throws Exception {
testServer(MESSAGE_WITH_SPECIAL_CHARS);
}
private void testServer(final int size) throws Exception {
final String[] messages = new String[size];
for (int i = 0; i < messages.length; i++) {
messages[i] = MESSAGE + " " + i;
}
testServer(messages);
}
protected void testServer(final String... messages) throws Exception {
final Filter socketFilter = new ThreadNameFilter(Filter.Result.NEUTRAL, Filter.Result.DENY);
final Filter serverFilter = new ThreadNameFilter(Filter.Result.DENY, Filter.Result.NEUTRAL);
final Layout<? extends Serializable> socketLayout = createLayout();
final SocketAppender socketAppender = createSocketAppender(socketFilter, socketLayout);
socketAppender.start();
final ListAppender listAppender = new ListAppender("Events", serverFilter, null, false, false);
listAppender.start();
final PatternLayout layout = PatternLayout.newBuilder().withPattern("%m %ex%n").build();
final ConsoleAppender console = ConsoleAppender.createDefaultAppenderForLayout(layout);
final Logger serverLogger = ctx.getLogger(this.getClass().getName());
serverLogger.addAppender(console);
serverLogger.setAdditive(false);
// set appender on root and set level to debug
rootLogger.addAppender(socketAppender);
rootLogger.addAppender(listAppender);
rootLogger.setAdditive(false);
rootLogger.setLevel(Level.DEBUG);
for (final String message : messages) {
rootLogger.debug(message);
}
final int MAX_TRIES = 400;
for (int i = 0; i < MAX_TRIES; i++) {
if (listAppender.getEvents().size() < messages.length) {
try {
// Let the server-side read the messages.
Thread.sleep(50);
} catch (final Exception e) {
e.printStackTrace();
}
} else {
break;
}
}
final List<LogEvent> events = listAppender.getEvents();
assertNotNull("No event retrieved", events);
assertEquals("Incorrect number of events received", messages.length, events.size());
for (int i = 0; i < messages.length; i++) {
assertTrue("Incorrect event", events.get(i).getMessage().getFormattedMessage().equals(messages[i]));
}
}
protected SocketAppender createSocketAppender(final Filter socketFilter,
final Layout<? extends Serializable> socketLayout) {
return SocketAppender.createAppender("localhost", this.port, this.protocol, null, 0, -1, true,
"Test", true, false, socketLayout, socketFilter, false, null);
}
}
| {
"content_hash": "907c1bad248421b9bf2488630c1c8523",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 118,
"avg_line_length": 35.121212121212125,
"alnum_prop": 0.6629278113316077,
"repo_name": "lburgazzoli/apache-logging-log4j2",
"id": "ee5c2de5d31a7046c9529f01f50efaaa93419270",
"size": "7754",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "log4j-core/src/test/java/org/apache/logging/log4j/core/net/server/AbstractSocketServerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1024"
},
{
"name": "CSS",
"bytes": "3981"
},
{
"name": "Groovy",
"bytes": "198"
},
{
"name": "Java",
"bytes": "6349226"
},
{
"name": "JavaScript",
"bytes": "59116"
},
{
"name": "Shell",
"bytes": "861"
}
],
"symlink_target": ""
} |
from flask_webtest import SessionScope
from pytest import fixture
from portal.database import db
from portal.models.questionnaire_bank import (
QuestionnaireBank,
QuestionnaireBankQuestionnaire
)
from portal.models.recur import Recur
@fixture
def initialized_with_ss_qb(
initialized_with_ss_protocol, initialized_with_ss_q):
rp_id = db.session.merge(initialized_with_ss_protocol).id
ss_qb = QuestionnaireBank(
name='substudy_qb_baseline',
start='{"days": 0}',
expired='{"months": 1}',
research_protocol_id=rp_id)
qbq = QuestionnaireBankQuestionnaire(
questionnaire=initialized_with_ss_q, rank=0)
ss_qb.questionnaires.append(qbq)
with SessionScope(db):
db.session.add(ss_qb)
db.session.commit()
return db.session.merge(ss_qb)
@fixture
def initialized_with_ss_recur_qb(
initialized_with_ss_protocol, initialized_with_ss_q):
rp_id = db.session.merge(initialized_with_ss_protocol).id
monthly_recur = Recur(
start='{"months": 1}', cycle_length='{"months": 1}',
termination='{"months": 11}')
ss_qb = QuestionnaireBank(
name='substudy_qb_monthly',
start='{"days": 0}',
expired='{"months": 1, "days": -1}',
recurs=[monthly_recur],
research_protocol_id=rp_id)
qbq = QuestionnaireBankQuestionnaire(
questionnaire=initialized_with_ss_q, rank=0)
ss_qb.questionnaires.append(qbq)
with SessionScope(db):
db.session.add(ss_qb)
db.session.commit()
return db.session.merge(ss_qb)
| {
"content_hash": "9975e6d5097e431fdf5bfc55b00328bd",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 61,
"avg_line_length": 31.019607843137255,
"alnum_prop": 0.6599241466498104,
"repo_name": "uwcirg/true_nth_usa_portal",
"id": "a54cff346a634f29eab4ba4fe8683c7f7fe77c5a",
"size": "1582",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/fixtures/quesionnaire_bank.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1733344"
},
{
"name": "Dockerfile",
"bytes": "947"
},
{
"name": "HTML",
"bytes": "435596"
},
{
"name": "JavaScript",
"bytes": "588006"
},
{
"name": "Mako",
"bytes": "414"
},
{
"name": "Python",
"bytes": "1837126"
},
{
"name": "Shell",
"bytes": "13976"
},
{
"name": "Vue",
"bytes": "62901"
}
],
"symlink_target": ""
} |
FolderUploadConfirmationView::FolderUploadConfirmationView(
const base::FilePath& path,
base::OnceCallback<void(const std::vector<ui::SelectedFileInfo>&)> callback,
std::vector<ui::SelectedFileInfo> selected_files)
: callback_(std::move(callback)),
selected_files_(std::move(selected_files)) {
SetTitle(l10n_util::GetPluralStringFUTF16(
IDS_CONFIRM_FILE_UPLOAD_TITLE,
base::saturated_cast<int>(selected_files_.size())));
SetButtonLabel(ui::DIALOG_BUTTON_OK,
l10n_util::GetStringUTF16(IDS_CONFIRM_FILE_UPLOAD_OK_BUTTON));
SetAcceptCallback(base::BindOnce(
[](FolderUploadConfirmationView* dialog) {
std::move(dialog->callback_).Run(dialog->selected_files_);
},
base::Unretained(this)));
SetCancelCallback(base::BindOnce(
[](FolderUploadConfirmationView* dialog) {
std::move(dialog->callback_).Run({});
},
base::Unretained(this)));
SetCloseCallback(base::BindOnce(
[](FolderUploadConfirmationView* dialog) {
std::move(dialog->callback_).Run({});
},
base::Unretained(this)));
SetModalType(ui::MODAL_TYPE_CHILD);
SetShowCloseButton(false);
set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH));
SetUseDefaultFillLayout(true);
auto label = std::make_unique<views::Label>(
l10n_util::GetStringFUTF16(IDS_CONFIRM_FILE_UPLOAD_TEXT,
path.BaseName().LossyDisplayName()),
views::style::CONTEXT_DIALOG_BODY_TEXT, views::style::STYLE_SECONDARY);
label->SetMultiLine(true);
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
AddChildView(std::move(label));
set_margins(ChromeLayoutProvider::Get()->GetDialogInsetsForContentType(
views::DialogContentType::kText, views::DialogContentType::kText));
}
FolderUploadConfirmationView::~FolderUploadConfirmationView() {
// Make sure the dialog ends up calling the callback no matter what as
// FileSelectHelper keeps itself alive until it sends the result.
if (!callback_.is_null())
Cancel();
}
views::Widget* FolderUploadConfirmationView::ShowDialog(
const base::FilePath& path,
base::OnceCallback<void(const std::vector<ui::SelectedFileInfo>&)> callback,
std::vector<ui::SelectedFileInfo> selected_files,
content::WebContents* web_contents) {
auto delegate = std::make_unique<FolderUploadConfirmationView>(
path, std::move(callback), std::move(selected_files));
return constrained_window::ShowWebModalDialogViews(delegate.release(),
web_contents);
}
views::View* FolderUploadConfirmationView::GetInitiallyFocusedView() {
return GetCancelButton();
}
BEGIN_METADATA(FolderUploadConfirmationView, views::DialogDelegateView)
END_METADATA
void ShowFolderUploadConfirmationDialog(
const base::FilePath& path,
base::OnceCallback<void(const std::vector<ui::SelectedFileInfo>&)> callback,
std::vector<ui::SelectedFileInfo> selected_files,
content::WebContents* web_contents) {
FolderUploadConfirmationView::ShowDialog(
path, std::move(callback), std::move(selected_files), web_contents);
}
| {
"content_hash": "38d6cd0750c9eab4ad3d9598bf3aa043",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 80,
"avg_line_length": 40.56962025316456,
"alnum_prop": 0.7039001560062402,
"repo_name": "chromium/chromium",
"id": "3d053fc89047978222fa7efcc372e632128e7644",
"size": "3989",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "chrome/browser/ui/views/folder_upload_confirmation_view.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
#pragma once
#include "antlr4-common.h"
namespace antlrcpp {
ANTLR4CPP_PUBLIC std::string join(const std::vector<std::string> &strings, const std::string &separator);
ANTLR4CPP_PUBLIC std::map<std::string, size_t> toMap(const std::vector<std::string> &keys);
ANTLR4CPP_PUBLIC std::string escapeWhitespace(std::string str, bool escapeSpaces);
ANTLR4CPP_PUBLIC std::string toHexString(const int t);
ANTLR4CPP_PUBLIC std::string arrayToString(const std::vector<std::string> &data);
ANTLR4CPP_PUBLIC std::string replaceString(const std::string &s, const std::string &from, const std::string &to);
ANTLR4CPP_PUBLIC std::vector<std::string> split(const std::string &s, const std::string &sep, int count);
ANTLR4CPP_PUBLIC std::string indent(const std::string &s, const std::string &indentation, bool includingFirst = true);
// Using RAII + a lambda to implement a "finally" replacement.
template <typename OnEnd>
struct FinalAction {
FinalAction(OnEnd f) : _cleanUp { std::move(f) } {}
FinalAction(FinalAction &&other) :
_cleanUp(std::move(other._cleanUp)), _enabled(other._enabled) {
other._enabled = false; // Don't trigger the lambda after ownership has moved.
}
~FinalAction() { if (_enabled) _cleanUp(); }
void disable() { _enabled = false; }
private:
OnEnd _cleanUp;
bool _enabled {true};
};
template <typename OnEnd>
FinalAction<OnEnd> finally(OnEnd f) {
return FinalAction<OnEnd>(std::move(f));
}
// Convenience functions to avoid lengthy dynamic_cast() != nullptr checks in many places.
template <typename T1, typename T2>
inline bool is(T2 *obj) { // For pointer types.
return dynamic_cast<typename std::add_const<T1>::type>(obj) != nullptr;
}
template <typename T1, typename T2>
inline bool is(Ref<T2> const& obj) { // For shared pointers.
return dynamic_cast<T1 *>(obj.get()) != nullptr;
}
template <typename T>
std::string toString(const T &o) {
std::stringstream ss;
// typeid gives the mangled class name, but that's all what's possible
// in a portable way.
ss << typeid(o).name() << "@" << std::hex << reinterpret_cast<uintptr_t>(&o);
return ss.str();
}
// Get the error text from an exception pointer or the current exception.
ANTLR4CPP_PUBLIC std::string what(std::exception_ptr eptr = std::current_exception());
} // namespace antlrcpp
| {
"content_hash": "cff219769b1c5fbae1aea713366ba546",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 120,
"avg_line_length": 38.483870967741936,
"alnum_prop": 0.6886001676445934,
"repo_name": "SystemRDL/systemrdl-compiler",
"id": "2eb1a36037a241c96cf92584059ce72901ead9d7",
"size": "2582",
"binary": false,
"copies": "7",
"ref": "refs/heads/main",
"path": "systemrdl/parser/ext/antlr4-cpp-runtime/support/CPPUtils.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "15247"
},
{
"name": "C++",
"bytes": "1101311"
},
{
"name": "Perl",
"bytes": "1885"
},
{
"name": "Python",
"bytes": "998085"
},
{
"name": "Shell",
"bytes": "1886"
}
],
"symlink_target": ""
} |
import ConfigParser
import os
import tarfile
import urllib2
# Default client libs
import glanceclient as glance_client
import keystoneclient.v2_0.client as keystone_client
# Import Openstack exceptions
import glanceclient.exc as glance_exception
import keystoneclient.exceptions as keystone_exception
TEMPEST_TEMP_DIR = os.getenv("TEMPEST_TEMP_DIR", "/tmp").rstrip('/')
TEMPEST_ROOT_DIR = os.getenv("TEMPEST_ROOT_DIR", os.getenv("HOME")).rstrip('/')
# Environment variables override defaults
TEMPEST_CONFIG_DIR = os.getenv("TEMPEST_CONFIG_DIR",
"%s%s" % (TEMPEST_ROOT_DIR, "/etc")).rstrip('/')
TEMPEST_CONFIG_FILE = os.getenv("TEMPEST_CONFIG_FILE",
"%s%s" % (TEMPEST_CONFIG_DIR, "/tempest.conf"))
TEMPEST_CONFIG_SAMPLE = os.getenv("TEMPEST_CONFIG_SAMPLE",
"%s%s" % (TEMPEST_CONFIG_DIR,
"/tempest.conf.sample"))
# Image references
IMAGE_DOWNLOAD_CHUNK_SIZE = 8 * 1024
IMAGE_UEC_SOURCE_URL = os.getenv("IMAGE_UEC_SOURCE_URL",
"http://download.cirros-cloud.net/0.3.1/"
"cirros-0.3.1-x86_64-uec.tar.gz")
TEMPEST_IMAGE_ID = os.getenv('IMAGE_ID')
TEMPEST_IMAGE_ID_ALT = os.getenv('IMAGE_ID_ALT')
IMAGE_STATUS_ACTIVE = 'active'
class ClientManager(object):
"""
Manager that provides access to the official python clients for
calling various OpenStack APIs.
"""
def __init__(self):
self.identity_client = None
self.image_client = None
self.network_client = None
self.compute_client = None
self.volume_client = None
def get_identity_client(self, **kwargs):
"""
Returns the openstack identity python client
:param username: a string representing the username
:param password: a string representing the user's password
:param tenant_name: a string representing the tenant name of the user
:param auth_url: a string representing the auth url of the identity
:param insecure: True if we wish to disable ssl certificate validation,
False otherwise
:returns an instance of openstack identity python client
"""
if not self.identity_client:
self.identity_client = keystone_client.Client(**kwargs)
return self.identity_client
def get_image_client(self, version="1", *args, **kwargs):
"""
This method returns Openstack glance python client
:param version: a string representing the version of the glance client
to use.
:param string endpoint: A user-supplied endpoint URL for the glance
service.
:param string token: Token for authentication.
:param integer timeout: Allows customization of the timeout for client
http requests. (optional)
:return: a Client object representing the glance client
"""
if not self.image_client:
self.image_client = glance_client.Client(version, *args, **kwargs)
return self.image_client
def get_tempest_config(path_to_config):
"""
Gets the tempest configuration file as a ConfigParser object
:param path_to_config: path to the config file
:return: a ConfigParser object representing the tempest configuration file
"""
# get the sample config file from the sample
config = ConfigParser.ConfigParser()
config.readfp(open(path_to_config))
return config
def update_config_admin_credentials(config, config_section):
"""
Updates the tempest config with the admin credentials
:param config: a ConfigParser object representing the tempest config file
:param config_section: the section name where the admin credentials are
"""
# Check if credentials are present, default uses the config credentials
OS_USERNAME = os.getenv('OS_USERNAME',
config.get(config_section, "admin_username"))
OS_PASSWORD = os.getenv('OS_PASSWORD',
config.get(config_section, "admin_password"))
OS_TENANT_NAME = os.getenv('OS_TENANT_NAME',
config.get(config_section, "admin_tenant_name"))
OS_AUTH_URL = os.getenv('OS_AUTH_URL', config.get(config_section, "uri"))
if not (OS_AUTH_URL and
OS_USERNAME and
OS_PASSWORD and
OS_TENANT_NAME):
raise Exception("Admin environment variables not found.")
# TODO(tkammer): Add support for uri_v3
config_identity_params = {'uri': OS_AUTH_URL,
'admin_username': OS_USERNAME,
'admin_password': OS_PASSWORD,
'admin_tenant_name': OS_TENANT_NAME}
update_config_section_with_params(config,
config_section,
config_identity_params)
def update_config_section_with_params(config, config_section, params):
"""
Updates a given config object with given params
:param config: a ConfigParser object representing the tempest config file
:param config_section: the section we would like to update
:param params: the parameters we wish to update for that section
"""
for option, value in params.items():
config.set(config_section, option, value)
def get_identity_client_kwargs(config, config_section):
"""
Get the required arguments for the identity python client
:param config: a ConfigParser object representing the tempest config file
:param config_section: the section name in the configuration where the
arguments can be found
:return: a dictionary representing the needed arguments for the identity
client
"""
username = config.get(config_section, 'admin_username')
password = config.get(config_section, 'admin_password')
tenant_name = config.get(config_section, 'admin_tenant_name')
auth_url = config.get(config_section, 'uri')
dscv = config.get(config_section, 'disable_ssl_certificate_validation')
kwargs = {'username': username,
'password': password,
'tenant_name': tenant_name,
'auth_url': auth_url,
'insecure': dscv}
return kwargs
def create_user_with_tenant(identity_client, username, password, tenant_name):
"""
Creates a user using a given identity client
:param identity_client: openstack identity python client
:param username: a string representing the username
:param password: a string representing the user's password
:param tenant_name: a string representing the tenant name of the user
"""
# Try to create the necessary tenant
tenant_id = None
try:
tenant_description = "Tenant for Tempest %s user" % username
tenant = identity_client.tenants.create(tenant_name,
tenant_description)
tenant_id = tenant.id
except keystone_exception.Conflict:
# if already exist, use existing tenant
tenant_list = identity_client.tenants.list()
for tenant in tenant_list:
if tenant.name == tenant_name:
tenant_id = tenant.id
# Try to create the user
try:
email = "%[email protected]" % username
identity_client.users.create(name=username,
password=password,
email=email,
tenant_id=tenant_id)
except keystone_exception.Conflict:
# if already exist, use existing user
pass
def create_users_and_tenants(identity_client,
config,
config_section):
"""
Creates the two non admin users and tenants for tempest
:param identity_client: openstack identity python client
:param config: a ConfigParser object representing the tempest config file
:param config_section: the section name of identity in the config
"""
# Get the necessary params from the config file
tenant_name = config.get(config_section, 'tenant_name')
username = config.get(config_section, 'username')
password = config.get(config_section, 'password')
alt_tenant_name = config.get(config_section, 'alt_tenant_name')
alt_username = config.get(config_section, 'alt_username')
alt_password = config.get(config_section, 'alt_password')
# Create the necessary users for the test runs
create_user_with_tenant(identity_client, username, password, tenant_name)
create_user_with_tenant(identity_client, alt_username, alt_password,
alt_tenant_name)
def get_image_client_kwargs(identity_client, config, config_section):
"""
Get the required arguments for the image python client
:param identity_client: openstack identity python client
:param config: a ConfigParser object representing the tempest config file
:param config_section: the section name of identity in the config
:return: a dictionary representing the needed arguments for the image
client
"""
token = identity_client.auth_token
endpoint = identity_client.\
service_catalog.url_for(service_type='image', endpoint_type='publicURL'
)
dscv = config.get(config_section, 'disable_ssl_certificate_validation')
kwargs = {'endpoint': endpoint,
'token': token,
'insecure': dscv}
return kwargs
def images_exist(image_client):
"""
Checks whether the images ID's located in the environment variable are
indeed registered
:param image_client: the openstack python client representing the image
client
"""
exist = True
if not TEMPEST_IMAGE_ID or not TEMPEST_IMAGE_ID_ALT:
exist = False
else:
try:
image_client.images.get(TEMPEST_IMAGE_ID)
image_client.images.get(TEMPEST_IMAGE_ID_ALT)
except glance_exception.HTTPNotFound:
exist = False
return exist
def download_and_register_uec_images(image_client, download_url,
download_folder):
"""
Downloads and registered the UEC AKI/AMI/ARI images
:param image_client:
:param download_url: the url of the uec tar file
:param download_folder: the destination folder we wish to save the file to
"""
basename = os.path.basename(download_url)
path = os.path.join(download_folder, basename)
request = urllib2.urlopen(download_url)
# First, download the file
with open(path, "wb") as fp:
while True:
chunk = request.read(IMAGE_DOWNLOAD_CHUNK_SIZE)
if not chunk:
break
fp.write(chunk)
# Then extract and register images
tar = tarfile.open(path, "r")
for name in tar.getnames():
file_obj = tar.extractfile(name)
format = "aki"
if file_obj.name.endswith(".img"):
format = "ami"
if file_obj.name.endswith("initrd"):
format = "ari"
# Register images in image client
image_client.images.create(name=file_obj.name, disk_format=format,
container_format=format, data=file_obj,
is_public="true")
tar.close()
def create_images(image_client, config, config_section,
download_url=IMAGE_UEC_SOURCE_URL,
download_folder=TEMPEST_TEMP_DIR):
"""
Creates images for tempest's use and registers the environment variables
IMAGE_ID and IMAGE_ID_ALT with registered images
:param image_client: Openstack python image client
:param config: a ConfigParser object representing the tempest config file
:param config_section: the section name where the IMAGE ids are set
:param download_url: the URL from which we should download the UEC tar
:param download_folder: the place where we want to save the download file
"""
if not images_exist(image_client):
# Falls down to the default uec images
download_and_register_uec_images(image_client, download_url,
download_folder)
image_ids = []
for image in image_client.images.list():
image_ids.append(image.id)
os.environ["IMAGE_ID"] = image_ids[0]
os.environ["IMAGE_ID_ALT"] = image_ids[1]
params = {'image_ref': os.getenv("IMAGE_ID"),
'image_ref_alt': os.getenv("IMAGE_ID_ALT")}
update_config_section_with_params(config, config_section, params)
def main():
"""
Main module to control the script
"""
# Check if config file exists or fall to the default sample otherwise
path_to_config = TEMPEST_CONFIG_SAMPLE
if os.path.isfile(TEMPEST_CONFIG_FILE):
path_to_config = TEMPEST_CONFIG_FILE
config = get_tempest_config(path_to_config)
update_config_admin_credentials(config, 'identity')
client_manager = ClientManager()
# Set the identity related info for tempest
identity_client_kwargs = get_identity_client_kwargs(config,
'identity')
identity_client = client_manager.get_identity_client(
**identity_client_kwargs)
# Create the necessary users and tenants for tempest run
create_users_and_tenants(identity_client, config, 'identity')
# Set the image related info for tempest
image_client_kwargs = get_image_client_kwargs(identity_client,
config,
'identity')
image_client = client_manager.get_image_client(**image_client_kwargs)
# Create the necessary users and tenants for tempest run
create_images(image_client, config, 'compute')
# TODO(tkammer): add network implementation
if __name__ == "__main__":
main()
| {
"content_hash": "0df2e3d2e381db3ea5b0a85942582e3d",
"timestamp": "",
"source": "github",
"line_count": 370,
"max_line_length": 79,
"avg_line_length": 37.95135135135135,
"alnum_prop": 0.6306793904002279,
"repo_name": "eltonkevani/tempest_el_env",
"id": "fe9f5afef19ae90f5d96369d452a27d49a1756b9",
"size": "15134",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tools/tempest_auto_config.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "1871339"
},
{
"name": "Shell",
"bytes": "5748"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\ProductAlert\Test\Unit\Block\Product;
class ViewTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $block;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $postHelper;
protected function setUp()
{
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->postHelper = $this->getMock(
'Magento\Framework\Data\Helper\PostHelper',
[],
[],
'',
false
);
$this->block = $objectManager->getObject(
'Magento\ProductAlert\Block\Product\View',
['coreHelper' => $this->postHelper]
);
}
public function testGetPostAction()
{
$this->block->setSignupUrl('someUrl');
$this->postHelper->expects($this->once())
->method('getPostData')
->with('someUrl')
->will($this->returnValue('{parsedAction}'));
$this->assertEquals('{parsedAction}', $this->block->getPostAction());
}
}
| {
"content_hash": "b9ce2b8b37c56598ae803b096d8a4e65",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 95,
"avg_line_length": 27.142857142857142,
"alnum_prop": 0.5728070175438597,
"repo_name": "j-froehlich/magento2_wk",
"id": "394faf83756912420e656bcf3e4c5f0e08997c24",
"size": "1248",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/magento/module-product-alert/Test/Unit/Block/Product/ViewTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "13636"
},
{
"name": "CSS",
"bytes": "2076720"
},
{
"name": "HTML",
"bytes": "6151072"
},
{
"name": "JavaScript",
"bytes": "2488727"
},
{
"name": "PHP",
"bytes": "12466046"
},
{
"name": "Shell",
"bytes": "6088"
},
{
"name": "XSLT",
"bytes": "19979"
}
],
"symlink_target": ""
} |
package org.apache.ranger.plugin.conditionevaluator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ranger.plugin.policyengine.RangerAccessRequest;
public class RangerAccessedFromClusterTypeCondition extends RangerAbstractConditionEvaluator{
private static final Log LOG = LogFactory.getLog(RangerAccessedFromClusterTypeCondition.class);
private boolean isAlwaysTrue = false;
@Override
public void init() {
if (LOG.isDebugEnabled()) {
LOG.debug("==> RangerAccessedFromClusterTypeCondition.init(" + condition + ")");
}
super.init();
isAlwaysTrue = CollectionUtils.isEmpty(condition.getValues());
if (LOG.isDebugEnabled()) {
LOG.debug("<== RangerAccessedFromClusterTypeCondition.init(" + condition + ")");
}
}
@Override
public boolean isMatched(RangerAccessRequest request) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> RangerAccessedFromClusterTypeCondition.isMatched(" + condition + ")");
}
final boolean ret;
if (isAlwaysTrue || request.getClusterType() == null) {
ret = isAlwaysTrue;
} else {
ret = condition.getValues().contains(request.getClusterType());
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== RangerAccessedFromClusterTypeCondition.isMatched(" + condition + "): " + ret);
}
return ret;
}
}
| {
"content_hash": "5ffcad5b464874bb91727d245298e26d",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 96,
"avg_line_length": 28.729166666666668,
"alnum_prop": 0.7403915881073242,
"repo_name": "gzsombor/ranger",
"id": "50a92bd6ff725efb9e38399b8a3810935c64b0a5",
"size": "2184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "agents-common/src/main/java/org/apache/ranger/plugin/conditionevaluator/RangerAccessedFromClusterTypeCondition.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5370"
},
{
"name": "CSS",
"bytes": "88486"
},
{
"name": "HTML",
"bytes": "248217"
},
{
"name": "Java",
"bytes": "10183904"
},
{
"name": "JavaScript",
"bytes": "2241776"
},
{
"name": "PLSQL",
"bytes": "193256"
},
{
"name": "PLpgSQL",
"bytes": "102937"
},
{
"name": "Python",
"bytes": "690832"
},
{
"name": "SQLPL",
"bytes": "35351"
},
{
"name": "Shell",
"bytes": "396435"
},
{
"name": "TSQL",
"bytes": "1158183"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe SecureHeaders do
class DummyClass
include ::SecureHeaders
end
subject {DummyClass.new}
let(:headers) {double}
let(:response) {double(:headers => headers)}
let(:max_age) {99}
let(:request) {double(:ssl? => true, :url => 'https://example.com')}
before(:each) do
stub_user_agent(nil)
allow(headers).to receive(:[])
allow(subject).to receive(:response).and_return(response)
allow(subject).to receive(:request).and_return(request)
end
def stub_user_agent val
allow(request).to receive_message_chain(:env, :[]).and_return(val)
end
def reset_config
::SecureHeaders::Configuration.configure do |config|
config.hpkp = nil
config.hsts = nil
config.x_frame_options = nil
config.x_content_type_options = nil
config.x_xss_protection = nil
config.csp = nil
config.x_download_options = nil
config.x_permitted_cross_domain_policies = nil
end
end
def set_security_headers(subject)
subject.set_csp_header
subject.set_hpkp_header
subject.set_hsts_header
subject.set_x_frame_options_header
subject.set_x_content_type_options_header
subject.set_x_xss_protection_header
subject.set_x_download_options_header
subject.set_x_permitted_cross_domain_policies_header
end
describe "#set_header" do
it "accepts name/value pairs" do
should_assign_header("X-Hipster-Ipsum", "kombucha")
subject.send(:set_header, "X-Hipster-Ipsum", "kombucha")
end
it "accepts header objects" do
should_assign_header("Strict-Transport-Security", SecureHeaders::StrictTransportSecurity::Constants::DEFAULT_VALUE)
subject.send(:set_header, SecureHeaders::StrictTransportSecurity.new)
end
end
describe "#set_security_headers" do
USER_AGENTS.each do |name, useragent|
it "sets all default headers for #{name} (smoke test)" do
stub_user_agent(useragent)
number_of_headers = 7
expect(subject).to receive(:set_header).exactly(number_of_headers).times # a request for a given header
subject.set_csp_header
subject.set_x_frame_options_header
subject.set_hsts_header
subject.set_hpkp_header
subject.set_x_xss_protection_header
subject.set_x_content_type_options_header
subject.set_x_download_options_header
subject.set_x_permitted_cross_domain_policies_header
end
end
it "does not set the X-Content-Type-Options header if disabled" do
stub_user_agent(USER_AGENTS[:ie])
should_not_assign_header(X_CONTENT_TYPE_OPTIONS_HEADER_NAME)
subject.set_x_content_type_options_header(false)
end
it "does not set the X-XSS-Protection header if disabled" do
should_not_assign_header(X_XSS_PROTECTION_HEADER_NAME)
subject.set_x_xss_protection_header(false)
end
it "does not set the X-Download-Options header if disabled" do
should_not_assign_header(XDO_HEADER_NAME)
subject.set_x_download_options_header(false)
end
it "does not set the X-Frame-Options header if disabled" do
should_not_assign_header(XFO_HEADER_NAME)
subject.set_x_frame_options_header(false)
end
it "does not set the X-Permitted-Cross-Domain-Policies header if disabled" do
should_not_assign_header(XPCDP_HEADER_NAME)
subject.set_x_permitted_cross_domain_policies_header(false)
end
it "does not set the HSTS header if disabled" do
should_not_assign_header(HSTS_HEADER_NAME)
subject.set_hsts_header(false)
end
it "does not set the HSTS header if request is over HTTP" do
allow(subject).to receive_message_chain(:request, :ssl?).and_return(false)
should_not_assign_header(HSTS_HEADER_NAME)
subject.set_hsts_header({:include_subdomains => true})
end
it "does not set the HPKP header if disabled" do
should_not_assign_header(HPKP_HEADER_NAME)
subject.set_hpkp_header
end
it "does not set the HPKP header if request is over HTTP" do
allow(subject).to receive_message_chain(:request, :ssl?).and_return(false)
should_not_assign_header(HPKP_HEADER_NAME)
subject.set_hpkp_header(:max_age => 1234)
end
it "does not set the CSP header if disabled" do
stub_user_agent(USER_AGENTS[:chrome])
should_not_assign_header(HEADER_NAME)
subject.set_csp_header(false)
end
it "saves the options to the env when using script hashes" do
opts = {
:default_src => 'self',
:script_hash_middleware => true
}
stub_user_agent(USER_AGENTS[:chrome])
expect(SecureHeaders::ContentSecurityPolicy).to receive(:add_to_env)
subject.set_csp_header(opts)
end
context "when disabled by configuration settings" do
it "does not set any headers when disabled" do
::SecureHeaders::Configuration.configure do |config|
config.hsts = false
config.hpkp = false
config.x_frame_options = false
config.x_content_type_options = false
config.x_xss_protection = false
config.csp = false
config.x_download_options = false
config.x_permitted_cross_domain_policies = false
end
expect(subject).not_to receive(:set_header)
set_security_headers(subject)
reset_config
end
end
end
describe "#set_x_frame_options_header" do
it "sets the X-Frame-Options header" do
should_assign_header(XFO_HEADER_NAME, SecureHeaders::XFrameOptions::Constants::DEFAULT_VALUE)
subject.set_x_frame_options_header
end
it "allows a custom X-Frame-Options header" do
should_assign_header(XFO_HEADER_NAME, "DENY")
subject.set_x_frame_options_header(:value => 'DENY')
end
end
describe "#set_x_download_options_header" do
it "sets the X-Download-Options header" do
should_assign_header(XDO_HEADER_NAME, SecureHeaders::XDownloadOptions::Constants::DEFAULT_VALUE)
subject.set_x_download_options_header
end
it "allows a custom X-Download-Options header" do
should_assign_header(XDO_HEADER_NAME, "noopen")
subject.set_x_download_options_header(:value => 'noopen')
end
end
describe "#set_strict_transport_security" do
it "sets the Strict-Transport-Security header" do
should_assign_header(HSTS_HEADER_NAME, SecureHeaders::StrictTransportSecurity::Constants::DEFAULT_VALUE)
subject.set_hsts_header
end
it "allows you to specific a custom max-age value" do
should_assign_header(HSTS_HEADER_NAME, 'max-age=1234')
subject.set_hsts_header(:max_age => 1234)
end
it "allows you to specify includeSubdomains" do
should_assign_header(HSTS_HEADER_NAME, "max-age=#{HSTS_MAX_AGE}; includeSubdomains")
subject.set_hsts_header(:max_age => HSTS_MAX_AGE, :include_subdomains => true)
end
it "allows you to specify preload" do
should_assign_header(HSTS_HEADER_NAME, "max-age=#{HSTS_MAX_AGE}; includeSubdomains; preload")
subject.set_hsts_header(:max_age => HSTS_MAX_AGE, :include_subdomains => true, :preload => true)
end
end
describe "#set_public_key_pins" do
it "sets the Public-Key-Pins header" do
should_assign_header(HPKP_HEADER_NAME + "-Report-Only", "max-age=1234")
subject.set_hpkp_header(:max_age => 1234)
end
it "allows you to enforce public key pinning" do
should_assign_header(HPKP_HEADER_NAME, "max-age=1234")
subject.set_hpkp_header(:max_age => 1234, :enforce => true)
end
it "allows you to specific a custom max-age value" do
should_assign_header(HPKP_HEADER_NAME + "-Report-Only", 'max-age=1234')
subject.set_hpkp_header(:max_age => 1234)
end
it "allows you to specify includeSubdomains" do
should_assign_header(HPKP_HEADER_NAME, "max-age=1234; includeSubDomains")
subject.set_hpkp_header(:max_age => 1234, :include_subdomains => true, :enforce => true)
end
it "allows you to specify a report-uri" do
should_assign_header(HPKP_HEADER_NAME, "max-age=1234; report-uri=\"https://foobar.com\"")
subject.set_hpkp_header(:max_age => 1234, :report_uri => "https://foobar.com", :enforce => true)
end
it "allows you to specify a report-uri with app_name" do
should_assign_header(HPKP_HEADER_NAME, "max-age=1234; report-uri=\"https://foobar.com?enforce=true&app_name=my_app\"")
subject.set_hpkp_header(:max_age => 1234, :report_uri => "https://foobar.com", :app_name => "my_app", :tag_report_uri => true, :enforce => true)
end
end
describe "#set_x_xss_protection" do
it "sets the X-XSS-Protection header" do
should_assign_header(X_XSS_PROTECTION_HEADER_NAME, SecureHeaders::XXssProtection::Constants::DEFAULT_VALUE)
subject.set_x_xss_protection_header
end
it "sets a custom X-XSS-Protection header" do
should_assign_header(X_XSS_PROTECTION_HEADER_NAME, '0')
subject.set_x_xss_protection_header("0")
end
it "sets the block flag" do
should_assign_header(X_XSS_PROTECTION_HEADER_NAME, '1; mode=block')
subject.set_x_xss_protection_header(:mode => 'block', :value => 1)
end
end
describe "#set_x_content_type_options" do
USER_AGENTS.each do |useragent|
context "when using #{useragent}" do
before(:each) do
stub_user_agent(USER_AGENTS[useragent])
end
it "sets the X-Content-Type-Options header" do
should_assign_header(X_CONTENT_TYPE_OPTIONS_HEADER_NAME, SecureHeaders::XContentTypeOptions::Constants::DEFAULT_VALUE)
subject.set_x_content_type_options_header
end
it "lets you override X-Content-Type-Options" do
should_assign_header(X_CONTENT_TYPE_OPTIONS_HEADER_NAME, 'nosniff')
subject.set_x_content_type_options_header(:value => 'nosniff')
end
end
end
end
describe "#set_csp_header" do
context "when using Firefox" do
it "sets CSP headers" do
stub_user_agent(USER_AGENTS[:firefox])
should_assign_header(HEADER_NAME + "-Report-Only", DEFAULT_CSP_HEADER)
subject.set_csp_header
end
end
context "when using Chrome" do
it "sets default CSP header" do
stub_user_agent(USER_AGENTS[:chrome])
should_assign_header(HEADER_NAME + "-Report-Only", DEFAULT_CSP_HEADER)
subject.set_csp_header
end
end
context "when using a browser besides chrome/firefox" do
it "sets the CSP header" do
stub_user_agent(USER_AGENTS[:opera])
should_assign_header(HEADER_NAME + "-Report-Only", DEFAULT_CSP_HEADER)
subject.set_csp_header
end
end
end
describe "#set_x_permitted_cross_domain_policies_header" do
it "sets the X-Permitted-Cross-Domain-Policies header" do
should_assign_header(XPCDP_HEADER_NAME, SecureHeaders::XPermittedCrossDomainPolicies::Constants::DEFAULT_VALUE)
subject.set_x_permitted_cross_domain_policies_header
end
it "allows a custom X-Permitted-Cross-Domain-Policies header" do
should_assign_header(XPCDP_HEADER_NAME, "master-only")
subject.set_x_permitted_cross_domain_policies_header(:value => 'master-only')
end
end
end
| {
"content_hash": "67f2b77d3595f5e6e395e0ee7b8b1d05",
"timestamp": "",
"source": "github",
"line_count": 314,
"max_line_length": 150,
"avg_line_length": 35.8343949044586,
"alnum_prop": 0.6753466050479915,
"repo_name": "reedloden/secureheaders",
"id": "6f3d053292280caa69aec4bc086c7e4a20830d52",
"size": "11252",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "spec/lib/secure_headers_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "568"
},
{
"name": "Ruby",
"bytes": "97665"
},
{
"name": "Shell",
"bytes": "285"
}
],
"symlink_target": ""
} |
TEST(ProbUniform, cdf_log_matches_lcdf) {
double y = 0.8;
double alpha = 0.4;
double beta = 2.3;
EXPECT_FLOAT_EQ((stan::math::uniform_lcdf(y, alpha, beta)),
(stan::math::uniform_cdf_log(y, alpha, beta)));
EXPECT_FLOAT_EQ(
(stan::math::uniform_lcdf<double, double, double>(y, alpha, beta)),
(stan::math::uniform_cdf_log<double, double, double>(y, alpha, beta)));
}
| {
"content_hash": "ebb5952b9362ab828b0ea2dc0f5de3c4",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 77,
"avg_line_length": 36.81818181818182,
"alnum_prop": 0.6123456790123457,
"repo_name": "stan-dev/math",
"id": "4c75fa8ce1df49f4f85e1bf908965eb3800b87f2",
"size": "461",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "test/unit/math/prim/prob/uniform_cdf_log_test.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "89079"
},
{
"name": "Assembly",
"bytes": "566183"
},
{
"name": "Batchfile",
"bytes": "33076"
},
{
"name": "C",
"bytes": "7093229"
},
{
"name": "C#",
"bytes": "54013"
},
{
"name": "C++",
"bytes": "166268432"
},
{
"name": "CMake",
"bytes": "820167"
},
{
"name": "CSS",
"bytes": "11283"
},
{
"name": "Cuda",
"bytes": "342187"
},
{
"name": "DIGITAL Command Language",
"bytes": "32438"
},
{
"name": "Dockerfile",
"bytes": "118"
},
{
"name": "Fortran",
"bytes": "2299405"
},
{
"name": "HTML",
"bytes": "8320473"
},
{
"name": "JavaScript",
"bytes": "38507"
},
{
"name": "M4",
"bytes": "10525"
},
{
"name": "Makefile",
"bytes": "74538"
},
{
"name": "Meson",
"bytes": "4233"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NASL",
"bytes": "106079"
},
{
"name": "Objective-C",
"bytes": "420"
},
{
"name": "Objective-C++",
"bytes": "420"
},
{
"name": "Pascal",
"bytes": "75208"
},
{
"name": "Perl",
"bytes": "47080"
},
{
"name": "Python",
"bytes": "1958975"
},
{
"name": "QMake",
"bytes": "18714"
},
{
"name": "Roff",
"bytes": "30570"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "SWIG",
"bytes": "5501"
},
{
"name": "Shell",
"bytes": "187001"
},
{
"name": "Starlark",
"bytes": "29435"
},
{
"name": "XSLT",
"bytes": "567938"
},
{
"name": "Yacc",
"bytes": "22343"
}
],
"symlink_target": ""
} |
ALTER TABLE stop_areas ADD COLUMN referent_id uuid;
-- +migrate Down
-- SQL section 'Down' is executed when this migration is rolled back
ALTER TABLE stop_areas DROP COLUMN IF EXISTS referent_id; | {
"content_hash": "da7c4a59f23128f2499aeb50fc06c9c1",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 68,
"avg_line_length": 32.833333333333336,
"alnum_prop": 0.7766497461928934,
"repo_name": "af83/edwig",
"id": "0e9ccd236f5fa39c004bf4a793bdb81278f8af67",
"size": "279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrations/1525418909.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "986"
},
{
"name": "Gherkin",
"bytes": "472038"
},
{
"name": "Go",
"bytes": "1172570"
},
{
"name": "Makefile",
"bytes": "365"
},
{
"name": "Ruby",
"bytes": "43352"
},
{
"name": "Shell",
"bytes": "2603"
},
{
"name": "TSQL",
"bytes": "10982"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
<preConditions>
<dbms type="asany"/>
<runningAs username="liquibase"/>
</preConditions>
<changeSet id="1" author="nvoxland">
<comment>
You can add comments to changeSets.
They can even be multiple lines if you would like.
They aren't used to compute the changeSet MD5Sum, so you can update them whenever you want without causing problems.
</comment>
<createTable tableName="person">
<column name="id" type="int" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="firstname" type="varchar(50)"/>
<column name="lastname" type="varchar(50)">
<constraints nullable="false"/>
</column>
</createTable>
</changeSet>
<changeSet id="2" author="nvoxland">
<comment>Add a username column so we can use "person" for authentication</comment>
<addColumn tableName="person">
<column name="username" type="varchar(8)" />
</addColumn>
</changeSet>
<!--<changeSet id="3" author="nvoxland">-->
<!--<comment>Fix misspelled "username" column</comment>-->
<!--<renameColumn tableName="person" oldColumnName="usernae" newColumnName="username"/>-->
<!--</changeSet>-->
<changeSet id="5" author="nvoxland" context="test">
<insert tableName="person">
<column name="firstname" value="John"/>
<column name="lastname" value="Doe"/>
<column name="username" value="jdoe"/>
</insert>
<insert tableName="person">
<column name="firstname" value="Jane"/>
<column name="lastname" value="Doe"/>
<column name="username" value="janedoe"/>
</insert>
<insert tableName="person">
<column name="firstname" value="Bob"/>
<column name="lastname" value="Johnson"/>
<column name="username" value="bjohnson"/>
</insert>
</changeSet>
<changeSet id="6" author="nvoxland">
<comment>Don't keep username in the person table</comment>
<dropColumn tableName="person" columnName="username"/>
</changeSet>
<changeSet id="7" author="nvoxland">
<createTable tableName="employee">
<column name="id" type="int" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="name" type="varchar(50)">
<constraints nullable="false"/>
</column>
</createTable>
</changeSet>
<changeSet id="7" author="bjohnson" context="test">
<insert tableName="employee">
<column name="name" value="ACME Corp"/>
</insert>
<insert tableName="employee">
<column name="name" value="Widgets Inc."/>
</insert>
</changeSet>
<changeSet id="7a" author="nvoxland">
<addColumn tableName="employee">
<column name="company_id" type="int">
<constraints nullable="true" foreignKeyName="fk_employee_company" references="employee(id)"/>
</column>
</addColumn>
</changeSet>
<changeSet id="8" author="bjohnson">
<dropNotNullConstraint tableName="employee" columnName="name" columnDataType="varchar(50)"/>
</changeSet>
<changeSet id="8.1" author="bjohnson">
<comment>I guess name needs to be not-null</comment>
<addNotNullConstraint tableName='employee' columnName="name" defaultNullValue="UNKNOWN" columnDataType="varchar(50)"/>
</changeSet>
<changeSet id="9" author="nvoxland">
<renameTable oldTableName="employee" newTableName="company"/>
</changeSet>
<changeSet id="10" author="nvoxland">
<createTable tableName="testtable">
<column name="id" type="int" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="value" type="varchar(50)">
<constraints nullable="false"/>
</column>
<column name="person_id" type="int">
<constraints nullable="false" foreignKeyName="fk_test_person" references="person(id)"/>
</column>
</createTable>
</changeSet>
<changeSet id="11" author="nvoxland">
<dropTable tableName="testtable"/>
</changeSet>
<changeSet id="12" author="nvoxland">
<createIndex indexName="idx_company_name" tableName="company">
<column name="name"/>
</createIndex>
<createIndex indexName="idx_person_lastname" tableName="person">
<column name="lastname"/>
</createIndex>
</changeSet>
<changeSet id="13" author="nvoxland">
<dropIndex indexName="idx_person_lastname" tableName="person"/>
</changeSet>
<changeSet id="14" author="nvoxland">
<createTable tableName="liquibaseRunInfo">
<column name="timesRan" type="int"/>
</createTable>
<insert tableName="liquibaseRunInfo">
<column name="timesRan" valueNumeric="1"/>
</insert>
</changeSet>
<changeSet id="15" author="nvoxland" runAlways="true">
<sql>update liquibaseRunInfo set timesRan=timesRan+1</sql>
</changeSet>
<changeSet id="16" author="nvoxland">
<createView viewName="personView">
select * from liquibase.person
</createView>
</changeSet>
<changeSet id="18" author="nvoxland">
<dropView viewName="personView"/>
</changeSet>
<changeSet id="19" author="nvoxland">
<mergeColumns
tableName="person"
column1Name="firstname"
joinString=" "
column2Name="lastname"
finalColumnName="fullname"
finalColumnType="varchar(100)"/>
</changeSet>
<changeSet id="20" author="nvoxland">
<createView viewName="personView">
select id, fullname from person
</createView>
</changeSet>
<!--
Sybase ASA does not support view rename.
<changeSet id="21" author="nvoxland">
<renameView oldViewName="personView" newViewName="v_person"/>
</changeSet>
-->
<changeSet id="22" author="nvoxland">
<addColumn tableName="person">
<column name="employer_id" type="int"/>
</addColumn>
</changeSet>
<changeSet id="23" author="nvoxland">
<addForeignKeyConstraint
baseTableName="person" baseColumnNames="employer_id"
constraintName="fk_person_employer"
referencedTableName="company" referencedColumnNames="id"
deleteCascade="true"/>
</changeSet>
<changeSet id="24" author="nvoxland">
<dropForeignKeyConstraint baseTableName="person" constraintName="fk_person_employer"/>
</changeSet>
<changeSet id="25" author="nvoxland">
<createTable tableName="address">
<column name="id" type="int" autoIncrement="true"/>
<column name="line1" type="varchar(255)"/>
<column name="line2" type="varchar(255)">
<constraints nullable="true"/>
</column>
<column name="city" type="varchar(255)"/>
<column name="state" type="char(2)">
<constraints nullable="true"/>
</column>
<column name="postalcode" type="varchar(15)"/>
</createTable>
</changeSet>
<changeSet id="25.1" author="nvoxland">
<addNotNullConstraint tableName="address" columnName="id" columnDataType="int"/>
</changeSet>
<changeSet id="25.2" author="nvoxland">
<addPrimaryKey tableName="address" columnNames="id" constraintName="pk_address"/>
</changeSet>
<changeSet id="26" author="nvoxland">
<insert tableName="address">
<column name="line1" value="123 4th St"/>
<column name="line2" value="Suite 432"/>
<column name="city" value="New York"/>
<column name="state" value="NY"/>
<column name="postalcode" value="01235"/>
</insert>
<insert tableName="address">
<column name="line1" value="6123 64th St"/>
<column name="city" value="New York"/>
<column name="state" value="NY"/>
<column name="postalcode" value="01235"/>
</insert>
<insert tableName="address">
<column name="line1" value="One Liquibase Way"/>
<column name="city" value="Fargo"/>
<column name="state" value="ND"/>
<column name="postalcode" value="58103"/>
</insert>
<insert tableName="address">
<column name="line1" value="123 Main Ave"/>
<column name="city" value="City With No State"/>
<column name="postalcode" value="00000"/>
</insert>
</changeSet>
<!--
<changeSet id="27" author="nvoxland">
<addLookupTable
existingTableName="address" existingColumnName="state"
newTableName="state" newColumnName="id" newColumnDataType="char(2)"/>
</changeSet>
-->
<changeSet id="28" author="nvoxland">
<addDefaultValue tableName="address" columnName="line2" defaultValue="N/A"/>
</changeSet>
<changeSet id="30" author="nvoxland">
<dropPrimaryKey tableName="address" constraintName="pk_address"/>
</changeSet>
<changeSet id="31" author="nvoxland">
<addPrimaryKey tableName="address" columnNames="id" constraintName="pk_address"/>
</changeSet>
<changeSet id="32.0" author="otaranenko">
<addNotNullConstraint tableName="address" columnName="line1" />
<addNotNullConstraint tableName="address" columnName="line2" defaultNullValue="N/A" />
</changeSet>
<changeSet id="32" author="nvoxland">
<addUniqueConstraint tableName="address" columnNames="line1, line2" constraintName="uq_address_line1line2"/>
</changeSet>
<changeSet id="33" author="nvoxland">
<dropUniqueConstraint tableName="address" constraintName="uq_address_line1line2"/>
</changeSet>
<changeSet id="50" author="nvoxland">
<modifyDataType tableName="address" columnName="postalcode" newDataType="varchar(20)"/>
</changeSet>
<include file="changelogs/sybase/complete/included.changelog.xml"/>
<include file="changelogs/sybase/complete/renamed.changelog.xml"/>
<include file="changelogs/common/common.tests.changelog.xml" />
<include file="changelogs/common/autoincrement.tests.changelog.xml" />
<changeSet id="56" author="nvoxland">
<customChange class="liquibase.change.custom.ExampleCustomSqlChange">
<param name="tableName" value="person"/>
<param name="columnName" value="employer_id"/>
<param name="newValue" value="3"/>
</customChange>
</changeSet>
<changeSet id="57" author="nvoxland">
<customChange class="liquibase.change.custom.ExampleCustomSqlChange" tableName="person" columnName="employer_id" newValue="4"/>
</changeSet>
<changeSet id="58" author="nvoxland">
<customChange class="liquibase.change.custom.ExampleCustomTaskChange" helloTo="world"/>
</changeSet>
<changeSet id="60" author="nvoxland">
<executeCommand executable="ping" os="Windows XP">
<arg value="localhost"/>
</executeCommand>
</changeSet>
</databaseChangeLog>
| {
"content_hash": "e615f82b895125ba53a0cd22b2a0bbe9",
"timestamp": "",
"source": "github",
"line_count": 300,
"max_line_length": 137,
"avg_line_length": 39.47,
"alnum_prop": 0.602482898403851,
"repo_name": "OculusVR/shanghai-liquibase",
"id": "f0e69482f1ab783161645a73dd2943e75c9fa601",
"size": "11841",
"binary": false,
"copies": "3",
"ref": "refs/heads/junbo",
"path": "liquibase-integration-tests/src/test/resources/changelogs/asany/complete/root.changelog.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1202"
},
{
"name": "Groff",
"bytes": "2297"
},
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Inno Setup",
"bytes": "2522"
},
{
"name": "Java",
"bytes": "3449068"
},
{
"name": "PLSQL",
"bytes": "5380"
},
{
"name": "PLpgSQL",
"bytes": "502"
},
{
"name": "Puppet",
"bytes": "4616"
},
{
"name": "Ruby",
"bytes": "4959"
},
{
"name": "Shell",
"bytes": "4565"
}
],
"symlink_target": ""
} |
<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns:form="sap.ui.layout.form"
xmlns:core="sap.ui.core"
controllerName="sap.ui.demo.tracker.view.IssueEdit"
displayBlock="true"
xmlns="sap.m">
<Page title="{i18n>EDIT_ISSUE_TITLE}">
<mvc:XMLView id="editFormView" viewName="sap.ui.demo.tracker.view.IssueEditForm"/>
<footer>
<Bar>
<contentRight>
<Button text="{i18n>ISSUECREATE_SAVE_BUTTON_TEXT}"
press="handleSavePress"
icon="sap-icon://save" />
<Button text="{i18n>ISSUECREATE_CANCEL_BUTTON_TEXT}"
press="handleCancelPress"
icon="sap-icon://sys-cancel" />
</contentRight>
</Bar>
</footer>
</Page>
</mvc:View> | {
"content_hash": "3400ca81297c56d6b57678db6c75fdfd",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 86,
"avg_line_length": 32.30434782608695,
"alnum_prop": 0.5908479138627187,
"repo_name": "shubhadeep/ui5-tracker-mvc",
"id": "0030f15415bf39af5fbc667dd983657cfe48d5db",
"size": "743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "view/IssueEdit.view.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "860"
},
{
"name": "JavaScript",
"bytes": "22800"
}
],
"symlink_target": ""
} |
package es.caib.zkib.jxpath.ri.model.container;
import java.util.Locale;
import es.caib.zkib.jxpath.Container;
import es.caib.zkib.jxpath.ri.QName;
import es.caib.zkib.jxpath.ri.compiler.NodeTest;
import es.caib.zkib.jxpath.ri.model.NodeIterator;
import es.caib.zkib.jxpath.ri.model.NodePointer;
import es.caib.zkib.jxpath.util.ValueUtils;
/**
* Transparent pointer to a Container. The {@link #getValue()} method
* returns the contents of the container, rather than the container
* itself.
*
* @author Dmitri Plotnikov
* @version $Revision: 1.2 $ $Date: 2009-04-03 12:19:35 $
*/
public class ContainerPointer extends NodePointer {
private Container container;
private NodePointer valuePointer;
private static final long serialVersionUID = 6140752946621686118L;
/**
* Create a new ContainerPointer.
* @param container Container object
* @param locale Locale
*/
public ContainerPointer(Container container, Locale locale) {
super(null, locale);
this.container = container;
}
/**
* Create a new ContainerPointer.
* @param parent parent pointer
* @param container Container object
*/
public ContainerPointer(NodePointer parent, Container container) {
super(parent);
this.container = container;
}
/**
* This type of node is auxiliary.
* @return <code>true</code>.
*/
public boolean isContainer() {
return true;
}
public QName getName() {
return null;
}
public Object getBaseValue() {
return container;
}
public boolean isCollection() {
Object value = getBaseValue();
return value != null && ValueUtils.isCollection(value);
}
public int getLength() {
Object value = getBaseValue();
return value == null ? 1 : ValueUtils.getLength(value);
}
public boolean isLeaf() {
return getValuePointer().isLeaf();
}
public Object getImmediateNode() {
Object value = getBaseValue();
if (index != WHOLE_COLLECTION) {
return index >= 0 && index < getLength() ? ValueUtils.getValue(value, index) : null;
}
return ValueUtils.getValue(value);
}
public void setValue(Object value) {
// TODO: what if this is a collection?
container.setValue(value);
}
public NodePointer getImmediateValuePointer() {
if (valuePointer == null) {
Object value = getImmediateNode();
valuePointer = NodePointer.newChildNodePointer(this, getName(), value);
}
return valuePointer;
}
public int hashCode() {
return System.identityHashCode(container) + index;
}
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof ContainerPointer)) {
return false;
}
ContainerPointer other = (ContainerPointer) object;
return container == other.container && index == other.index;
}
public NodeIterator childIterator(
NodeTest test,
boolean reverse,
NodePointer startWith,
boolean ignoreExceptions) {
return getValuePointer().childIterator(test, reverse, startWith, ignoreExceptions);
}
public NodeIterator attributeIterator(QName name, boolean ignoreExceptions) {
return getValuePointer().attributeIterator(name, ignoreExceptions);
}
public NodeIterator namespaceIterator() {
return getValuePointer().namespaceIterator();
}
public NodePointer namespacePointer(String namespace) {
return getValuePointer().namespacePointer(namespace);
}
public boolean testNode(NodeTest nodeTest) {
return getValuePointer().testNode(nodeTest);
}
public int compareChildNodePointers(
NodePointer pointer1,
NodePointer pointer2) {
return pointer1.getIndex() - pointer2.getIndex();
}
public String getNamespaceURI(String prefix) {
return getValuePointer().getNamespaceURI(prefix);
}
public String asPath() {
return parent == null ? "/" : parent.asPath();
}
}
| {
"content_hash": "c246533199260cb200a70aefbf870bd8",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 96,
"avg_line_length": 27.605263157894736,
"alnum_prop": 0.6453765490943756,
"repo_name": "SoffidIAM/jxpath",
"id": "4f0c2def17032086027462bd531c82171637001d",
"size": "4997",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/es/caib/zkib/jxpath/ri/model/container/ContainerPointer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "66"
},
{
"name": "Java",
"bytes": "1272243"
},
{
"name": "Shell",
"bytes": "991"
}
],
"symlink_target": ""
} |
namespace com { namespace microsoft { namespace maker { namespace SecuritySystem {
// Signals
} } } }
| {
"content_hash": "ccab2838724e1fd36aa7b85aeba38ad5",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 82,
"avg_line_length": 21,
"alnum_prop": 0.7047619047619048,
"repo_name": "mwmckee/securitysystem",
"id": "34e0610c5965b972d9725b5743ca10a1d5c5dd05",
"size": "1073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SecuritySystemUWP/com.microsoft.maker.SecuritySystem/SecuritySystemEventArgs.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "112615"
},
{
"name": "C++",
"bytes": "201318"
},
{
"name": "CSS",
"bytes": "4809"
},
{
"name": "HTML",
"bytes": "4423"
},
{
"name": "JavaScript",
"bytes": "11015"
}
],
"symlink_target": ""
} |
package org.lwjgl.opengl;
import org.lwjgl.system.*;
/**
* Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_color_buffer_float.txt">ARB_color_buffer_float</a> extension.
*
* <p>The standard OpenGL pipeline is based on a fixed-point pipeline. While color components are nominally floating-point values in the pipeline, components
* are frequently clamped to the range [0,1] to accomodate the fixed-point color buffer representation and allow for fixed-point computational hardware.</p>
*
* <p>This extension adds pixel formats or visuals with floating-point RGBA color components and controls for clamping of color components within the pipeline.</p>
*
* <p>For a floating-point RGBA pixel format, the size of each float components is specified using the same attributes that are used for defining the size of
* fixed-point components. 32-bit floating-point components are in the standard IEEE float format. 16-bit floating-point components have 1 sign bit, 5
* exponent bits, and 10 mantissa bits.</p>
*
* <p>Clamping control provides a way to disable certain color clamps and allow programs, and the fixed-function pipeline, to deal in unclamped colors. There
* are controls to modify clamping of vertex colors, clamping of fragment colors throughout the pipeline, and for pixel return data.</p>
*
* <p>The default state for fragment clamping is {@link #GL_FIXED_ONLY_ARB FIXED_ONLY_ARB}, which has the behavior of clamping colors for fixed-point color buffers and not clamping
* colors for floating-pont color buffers.</p>
*
* <p>Vertex colors are clamped by default.</p>
*
* <p>Promoted to core in {@link GL30 OpenGL 3.0}.</p>
*/
public class ARBColorBufferFloat {
static { GL.initialize(); }
/** Accepted by the {@code pname} parameters of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. */
public static final int GL_RGBA_FLOAT_MODE_ARB = 0x8820;
/** Accepted by the {@code target} parameter of ClampColorARB and the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. */
public static final int
GL_CLAMP_VERTEX_COLOR_ARB = 0x891A,
GL_CLAMP_FRAGMENT_COLOR_ARB = 0x891B,
GL_CLAMP_READ_COLOR_ARB = 0x891C;
/** Accepted by the {@code clamp} parameter of ClampColorARB. */
public static final int GL_FIXED_ONLY_ARB = 0x891D;
protected ARBColorBufferFloat() {
throw new UnsupportedOperationException();
}
// --- [ glClampColorARB ] ---
/**
* Controls color clamping.
*
* @param target the color target. One of:<br><table><tr><td>{@link #GL_CLAMP_VERTEX_COLOR_ARB CLAMP_VERTEX_COLOR_ARB}</td><td>{@link #GL_CLAMP_FRAGMENT_COLOR_ARB CLAMP_FRAGMENT_COLOR_ARB}</td><td>{@link #GL_CLAMP_READ_COLOR_ARB CLAMP_READ_COLOR_ARB}</td></tr></table>
* @param clamp the new clamping state. One of:<br><table><tr><td>{@link GL11#GL_TRUE TRUE}</td><td>{@link GL11#GL_FALSE FALSE}</td><td>{@link #GL_FIXED_ONLY_ARB FIXED_ONLY_ARB}</td></tr></table>
*/
public static native void glClampColorARB(@NativeType("GLenum") int target, @NativeType("GLenum") int clamp);
} | {
"content_hash": "931a7a61ac46f77e4f503ef1a9769f75",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 272,
"avg_line_length": 54.96551724137931,
"alnum_prop": 0.7180050188205772,
"repo_name": "code-disaster/lwjgl3",
"id": "94837a32863491b23898df0bcb495ffc6fea6f1b",
"size": "3322",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "modules/lwjgl/opengl/src/generated/java/org/lwjgl/opengl/ARBColorBufferFloat.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "14340"
},
{
"name": "C",
"bytes": "12123701"
},
{
"name": "C++",
"bytes": "1982042"
},
{
"name": "GLSL",
"bytes": "1703"
},
{
"name": "Java",
"bytes": "71118728"
},
{
"name": "Kotlin",
"bytes": "18559115"
},
{
"name": "Objective-C",
"bytes": "14684"
},
{
"name": "Objective-C++",
"bytes": "2004"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFactorsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('factors', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('exercise_id');
$table->unsignedInteger('parent_id')->nullable();
$table->string('text');
$table->char('type',2);
$table->float('weight')->nullable();
$table->nullableTimestamps();
$table->softDeletes();
$table->engine = 'InnoDB';
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
$table->foreign('parent_id', 'f_parent_id')->references('id')->on('factors')->onDelete('restrict')->onUpdate('cascade');
$table->foreign('exercise_id', 'f_exercise_id')->references('id')->on('exercises')->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('factors');
}
}
| {
"content_hash": "40999a45494fdeb2ead64a20b266e0c9",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 137,
"avg_line_length": 28.84090909090909,
"alnum_prop": 0.5571315996847912,
"repo_name": "jcnwobodo/ASPES",
"id": "64e8c7da67691db365fc835611c91d0086e5a5b1",
"size": "1269",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "database/migrations/2016_10_22_115320_create_factors_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "HTML",
"bytes": "4777"
},
{
"name": "JavaScript",
"bytes": "1133"
},
{
"name": "PHP",
"bytes": "84436"
},
{
"name": "Vue",
"bytes": "559"
}
],
"symlink_target": ""
} |
This project is forked from socket.io 0.9.16
It removed support for long polling & flashsocket.
It just support websocket transport, and a subset of socket.io 0.9.16 protocol.
We aimed to make this project simple.
| {
"content_hash": "dcaecb94b3209ff5f47a7402d9e41517",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 79,
"avg_line_length": 31,
"alnum_prop": 0.7788018433179723,
"repo_name": "cynron/sio-lite",
"id": "ac5a171a6a9c2764cab3cd46f963d6bb855db199",
"size": "217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Readme.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "60191"
},
{
"name": "Makefile",
"bytes": "235"
}
],
"symlink_target": ""
} |
<div class="main-list-item experience-section" id="projects">
<h2 class="main-list-item-title">Projects</h2>
<ul>
<li class="project">
<div class="project-info">
<h3 class="project-name"><a href="https://hiveapp.org">Hive</a></h3><p class="date">2017 - Present</p>
</div>
<ul>
<li>
A platform/social network with a focus on facilitating peer
mentorship. Connects students to more experienced peers who
can act in a mentorship capacity. Works to foster strong
relationships by placing an emphasis on in person
interaction and providing personalized recommendations for
people one should connect with to help advance their career.
</li>
</ul>
</li>
<li class="project">
<div class="project-info">
<h3 class="project-name">Distribute</h3> <p class="date">2016 - Present</p>
</div>
<ul>
<li>
A distributed computation framework. Can schedule MapReduce
jobs on a cluster of web browsers, using each browsers' resources to
perform large scale computations.
</li>
</ul>
</li>
</ul>
</div>
| {
"content_hash": "8f93f789b8ec3fbb4e3c5b269f7ef779",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 118,
"avg_line_length": 43.6875,
"alnum_prop": 0.5200286123032904,
"repo_name": "andrew749/andrew749.github.io",
"id": "5ab5f10b616437c8b354d447753781f076579ed7",
"size": "1398",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/projects_section.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "19138"
},
{
"name": "Dockerfile",
"bytes": "493"
},
{
"name": "HTML",
"bytes": "20181"
},
{
"name": "JavaScript",
"bytes": "8467"
},
{
"name": "Makefile",
"bytes": "811"
},
{
"name": "Python",
"bytes": "20212"
},
{
"name": "Shell",
"bytes": "153"
}
],
"symlink_target": ""
} |
module Dummy
module Generators
class UrlsGenerator < Rails::Generators::Base
include Dummy::Generators::Common
def self.source_root
@source_root ||= File.expand_path("../templates", __FILE__)
end
class_option :divisor, :type => :numeric, :default => 10,
:desc => "The divisor to use when determining the amount of urls to generate."
class_option :manual_amounts, :type => :boolean, :default => false,
:desc => "Manually set the amount of urls to generate for each model."
class_option :output_folder, :type => :string, :default => "test/dummy",
:desc => "Dummy output folder, urls/ will be used when storing the resulting YAML files."
def install_dummy_urls
initialize_application
generate_dummy_urls
copy_rake_files
update_dummyfile
end
private
def initialize_application
require File.expand_path("#{Rails.root}/config/environment.rb")
say_status :successful, "initialize Rails application"
end
def generate_dummy_urls
get_table_names
load_dummyfile
predict_url_amounts
gather_associations
end
def get_table_names
@models = Hash.new
Dir["app/models/*.rb"].each do |full_path|
model = File.basename(full_path).chomp(File.extname(full_path)).camelcase.constantize
@models.merge!({model => {
:record_amount => 0, :url_amount => 0, :associations => []
}}) if model.respond_to?(:columns)
end
end
def load_dummyfile
begin
records = YAML.load_file "#{options.output_folder}/Dummyfile"
rescue
raise MissingDummyfile, "Could not find the Dummyfile. Did you forget to generate dummy data or specified a different directory?"
end
records.each do |record, amount|
model = record.singularize.camelcase.constantize
@models[model][:record_amount] = amount[:records]
end
end
def predict_url_amounts
@models.each do |model, data|
amount = data[:record_amount] / options.divisor
if options.manual_amounts
user_defined = ask("Number of urls for #{model} (default: #{amount}): ")
amount = user_defined unless user_defined.empty?
end
@models[model][:url_amount] = amount.to_i
end
end
def copy_rake_files
empty_directory "test/dummy/urls"
@models.each do |model, info|
@generated_ids = Array.new
@model_name = model.to_s.underscore.pluralize
@url_amount = info[:url_amount]
template "model.yml", "#{options.output_folder}/urls/#{@model_name}.yml"
end
end
def generate_id(model_name)
model = model_name.singularize.camelcase.constantize
begin
yaml_id = rand(@models[model][:record_amount])
end while @generated_ids.include?(yaml_id)
@generated_ids.push(yaml_id)
Fixtures.identify("#{model_name.singularize}_#{yaml_id}")
end
def generate_data(model_name)
data = Hash.new
key_value = Hash.new
model = model_name.singularize.camelcase.constantize
model.columns.each do |column|
name = model.to_s.underscore
info = @models[model]
key_value = generate_record_data(name, info, column, false)
data.merge!(key_value) unless key_value.nil?
end
data
end
def update_dummyfile
data = Hash.new
dummyfile_path = "#{options.output_folder}/Dummyfile"
@models.each do |model, info|
data[model.to_s.underscore.pluralize] = {:records => info[:record_amount],
:urls => info[:url_amount]}
end
content = "# This file was automatically generated by Dummy. Do NOT change it.\n"
content << YAML.dump(data)
remove_file dummyfile_path, :verbose => false if File.exists?(dummyfile_path)
create_file dummyfile_path, content
end
end
end
end
| {
"content_hash": "85413588b8ebaf463c5c0710afc19db4",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 139,
"avg_line_length": 33.715384615384615,
"alnum_prop": 0.5653661875427789,
"repo_name": "goncalossilva/dummy_urls",
"id": "a3f0532df70923d4cffdc0720e405eaa8860389c",
"size": "4383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/generators/urls/urls_generator.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "11060"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import core
import numpy
import six.moves as six
from framework import Variable, default_main_program
__all__ = ['DataFeeder']
class DataToLoDTensorConverter(object):
def __init__(self, place, lod_level, shape, dtype):
self.place = place
self.lod_level = lod_level
self.shape = shape
if dtype == core.VarDesc.VarType.FP32:
self.dtype = 'float32'
elif dtype == core.VarDesc.VarType.INT64:
self.dtype = 'int64'
elif dtype == core.VarDesc.VarType.FP64:
self.dtype = 'float64'
elif dtype == core.VarDesc.VarType.INT32:
self.dtype = 'int32'
else:
raise ValueError("dtype must be any of [int32, float32, int64, "
"float64]")
self.data = []
self.lod = []
for i in six.range(lod_level):
self.lod.append([0])
def feed(self, data):
self._feed_impl_(data, self.lod, self.lod_level)
def _feed_impl_(self, data, lod, lod_level):
if lod_level == 0:
self.data.append(data)
else:
cur_lod_len = len(data)
lod[-1].append(lod[-1][-1] + cur_lod_len)
for each_data in data:
self._feed_impl_(each_data, lod[:-1], lod_level - 1)
def done(self):
arr = numpy.array(self.data, dtype=self.dtype).reshape(self.shape)
t = core.LoDTensor()
t.set(arr, self.place)
if self.lod_level > 0:
t.set_lod(self.lod)
return t
class DataFeeder(object):
def __init__(self, feed_list, place, program=None):
self.feed_dtypes = []
self.feed_names = []
self.feed_shapes = []
self.feed_lod_level = []
if program is None:
program = default_main_program()
for each_var in feed_list:
if isinstance(each_var, basestring):
each_var = program.block(0).var(each_var)
if not isinstance(each_var, Variable):
raise TypeError("Feed list should contain a list of variable")
self.feed_dtypes.append(each_var.dtype)
self.feed_names.append(each_var.name)
shape = each_var.shape
batch_size_dim = -1
for i, s in enumerate(shape):
if s < 0:
batch_size_dim = i
break
if batch_size_dim == -1:
raise ValueError("Variable {0} must has a batch size dimension",
each_var.name)
self.feed_lod_level.append(each_var.lod_level)
self.feed_shapes.append(shape)
self.place = place
def feed(self, iterable):
converter = []
for lod_level, shape, dtype in six.zip(
self.feed_lod_level, self.feed_shapes, self.feed_dtypes):
converter.append(
DataToLoDTensorConverter(
place=self.place,
lod_level=lod_level,
shape=shape,
dtype=dtype))
for each_sample in iterable:
assert len(each_sample) == len(converter), (
"The number of fields in data (%s) does not match " +
"len(feed_list) (%s)") % (len(each_sample), len(converter))
for each_converter, each_slot in six.zip(converter, each_sample):
each_converter.feed(each_slot)
ret_dict = {}
for each_name, each_converter in six.zip(self.feed_names, converter):
ret_dict[each_name] = each_converter.done()
return ret_dict
| {
"content_hash": "2871619d46da6f1e9f9d35e90146574d",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 80,
"avg_line_length": 35.25,
"alnum_prop": 0.5365521003818876,
"repo_name": "lcy-seso/Paddle",
"id": "ac02401c79b787716b2e5f43e0d1c5686cf2bd13",
"size": "4279",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "python/paddle/fluid/data_feeder.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "278852"
},
{
"name": "C++",
"bytes": "7213431"
},
{
"name": "CMake",
"bytes": "258158"
},
{
"name": "Cuda",
"bytes": "1077180"
},
{
"name": "Go",
"bytes": "109501"
},
{
"name": "Perl",
"bytes": "11456"
},
{
"name": "Python",
"bytes": "3337838"
},
{
"name": "Shell",
"bytes": "147571"
}
],
"symlink_target": ""
} |
..
Copyright © 2012-2014 Cask Data, 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.
.. _overview_multi_data_center_high-availability:
.. index::
single: Hot-Hot : Synchronous Database Cluster
======================================
Hot-Hot : Synchronous Database Cluster
======================================
.. _synchronous-repl:
.. figure:: /_images/ha_synchronous_repl.png
:align: center
:alt: Synchronous Database Architecture Diagram
:figclass: align-center
Overview
--------
Among all Coopr components, database is the only component that stores persistent state information. Any HA configuration that runs redundant Coopr services across datacenters will have to make sure that the services in all datacenters have a consistent view of this data. One way of achieving this consistency is to share a single database cluster across all datacenters as discussed below.
In this configuration a database cluster with synchronous replication is shared across all datacenters. Coopr Servers in each datacenter will connect to the local instance of the database cluster. All other components are configured as mentioned in :doc:`Datacenter High Availability </guide/bcp/data-center-bcp>` section.
An advantage of this approach is that Coopr Servers in all datacenters have the same view of data at all times. Hence, users in all datacenters will get to see the same state for all clusters at all times.
Failover
--------
When a datacenter fails in this setup, the data of the failed datacenter is still available in other datacenters due to synchronous replication.
Hence Coopr Servers in other datacenters should be able to handle user traffic from the failed datacenter.
However, any transaction that was in progress when the datacenter failed will be lost as it was not committed.
Also, any jobs that were in progress in the failed datacenter will not make any progress when the datacenter goes down.
User traffic from the failed datacenter will be re-routed to other datacenters automatically by the load balancer.
| {
"content_hash": "12804cd942164d5a356565e6566b78eb",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 391,
"avg_line_length": 55.630434782608695,
"alnum_prop": 0.7588901914810473,
"repo_name": "cdapio/coopr",
"id": "66cd09cbda569aa92407ae6e5c2679867e0dc361",
"size": "2560",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "coopr-docs/docs/source/guide/bcp/option1/index.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2019"
},
{
"name": "CSS",
"bytes": "21741"
},
{
"name": "CoffeeScript",
"bytes": "138981"
},
{
"name": "Dockerfile",
"bytes": "3077"
},
{
"name": "HTML",
"bytes": "90931"
},
{
"name": "Java",
"bytes": "2865887"
},
{
"name": "JavaScript",
"bytes": "433691"
},
{
"name": "Python",
"bytes": "11958"
},
{
"name": "Shell",
"bytes": "39128"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.