text stringlengths 2 1.04M | meta dict |
|---|---|
Titan is a tool to encrypt or decrypt a string using a AES256 symmetric key.
This tool was written to store securely sensitive data in services that can't encrypt data like [etcd](https://github.com/coreos/etcd) and [consul](https://consul.io/).
The generated key is stored in Base64 format.
To make things less predictable, a random initialization vector (IV) is generated each time
a string is encrypted, even if it's the same string. The IV is stored with the encrypted
string and is then used for decryption later.
## Usage
~~~ text
Usage: ./bin/titan (options)
-d STRING Decrypt string
-e STRING Encrypt string
-k PATH Symmetric key to use
-g PATH Generate a key
~~~
## Example
First, you need to generate a symmetric key. Once you've generated your symmetric key, you can distribute it between machines that need to use it using an encrypted Chef data bag for example.
~~~ text
$ ./bin/titan -k /tmp/key -g
Key '7tLW8OR3XbG3LJvxKwYmg7w0Y7rAF+DFeWZVLWDVVCE=' was written to '/tmp/key'.
~~~
You can then use that key to encrypt some string.
~~~ text
$ ./bin/titan -k /tmp/key -e 'some super secret'
MEQ0b2loc3oxSmMySnRiRGQwajZzR2hLM3RVZzhCeWV2cTB6M1Zoekd6VT0sbXo1Ymd0eUIyVm9vdFhvb1BSa0piZz09
~~~
And then you can later decrypt it using the same symmetric key.
~~~ text
$ ./bin/titan -k /tmp/key -d MEQ0b2loc3oxSmMySnRiRGQwajZzR2hLM3RVZzhCeWV2cTB6M1Zoekd6VT0sbXo1Ymd0eUIyVm9vdFhvb1BSa0piZz09
some super secret
~~~
| {
"content_hash": "f57aa95120649acde34ea91ae2ea39d5",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 191,
"avg_line_length": 36.69047619047619,
"alnum_prop": 0.7164179104477612,
"repo_name": "failshell/titan",
"id": "36a50d061099b15f9a045512c6bcff733930f466",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2913"
}
],
"symlink_target": ""
} |
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "sortvec_source.c"
#include "templates_off.h"
#undef BASE_CHAR
| {
"content_hash": "83518dfcb01dce332ff713fa1e21b164",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 32,
"avg_line_length": 20.027397260273972,
"alnum_prop": 0.7373461012311902,
"repo_name": "ICML14MoMCompare/spectral-learn",
"id": "182a9f59336906b2fad27d2223266243fc552c22",
"size": "2154",
"binary": false,
"copies": "41",
"ref": "refs/heads/master",
"path": "code/em/treba/gsl-1.16/sort/sortvec.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "14902045"
},
{
"name": "C++",
"bytes": "110685913"
},
{
"name": "Cuda",
"bytes": "29867"
},
{
"name": "EmberScript",
"bytes": "6466967"
},
{
"name": "Makefile",
"bytes": "1692178"
},
{
"name": "Matlab",
"bytes": "3361"
},
{
"name": "Objective-C",
"bytes": "17070"
},
{
"name": "Perl",
"bytes": "6080"
},
{
"name": "Python",
"bytes": "1123728"
},
{
"name": "Shell",
"bytes": "977479"
},
{
"name": "TeX",
"bytes": "2118884"
}
],
"symlink_target": ""
} |
FROM balenalib/colibri-imx6-ubuntu:xenial-build
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.10.2
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" \
&& echo "0ca3078d312f2723683aa8aadf455f6a08689926995cd76bd3032329411b8ef3 Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.2.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.18
# install dbus-python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
libdbus-1-dev \
libdbus-glib-1-dev \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -y autoremove
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu xenial \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.10.2, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "843440844f25b5ca03c48ce494add3a4",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 711,
"avg_line_length": 50.642105263157895,
"alnum_prop": 0.7040116399916857,
"repo_name": "resin-io-library/base-images",
"id": "75deccad1c14340163a0c386ae31349e0661f276",
"size": "4832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/python/colibri-imx6/ubuntu/xenial/3.10.2/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
namespace se3
{
template<int _Dim, typename _Scalar, int _Options=0> class ConstraintTpl;
template< class Derived>
class ConstraintBase
{
protected:
typedef Derived Derived_t;
SPATIAL_TYPEDEF_TEMPLATE(Derived_t);
typedef typename traits<Derived_t>::JointMotion JointMotion;
typedef typename traits<Derived_t>::JointForce JointForce;
typedef typename traits<Derived_t>::DenseBase DenseBase;
public:
Derived_t & derived() { return *static_cast<Derived_t*>(this); }
const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); }
Motion operator* (const JointMotion& vj) const { return derived().__mult__(vj); }
DenseBase & matrix() { return derived().matrix_impl(); }
const DenseBase & matrix() const { return derived().matrix_impl(); }
int nv() const { return derived().nv_impl(); }
void disp(std::ostream & os) const { static_cast<const Derived_t*>(this)->disp_impl(os); }
friend std::ostream & operator << (std::ostream & os,const ConstraintBase<Derived> & X)
{
X.disp(os);
return os;
}
}; // class ConstraintBase
template<int D, typename T, int U>
struct traits< ConstraintTpl<D, T, U> >
{
typedef T Scalar_t;
typedef Eigen::Matrix<T,3,1,U> Vector3;
typedef Eigen::Matrix<T,4,1,U> Vector4;
typedef Eigen::Matrix<T,6,1,U> Vector6;
typedef Eigen::Matrix<T,3,3,U> Matrix3;
typedef Eigen::Matrix<T,4,4,U> Matrix4;
typedef Eigen::Matrix<T,6,6,U> Matrix6;
typedef Matrix3 Angular_t;
typedef Vector3 Linear_t;
typedef Matrix6 ActionMatrix_t;
typedef Eigen::Quaternion<T,U> Quaternion_t;
typedef SE3Tpl<T,U> SE3;
typedef ForceTpl<T,U> Force;
typedef MotionTpl<T,U> Motion;
typedef Symmetric3Tpl<T,U> Symmetric3;
enum {
LINEAR = 0,
ANGULAR = 3
};
typedef Eigen::Matrix<Scalar_t,D,1,U> JointMotion;
typedef Eigen::Matrix<Scalar_t,D,1,U> JointForce;
typedef Eigen::Matrix<Scalar_t,6,D> DenseBase;
}; // traits ConstraintTpl
namespace internal
{
template<int Dim, typename Scalar, int Options>
struct ActionReturn<ConstraintTpl<Dim,Scalar,Options> >
{ typedef Eigen::Matrix<Scalar,6,Dim> Type; };
}
template<int _Dim, typename _Scalar, int _Options>
class ConstraintTpl : public ConstraintBase<ConstraintTpl < _Dim, _Scalar, _Options > >
{
public:
friend class ConstraintBase< ConstraintTpl< _Dim, _Scalar, _Options > >;
SPATIAL_TYPEDEF_TEMPLATE(ConstraintTpl);
enum { NV = _Dim, Options = _Options };
typedef typename traits<ConstraintTpl>::JointMotion JointMotion;
typedef typename traits<ConstraintTpl>::JointForce JointForce;
typedef typename traits<ConstraintTpl>::DenseBase DenseBase;
public:
template<typename D>
ConstraintTpl( const Eigen::MatrixBase<D> & _S ) : S(_S) {}
ConstraintTpl() : S()
{
#ifndef NDEBUG
S.fill( NAN );
#endif
}
ConstraintTpl(const int dim) : S(6,dim)
{
#ifndef NDEBUG
S.fill( NAN );
#endif
}
Motion __mult__(const JointMotion& vj) const
{
return Motion(S*vj);
}
struct Transpose
{
const ConstraintTpl & ref;
Transpose( const ConstraintTpl & ref ) : ref(ref) {}
JointForce operator* (const Force& f) const
{ return ref.S.transpose()*f.toVector(); }
template<typename D>
typename Eigen::Matrix<_Scalar,NV,Eigen::Dynamic>
operator*( const Eigen::MatrixBase<D> & F )
{
return ref.S.transpose()*F;
}
};
Transpose transpose() const { return Transpose(*this); }
DenseBase & matrix_impl() { return S; }
const DenseBase & matrix_impl() const { return S; }
int nv_impl() const { return NV; }
//template<int Dim,typename Scalar,int Options>
friend Eigen::Matrix<_Scalar,6,_Dim>
operator*( const InertiaTpl<_Scalar,_Options> & Y,const ConstraintTpl<_Dim,_Scalar,_Options> & S)
{ return Y.matrix()*S.S; }
Eigen::Matrix<_Scalar,6,NV> se3Action(const SE3 & m) const
{
return m.toActionMatrix()*S;
}
void disp_impl(std::ostream & os) const { os << "S =\n" << S << std::endl;}
protected:
DenseBase S;
}; // class ConstraintTpl
typedef ConstraintTpl<1,double,0> Constraint1d;
typedef ConstraintTpl<3,double,0> Constraint3d;
typedef ConstraintTpl<6,double,0> Constraint6d;
typedef ConstraintTpl<Eigen::Dynamic,double,0> ConstraintXd;
} // namespace se3
#endif // ifndef __se3_constraint_hpp__
| {
"content_hash": "55e63afc5651c08e27bd3d6d25aa5be7",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 101,
"avg_line_length": 29.483660130718953,
"alnum_prop": 0.6512968299711815,
"repo_name": "fvalenza/pinocchio",
"id": "5d158ec4b70621cc74ff855a5cd9d3743d4db382",
"size": "5489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/multibody/constraint.hpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C++",
"bytes": "794449"
},
{
"name": "CMake",
"bytes": "21876"
},
{
"name": "Lua",
"bytes": "1533"
},
{
"name": "Makefile",
"bytes": "256"
},
{
"name": "Matlab",
"bytes": "3566"
},
{
"name": "Python",
"bytes": "36094"
},
{
"name": "Shell",
"bytes": "1388"
}
],
"symlink_target": ""
} |
import type * as Host from '../../../../../front_end/core/host/host.js';
import type * as Platform from '../../../../../front_end/core/platform/platform.js';
import * as SDK from '../../../../../front_end/core/sdk/sdk.js';
import type * as Protocol from '../../../../../front_end/generated/protocol.js';
import {createTarget} from '../../helpers/EnvironmentHelpers.js';
import {describeWithMockConnection} from '../../helpers/MockConnection.js';
const {assert} = chai;
interface LoadResult {
success: boolean;
content: string;
errorDescription: Host.ResourceLoader.LoadErrorDescription;
}
describeWithMockConnection('SourceMapManager', () => {
const sourceMapContent = JSON.stringify({
'version': 3,
'file': '/script.js',
'mappings': '',
'sources': [
'/original-script.js',
],
});
const loadSourceMap = async(_url: string): Promise<LoadResult> => {
return {
success: true,
content: sourceMapContent,
errorDescription: {message: '', statusCode: 0, netError: 0, netErrorName: '', urlValid: true},
};
};
it('uses url for a worker\'s source maps from frame', async () => {
SDK.PageResourceLoader.PageResourceLoader.instance(
{forceNew: true, loadOverride: loadSourceMap, maxConcurrentLoads: 1, loadTimeout: 2000});
const frameUrl = 'https://frame-host/index.html' as Platform.DevToolsPath.UrlString;
const scriptUrl = 'https://script-host/script.js' as Platform.DevToolsPath.UrlString;
const sourceUrl = 'script.js' as Platform.DevToolsPath.UrlString;
const sourceMapUrl = 'script.js.map' as Platform.DevToolsPath.UrlString;
const mainTarget =
createTarget({id: 'main' as Protocol.Target.TargetID, name: 'main', type: SDK.Target.Type.Frame});
mainTarget.setInspectedURL(frameUrl);
const workerTarget = createTarget({
id: 'worker' as Protocol.Target.TargetID,
name: 'worker',
type: SDK.Target.Type.Worker,
parentTarget: mainTarget,
});
const debuggerModel = workerTarget.model(SDK.DebuggerModel.DebuggerModel);
assert.isNotNull(debuggerModel);
if (debuggerModel === null) {
return;
}
const sourceMapManager = debuggerModel.sourceMapManager();
const script = new SDK.Script.Script(
debuggerModel, '1' as Protocol.Runtime.ScriptId, scriptUrl, 0, 0, 0, 0, 0, '', false, false, sourceMapUrl,
false, 0, null, null, null, null, null, null);
sourceMapManager.attachSourceMap(script, sourceUrl, sourceMapUrl);
const sourceMap = await sourceMapManager.sourceMapForClientPromise(script);
// Check that the URLs are resolved relative to the frame.
assert.strictEqual(sourceMap?.url(), 'https://frame-host/script.js.map' as Platform.DevToolsPath.UrlString);
assert.deepEqual(
sourceMap?.sourceURLs(), ['https://frame-host/original-script.js' as Platform.DevToolsPath.UrlString]);
});
it('can handle source maps in a data URL frame', async () => {
SDK.PageResourceLoader.PageResourceLoader.instance(
{forceNew: true, loadOverride: loadSourceMap, maxConcurrentLoads: 1, loadTimeout: 2000});
const sourceMapContent = JSON.stringify({
'version': 3,
'file': '/script.js',
'mappings': '',
'sources': [
'/original-script.js',
],
});
const sourceUrl = 'script.js' as Platform.DevToolsPath.UrlString;
const sourceMapUrl = `data:test/html;base64,${btoa(sourceMapContent)}` as Platform.DevToolsPath.UrlString;
const frameSource =
'<script>0\n//# sourceURL=' + sourceUrl + '\n//# sourceMappingURL=' + sourceMapUrl + '</script>';
const frameUrl = `data:test/html;base64,${btoa(frameSource)}` as Platform.DevToolsPath.UrlString;
const scriptUrl = 'https://script-host/script.js' as Platform.DevToolsPath.UrlString;
const mainTarget =
createTarget({id: 'main' as Protocol.Target.TargetID, name: 'main', type: SDK.Target.Type.Frame});
mainTarget.setInspectedURL(frameUrl);
const debuggerModel = mainTarget.model(SDK.DebuggerModel.DebuggerModel);
assert.isNotNull(debuggerModel);
if (debuggerModel === null) {
return;
}
const sourceMapManager = debuggerModel.sourceMapManager();
const script = new SDK.Script.Script(
debuggerModel, '1' as Protocol.Runtime.ScriptId, scriptUrl, 0, 0, 0, 0, 0, '', false, false, sourceMapUrl,
false, 0, null, null, null, null, null, null);
sourceMapManager.attachSourceMap(script, sourceUrl, sourceMapUrl);
const sourceMap = await sourceMapManager.sourceMapForClientPromise(script);
assert.deepEqual(sourceMap?.sourceURLs(), ['/original-script.js' as Platform.DevToolsPath.UrlString]);
});
});
| {
"content_hash": "bce67397ecabe04adb4a5fc686466539",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 114,
"avg_line_length": 40.834782608695654,
"alnum_prop": 0.6839863713798978,
"repo_name": "ChromeDevTools/devtools-frontend",
"id": "9120658eed1816609922612062291af580f92a77",
"size": "4862",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "test/unittests/front_end/core/sdk/SourceMapManager_test.ts",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "615241"
},
{
"name": "Dart",
"bytes": "205"
},
{
"name": "HTML",
"bytes": "317251"
},
{
"name": "JavaScript",
"bytes": "1401177"
},
{
"name": "LLVM",
"bytes": "1918"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Python",
"bytes": "133111"
},
{
"name": "Shell",
"bytes": "1122"
},
{
"name": "TypeScript",
"bytes": "15230731"
},
{
"name": "WebAssembly",
"bytes": "921"
}
],
"symlink_target": ""
} |
"""
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = n * (n + 1) * (2 * n + 1) / 6
square_of_sum = (n * (n + 1) / 2) ** 2
return int(square_of_sum - sum_of_squares)
if __name__ == "__main__":
print(f"{solution() = }")
| {
"content_hash": "0b80801d2747c477431b04cb4a9f5f16",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 72,
"avg_line_length": 25.317073170731707,
"alnum_prop": 0.6204238921001927,
"repo_name": "wuweilin/python",
"id": "748b141490a056a1dcf66e181a4bde74534f1766",
"size": "1038",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "project_euler/problem_006/sol4.py",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace Raz {
class FilePath;
class Image;
namespace ImageFormat {
/// Loads an image from a file.
/// \param filePath File from which to load the image.
/// \param flipVertically Flip vertically the image when loading.
/// \return Loaded image's data.
Image load(const FilePath& filePath, bool flipVertically = false);
/// Saves an image to a file.
/// \param filePath File to which to save the image.
/// \param flipVertically Flip vertically the image when saving.
/// \param image Image to export data from.
void save(const FilePath& filePath, const Image& image, bool flipVertically = false);
} // namespace ImageFormat
} // namespace Raz
#endif // RAZ_IMAGEFORMAT_HPP
| {
"content_hash": "37ae8999788098375e87794e7b2afb5f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 85,
"avg_line_length": 28.458333333333332,
"alnum_prop": 0.7364568081991215,
"repo_name": "Razakhel/RaZ",
"id": "2d8a4f617d965925e94dd5ef7065d19d5f408397",
"size": "754",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/RaZ/Data/ImageFormat.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1143468"
},
{
"name": "CMake",
"bytes": "33498"
},
{
"name": "Dockerfile",
"bytes": "2522"
},
{
"name": "GDB",
"bytes": "99"
},
{
"name": "GLSL",
"bytes": "19731"
},
{
"name": "Python",
"bytes": "1920"
}
],
"symlink_target": ""
} |
require 'whois/record/parser/base_cocca2'
module Whois
class Record
class Parser
# Parser for the whois.nic.cx server.
#
# @see Whois::Record::Parser::Example
# The Example parser for the list of all available methods.
#
class WhoisNicCx < BaseCocca2
end
end
end
end
| {
"content_hash": "ecb291451bb4026dacea099f2685cc99",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 67,
"avg_line_length": 18.166666666666668,
"alnum_prop": 0.6299694189602446,
"repo_name": "opensrs-pso/whois",
"id": "bb6bede46031aa525f298559906c47e9e7bcc0d9",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/whois/record/parser/whois.nic.cx.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2161229"
}
],
"symlink_target": ""
} |
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile stylesheet("./styles/stylesheet.txt");
stylesheet.open(QFile::ReadOnly);
QString setSheet = QLatin1String(stylesheet.readAll());
a.setStyleSheet(setSheet);
TexturePainter w;
w.show();
return a.exec();
}
| {
"content_hash": "480d3d71b33b65d998d95b2f2bf4c0c6",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 56,
"avg_line_length": 25.454545454545453,
"alnum_prop": 0.7214285714285714,
"repo_name": "billhj/Etoile2015",
"id": "e4a2a680843d3323f4b8f895886e0253e38c97bb",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "applications/TexturePainter/main.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "31804"
},
{
"name": "C++",
"bytes": "1162990"
}
],
"symlink_target": ""
} |
/*Universidad de Guadalajara
*Centro Universitario de Ciencias Exactas e Ingenierias
*Programacion Web
*Sistema Universitario de Control Escolar SUCE
*Cuauhtemoc Herrera Muñoz
*/
function login_validator( ){
if( document.getElementById( "errorLine" ) == null ){
var title = document.getElementById( "lostPasswd" );
var cleaner = document.createElement( "div" );
var err = document.createElement( "p" );
cleaner.setAttribute( "class", "cleaner" );
err.setAttribute( "class", "errorLine" );
err.setAttribute( "id", "errorLine" );
err.appendChild( document.createTextNode( "" ) );
title.parentNode.insertBefore( err, title.nextSibling );
title.parentNode.insertBefore( cleaner, title.nextSibling );
}
var errLine = document.getElementById( "errorLine" );
var usr = document.getElementById( "user" );
var passwd = document.getElementById( "passwd" );
var regex = /\w+/;
var error1 = document.createTextNode( "Usuario invalido" );
var error2 = document.createTextNode( "Debes especificar un nombre de usuario" );
var error3 = document.createTextNode( "Debes especificar una contraseña" );
if ( usr.value.match( regex ) == null){
if( usr.value.length == 0 ){
errLine.replaceChild( error2, errLine.firstChild );
}
else{
errLine.replaceChild( error1, errLine.firstChild );
}
}
else if( passwd.value.length == 0 ){
errLine.replaceChild( error3, errLine.firstChild );
}
else{
document.fLogin.submit( );
}
}
function passwdRecoveryValidator( ){
if( document.getElementById( "errorLine" ) == null ){
var cleaner = document.createElement( "div" );
var err = document.createElement( "p" );
var button = document.getElementById( "endButton" );
cleaner.setAttribute( "class", "cleaner" );
err.setAttribute( "class", "errorLine" );
err.setAttribute( "id", "errorLine" );
err.appendChild( document.createTextNode( "" ) );
button.parentNode.appendChild( cleaner );
button.parentNode.appendChild( err );
}
var errLine = document.getElementById( "errorLine" );
var mail = document.getElementById( "mail" );
var regex = /(\w+(\.|\-)?)+@(\w+(\.|\-)?)+/;
var error1 = document.createTextNode( "Correo Invalido" );
if ( mail.value.match( regex ) == null ){
errLine.replaceChild( error1, errLine.firstChild );
}
else{
document.fRecovery.submit( );
}
}
function cicleValidatorNew(){
var ab = document.getElementById( "ab" );
var year = document.getElementById( "year" );
var init = document.getElementById( "init" );
var end = document.getElementById( "end" );
var body = document.getElementById( "tableBody" );
var days = new Array( );
var reasons = new Array( );
var flag = true;
if( body != null ){
for( i = 0; i < body.childNodes.length; i++ ){
reasons[ i ] = document.getElementById( "reason"+i ).value;
days[ i ] = document.getElementById( "day"+i ).value;
}
document.form.submit( );
}
else{
document.form.submit( );
}
}
function alumnValidator( ){
if( document.getElementById( "errorName" ) == null ){
var errorName = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var name = document.getElementById( "name" );
cleaner.setAttribute( "class", "cleaner" );
errorName.setAttribute( "class", "errorLine" );
errorName.setAttribute( "id", "errorName" );
errorName.appendChild( document.createTextNode( "" ) );
name.parentNode.insertBefore( errorName, name.nextSibling );
name.parentNode.insertBefore( cleaner, name.nextSibling );
}
if( document.getElementById( "errorCode" ) == null ){
var errorCode = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var code = document.getElementById( "code" );
cleaner.setAttribute( "class", "cleaner" );
errorCode.setAttribute( "class", "errorLine" );
errorCode.setAttribute( "id", "errorCode" );
errorCode.appendChild( document.createTextNode( "" ) );
code.parentNode.insertBefore( errorCode, code.nextSibling );
code.parentNode.insertBefore( cleaner, code.nextSibling );
}
if( document.getElementById( "errorPhone" ) == null ){
var errorPhone = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var phone = document.getElementById( "phone" );
cleaner.setAttribute( "class", "cleaner" );
errorPhone.setAttribute( "class", "errorLine" );
errorPhone.setAttribute( "id", "errorPhone" );
errorPhone.appendChild( document.createTextNode( "" ) );
phone.parentNode.insertBefore( errorPhone, phone.nextSibling );
phone.parentNode.insertBefore( cleaner, phone.nextSibling );
}
if( document.getElementById( "errorMail" ) == null ){
var errorMail = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var mail = document.getElementById( "mail" );
cleaner.setAttribute( "class", "cleaner" );
errorMail.setAttribute( "class", "errorLine" );
errorMail.setAttribute( "id", "errorMail" );
errorMail.appendChild( document.createTextNode( "" ) );
mail.parentNode.insertBefore( errorMail, mail.nextSibling );
mail.parentNode.insertBefore( cleaner, mail.nextSibling );
}
if( document.getElementById( "errorGit" ) == null ){
var errorGit = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var git = document.getElementById( "git" );
cleaner.setAttribute( "class", "cleaner" );
errorGit.setAttribute( "class", "errorLine" );
errorGit.setAttribute( "id", "errorGit" );
errorGit.appendChild( document.createTextNode( "" ) );
git.parentNode.insertBefore( errorGit, git.nextSibling );
git.parentNode.insertBefore( cleaner, git.nextSibling );
}
if( document.getElementById( "errorWeb" ) == null ){
var errorWeb = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var web = document.getElementById( "web" );
cleaner.setAttribute( "class", "cleaner" );
errorWeb.setAttribute( "class", "errorLine" );
errorWeb.setAttribute( "id", "errorWeb" );
errorWeb.appendChild( document.createTextNode( "" ) );
web.parentNode.insertBefore( errorWeb, web.nextSibling );
web.parentNode.insertBefore( cleaner, web.nextSibling );
}
if( document.getElementById( "errorCel" ) == null ){
var errorCel = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var cel = document.getElementById( "cel" );
cleaner.setAttribute( "class", "cleaner" );
errorCel.setAttribute( "class", "errorLine" );
errorCel.setAttribute( "id", "errorCel" );
errorCel.appendChild( document.createTextNode( "" ) );
cel.parentNode.insertBefore( errorCel, cel.nextSibling );
cel.parentNode.insertBefore( cleaner, cel.nextSibling );
}
var name = document.getElementById( "name" );
var acount = document.getElementById( "acount" );
var phone = document.getElementById( "phone" );
var code = document.getElementById( "code" );
var mail = document.getElementById( "mail" );
var web = document.getElementById( "webCheck" );
var git = document.getElementById( "gitCheck" );
var cel = document.getElementById( "celCheck" );
var nameRegex = /(\w+(\s)?)+/;
var numberRegex = /\d+/;
var mailRegex = /(\w+(\.|\-)?)+@(\w+(\.\-)?)+/;
var error1 = "Campo obligatorio";
var error2 = document.createTextNode( "Nombre invalido" );
var error4 = document.createTextNode( "Codigo invalido" );
var error5 = document.createTextNode( "Telefono invalido" );
var error6 = document.createTextNode( "Correo invalido" );
var error7 = "Pagina invalida";
var error8 = "Cuenta invalida, formato <github.com/user>";
var error9 = "Celular invalido";
var flag = false;
if( name.value.match( nameRegex ) == null ){
flag = true;
var err = document.getElementById( "errorName" );
if( name.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error2, err.firstChild );
}
}
else{
var err = document.getElementById( "errorName" );
err.parentNode.removeChild( err );
}
if( phone.value.match( numberRegex ) == null ){
flag = true;
var err = document.getElementById( "errorPhone" );
if( phone.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error5, err.firstChild );
}
}
else{
var err = document.getElementById( "errorPhone" );
err.parentNode.removeChild( err );
}
if( code.value.match( numberRegex ) == null ){
flag = true;
var err = document.getElementById( "errorCode" );
if( code.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error4, err.firstChild );
}
}
else{
var err = document.getElementById( "errorCode" );
err.parentNode.removeChild( err );
}
if( mail.value.match( mailRegex ) == null ){
flag = true;
var err = document.getElementById( "errorMail" );
if( mail.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error6, err.firstChild );
}
}
else{
var err = document.getElementById( "errorMail" );
err.parentNode.removeChild( err );
}
if( web.checked ){
var field = document.getElementById( "web" );
var regex = /(\w+(\.|\/)?)+/;
var err = document.getElementById( "errorWeb" );
if( field.value.match( regex ) == null ){
flag = true;
err.replaceChild( document.createTextNode( error7 ), err.firstChild );
}
else{
err.parentNode.removeChild( err );
}
}
else{
var err = document.getElementById( "errorWeb" );
err.parentNode.removeChild( err );
}
if( cel.checked ){
var field = document.getElementById( "cel" );
var err = document.getElementById( "errorCel" );
if( field.value.match( numberRegex ) == null ){
flag = true;
err.replaceChild( document.createTextNode( error9 ), err.firstChild );
}
else{
err.parentNode.removeChild( err );
}
}
else{
var err = document.getElementById( "errorCel" );
err.parentNode.removeChild( err );
}
if( git.checked){
var regex = /github\.com\/[\w]+/;
var field = document.getElementById( "git" );
var err = document.getElementById( "errorGit" );
if( field.value.match( regex ) == null ){
flag = true;
err.replaceChild( document.createTextNode( error8 ), err.firstChild );
}
else{
err.parentNode.removeChild( err );
}
}
else{
var err = document.getElementById( "errorGit" );
err.parentNode.removeChild( err );
}
if( !flag ){
document.form.submit( );
}
}
function teacherValidator( ){
if( document.getElementById( "errorName" ) == null ){
var errorName = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var name = document.getElementById( "name" );
cleaner.setAttribute( "class", "cleaner" );
errorName.setAttribute( "class", "errorLine" );
errorName.setAttribute( "id", "errorName" );
errorName.appendChild( document.createTextNode( "" ) );
name.parentNode.insertBefore( errorName, name.nextSibling );
name.parentNode.insertBefore( cleaner, name.nextSibling );
}
if( document.getElementById( "errorCode" ) == null ){
var errorCode = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var code = document.getElementById( "code" );
cleaner.setAttribute( "class", "cleaner" );
errorCode.setAttribute( "class", "errorLine" );
errorCode.setAttribute( "id", "errorCode" );
errorCode.appendChild( document.createTextNode( "" ) );
code.parentNode.insertBefore( errorCode, code.nextSibling );
code.parentNode.insertBefore( cleaner, code.nextSibling );
}
if( document.getElementById( "errorPhone" ) == null ){
var errorPhone = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var phone = document.getElementById( "phone" );
cleaner.setAttribute( "class", "cleaner" );
errorPhone.setAttribute( "class", "errorLine" );
errorPhone.setAttribute( "id", "errorPhone" );
errorPhone.appendChild( document.createTextNode( "" ) );
phone.parentNode.insertBefore( errorPhone, phone.nextSibling );
phone.parentNode.insertBefore( cleaner, phone.nextSibling );
}
if( document.getElementById( "errorMail" ) == null ){
var errorMail = document.createElement( "p" );
var cleaner = document.createElement( "div" );
var mail = document.getElementById( "mail" );
cleaner.setAttribute( "class", "cleaner" );
errorMail.setAttribute( "class", "errorLine" );
errorMail.setAttribute( "id", "errorMail" );
errorMail.appendChild( document.createTextNode( "" ) );
mail.parentNode.insertBefore( errorMail, mail.nextSibling );
mail.parentNode.insertBefore( cleaner, mail.nextSibling );
}
var name = document.getElementById( "name" );
var phone = document.getElementById( "phone" );
var code = document.getElementById( "code" );
var mail = document.getElementById( "mail" );
var nameRegex = /(\w+(\s)?)+/;
var acountRegex = /\w+\.\w+/;
var numberRegex = /\d+/;
var mailRegex = /(\w+(\.|\-)?)+@(\w+(\.\-)?)+/;
var error1 = "Campo obligatorio";
var error2 = document.createTextNode( "Nombre invalido" );
var error4 = document.createTextNode( "Codigo invalido" );
var error5 = document.createTextNode( "Telefono invalido" );
var error6 = document.createTextNode( "Correo invalido" );
var flag = false;
if( name.value.match( nameRegex ) == null ){
flag = true;
var err = document.getElementById( "errorName" );
if( name.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error2, err.firstChild );
}
}
else{
var err = document.getElementById( "errorName" );
err.parentNode.removeChild( err );
}
if( phone.value.match( numberRegex ) == null ){
flag = true;
var err = document.getElementById( "errorPhone" );
if( phone.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error5, err.firstChild );
}
}
else{
var err = document.getElementById( "errorPhone" );
err.parentNode.removeChild( err );
}
if( code.value.match( numberRegex ) == null ){
flag = true;
var err = document.getElementById( "errorCode" );
if( code.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error4, err.firstChild );
}
}
else{
var err = document.getElementById( "errorCode" );
err.parentNode.removeChild( err );
}
if( mail.value.match( mailRegex ) == null ){
flag = true;
var err = document.getElementById( "errorMail" );
if( mail.value.length == 0 ){
err.replaceChild( document.createTextNode( error1 ), err.firstChild );
}
else{
err.replaceChild( error6, err.firstChild );
}
}
else{
var err = document.getElementById( "errorMail" );
err.parentNode.removeChild( err );
}
if( !flag ){
document.form.submit( );
}
} | {
"content_hash": "78fba3b9256dc4f4dc9ebae219e2f2bb",
"timestamp": "",
"source": "github",
"line_count": 425,
"max_line_length": 82,
"avg_line_length": 35.908235294117645,
"alnum_prop": 0.665159557040823,
"repo_name": "Seiferxx/user211",
"id": "d9edf341512494256d658123316800e22a6e7603",
"size": "15261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/js/validators.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24020"
},
{
"name": "JavaScript",
"bytes": "35065"
},
{
"name": "PHP",
"bytes": "34978"
},
{
"name": "Perl",
"bytes": "200"
}
],
"symlink_target": ""
} |
module CoffeeTrace
class InsertLogStatement
def for line, prefix=nil
leading_spaces, method_name, args = parse_function line
return unless leading_spaces
method_name = (prefix + "-" + method_name) if prefix
result = "#{leading_spaces} console.log '#{method_name}'"
result += ", #{args}" if args
result += " #coffee_trace"
result
end
private
def parse_function line
no_arg_function_match = line.scan(/^( *)(\w+): * \(? *\)? *[-=]> *$/)
no_arg_function_match.empty? ? parse_function_with_args(line) : no_arg_function_match.first
end
def parse_function_with_args line
arg_function_match = line.scan(/^( *)(\w+): *\((.*)\) *[-=]> *$/)
arg_function_match.empty? ? nil : arg_function_match.first
end
end
end
| {
"content_hash": "0fc657ec30da662ff2374a9b53a1e198",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 97,
"avg_line_length": 32.36,
"alnum_prop": 0.5908529048207664,
"repo_name": "cmaitchison/coffee_trace",
"id": "fcd57cbc471af748be5c97aec3e91dbe6da7fdc4",
"size": "809",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/coffee_trace/insert_log_statement.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "8391"
}
],
"symlink_target": ""
} |
package breadth_first_search;
import java.util.*;
import public_class.TreeNode;
public class Q103BinaryTreeZigzagLevelOrderTraversal {
//TAG: LinkedIn
//TAG: Tree
//TAG: breadth first search
//Difficulty: Medium
/**
* 103. Binary Tree Zigzag Level Order Traversal
* Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
*/
/**
* Solution:
* Similar as Binary tree level order traversal in legacy_code.legacy_code_class.Problem101To110, difference is every time the push and poll direction is not same, so we use a structure which could push/poll at two sides (deque)
* 1. if the level index is even number
* poll from deque left
* push left -> right from deque right
* 2. if the level index is odd number
* poll from right
* push right -> left from deque left
*
* Time: O(n)
* Space: O(n)
*/
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Deque<TreeNode> deque = new LinkedList<>();
deque.push(root);
while (!deque.isEmpty()) {
int size = deque.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
//res size is the same as current tree level index
if (res.size()%2 == 0) {
TreeNode cur = deque.pollFirst();
list.add(cur.val);
if (cur.left != null) deque.offerLast(cur.left);
if (cur.right != null) deque.offerLast(cur.right);
} else {
TreeNode cur = deque.pollLast();
list.add(cur.val);
if (cur.right != null) deque.offerFirst(cur.right);
if (cur.left != null) deque.offerFirst(cur.left);
}
}
res.add(list);
}
return res;
}
}
| {
"content_hash": "e25627137838c18389bf00e77271c9bd",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 232,
"avg_line_length": 32.52054794520548,
"alnum_prop": 0.537910699241786,
"repo_name": "StevenUpForever/LeetCode_Java",
"id": "cbb54d55adb1ae0e657ded8a3771bbf24f330d21",
"size": "2374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/breadth_first_search/Q103BinaryTreeZigzagLevelOrderTraversal.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "97"
},
{
"name": "Java",
"bytes": "500684"
}
],
"symlink_target": ""
} |
#include <stdio.h>
#include <unistd.h>
#include <barrelfish/barrelfish.h>
#include <vfs/vfs.h>
#include <sys/types.h>
#include <eclipse.h>
#include <include/skb_server.h>
#include <include/skb_debug.h>
#include <octopus_server/init.h>
#include <bench/bench.h>
#include "octopus/predicates.h"
#include "shared_lib_dict.h"
#define MEMORY_SIZE 32*1024*1024
#define ECLIPSE_DIR "/skb"
#define RESULT_BUF_SIZE 1024
int skb_init(void);
void execute_string(char *string);
/* XXX: used dlmalloc for benchmarking octopus */
#include <dmalloc/dmalloc.h>
typedef void *(*alt_malloc_t)(size_t bytes);
extern alt_malloc_t alt_malloc;
typedef void (*alt_free_t)(void *p);
extern alt_free_t alt_free;
typedef void *(*alt_realloc_t)(void *p, size_t bytes);
extern alt_realloc_t alt_realloc;
static void init_dmalloc(void)
{
alt_malloc = &dlmalloc;
alt_free = &dlfree;
alt_realloc = &dlrealloc;
}
int main(int argc, char**argv)
{
vfs_init();
init_dmalloc();
// we'll be needing this...
vfs_mkdir("/tmp");
chdir(ECLIPSE_DIR);
// make sure, that dlsym has the right table to the statically compiled-in
// shared libraries...
dlopen_set_params(&funcs, sizeof(funcs)/sizeof(struct function_entry));
// now set the right values for the eclipse-clp engine
ec_set_option_int(EC_OPTION_IO, MEMORY_IO);
ec_set_option_ptr(EC_OPTION_ECLIPSEDIR, ECLIPSE_DIR);
ec_set_option_long(EC_OPTION_GLOBALSIZE, MEMORY_SIZE);
//ec_set_option_long(EC_OPTION_PRIVATESIZE, MEMORY_SIZE);
// ec_.m.vm_flags |= 8;
SKB_DEBUG("before ec init\n");
int n = ec_init();
if (n != 0) {
SKB_DEBUG("\nskb_main: ec_init() failed. Return code = %d\n", n);
} else {
SKB_DEBUG("\nskb_main: ec_init() succeeded.\n");
}
execute_string("set_flag(print_depth,100).");
if(disp_get_core_id() == 0) {
//debug_printf("oct_server_init\n");
//execute_string("set_flag(gc, off).");
//execute_string("set_flag(gc_policy, fixed).");
//execute_string("set_flat(gc_interval, 536870912)."); // 512 mb
//execute_string("set_flag(gc_interval_dict, 10000).");
//execute_string("set_flag(enable_interrupts, off).");
//execute_string("set_flag(debug_compile, off).");
//execute_string("set_flag(debugging, nodebug).");
//bench_init();
// octopus related stuff
execute_string("[objects3].");
execute_string("[pubsub3].");
execute_string("[bindings].");
dident e = ec_did("eclipse", 0);
//ec_external(ec_did("notify_client", 2), p_notify_client, e);
ec_external(ec_did("trigger_watch", 6), p_trigger_watch, e);
ec_external(ec_did("save_index", 3), p_save_index, e);
ec_external(ec_did("remove_index", 3), p_remove_index, e);
ec_external(ec_did("index_intersect", 4), p_index_intersect, e);
ec_external(ec_did("bitfield_add", 3), p_bitfield_add, e);
ec_external(ec_did("bitfield_remove", 3), p_bitfield_remove, e);
ec_external(ec_did("bitfield_union", 4), p_bitfield_union, e);
ec_external(ec_did("match", 3), (int (*)()) ec_regmatch, e);
ec_external(ec_did("split", 4), (int (*)()) ec_regsplit, e);
// end
errval_t err = oct_server_init();
assert(err_is_ok(err));
}
if (disp_get_core_id() == 0) {
skb_server_init();
SKB_DEBUG("\nskb initialized\n");
}
// SKB Hardware related
execute_string("[queries].");
// execute_string("get_local_affinity(1,B,L),write(output,[B,L]).");
// execute_string("lib(branch_and_bound).");
// execute_string("minimize(member(X,[4,1,2]),X),write(output,X).");
messages_handler_loop();
}
int skb_init(void)
{
int n;
SKB_DEBUG("\ninitialize eclipse\n");
n = ec_init();
if (n != 0) {
SKB_DEBUG("\nskb_main: ec_init() failed.");
}
return (0);
}
void execute_string(char *string)
{
char buf[RESULT_BUF_SIZE];
int n;
ec_post_string(string);
int res = 7; //means that we have to flush the output.
while (res == 7) {
res = ec_resume();
SKB_DEBUG("\nres = %d\n", res);
//give back the result and the error messages.
//in case there is no message, a '.' is still returned
n = ec_queue_read(1, buf, RESULT_BUF_SIZE);
if ((n >=0) && (n < RESULT_BUF_SIZE)) {
buf[n] = 0;
}
SKB_DEBUG("eclipse returned: %s with length %d.\n", buf,n);
n = ec_queue_read(2, buf, RESULT_BUF_SIZE);
if ((n >=0) && (n < RESULT_BUF_SIZE)) {
buf[n] = 0;
}
SKB_DEBUG("eclipse error returned: %s with length %d.\n", buf,n);
}
}
| {
"content_hash": "626e0f24f6103c0c7e27d58306144176",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 75,
"avg_line_length": 29.81645569620253,
"alnum_prop": 0.5924432180004245,
"repo_name": "modeswitch/barrelfish",
"id": "2eaeb9d574126f6b2fca20685f29d2f5d25ea2fd",
"size": "5016",
"binary": false,
"copies": "1",
"ref": "refs/heads/default",
"path": "usr/skb/skb_main.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "998862"
},
{
"name": "C",
"bytes": "46857143"
},
{
"name": "C++",
"bytes": "1745172"
},
{
"name": "Clojure",
"bytes": "7002"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "Gnuplot",
"bytes": "3830"
},
{
"name": "Haskell",
"bytes": "141869"
},
{
"name": "Objective-C",
"bytes": "115504"
},
{
"name": "Perl",
"bytes": "2716335"
},
{
"name": "Prolog",
"bytes": "2743156"
},
{
"name": "Python",
"bytes": "5352"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Scilab",
"bytes": "5315"
},
{
"name": "Shell",
"bytes": "171692"
},
{
"name": "Tcl",
"bytes": "18591"
},
{
"name": "TeX",
"bytes": "735459"
},
{
"name": "eC",
"bytes": "5079"
}
],
"symlink_target": ""
} |
namespace content {
// Callback interface to receive the color selection from the eye dropper.
class EyeDropperListener {
public:
virtual ~EyeDropperListener() = default;
virtual void ColorSelected(SkColor color) = 0;
virtual void ColorSelectionCanceled() = 0;
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_EYE_DROPPER_LISTENER_H_
| {
"content_hash": "8037570071edb217f699cc82fd9075ab",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 74,
"avg_line_length": 25.5,
"alnum_prop": 0.7507002801120448,
"repo_name": "endlessm/chromium-browser",
"id": "770f969d79eac1c409bc96c43e4829204556a574",
"size": "705",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/public/browser/eye_dropper_listener.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('small.author::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
}
| {
"content_hash": "ec0ece485b53b816a12734d84ce96822",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 30.352941176470587,
"alnum_prop": 0.5368217054263565,
"repo_name": "netodeolino/TCC",
"id": "e59b28093e459667e421e2bf85ff55d40fc3fb95",
"size": "516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TCC 01/Tutorial/new.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "70361"
},
{
"name": "Jupyter Notebook",
"bytes": "2817386"
},
{
"name": "Python",
"bytes": "48474"
}
],
"symlink_target": ""
} |
[//000000001]: # (log \- Logging facility)
[//000000002]: # (Generated from file 'log\.man' by tcllib/doctools with format 'markdown')
[//000000003]: # (Copyright © 2001\-2009 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>)
[//000000004]: # (log\(n\) 1\.4 tcllib "Logging facility")
<hr> [ <a href="../../../../toc.md">Main Table Of Contents</a> | <a
href="../../../toc.md">Table Of Contents</a> | <a
href="../../../../index.md">Keyword Index</a> | <a
href="../../../../toc0.md">Categories</a> | <a
href="../../../../toc1.md">Modules</a> | <a
href="../../../../toc2.md">Applications</a> ] <hr>
# NAME
log \- Procedures to log messages of libraries and applications\.
# <a name='toc'></a>Table Of Contents
- [Table Of Contents](#toc)
- [Synopsis](#synopsis)
- [Description](#section1)
- [API](#section2)
- [LEVELS](#section3)
- [Bugs, Ideas, Feedback](#section4)
- [Keywords](#keywords)
- [Category](#category)
- [Copyright](#copyright)
# <a name='synopsis'></a>SYNOPSIS
package require Tcl 8
package require log ?1\.4?
[__::log::levels__](#1)
[__::log::lv2longform__ *level*](#2)
[__::log::lv2color__ *level*](#3)
[__::log::lv2priority__ *level*](#4)
[__::log::lv2cmd__ *level*](#5)
[__::log::lv2channel__ *level*](#6)
[__::log::lvCompare__ *level1* *level2*](#7)
[__::log::lvSuppress__ *level* \{*suppress* 1\}](#8)
[__::log::lvSuppressLE__ *level* \{*suppress* 1\}](#9)
[__::log::lvIsSuppressed__ *level*](#10)
[__::log::lvCmd__ *level* *cmd*](#11)
[__::log::lvCmdForall__ *cmd*](#12)
[__::log::lvChannel__ *level* *chan*](#13)
[__::log::lvChannelForall__ *chan*](#14)
[__::log::lvColor__ *level* *color*](#15)
[__::log::lvColorForall__ *color*](#16)
[__::log::log__ *level* *text*](#17)
[__::log::logarray__ *level* *arrayvar* ?*pattern*?](#18)
[__::log::loghex__ *level* *text* *data*](#19)
[__::log::logsubst__ *level* *msg*](#20)
[__::log::logMsg__ *text*](#21)
[__::log::logError__ *text*](#22)
[__::log::Puts__ *level* *text*](#23)
# <a name='description'></a>DESCRIPTION
The __log__ package provides commands that allow libraries and applications
to selectively log information about their internal operation and state\.
To use the package just execute
package require log
log::log notice "Some message"
As can be seen above, each message given to the log facility is associated with
a *level* determining the importance of the message\. The user can then select
which levels to log, what commands to use for the logging of each level and the
channel to write the message to\. In the following example the logging of all
message with level __debug__ is deactivated\.
package require log
log::lvSuppress debug
log::log debug "Unseen message" ; # No output
By default all messages associated with an error\-level \(__emergency__,
__alert__, __critical__, and __error__\) are written to
__stderr__\. Messages with any other level are written to __stdout__\. In
the following example the log module is reconfigured to write __debug__
messages to __stderr__ too\.
package require log
log::lvChannel debug stderr
log::log debug "Written to stderr"
Each message level is also associated with a command to use when logging a
message with that level\. The behaviour above for example relies on the fact that
all message levels use by default the standard command __::log::Puts__ to
log any message\. In the following example all messages of level __notice__
are given to the non\-standard command __toText__ for logging\. This disables
the channel setting for such messages, assuming that __toText__ does not use
it by itself\.
package require log
log::lvCmd notice toText
log::log notice "Handled by \"toText\""
Another database maintained by this facility is a map from message levels to
colors\. The information in this database has *no* influence on the behaviour
of the module\. It is merely provided as a convenience and in anticipation of the
usage of this facility in __tk__\-based application which may want to
colorize message logs\.
# <a name='section2'></a>API
The following commands are available:
- <a name='1'></a>__::log::levels__
Returns the names of all known levels, in alphabetical order\.
- <a name='2'></a>__::log::lv2longform__ *level*
Converts any unique abbreviation of a level name to the full level name\.
- <a name='3'></a>__::log::lv2color__ *level*
Converts any level name including unique abbreviations to the corresponding
color\.
- <a name='4'></a>__::log::lv2priority__ *level*
Converts any level name including unique abbreviations to the corresponding
priority\.
- <a name='5'></a>__::log::lv2cmd__ *level*
Converts any level name including unique abbreviations to the command prefix
used to write messages with that level\.
- <a name='6'></a>__::log::lv2channel__ *level*
Converts any level name including unique abbreviations to the channel used
by __::log::Puts__ to write messages with that level\.
- <a name='7'></a>__::log::lvCompare__ *level1* *level2*
Compares two levels \(including unique abbreviations\) with respect to their
priority\. This command can be used by the \-command option of lsort\. The
result is one of \-1, 0 or 1 or an error\. A result of \-1 signals that level1
is of less priority than level2\. 0 signals that both levels have the same
priority\. 1 signals that level1 has higher priority than level2\.
- <a name='8'></a>__::log::lvSuppress__ *level* \{*suppress* 1\}
\(Un\)suppresses the output of messages having the specified level\. Unique
abbreviations for the level are allowed here too\.
- <a name='9'></a>__::log::lvSuppressLE__ *level* \{*suppress* 1\}
\(Un\)suppresses the output of messages having the specified level or one of
lesser priority\. Unique abbreviations for the level are allowed here too\.
- <a name='10'></a>__::log::lvIsSuppressed__ *level*
Asks the package whether the specified level is currently suppressed\. Unique
abbreviations of level names are allowed\.
- <a name='11'></a>__::log::lvCmd__ *level* *cmd*
Defines for the specified level with which command to write the messages
having this level\. Unique abbreviations of level names are allowed\. The
command is actually a command prefix and this facility will append 2
arguments before calling it, the level of the message and the message
itself, in this order\.
- <a name='12'></a>__::log::lvCmdForall__ *cmd*
Defines for all known levels with which command to write the messages having
this level\. The command is actually a command prefix and this facility will
append 2 arguments before calling it, the level of the message and the
message itself, in this order\.
- <a name='13'></a>__::log::lvChannel__ *level* *chan*
Defines for the specified level into which channel __::log::Puts__ \(the
standard command\) shall write the messages having this level\. Unique
abbreviations of level names are allowed\. The command is actually a command
prefix and this facility will append 2 arguments before calling it, the
level of the message and the message itself, in this order\.
- <a name='14'></a>__::log::lvChannelForall__ *chan*
Defines for all known levels with which which channel __::log::Puts__
\(the standard command\) shall write the messages having this level\. The
command is actually a command prefix and this facility will append 2
arguments before calling it, the level of the message and the message
itself, in this order\.
- <a name='15'></a>__::log::lvColor__ *level* *color*
Defines for the specified level the color to return for it in a call to
__::log::lv2color__\. Unique abbreviations of level names are allowed\.
- <a name='16'></a>__::log::lvColorForall__ *color*
Defines for all known levels the color to return for it in a call to
__::log::lv2color__\. Unique abbreviations of level names are allowed\.
- <a name='17'></a>__::log::log__ *level* *text*
Log a message according to the specifications for commands, channels and
suppression\. In other words: The command will do nothing if the specified
level is suppressed\. If it is not suppressed the actual logging is delegated
to the specified command\. If there is no command specified for the level the
message won't be logged\. The standard command __::log::Puts__ will write
the message to the channel specified for the given level\. If no channel is
specified for the level the message won't be logged\. Unique abbreviations of
level names are allowed\. Errors in the actual logging command are *not*
caught, but propagated to the caller, as they may indicate misconfigurations
of the log facility or errors in the callers code itself\.
- <a name='18'></a>__::log::logarray__ *level* *arrayvar* ?*pattern*?
Like __::log::log__, but logs the contents of the specified array
variable *arrayvar*, possibly restricted to entries matching the
*pattern*\. The pattern defaults to __\*__ \(i\.e\. all entries\) if none
was specified\.
- <a name='19'></a>__::log::loghex__ *level* *text* *data*
Like __::log::log__, but assumes that *data* contains binary data\. It
converts this into a mixed hex/ascii representation before writing them to
the log\.
- <a name='20'></a>__::log::logsubst__ *level* *msg*
Like __::log::log__, but *msg* may contain substitutions and variable
references, which are evaluated in the caller scope first\. The purpose of
this command is to avoid overhead in the non\-logging case, if the log
message building is expensive\. Any substitution errors raise an error in the
command execution\. The following example shows an xml text representation,
which is only generated in debug mode:
log::logsubst debug {XML of node $node is '[$node toXml]'}
- <a name='21'></a>__::log::logMsg__ *text*
Convenience wrapper around __::log::log__\. Equivalent to __::log::log
info text__\.
- <a name='22'></a>__::log::logError__ *text*
Convenience wrapper around __::log::log__\. Equivalent to __::log::log
error text__\.
- <a name='23'></a>__::log::Puts__ *level* *text*
The standard log command, it writes messages and their levels to
user\-specified channels\. Assumes that the suppression checks were done by
the caller\. Expects full level names, abbreviations are *not allowed*\.
# <a name='section3'></a>LEVELS
The package currently defines the following log levels, the level of highest
importance listed first\.
- emergency
- alert
- critical
- error
- warning
- notice
- info
- debug
*Note* that by default all messages with levels __warning__ down to
__debug__ are suppressed\. This is done intentionally, because \(we believe
that\) in most situations debugging output is not wanted\. Most people wish to
have such output only when actually debugging an application\.
# <a name='section4'></a>Bugs, Ideas, Feedback
This document, and the package it describes, will undoubtedly contain bugs and
other problems\. Please report such in the category *log* of the [Tcllib
Trackers](http://core\.tcl\.tk/tcllib/reportlist)\. Please also report any ideas
for enhancements you may have for either package and/or documentation\.
When proposing code changes, please provide *unified diffs*, i\.e the output of
__diff \-u__\.
Note further that *attachments* are strongly preferred over inlined patches\.
Attachments can be made by going to the __Edit__ form of the ticket
immediately after its creation, and then using the left\-most button in the
secondary navigation bar\.
# <a name='keywords'></a>KEYWORDS
[log](\.\./\.\./\.\./\.\./index\.md\#log), [log
level](\.\./\.\./\.\./\.\./index\.md\#log\_level),
[message](\.\./\.\./\.\./\.\./index\.md\#message), [message
level](\.\./\.\./\.\./\.\./index\.md\#message\_level)
# <a name='category'></a>CATEGORY
Programming tools
# <a name='copyright'></a>COPYRIGHT
Copyright © 2001\-2009 Andreas Kupries <andreas\_kupries@users\.sourceforge\.net>
| {
"content_hash": "4c4e180ec174f0ac4cc1804a0caa01e5",
"timestamp": "",
"source": "github",
"line_count": 317,
"max_line_length": 105,
"avg_line_length": 38.63406940063091,
"alnum_prop": 0.6759206336245611,
"repo_name": "macports/macports-base",
"id": "85533408e11264c2374c40649de405bdeeb8bd03",
"size": "12248",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/tcllib-1.21/embedded/md/tcllib/files/modules/log/log.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1023346"
},
{
"name": "M4",
"bytes": "92177"
},
{
"name": "Makefile",
"bytes": "27509"
},
{
"name": "Rich Text Format",
"bytes": "6834"
},
{
"name": "Shell",
"bytes": "39512"
},
{
"name": "Tcl",
"bytes": "1531263"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ba40b71df852d0317391983c21a1f2bb",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 32,
"avg_line_length": 9.76923076923077,
"alnum_prop": 0.7007874015748031,
"repo_name": "mdoering/backbone",
"id": "ad3eb26de45737f8683651c15700187550c5559b",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Bacteria/Cyanobacteria/Plexostromataceae/Papulophycus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import codecs
import os
import re
import sys
from setuptools import setup, find_packages
PACKAGES = find_packages(where='src')
KEYWORDS = ['Toxicogenomics', 'Database', 'Bioinformatics', 'Human health']
INSTALL_REQUIRES = [
'pandas',
'sqlalchemy',
'requests',
'click',
'pymysql',
'numpy',
'pydantic',
'cryptography'
]
if sys.version_info < (3,):
INSTALL_REQUIRES.append('configparser')
ENTRY_POINTS = {
'console_scripts': [
'pyctd = pyctd.cli:main',
]
}
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""Build an absolute path from *parts* and return the contents of the resulting file. Assume UTF-8 encoding."""
with codecs.open(os.path.join(HERE, *parts), 'rb', 'utf-8') as f:
return f.read()
META_PATH = os.path.join('src', 'pyctd', '__init__.py')
META_FILE = read(META_PATH)
def find_meta(meta):
"""Extract __*meta*__ from META_FILE"""
meta_match = re.search(
r'^__{meta}__ = ["\']([^"\']*)["\']'.format(meta=meta),
META_FILE, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError('Unable to find __{meta}__ string'.format(meta=meta))
def get_long_description():
"""Get the long_description from the README.rst file. Assume UTF-8 encoding."""
with codecs.open(os.path.join(HERE, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
return long_description
setup(
name=find_meta('title'),
version=find_meta('version'),
url=find_meta('url'),
author=find_meta('author'),
author_email=find_meta('email'),
maintainer='Christian Ebeling',
maintainer_email=find_meta('email'),
description=find_meta('description'),
long_description=get_long_description(),
keywords=KEYWORDS,
license=find_meta('license'),
packages=PACKAGES,
install_requires=INSTALL_REQUIRES,
package_dir={'': 'src'},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Environment :: Console',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Database',
"Topic :: Scientific/Engineering :: Bio-Informatics",
],
entry_points=ENTRY_POINTS,
)
| {
"content_hash": "b21b6190083b6c2b01bb81e4eb504b93",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 115,
"avg_line_length": 27.419354838709676,
"alnum_prop": 0.6164705882352941,
"repo_name": "cebel/pyctd",
"id": "c20992bb91fb4738b621111b36a62d86c7614aef",
"size": "2597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "99912"
}
],
"symlink_target": ""
} |
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([XBAppDelegate class]));
}
}
| {
"content_hash": "86735d5b497662d42189698c5ad120fd",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 92,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.6625,
"repo_name": "anuj-xebia/appium_samples",
"id": "b5437bf7986445cd3af61def0c5ea2a18ab3d27e",
"size": "335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iOSCreateNote/ioscreatenote/iOSCreateNote/iOSCreateNote/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "D",
"bytes": "4356"
},
{
"name": "Java",
"bytes": "11363"
},
{
"name": "Objective-C",
"bytes": "17417"
},
{
"name": "Perl",
"bytes": "1329"
},
{
"name": "Ruby",
"bytes": "5843"
}
],
"symlink_target": ""
} |
package com.intellij.lang.jsgraphql.endpoint.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface JSGraphQLEndpointInputValueDefinitions extends PsiElement {
@NotNull
List<JSGraphQLEndpointInputValueDefinition> getInputValueDefinitionList();
}
| {
"content_hash": "63f13ecd4122dbd60ae430274579ba30",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 76,
"avg_line_length": 26.333333333333332,
"alnum_prop": 0.8354430379746836,
"repo_name": "jimkyndemeyer/js-graphql-intellij-plugin",
"id": "17adbdf52cec0464881889722e6e0cc96e80c90b",
"size": "378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gen/com/intellij/lang/jsgraphql/endpoint/psi/JSGraphQLEndpointInputValueDefinitions.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1439"
},
{
"name": "HTML",
"bytes": "355"
},
{
"name": "Java",
"bytes": "980536"
},
{
"name": "JavaScript",
"bytes": "13180"
},
{
"name": "Lex",
"bytes": "9659"
}
],
"symlink_target": ""
} |
define('getlibs/src/worker', [], function(){
function remote(){
var port = self;
self.onmessage = function(event){
try {
var request = {};
request = JSON.parse(event.data);
port.postMessage(JSON.stringify({
id: request.id,
result: self[request.method].apply(self, request.args)
}));
}
catch(err){
port.postMessage(JSON.stringify({
id: request.id,
error: {
message: err.message,
stack: err.stack
}
}));
}
};
self.onconnect = function(event){
port = event.ports[0];
port.onmessage = self.onmessage;
};
}
function createWorker(scripts){
var source = scripts.concat(remote).map(function(item){
if (typeof item == 'string'){
return 'importScripts(' + JSON.stringify(System.normalizeSync(item)) + ');\n';
}
if (typeof item == 'function'){
return '(' + item + ')();\n';
}
});
var blob = new Blob(source, {type: 'application/javascript'});
return new Worker(URL.createObjectURL(blob));
}
return function(scripts){
var serial = 0,
tasks = [],
error = null;
var worker = createWorker(scripts);
function handleError(err){
error = err;
tasks.forEach(function(task, i){
if (task) {
tasks[i] = null;
task.failure(err);
}
});
}
worker.onerror = function(event){
handleError(new Error(event.message, event.filename, event.lineno));
};
worker.onmessage = function(e){
try {
var msg = JSON.parse(e.data),
task = tasks[msg.id];
tasks[msg.id] = null;
if (msg.error) {
task.failure(msg.error);
}
else {
task.success(msg.result);
}
}
catch(err){
handleError(err);
}
};
this.call = function(method){
if (error){
return Promise.reject(error);
}
var i, args = [], id = ++serial;
for(i=1; i<arguments.length; i++){
args[i-1] = arguments[i];
}
return new Promise(function(success, failure){
tasks[id] = {
success: success,
failure: failure
};
worker.postMessage(JSON.stringify({
id: id,
method: method,
args: args
}));
});
};
};
}); | {
"content_hash": "60fceb6eee1d62f7a4584231d76a0de0",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 82,
"avg_line_length": 17.265151515151516,
"alnum_prop": 0.5397103992979377,
"repo_name": "activewidgets/getlibs",
"id": "74610020ed1825da89b357ea43f13ef55848828c",
"size": "2281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/worker.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "35049"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Bridge\PhpUnit;
/**
* Catch deprecation notices and print a summary report at the end of the test suite.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class DeprecationErrorHandler
{
private static $isRegistered = false;
public static function register($mode = false)
{
if (self::$isRegistered) {
return;
}
$getMode = function () use ($mode) {
static $memoizedMode = false;
if (false !== $memoizedMode) {
return $memoizedMode;
}
if (false === $mode) {
$mode = getenv('SYMFONY_DEPRECATIONS_HELPER') ?: '';
}
return $memoizedMode = $mode;
};
$deprecations = array(
'unsilencedCount' => 0,
'remainingCount' => 0,
'legacyCount' => 0,
'otherCount' => 0,
'unsilenced' => array(),
'remaining' => array(),
'legacy' => array(),
'other' => array(),
);
$deprecationHandler = function ($type, $msg, $file, $line, $context) use (&$deprecations, $getMode) {
if (E_USER_DEPRECATED !== $type) {
return \PHPUnit_Util_ErrorHandler::handleError($type, $msg, $file, $line, $context);
}
$mode = $getMode();
$trace = debug_backtrace(true);
$group = 'other';
$i = count($trace);
while (1 < $i && (!isset($trace[--$i]['class']) || ('ReflectionMethod' === $trace[$i]['class'] || 0 === strpos($trace[$i]['class'], 'PHPUnit_')))) {
// No-op
}
if (isset($trace[$i]['object']) || isset($trace[$i]['class'])) {
$class = isset($trace[$i]['object']) ? get_class($trace[$i]['object']) : $trace[$i]['class'];
$method = $trace[$i]['function'];
if (0 !== error_reporting()) {
$group = 'unsilenced';
} elseif (0 === strpos($method, 'testLegacy')
|| 0 === strpos($method, 'provideLegacy')
|| 0 === strpos($method, 'getLegacy')
|| strpos($class, '\Legacy')
|| in_array('legacy', \PHPUnit_Util_Test::getGroups($class, $method), true)
) {
$group = 'legacy';
} else {
$group = 'remaining';
}
if ('legacy' !== $group && 'weak' !== $mode) {
$ref = &$deprecations[$group][$msg]['count'];
++$ref;
$ref = &$deprecations[$group][$msg][$class.'::'.$method];
++$ref;
}
} elseif ('weak' !== $mode) {
$ref = &$deprecations[$group][$msg]['count'];
++$ref;
}
++$deprecations[$group.'Count'];
};
$oldErrorHandler = set_error_handler($deprecationHandler);
if (null !== $oldErrorHandler) {
restore_error_handler();
if (array('PHPUnit_Util_ErrorHandler', 'handleError') === $oldErrorHandler) {
restore_error_handler();
self::register($mode);
}
} else {
self::$isRegistered = true;
if (self::hasColorSupport()) {
$colorize = function ($str, $red) {
$color = $red ? '41;37' : '43;30';
return "\x1B[{$color}m{$str}\x1B[0m";
};
} else {
$colorize = function ($str) {return $str;};
}
register_shutdown_function(function () use ($getMode, &$deprecations, $deprecationHandler, $colorize) {
$mode = $getMode();
$currErrorHandler = set_error_handler('var_dump');
restore_error_handler();
if ('weak' === $mode) {
$colorize = function ($str) {return $str;};
}
if ($currErrorHandler !== $deprecationHandler) {
echo "\n", $colorize('THE ERROR HANDLER HAS CHANGED!', true), "\n";
}
$cmp = function ($a, $b) {
return $b['count'] - $a['count'];
};
foreach (array('unsilenced', 'remaining', 'legacy', 'other') as $group) {
if ($deprecations[$group.'Count']) {
echo "\n", $colorize(sprintf('%s deprecation notices (%d)', ucfirst($group), $deprecations[$group.'Count']), 'legacy' !== $group), "\n";
uasort($deprecations[$group], $cmp);
foreach ($deprecations[$group] as $msg => $notices) {
echo "\n", rtrim($msg, '.'), ': ', $notices['count'], "x\n";
arsort($notices);
foreach ($notices as $method => $count) {
if ('count' !== $method) {
echo ' ', $count, 'x in ', preg_replace('/(.*)\\\\(.*?::.*?)$/', '$2 from $1', $method), "\n";
}
}
}
}
}
if (!empty($notices)) {
echo "\n";
}
if ('weak' !== $mode && ($deprecations['unsilenced'] || $deprecations['remaining'] || $deprecations['other'])) {
exit(1);
}
});
}
}
private static function hasColorSupport()
{
if ('\\' === DIRECTORY_SEPARATOR) {
return
0 >= version_compare('10.0.10586', PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD)
|| false !== getenv('ANSICON')
|| 'ON' === getenv('ConEmuANSI')
|| 'xterm' === getenv('TERM');
}
return defined('STDOUT') && function_exists('posix_isatty') && @posix_isatty(STDOUT);
}
}
| {
"content_hash": "0c49d39146e333b9811fdd4273b1586a",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 160,
"avg_line_length": 37.04242424242424,
"alnum_prop": 0.42277486910994766,
"repo_name": "DevKhater/YallaWebSite",
"id": "21fbc30ee68dd2cacb9877e96f7a5459b5b4fcc5",
"size": "6341",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "vendor/symfony/symfony/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3606"
},
{
"name": "Batchfile",
"bytes": "5124"
},
{
"name": "CSS",
"bytes": "216209"
},
{
"name": "HTML",
"bytes": "129116"
},
{
"name": "JavaScript",
"bytes": "539065"
},
{
"name": "Makefile",
"bytes": "5620"
},
{
"name": "PHP",
"bytes": "188837"
},
{
"name": "Python",
"bytes": "8002"
}
],
"symlink_target": ""
} |
.class public Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;
.super Ljava/lang/Object;
.source "DetailsFragmentBackgroundController.java"
# instance fields
.field mCanUseHost:Z
.field final mFragment:Landroid/support/v17/leanback/app/DetailsFragment;
.field mInitialControlVisible:Z
.field private mLastVideoFragmentForGlueHost:Landroid/app/Fragment;
.field mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
.field mVideoHelper:Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;
# virtual methods
.method public canNavigateToVideoFragment()Z
.locals 1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
if-eqz v0, :cond_0
const/4 v0, 0x1
:goto_0
return v0
:cond_0
const/4 v0, 0x0
goto :goto_0
.end method
.method createGlueHost()Landroid/support/v17/leanback/media/PlaybackGlueHost;
.locals 3
const/4 v2, 0x0
invoke-virtual {p0}, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->onCreateGlueHost()Landroid/support/v17/leanback/media/PlaybackGlueHost;
move-result-object v0
iget-boolean v1, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mInitialControlVisible:Z
if-eqz v1, :cond_0
invoke-virtual {v0, v2}, Landroid/support/v17/leanback/media/PlaybackGlueHost;->showControlsOverlay(Z)V
:goto_0
return-object v0
:cond_0
invoke-virtual {v0, v2}, Landroid/support/v17/leanback/media/PlaybackGlueHost;->hideControlsOverlay(Z)V
goto :goto_0
.end method
.method disableVideoParallax()Z
.locals 1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mVideoHelper:Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;
if-eqz v0, :cond_0
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mVideoHelper:Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;
invoke-virtual {v0}, Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;->stopParallax()V
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mVideoHelper:Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;
invoke-virtual {v0}, Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;->isVideoVisible()Z
move-result v0
return v0
:cond_0
const/4 v0, 0x0
return v0
.end method
.method public final findOrCreateVideoFragment()Landroid/app/Fragment;
.locals 1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mFragment:Landroid/support/v17/leanback/app/DetailsFragment;
invoke-virtual {v0}, Landroid/support/v17/leanback/app/DetailsFragment;->findOrCreateVideoFragment()Landroid/app/Fragment;
move-result-object v0
return-object v0
.end method
.method public onCreateGlueHost()Landroid/support/v17/leanback/media/PlaybackGlueHost;
.locals 2
new-instance v1, Landroid/support/v17/leanback/app/VideoFragmentGlueHost;
invoke-virtual {p0}, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->findOrCreateVideoFragment()Landroid/app/Fragment;
move-result-object v0
check-cast v0, Landroid/support/v17/leanback/app/VideoFragment;
invoke-direct {v1, v0}, Landroid/support/v17/leanback/app/VideoFragmentGlueHost;-><init>(Landroid/support/v17/leanback/app/VideoFragment;)V
return-object v1
.end method
.method public onCreateVideoFragment()Landroid/app/Fragment;
.locals 1
new-instance v0, Landroid/support/v17/leanback/app/VideoFragment;
invoke-direct {v0}, Landroid/support/v17/leanback/app/VideoFragment;-><init>()V
return-object v0
.end method
.method onStart()V
.locals 2
iget-boolean v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mCanUseHost:Z
if-nez v0, :cond_0
const/4 v0, 0x1
iput-boolean v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mCanUseHost:Z
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
if-eqz v0, :cond_0
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
invoke-virtual {p0}, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->createGlueHost()Landroid/support/v17/leanback/media/PlaybackGlueHost;
move-result-object v1
invoke-virtual {v0, v1}, Landroid/support/v17/leanback/media/PlaybackGlue;->setHost(Landroid/support/v17/leanback/media/PlaybackGlueHost;)V
invoke-virtual {p0}, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->findOrCreateVideoFragment()Landroid/app/Fragment;
move-result-object v0
iput-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mLastVideoFragmentForGlueHost:Landroid/app/Fragment;
:cond_0
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
if-eqz v0, :cond_1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
invoke-virtual {v0}, Landroid/support/v17/leanback/media/PlaybackGlue;->isPrepared()Z
move-result v0
if-eqz v0, :cond_1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
invoke-virtual {v0}, Landroid/support/v17/leanback/media/PlaybackGlue;->play()V
:cond_1
return-void
.end method
.method onStop()V
.locals 1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
if-eqz v0, :cond_0
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mPlaybackGlue:Landroid/support/v17/leanback/media/PlaybackGlue;
invoke-virtual {v0}, Landroid/support/v17/leanback/media/PlaybackGlue;->pause()V
:cond_0
return-void
.end method
.method switchToVideoBeforeCreate()V
.locals 2
const/4 v1, 0x1
iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mVideoHelper:Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;
invoke-virtual {v0, v1, v1}, Landroid/support/v17/leanback/app/DetailsBackgroundVideoHelper;->crossFadeBackgroundToVideo(ZZ)V
iput-boolean v1, p0, Landroid/support/v17/leanback/app/DetailsFragmentBackgroundController;->mInitialControlVisible:Z
return-void
.end method
| {
"content_hash": "aafda9b72c5954e57e23ae3a5f9fff75",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 172,
"avg_line_length": 34.48768472906404,
"alnum_prop": 0.7821739751464076,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "02d7c6296abe5e8b2543e07da861adb3982e793f",
"size": "7001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SystemUI/smali/android/support/v17/leanback/app/DetailsFragmentBackgroundController.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
require 'spree_core'
require 'spree_products_tags_hooks'
module SpreeProductsTags
class Engine < Rails::Engine
config.autoload_paths += %W(#{config.root}/lib)
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
Rails.env.production? ? require(c) : load(c)
end
end
config.to_prepare &method(:activate).to_proc
end
end
| {
"content_hash": "791f02720d1cd0b2a57d9cb002671ccc",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 85,
"avg_line_length": 23.941176470588236,
"alnum_prop": 0.6461916461916462,
"repo_name": "secoint/spree_products_tags",
"id": "a07ecb36ac5ddddad0d0d0fb80964ed48d0a5967",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/spree_products_tags.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ruby",
"bytes": "7142"
}
],
"symlink_target": ""
} |
package com.thoughtworks.go.server.service;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.SubprocessExecutionContext;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.exception.StageAlreadyBuildingException;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.TestingMaterial;
import com.thoughtworks.go.domain.materials.svn.Subversion;
import com.thoughtworks.go.domain.materials.svn.SvnCommand;
import com.thoughtworks.go.fixture.PipelineWithTwoStages;
import com.thoughtworks.go.helper.PipelineMother;
import com.thoughtworks.go.helper.PipelineScheduleQueueMatcher;
import com.thoughtworks.go.helper.StageConfigMother;
import com.thoughtworks.go.helper.SvnTestRepo;
import com.thoughtworks.go.helper.TestRepo;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.dao.PipelineDao;
import com.thoughtworks.go.server.dao.StageSqlMapDao;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.scheduling.ScheduleHelper;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.TimeProvider;
import com.thoughtworks.go.utils.Assertions;
import com.thoughtworks.go.utils.Timeout;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.File;
import java.nio.file.Path;
import static com.thoughtworks.go.helper.MaterialConfigsMother.svnMaterialConfig;
import static com.thoughtworks.go.helper.ModificationsMother.modifyOneFile;
import static com.thoughtworks.go.util.GoConfigFileHelper.env;
import static com.thoughtworks.go.util.GoConstants.DEFAULT_APPROVED_BY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {
"classpath:/applicationContext-global.xml",
"classpath:/applicationContext-dataLocalAccess.xml",
"classpath:/testPropertyConfigurer.xml",
"classpath:/spring-all-servlet.xml",
})
public class PipelineScheduleServiceTest {
@Autowired private ScheduleService scheduleService;
@Autowired private GoConfigDao goConfigDao;
@Autowired private GoConfigService goConfigService;
@Autowired private PipelineDao pipelineDao;
@Autowired private StageSqlMapDao stageDao;
@Autowired PipelineScheduleQueue pipelineScheduleQueue;
@Autowired PipelineService pipelineService;
@Autowired private ScheduleHelper scheduleHelper;
@Autowired private DatabaseAccessHelper dbHelper;
@Autowired private PipelineLockService pipelineLockService;
@Autowired private GoCache goCache;
@Autowired private EnvironmentConfigService environmentConfigService;
@Autowired private MaterialRepository materialRepository;
@Autowired private TransactionTemplate transactionTemplate;
@Autowired private SubprocessExecutionContext subprocessExecutionContext;
@Autowired private InstanceFactory instanceFactory;
@Autowired private AgentService agentService;
private PipelineWithTwoStages pipelineWithTwoStages;
private PipelineConfig mingleConfig;
private PipelineConfig evolveConfig;
private String md5 = "md5-test";
private static final String STAGE_NAME = "dev";
private GoConfigFileHelper configHelper;
public Subversion repository;
public static TestRepo testRepo;
private PipelineConfig goConfig;
@BeforeEach
public void setup(@TempDir Path tempDir) throws Exception {
configHelper = new GoConfigFileHelper();
configHelper.usingCruiseConfigDao(goConfigDao);
configHelper.onSetUp();
testRepo = new SvnTestRepo(tempDir);
dbHelper.onSetUp();
repository = new SvnCommand(null, testRepo.projectRepositoryUrl());
mingleConfig = configHelper.addPipeline("mingle", STAGE_NAME, repository, "unit", "functional");
goConfig = configHelper.addPipeline("go", STAGE_NAME, repository, "unit");
StageConfig ftStageConfig = StageConfigMother.custom("ft", "twist");
ftStageConfig.jobConfigByConfigName(new CaseInsensitiveString("twist")).addVariable("JOB_LVL", "job value");
ftStageConfig.setVariables(env("STAGE_LVL", "stage value"));
configHelper.addStageToPipeline("go", ftStageConfig);
configHelper.addEnvironmentVariableToPipeline("go", env("PIPELINE_LVL", "pipeline value"));
configHelper.addEnvironments("uat");
EnvironmentConfig uatEnv = configHelper.currentConfig().getEnvironments().named(new CaseInsensitiveString("uat"));
uatEnv.addPipeline(new CaseInsensitiveString("go"));
uatEnv.addEnvironmentVariable("ENV_LVL", "env value");
evolveConfig = configHelper.addPipeline("evolve", STAGE_NAME, repository, "unit");
goCache.clear();
}
@AfterEach
public void teardown() throws Exception {
if (pipelineWithTwoStages != null) {
pipelineWithTwoStages.onTearDown();
}
dbHelper.onTearDown();
pipelineScheduleQueue.clear();
testRepo.tearDown();
FileUtils.deleteQuietly(new File("pipelines"));
configHelper.onTearDown();
}
@Test
public void shouldScheduleStageAfterModifications() throws Exception {
scheduleAndCompleteInitialPipelines();
Material stubMaterial = new TestingMaterial();
mingleConfig.setMaterialConfigs(new MaterialConfigs(stubMaterial.config()));
MaterialRevisions revisions = new MaterialRevisions();
revisions.addRevision(stubMaterial, ((TestingMaterial)stubMaterial).modificationsSince(null, null, subprocessExecutionContext));
BuildCause buildCause = BuildCause.createWithModifications(revisions, "");
dbHelper.saveMaterials(buildCause.getMaterialRevisions());
Pipeline pipeline = instanceFactory.createPipelineInstance(mingleConfig, buildCause, new DefaultSchedulingContext(DEFAULT_APPROVED_BY), md5, new TimeProvider());
pipelineService.save(pipeline);
verifyMingleScheduledWithModifications();
}
@Test
public void shouldLockPipelineWhenSchedulingIt() throws Exception {
scheduleAndCompleteInitialPipelines();
configHelper.lockPipeline("mingle");
Material stubMaterial = new TestingMaterial();
mingleConfig.setMaterialConfigs(new MaterialConfigs(stubMaterial.config()));
assertThat(pipelineLockService.isLocked("mingle"), is(false));
MaterialRevisions revisions = new MaterialRevisions();
revisions.addRevision(stubMaterial, ((TestingMaterial) stubMaterial).modificationsSince(null, null, subprocessExecutionContext));
BuildCause buildCause = BuildCause.createWithModifications(revisions, "");
dbHelper.saveMaterials(buildCause.getMaterialRevisions());
Pipeline pipeline = instanceFactory.createPipelineInstance(mingleConfig, buildCause, new DefaultSchedulingContext(DEFAULT_APPROVED_BY), md5, new TimeProvider());
pipelineService.save(pipeline);
assertThat(pipelineLockService.isLocked("mingle"), is(true));
}
@Test
public void shouldScheduleJobForAllAgentsWhenToBeRunOnAllAgents() throws Exception {
configHelper.addEnvironments("dev");
Agent agentConfigWithUuid1 = new Agent("uuid1", "localhost", "127.0.0.1", "cookie1");
agentConfigWithUuid1.setEnvironments("dev");
agentService.saveOrUpdate(agentConfigWithUuid1);
agentService.saveOrUpdate(new Agent("uuid2", "localhost", "127.0.0.1", "cookie2"));
agentService.saveOrUpdate(new Agent("uuid3", "localhost", "127.0.0.1", "cookie3"));
configHelper.setRunOnAllAgents(CaseInsensitiveString.str(evolveConfig.name()), STAGE_NAME, "unit", true);
Material stubMaterial = new TestingMaterial();
evolveConfig.setMaterialConfigs(new MaterialConfigs(stubMaterial.config()));
MaterialRevisions revisions = new MaterialRevisions();
revisions.addRevision(stubMaterial, ((TestingMaterial) stubMaterial).modificationsSince(null, null, subprocessExecutionContext));
BuildCause buildCause = BuildCause.createWithModifications(revisions, "");
dbHelper.saveMaterials(buildCause.getMaterialRevisions());
Pipeline pipeline = instanceFactory.createPipelineInstance(evolveConfig, buildCause, new DefaultSchedulingContext(DEFAULT_APPROVED_BY, environmentConfigService.agentsForPipeline(evolveConfig.name())), md5,
new TimeProvider());
pipelineService.save(pipeline);
Stage instance = scheduleService.scheduleStage(pipeline, STAGE_NAME, "anyone", new ScheduleService.NewStageInstanceCreator(goConfigService),
new ScheduleService.ExceptioningErrorHandler());
JobInstances scheduledJobs = instance.getJobInstances();
assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("name", is(RunOnAllAgents.CounterBasedJobNameGenerator.appendMarker("unit", 1)))));
assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("agentUuid", is("uuid2"))));
assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("name", is(RunOnAllAgents.CounterBasedJobNameGenerator.appendMarker("unit", 2)))));
assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("agentUuid", is("uuid3"))));
assertThat(scheduledJobs.size(), is(2));
}
@Test
public void shouldScheduleMultipleJobsWhenToBeRunMultipleInstance() throws Exception {
configHelper.setRunMultipleInstance(CaseInsensitiveString.str(evolveConfig.name()), STAGE_NAME, "unit", 2);
Material stubMaterial = new TestingMaterial();
evolveConfig.setMaterialConfigs(new MaterialConfigs(stubMaterial.config()));
MaterialRevisions revisions = new MaterialRevisions();
revisions.addRevision(stubMaterial, ((TestingMaterial) stubMaterial).modificationsSince(null, null, subprocessExecutionContext));
BuildCause buildCause = BuildCause.createWithModifications(revisions, "");
dbHelper.saveMaterials(buildCause.getMaterialRevisions());
Pipeline pipeline = instanceFactory.createPipelineInstance(evolveConfig, buildCause, new DefaultSchedulingContext(DEFAULT_APPROVED_BY, environmentConfigService.agentsForPipeline(evolveConfig.name())), md5, new TimeProvider());
pipelineService.save(pipeline);
Stage instance = scheduleService.scheduleStage(pipeline, STAGE_NAME, "anyone", new ScheduleService.NewStageInstanceCreator(goConfigService), new ScheduleService.ExceptioningErrorHandler());
JobInstances scheduledJobs = instance.getJobInstances();
assertThat(scheduledJobs.size(), is(2));
assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("name", is(RunMultipleInstance.CounterBasedJobNameGenerator.appendMarker("unit", 1)))));
assertThat(scheduledJobs.toArray(), hasItemInArray(hasProperty("name", is(RunMultipleInstance.CounterBasedJobNameGenerator.appendMarker("unit", 2)))));
}
@Test
public void shouldPassEnvironmentLevelEnvironmentVariablesToJobsForNewlyScheduledStage() throws Exception {
scheduleAndCompleteInitialPipelines();
Pipeline pipeline = pipelineDao.mostRecentPipeline("go");
Stage stage = scheduleService.scheduleStage(pipeline, "ft", "anonymous", new ScheduleService.NewStageInstanceCreator(goConfigService), new ScheduleService.ExceptioningErrorHandler());
EnvironmentVariables jobVariables = stage.getJobInstances().first().getPlan().getVariables();
assertThat(jobVariables.size(), is(3)); //pipeline, stage, job, env is applied while creating work
assertThat(jobVariables, hasItem(new EnvironmentVariable("PIPELINE_LVL", "pipeline value")));
assertThat(jobVariables, hasItem(new EnvironmentVariable("STAGE_LVL", "stage value")));
assertThat(jobVariables, hasItem(new EnvironmentVariable("JOB_LVL", "job value")));
}
@Test
public void shouldLockPipelineWhenSchedulingStage() throws Exception {
scheduleAndCompleteInitialPipelines();
Pipeline pipeline = pipelineDao.mostRecentPipeline("mingle");
configHelper.lockPipeline("mingle");
assertThat(pipelineLockService.isLocked("mingle"), is(false));
scheduleService.scheduleStage(pipeline, STAGE_NAME, "anonymous", new ScheduleService.NewStageInstanceCreator(goConfigService), new ScheduleService.ExceptioningErrorHandler());
assertThat(pipelineLockService.isLocked("mingle"), is(true));
}
@Test
public void shouldForceFirstStagePlan(@TempDir Path tempDir) throws Exception {
pipelineWithTwoStages = new PipelineWithTwoStages(materialRepository, transactionTemplate, tempDir);
pipelineWithTwoStages.usingDbHelper(dbHelper).usingConfigHelper(configHelper).onSetUp();
pipelineWithTwoStages.createPipelineWithFirstStagePassedAndSecondStageRunning();
Pipeline pipeline = manualSchedule(pipelineWithTwoStages.pipelineName);
assertThat(pipeline.getFirstStage().stageState(), is(StageState.Building));
}
@Test
public void shouldForceFirstStagePlanWhenOtherStageIsRunning(@TempDir Path tempDir) throws Exception {
pipelineWithTwoStages = new PipelineWithTwoStages(materialRepository, transactionTemplate, tempDir);
pipelineWithTwoStages.usingDbHelper(dbHelper).usingConfigHelper(configHelper).onSetUp();
pipelineWithTwoStages.createPipelineWithFirstStagePassedAndSecondStageRunning();
Pipeline pipeline = manualSchedule(pipelineWithTwoStages.pipelineName);
assertThat(pipeline.getFirstStage().isActive(), is(true));
}
@Test
public void shouldForceStagePlanWithModificationsSinceLast() throws Exception {
Pipeline completedMingle = scheduleAndCompleteInitialPipelines();
pipelineDao.loadPipeline(completedMingle.getId());
TestingMaterial testingMaterial = new TestingMaterial();
mingleConfig.setMaterialConfigs(new MaterialConfigs(testingMaterial.config()));
MaterialRevisions revisions = new MaterialRevisions();
revisions.addRevision(testingMaterial, testingMaterial.modificationsSince(null, null, subprocessExecutionContext));
BuildCause buildCause = BuildCause.createManualForced(revisions, Username.ANONYMOUS);
dbHelper.saveMaterials(buildCause.getMaterialRevisions());
Pipeline forcedPipeline = instanceFactory.createPipelineInstance(mingleConfig, buildCause, new DefaultSchedulingContext(
DEFAULT_APPROVED_BY), md5, new TimeProvider());
pipelineService.save(forcedPipeline);
verifyMingleScheduledWithModifications();
}
@Test
public void shouldNotScheduleAnyNewPipelineWhenErrorHappens() throws Exception {
String stageName = "invalidStageName";
PipelineConfig invalidPipeline = configHelper.addPipelineWithInvalidMaterial("invalidPipeline", stageName);
int beforeScheduling = pipelineDao.count(CaseInsensitiveString.str(invalidPipeline.name()));
autoSchedulePipelines();
int afterScheduling = pipelineDao.count(CaseInsensitiveString.str(invalidPipeline.name()));
assertThat(beforeScheduling, is(afterScheduling));
}
@Test
public void shouldNotScheduleActivePipeline() throws Exception {
Pipeline pipeline = PipelineMother.building(mingleConfig);
pipeline = dbHelper.savePipelineWithStagesAndMaterials(pipeline);
Pipeline newPipeline = manualSchedule(CaseInsensitiveString.str(mingleConfig.name()));
assertThat(newPipeline.getId(), is(pipeline.getId()));
}
@Test
public void shouldNotScheduleBuildIfNoModification() throws Exception {
autoSchedulePipelines("mingle", "evolve");
// Get the scheduled evolve stage and complete it.
Stage evolveInstance = stageDao.mostRecentWithBuilds(CaseInsensitiveString.str(evolveConfig.name()), evolveConfig.findBy(new CaseInsensitiveString("dev")));
dbHelper.passStage(evolveInstance);
stageDao.stageStatusChanged(evolveInstance);
autoSchedulePipelines();
Stage mostRecent = stageDao.mostRecentWithBuilds(CaseInsensitiveString.str(evolveConfig.name()), evolveConfig.findBy(new CaseInsensitiveString("dev")));
assertThat(mostRecent.getId(), is(evolveInstance.getId()));
assertThat(mostRecent.getJobInstances().first().getState(), is(JobState.Completed));
}
@Test
public void shouldSaveBuildStateCorrectly() throws Exception {
PipelineConfig cruisePlan = configHelper.addPipeline("cruise", "dev", repository);
goConfigService.forceNotifyListeners();
autoSchedulePipelines("mingle", "evolve", "cruise");
Stage cruise = stageDao.mostRecentWithBuilds(CaseInsensitiveString.str(cruisePlan.name()), cruisePlan.findBy(new CaseInsensitiveString("dev")));
JobInstance instance = cruise.getJobInstances().first();
assertThat(instance.getState(), is(JobState.Scheduled));
}
@Test
public void shouldRemoveBuildCauseIfPipelineNotExist() throws Exception {
configHelper.addPipeline("cruise", "dev", repository);
goConfigService.forceNotifyListeners();
scheduleHelper.autoSchedulePipelinesWithRealMaterials("mingle", "evolve", "cruise");
Assertions.assertWillHappen(2, PipelineScheduleQueueMatcher.numberOfScheduledPipelinesIsAtLeast(pipelineScheduleQueue), Timeout.FIVE_SECONDS);
int originalSize = pipelineScheduleQueue.toBeScheduled().size();
assertThat(originalSize, greaterThan(1));
configHelper.initializeConfigFile();
goConfigService.forceNotifyListeners();
scheduleService.autoSchedulePipelinesFromRequestBuffer();
assertThat(pipelineScheduleQueue.toBeScheduled().size(), is(0));
}
@Test
public void shouldRemoveBuildCauseIfAnyExceptionIsThrown() throws Exception {
configHelper.addPipeline("cruise", "dev", repository);
goConfigService.forceNotifyListeners();
goConfigService.getCurrentConfig().pipelineConfigByName(new CaseInsensitiveString("cruise")).get(0).jobConfigByConfigName(new CaseInsensitiveString("unit")).setRunOnAllAgents(true);
scheduleHelper.autoSchedulePipelinesWithRealMaterials("cruise");
goConfigService.forceNotifyListeners();
scheduleService.autoSchedulePipelinesFromRequestBuffer();
assertThat(pipelineScheduleQueue.toBeScheduled().size(), is(0));
}
@Test
public void shouldNotThrowErrorWhenMaterialsChange() throws Exception {
configHelper.addPipeline("cruise", "dev", repository);
goConfigService.forceNotifyListeners();
scheduleHelper.autoSchedulePipelinesWithRealMaterials("mingle", "evolve", "cruise");
configHelper.replaceMaterialForPipeline("cruise", svnMaterialConfig("http://new-material", null));
goConfigService.forceNotifyListeners();
try {
scheduleService.autoSchedulePipelinesFromRequestBuffer();
} catch (Exception e) {
fail("#2520 - should not cause an error if materials have changed");
}
}
@Test
public void shouldConsumeAllBuildCausesInServerHealth() throws Exception {
pipelineScheduleQueue.schedule(new CaseInsensitiveString("mingle"), BuildCause.createManualForced(modifyOneFile(mingleConfig), Username.ANONYMOUS));
pipelineScheduleQueue.schedule(new CaseInsensitiveString("evolve"), BuildCause.createManualForced(modifyOneFile(evolveConfig), Username.ANONYMOUS));
scheduleService.autoSchedulePipelinesFromRequestBuffer();
assertThat(pipelineScheduleQueue.toBeScheduled().size(), is(0));
}
private void autoSchedulePipelines(String... pipelineNames) throws Exception {
scheduleHelper.autoSchedulePipelinesWithRealMaterials(pipelineNames);
scheduleService.autoSchedulePipelinesFromRequestBuffer();
}
private Pipeline manualSchedule(String pipelineName) throws Exception, StageAlreadyBuildingException {
scheduleHelper.manuallySchedulePipelineWithRealMaterials(pipelineName, new Username(new CaseInsensitiveString("some user name")));
scheduleService.autoSchedulePipelinesFromRequestBuffer();
return pipelineService.mostRecentFullPipelineByName(pipelineName);
}
private void assertPipelinesScheduled() {
Pipeline minglePipeline = pipelineDao.mostRecentPipeline(CaseInsensitiveString.str(mingleConfig.name()));
Stage mingleStage = minglePipeline.getFirstStage();
assertThat(mingleStage.getName(), is(STAGE_NAME));
assertThat(mingleStage.getJobInstances().size(), is(2));
JobInstance mingleJob = mingleStage.getJobInstances().first();
assertThat(mingleJob.getState(), is(JobState.Scheduled));
assertPipelineScheduled(evolveConfig);
assertPipelineScheduled(goConfig);
}
private void assertPipelineScheduled(PipelineConfig config) {
Stage evolveStage = stageDao.mostRecentWithBuilds(CaseInsensitiveString.str(config.name()), config.findBy(new CaseInsensitiveString("dev")));
assertThat(evolveStage.getName(), is("dev"));
assertThat(evolveStage.getJobInstances().size(), is(1));
assertThat(evolveStage.getJobInstances().first().getState(), is(JobState.Scheduled));
}
private void verifyMingleScheduledWithModifications() {
Pipeline scheduledPipeline = pipelineDao.mostRecentPipeline(CaseInsensitiveString.str(mingleConfig.name()));
BuildCause buildCause = scheduledPipeline.getBuildCause();
assertThat(buildCause.getMaterialRevisions().totalNumberOfModifications(), is(3));
JobInstance instance = scheduledPipeline.getFirstStage().getJobInstances().first();
assertThat(instance.getState(), is(JobState.Scheduled));
}
private Pipeline scheduleAndCompleteInitialPipelines() throws Exception {
autoSchedulePipelines("mingle", "evolve", "go");
assertPipelinesScheduled();
passFirstStage(goConfig);
return passFirstStage(mingleConfig);
}
private Pipeline passFirstStage(PipelineConfig pipelineConfig) {
Stage completedMingleStage = stageDao.mostRecentWithBuilds(CaseInsensitiveString.str(pipelineConfig.name()), pipelineConfig.findBy(new CaseInsensitiveString("dev")));
dbHelper.passStage(completedMingleStage);
dbHelper.passStage(completedMingleStage);
assertThat(completedMingleStage.getJobInstances().first().getState(), is(JobState.Completed));
Pipeline pipeline = pipelineDao.mostRecentPipeline(CaseInsensitiveString.str(pipelineConfig.name()));
return dbHelper.passPipeline(pipeline);
}
}
| {
"content_hash": "3e1b9911ff09f3052ccde5996c2ec01f",
"timestamp": "",
"source": "github",
"line_count": 438,
"max_line_length": 228,
"avg_line_length": 53.34931506849315,
"alnum_prop": 0.7613728762785125,
"repo_name": "GaneshSPatil/gocd",
"id": "69ce4b88c547936de9ad07a2f98a446626de1263",
"size": "23968",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/test-integration/java/com/thoughtworks/go/server/service/PipelineScheduleServiceTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "466"
},
{
"name": "CSS",
"bytes": "1578"
},
{
"name": "EJS",
"bytes": "1626"
},
{
"name": "FreeMarker",
"bytes": "10183"
},
{
"name": "Groovy",
"bytes": "2467987"
},
{
"name": "HTML",
"bytes": "330937"
},
{
"name": "Java",
"bytes": "21404638"
},
{
"name": "JavaScript",
"bytes": "2331039"
},
{
"name": "NSIS",
"bytes": "23525"
},
{
"name": "PowerShell",
"bytes": "664"
},
{
"name": "Ruby",
"bytes": "623850"
},
{
"name": "SCSS",
"bytes": "820788"
},
{
"name": "Sass",
"bytes": "21277"
},
{
"name": "Shell",
"bytes": "169730"
},
{
"name": "TypeScript",
"bytes": "4428865"
},
{
"name": "XSLT",
"bytes": "207072"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE758_Undefined_Behavior__wchar_t_pointer_malloc_use_13.c
Label Definition File: CWE758_Undefined_Behavior.alloc.label.xml
Template File: point-flaw-13.tmpl.c
*/
/*
* @description
* CWE: 758 Undefined Behavior
* Sinks: malloc_use
* GoodSink: Initialize then use data
* BadSink : Use data from malloc without initialization
* Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE758_Undefined_Behavior__wchar_t_pointer_malloc_use_13_bad()
{
if(GLOBAL_CONST_FIVE==5)
{
{
wchar_t * * pointer = (wchar_t * *)malloc(sizeof(wchar_t *));
if (pointer == NULL) {exit(-1);}
wchar_t * data = *pointer; /* FLAW: the value pointed to by pointer is undefined */
free(pointer);
printWLine(data);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good1() uses if(GLOBAL_CONST_FIVE!=5) instead of if(GLOBAL_CONST_FIVE==5) */
static void good1()
{
if(GLOBAL_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
wchar_t * data;
wchar_t * * pointer = (wchar_t * *)malloc(sizeof(wchar_t *));
if (pointer == NULL) {exit(-1);}
data = L"string";
*pointer = data; /* FIX: Assign a value to the thing pointed to by pointer */
{
wchar_t * data = *pointer;
printWLine(data);
}
free(pointer);
}
}
}
/* good2() reverses the bodies in the if statement */
static void good2()
{
if(GLOBAL_CONST_FIVE==5)
{
{
wchar_t * data;
wchar_t * * pointer = (wchar_t * *)malloc(sizeof(wchar_t *));
if (pointer == NULL) {exit(-1);}
data = L"string";
*pointer = data; /* FIX: Assign a value to the thing pointed to by pointer */
{
wchar_t * data = *pointer;
printWLine(data);
}
free(pointer);
}
}
}
void CWE758_Undefined_Behavior__wchar_t_pointer_malloc_use_13_good()
{
good1();
good2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE758_Undefined_Behavior__wchar_t_pointer_malloc_use_13_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE758_Undefined_Behavior__wchar_t_pointer_malloc_use_13_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "ebe3d2f7d78e908a96c89177627fb535",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 95,
"avg_line_length": 28.078260869565216,
"alnum_prop": 0.5620935274078662,
"repo_name": "JianpingZeng/xcc",
"id": "0a25e9b29b722908d8d2ead5c8719a13ff8f203f",
"size": "3229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE758_Undefined_Behavior/CWE758_Undefined_Behavior__wchar_t_pointer_malloc_use_13.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""
Oblique Mercator
================
Oblique configurations of the cylinder give rise to the oblique Mercator
projection. It is particularly useful when mapping regions of large lateral
extent in an oblique direction. Both parallels and meridians are complex
curves. The projection was developed in the early 1900s by several workers.
**ob**\|\ **oB**\ *lon0/lat0/lon1/lat1/scale*\ [**+v**] or
**Ob**\|\ **OB**\ *lon0/lat0/lon1/lat1/width*\ [**+v**]
The projection is set with **o** or **O**. The pole is set in the
northern hemisphere with **b** or the southern hemisphere
with **B**. The central meridian is set by *lon0/lat0*. The oblique
equator is set by *lon1/lat1*. Align the y-axis
with the optional **+v**. The figure size is set with *scale* or *width*.
"""
import pygmt
fig = pygmt.Figure()
# Using the origin and two points
fig.coast(
projection="Ob130/35/25/35/6c",
# Set bottom left and top right coordinates of the figure with "+r"
region="130/35/145/40+r",
frame="afg",
land="gray",
shorelines="1/thin",
water="lightblue",
)
fig.show()
| {
"content_hash": "00e41cd522f57050554130374c320fc2",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 75,
"avg_line_length": 34,
"alnum_prop": 0.6819852941176471,
"repo_name": "GenericMappingTools/gmt-python",
"id": "afe889863b683f772e39f47e0d2b00d6e0f94334",
"size": "1088",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/projections/cyl/cyl_oblique_mercator_2.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "1357"
},
{
"name": "Python",
"bytes": "292740"
},
{
"name": "Shell",
"bytes": "357"
}
],
"symlink_target": ""
} |
namespace ict {
// output string string with 80% functionality and 20X performance over
// std::ostringstream, and easier to spell.
struct osstream {
osstream() {}
osstream(const std::string &s) : x(s) {}
osstream(const osstream &) = delete;
osstream &operator=(const osstream &) = delete;
std::string x;
// Copy the current string
std::string str() const { return x; }
// Move the internal string to avoid copying. The stream is in an undefined
// state after this. It is meant to be the last thing you do. Call clear()
// after this if you want to use the string again.
std::string &&take() { return std::move(x); }
void clear() { x.clear(); }
};
// One weird trick to make sure there are no implicit conversions.
template <typename T> inline osstream &operator<<(osstream &os, T x) = delete;
namespace util {
template <typename S, typename T> S &append(S &os, const T &x) {
os.x += x;
return os;
}
template <typename S, typename T> S &append_number(S &os, const T &x) {
os.x += std::to_string(x);
return os;
}
} // namespace util
inline osstream &operator<<(osstream &os, char x) {
return util::append(os, x);
}
inline osstream &operator<<(osstream &os, const std::string &x) {
return util::append(os, x);
}
inline osstream &operator<<(osstream &os, const char *x) {
return util::append(os, x);
}
inline osstream &operator<<(osstream &os, int x) {
return util::append_number(os, x);
}
inline osstream &operator<<(osstream &os, unsigned long int x) {
return util::append_number(os, x);
}
inline osstream &operator<<(osstream &os, long int x) {
return util::append_number(os, x);
}
inline osstream &operator<<(osstream &os, long long x) {
return util::append_number(os, x);
}
#ifdef WIN32
inline osstream &operator<<(osstream &os, size_t x) {
return util::append_number(os, x);
}
#endif
} // namespace ict
| {
"content_hash": "628d7af6781e0c401ddf7d48fd207cc5",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 80,
"avg_line_length": 31.327868852459016,
"alnum_prop": 0.6572475143903715,
"repo_name": "intrig/ict",
"id": "e458b3cb2870c3c469db11abba2af5445484ad06",
"size": "1943",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "osstream.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "705"
},
{
"name": "C",
"bytes": "328"
},
{
"name": "C++",
"bytes": "196914"
},
{
"name": "CMake",
"bytes": "2018"
},
{
"name": "Makefile",
"bytes": "868"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Templating\Loader;
use Symfony\Component\Templating\Storage\Storage;
use Symfony\Component\Templating\Storage\FileStorage;
use Symfony\Component\Templating\TemplateReferenceInterface;
/**
* CacheLoader is a loader that caches other loaders responses
* on the filesystem.
*
* This cache only caches on disk to allow PHP accelerators to cache the opcodes.
* All other mechanism would imply the use of `eval()`.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class CacheLoader extends Loader {
protected $loader;
protected $dir;
/**
* Constructor.
*
* @param LoaderInterface $loader A Loader instance
* @param string $dir The directory where to store the cache files
*/
public function __construct(LoaderInterface $loader, $dir) {
$this->loader = $loader;
$this->dir = $dir;
}
/**
* Loads a template.
*
* @param TemplateReferenceInterface $template A template
*
* @return Storage|Boolean false if the template cannot be loaded, a Storage instance otherwise
*/
public function load(TemplateReferenceInterface $template) {
$key = md5($template->getLogicalName());
$dir = $this->dir . DIRECTORY_SEPARATOR . substr($key, 0, 2);
$file = substr($key, 2) . '.tpl';
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($path)) {
if (null !== $this->debugger) {
$this->debugger->log(sprintf('Fetching template "%s" from cache', $template->get('name')));
}
return new FileStorage($path);
}
if (false === $storage = $this->loader->load($template)) {
return false;
}
$content = $storage->getContent();
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($path, $content);
if (null !== $this->debugger) {
$this->debugger->log(sprintf('Storing template "%s" in cache', $template->get('name')));
}
return new FileStorage($path);
}
/**
* Returns true if the template is still fresh.
*
* @param TemplateReferenceInterface $template A template
* @param integer $time The last modification time of the cached template (timestamp)
*/
public function isFresh(TemplateReferenceInterface $template, $time) {
return $this->loader->isFresh($template, $time);
}
}
| {
"content_hash": "e4532983458154a75ab66065e7f7fa40",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 109,
"avg_line_length": 26.916666666666668,
"alnum_prop": 0.6753648827952233,
"repo_name": "flyingfeet/FlyingFeet",
"id": "1a23541601994ba3bfb81aab3d14dcb1e856ebff",
"size": "2490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/symfony/src/Symfony/Component/Templating/Loader/CacheLoader.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "18506"
},
{
"name": "PHP",
"bytes": "48999"
},
{
"name": "Shell",
"bytes": "192"
}
],
"symlink_target": ""
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PingMessageHandler.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Message handler for the <see cref="PingMessage" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Messaging.Ping
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Kephas.Messaging.Server;
/// <summary>
/// Message handler for the <see cref="PingMessage"/>.
/// </summary>
public class PingMessageHandler : MessageHandlerBase<PingMessage, PingBackMessage>
{
/// <summary>
/// Processes the provided message asynchronously and returns a response promise.
/// </summary>
/// <param name="message">The message to be handled.</param>
/// <param name="context">The processing context.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>
/// The response promise.
/// </returns>
public override Task<PingBackMessage> ProcessAsync(PingMessage message, IMessageProcessingContext context, CancellationToken token)
{
return Task.FromResult(new PingBackMessage { ServerTime = DateTimeOffset.Now });
}
}
} | {
"content_hash": "02f49c00dc4c14118924970aac4f2fba",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 139,
"avg_line_length": 40.270270270270274,
"alnum_prop": 0.5463087248322148,
"repo_name": "raimu/kephas",
"id": "538c09dab29ff37c0aab5247b7eabb1434c233ec",
"size": "1492",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Kephas.Messaging/Ping/PingMessageHandler.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4489"
},
{
"name": "C#",
"bytes": "1537848"
}
],
"symlink_target": ""
} |
from astropy.io.misc.asdf.types import AstropyAsdfType
from astropy.units import Unit, UnitBase
class UnitType(AstropyAsdfType):
name = 'unit/unit'
types = ['astropy.units.UnitBase']
requires = ['astropy']
@classmethod
def to_tree(cls, node, ctx):
if isinstance(node, str):
node = Unit(node, format='vounit', parse_strict='warn')
if isinstance(node, UnitBase):
return node.to_string(format='vounit')
raise TypeError(f"'{node}' is not a valid unit")
@classmethod
def from_tree(cls, node, ctx):
return Unit(node, format='vounit', parse_strict='silent')
| {
"content_hash": "fbb7cfaf39cdd690e7c1d9cdc81411a9",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 67,
"avg_line_length": 31.95,
"alnum_prop": 0.6447574334898278,
"repo_name": "larrybradley/astropy",
"id": "3a2a98d6781e756f47fdaf2daff01d8ebe26f0f1",
"size": "703",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "astropy/io/misc/asdf/tags/unit/unit.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "11040101"
},
{
"name": "C++",
"bytes": "47001"
},
{
"name": "Cython",
"bytes": "78755"
},
{
"name": "HTML",
"bytes": "1172"
},
{
"name": "Lex",
"bytes": "183333"
},
{
"name": "M4",
"bytes": "18757"
},
{
"name": "Makefile",
"bytes": "52508"
},
{
"name": "Python",
"bytes": "12335716"
},
{
"name": "Shell",
"bytes": "17024"
},
{
"name": "TeX",
"bytes": "853"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JSIL;
using JSIL.Ast;
using Mono.Cecil;
namespace WasmSExprEmitter {
public abstract class SExpression : JSExpression {
public readonly string Keyword;
public bool LineBreakAfter, LineBreakInside;
public SExpression (string keyword, params JSExpression[] values)
: base (values) {
Keyword = keyword;
}
internal virtual void BeforeWriteValues (AstEmitter astEmitter) {
}
internal virtual void AfterWriteValues (AstEmitter astEmitter) {
}
public override string ToString () {
return string.Format("({0} {1})", Keyword, string.Join<JSExpression>(", ", Values));
}
}
public class AbstractSExpression : SExpression {
public readonly TypeReference Type;
private readonly bool _IsConstant;
public readonly bool IsConstantIfArgumentsAre;
private readonly bool _HasGlobalStateDependency;
public AbstractSExpression (
string keyword, TypeReference type, JSExpression[] values,
bool isConstant = false, bool isConstantIfArgumentsAre = false,
bool hasGlobalStateDependency = false,
bool lineBreakAfter = false, bool lineBreakInside = false
) : base (keyword, values) {
Type = type;
_IsConstant = isConstant;
IsConstantIfArgumentsAre = isConstantIfArgumentsAre;
_HasGlobalStateDependency = hasGlobalStateDependency;
LineBreakAfter = lineBreakAfter;
LineBreakInside = lineBreakInside;
}
public override bool HasGlobalStateDependency {
get {
return _HasGlobalStateDependency;
}
}
public override bool IsConstant {
get {
if (_IsConstant)
return true;
if (IsConstantIfArgumentsAre && Values.All(v => v.IsConstant))
return true;
return false;
}
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return Type;
}
public override bool IsLValue {
get {
return false;
}
}
}
public class GetMemory : SExpression {
public readonly TypeReference Type;
public readonly bool IsAligned;
public GetMemory (
TypeReference type, bool isAligned,
JSExpression addressInBytes
) : base (
string.Format(
"{0}.load/{1}{2}",
WasmUtil.PickTypeKeyword(type),
WasmUtil.PickMemoryTypeKeyword(type),
isAligned
? ""
: "/1"
),
addressInBytes
) {
Type = type;
IsAligned = isAligned;
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return Type;
}
public override bool HasGlobalStateDependency {
get {
return true;
}
}
public override bool IsConstant {
get {
return false;
}
}
}
public class SetMemory : SExpression {
public readonly TypeReference Type;
public readonly bool IsAligned;
public SetMemory (
TypeReference type, bool isAligned,
JSExpression addressInBytes, JSExpression value
) : base (
string.Format(
"{0}.store/{1}{2}",
WasmUtil.PickTypeKeyword(type),
WasmUtil.PickMemoryTypeKeyword(type),
isAligned
? ""
: "/1"
),
addressInBytes, value
) {
Type = type;
IsAligned = isAligned;
LineBreakInside = true;
LineBreakAfter = true;
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return Type;
}
public override bool HasGlobalStateDependency {
get {
return true;
}
}
public override bool IsConstant {
get {
return false;
}
}
}
public class InvokeExport : SExpression {
public readonly string ExportedFunctionName;
public InvokeExport (string exportedFunctionName, JSExpression[] arguments)
: base ("invoke", arguments) {
ExportedFunctionName = exportedFunctionName;
}
internal override void BeforeWriteValues (AstEmitter astEmitter) {
astEmitter.Formatter.Value(ExportedFunctionName);
astEmitter.Formatter.Space();
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return typeSystem.Object;
}
}
public class AssertEq : SExpression {
public readonly string ExportedFunctionName;
public AssertEq (JSExpression expected, string exportedFunctionName, JSExpression[] arguments)
: base (
"assert_eq",
(new[] { expected }).Concat(arguments).ToArray()
) {
ExportedFunctionName = exportedFunctionName;
}
public JSExpression Expected {
get {
return Values[0];
}
}
public IEnumerable<JSExpression> Arguments {
get {
return Values.Skip(1);
}
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return typeSystem.Void;
}
}
public class AssertHeapEq : SExpression {
public readonly int Offset;
public readonly string Expected;
public AssertHeapEq (int offset, string expected)
: base (
"assert_heap_eq"
) {
Offset = offset;
Expected = expected;
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return typeSystem.Void;
}
}
public class GetStringLength : JSExpression {
public GetStringLength (JSExpression str)
: base(str) {
}
public JSExpression String {
get {
return Values[0];
}
}
public override TypeReference GetActualType (TypeSystem typeSystem) {
return typeSystem.Int32;
}
}
}
| {
"content_hash": "b20fa02c3357de2f5f41b731110ff2c2",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 102,
"avg_line_length": 27.74380165289256,
"alnum_prop": 0.548704200178731,
"repo_name": "Acidburn0zzz/ilwasm",
"id": "ea1c5343e05cc71bb5b6e83c2607db4167cedfa6",
"size": "6716",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WasmSExprEmitter/CustomNodes.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "100"
},
{
"name": "C#",
"bytes": "86891"
},
{
"name": "Python",
"bytes": "3471"
},
{
"name": "Shell",
"bytes": "525"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>District of Columbia | Is Lyft In</title>
<meta name="description" content="Find out where you can get a Lyft ride in District of Columbia.">
<meta property="og:title" content="District of Columbia | Is Lyft In" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://islyftin.com/sistrictofcolumbia " />
<meta property="og:image" content="img/logo.png" />
<meta property="og:description" content="Find out where you can get a Lyft ride in District of Columbia." />
<!-- Logo in Tab -->
<link rel="shortcut icon" href="img/logo.png">
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/islyftin.css" rel="stylesheet">
<!-- Bootstrap Button Pack -->
<link href="css/buttons.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome-4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-TD94C5 "height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f) ;})(window,document,'script','dataLayer','GTM-TD94C5');</script>
<!-- End Google Tag Manager -->
<!-- Navigation -->
<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand page-scroll" href="index.html"><img src="img/logo.png" style="width:101px;height:34px"></a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<i class="fa fa-bars"></i>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-right navbar-main-collapse">
<ul class="nav navbar-nav">
<!-- Hidden li included to remove active class from about link when scrolled up past about section -->
<li class="hidden">
<a href="#page-top"></a>
</li>
<li>
<a class="page-scroll" href="#cities">Cities</a>
</li>
<li>
<a class="page-scroll" href="#download">Download</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Intro Header -->
<header class="intro">
<div class="intro-body">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="brand-heading">Is Lyft In</h1>
<p class="intro-text">Lyft is Available in District of Columbia!<br>Click below to see the cities</p>
<a href="#cities" class="btn btn-circle page-scroll">
<i class="fa fa-angle-double-down animated"></i>
</a>
</div>
</div>
</div>
</div>
</header>
<!-- State Section -->
<section id="cities" class="container content-section text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h2>Cities</h2>
</div>
</div>
<!-- City Button -->
<div class="text-center">
<a href="districtofcolumbia/washington"><button type="button" class="btn btn-default outline">Washington D.C.</button></a>
</div>
<!-- Download Section -->
<section id="download" class="content-section text-center">
<div class="download-section">
<div class="container">
<div class="col-lg-8 col-lg-offset-2">
<h2>Download</h2>
<p>You can download Lyft for free</p>
<a target="_blank" href="https://www.lyft.com/invited/AKHIL23" class="btn btn-primary btn-info"><span class="glyphicon glyphicon-arrow-down"></span> Download Now</a>
</a>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer>
<div class="container text-center">
<p>Copyright © Is Lyft In 2014</p>
</div>
</footer>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="js/islyftin.js"></script>
</body>
</html>
| {
"content_hash": "4c9828e1fc9b7b9e243064a0deac84dd",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 352,
"avg_line_length": 40.86330935251799,
"alnum_prop": 0.5491197183098592,
"repo_name": "gmultani12/is_lyft_in",
"id": "1c34d6ff56dfc8308514fe05d65d5c7434eba5ca",
"size": "5680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "districtofcolumbia.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "235"
},
{
"name": "CSS",
"bytes": "142692"
},
{
"name": "HTML",
"bytes": "530992"
},
{
"name": "JavaScript",
"bytes": "5355"
}
],
"symlink_target": ""
} |
class Player;
class RandomPlayer : public PlayerInput
{
public:
RandomPlayer(bool writeResult=false);
virtual ~RandomPlayer();
// PlayerInput interface
public slots:
virtual void attachPlayer(Player* p);
void onGameEnded(IORequest* ir);
void onEventTriggered(IORequest* ir);
void askForAction(IORequest* ir);
void askForPosition(IORequest* ir);
void askForTarget(IORequest* ir);
private:
Player* mMe;
bool mWriteResults;
};
#endif // RANDOMPLAYER_H
| {
"content_hash": "27927e9aafe8129da835f730a3e72a79",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 41,
"avg_line_length": 20.75,
"alnum_prop": 0.7108433734939759,
"repo_name": "dtaralla/hearthstone",
"id": "c128684fb90a283840a80e6e546d9e24e43a05b8",
"size": "571",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hsdemo/inputs/randomplayer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3460"
},
{
"name": "C",
"bytes": "964"
},
{
"name": "C++",
"bytes": "445594"
},
{
"name": "Python",
"bytes": "38668"
},
{
"name": "QMake",
"bytes": "6638"
}
],
"symlink_target": ""
} |
package net.dsys.snio.api.codec;
import java.nio.ByteBuffer;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
/**
* Interface definition for framing and delimitation of messages.
*
* @author Ricardo Padilha
*/
public interface MessageCodec {
/**
* @return maximum length of the message header
*/
@Nonnegative
int getHeaderLength();
/**
* @return maximum length of the message body
*/
@Nonnegative
int getBodyLength();
/**
* @return maximum length of the message footer
*/
@Nonnegative
int getFooterLength();
/**
* @return maximum frame length
*/
@Nonnegative
int getFrameLength();
/**
* @return the length of the given {@link ByteBuffer} after encoding
*/
@Nonnegative
int getEncodedLength(@Nonnull ByteBuffer out);
/**
* @return <code>true</code> if the {@link ByteBuffer} fits in a frame
* @throws InvalidLengthException
* if the message body is longer than {@link #getBodyLength()}
*/
boolean isValid(@Nonnull ByteBuffer out);
/**
* @param in
* {@link ByteBuffer} containing the message body
* @param out
* {@link ByteBuffer} where the message will be placed
*/
void put(@Nonnull ByteBuffer in, @Nonnull ByteBuffer out) throws InvalidMessageException;
/**
* @return <code>true</code> if there is a frame inside that
* {@link ByteBuffer}
* @throws InvalidLengthException
* if the length encoded in the stream invalid.
*/
boolean hasNext(@Nonnull ByteBuffer in) throws InvalidEncodingException;
/**
* Only call after {@link #hasNext(ByteBuffer)} returns <code>true</code>.
*
* @return the length of the given {@link ByteBuffer} after decoding
*/
@Nonnegative
int getDecodedLength(@Nonnull ByteBuffer in);
/**
* @param in
* {@link ByteBuffer} containing the stream from the channel
* @param out
* {@link ByteBuffer} where the message body will be placed
*/
void get(@Nonnull ByteBuffer in, @Nonnull ByteBuffer out) throws InvalidEncodingException;
/**
* Close this codec, releasing any resources.
*/
void close();
}
| {
"content_hash": "30a5a7eb36c8b8f0f1bf850c52ad56f8",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 91,
"avg_line_length": 23.45054945054945,
"alnum_prop": 0.6785379568884724,
"repo_name": "ricardopadilha/dsys-snio",
"id": "e06526ce4bc5c7664dbade4a618837505349a241",
"size": "2733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/dsys/snio/api/codec/MessageCodec.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "423547"
}
],
"symlink_target": ""
} |
layout: resource
category: news
external_url: 'http://www.takepart.com/article/2015/04/14/open-source-mapping-ebola'
title: Crowdsourced Mapping Could Help Prevent the Next Big Ebola Outbreak
publication: TakePart
author: Jessica Dollin
date: 20150414
mapgive_is_author: no
explicit_mention: yes
type: news
photo: '../assets/img/crowdsourced_maps_medium.jpg'
video:
featured: yes
quote:
tags:
- insert here
---
| {
"content_hash": "a32a4110e9f20518d810d5c513913158",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 84,
"avg_line_length": 25.294117647058822,
"alnum_prop": 0.7488372093023256,
"repo_name": "d3netxer/Mapgive",
"id": "8ee27df0d7b24b3ff74f226b65e3000432433629",
"size": "435",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "_posts/news/2015-04-14-TakePart.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "336647"
},
{
"name": "HTML",
"bytes": "1204995"
},
{
"name": "JavaScript",
"bytes": "710924"
},
{
"name": "Ruby",
"bytes": "6352"
},
{
"name": "Shell",
"bytes": "152"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reace 02</title>
<script src="../lib/react.js"></script>
<script src="../lib/react-dom.js"></script>
<script src="../lib/babel-core/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
var Timer = React.createClass({
getInitialState: function() {
//console.log('init');
return { sec: 0 };
},
componentDidMount: function() {
//console.log('Compoennt Mount');
this.interval = setInterval((function(){
this.setState({
sec: this.state.sec + 1
});
}).bind(this), 1000);
},
componentWillUnmount: function() {
//console.log('Compoennt unMount');
},
render: function() {
//console.log('render');
return (
<div>Ticker: { this.state.sec }</div>
);
}
});
ReactDOM.render(<Timer />, document.querySelector('#example'));
</script>
</body>
</html> | {
"content_hash": "0917ba34c66b6a9baf713e3bf73eecfc",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 67,
"avg_line_length": 25.6,
"alnum_prop": 0.5380859375,
"repo_name": "tangsj/cc-learning",
"id": "e707cac0ec447a0fd5de597d7e7289aff614f0ff",
"size": "1024",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reactjs/02/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "649"
},
{
"name": "CSS",
"bytes": "18258"
},
{
"name": "Dockerfile",
"bytes": "355"
},
{
"name": "HTML",
"bytes": "149828"
},
{
"name": "JavaScript",
"bytes": "2411169"
},
{
"name": "Objective-C",
"bytes": "53351"
},
{
"name": "Python",
"bytes": "1758"
},
{
"name": "Ruby",
"bytes": "1600"
},
{
"name": "Vue",
"bytes": "791"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="NamedScopeManager">
<order />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="PropertiesComponent">
<property name="settings.editor.selected.configurable" value="preferences.sourceCode" />
<property name="settings.editor.splitter.proportion" value="0.2" />
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<created>1451389495028</created>
<option name="number" value="Default" />
<updated>1451389495028</updated>
</task>
<servers />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
<watches-manager />
</component>
</project> | {
"content_hash": "69230f84c23e0e12f84a0a50368b3ffc",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 92,
"avg_line_length": 40.40425531914894,
"alnum_prop": 0.684044233807267,
"repo_name": "ch710798472/GithubRecommended",
"id": "1f3bdd217c03f798c393bd4440e704fc7dc72e53",
"size": "1899",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/bootstrap/.idea/workspace.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "18"
},
{
"name": "HTML",
"bytes": "54544"
},
{
"name": "Jupyter Notebook",
"bytes": "210681"
},
{
"name": "Python",
"bytes": "48032"
}
],
"symlink_target": ""
} |
using System;
using System.Threading.Tasks;
using LeanCloud.Core.Internal;
using Foundation;
namespace LeanCloud.Push.Internal {
/// <summary>
/// This is a concrete implementation of IDeviceInfoController.
/// Everything is implemented to be a no-op, as an installation
/// on portable targets can't be used for push notifications.
/// </summary>
public class DeviceInfoController : IDeviceInfoController {
public string DeviceType {
get { return "ios"; }
}
public string DeviceTimeZone {
get {
NSTimeZone.ResetSystemTimeZone();
return NSTimeZone.SystemTimeZone.Name;
}
}
public string AppBuildVersion {
get { return GetAppAttribute("CFBundleVersion"); }
}
public string AppIdentifier {
get { return GetAppAttribute("CFBundleIdentifier"); }
}
public string AppName {
get { return GetAppAttribute("CFBundleDisplayName"); }
}
public Task ExecuteParseInstallationSaveHookAsync(AVInstallation installation) {
return Task.Run(() => {
installation.SetIfDifferent("badge", installation.Badge);
});
}
public void Initialize() {
}
/// <summary>
/// Gets an attribute from the Info.plist.
/// </summary>
/// <param name="attributeName">the attribute name</param>
/// <returns>the attribute value</returns>
/// This is a duplicate of what we have in AVInstallation. We do it because
/// it's easier to maintain this way (rather than referencing <c>PlatformHooks</c> everywhere).
private string GetAppAttribute(string attributeName) {
var appAttributes = NSBundle.MainBundle;
var attribute = appAttributes.ObjectForInfoDictionary(attributeName);
return attribute == null ? null : attribute.ToString();
}
}
}
| {
"content_hash": "b7fa96101cfd6e69c8786d7af5e77173",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 99,
"avg_line_length": 30.54237288135593,
"alnum_prop": 0.6798002219755827,
"repo_name": "wujun4code/Parse-SDK-dotNET",
"id": "c607d3f6704a9c5d20fedd1a0416a17e9bb0a268",
"size": "1802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LeanCloud.Push/Internal/DeviceInfo/iOS/DeviceInfoController.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "1250996"
},
{
"name": "Java",
"bytes": "26623"
},
{
"name": "Visual Basic",
"bytes": "36080"
}
],
"symlink_target": ""
} |
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 310, height: 530});
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
});
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here. | {
"content_hash": "682e03435513a8a954e56a4130703025",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 78,
"avg_line_length": 32.21666666666667,
"alnum_prop": 0.7040869115364718,
"repo_name": "TheGum/Lo6",
"id": "a5095071d256c1b83dd7c8d2823f523b67fd0d63",
"size": "1933",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "9"
},
{
"name": "CSS",
"bytes": "9621"
},
{
"name": "HTML",
"bytes": "3107"
},
{
"name": "JavaScript",
"bytes": "17778"
},
{
"name": "Visual Basic",
"bytes": "152"
}
],
"symlink_target": ""
} |
package ch.wsl.box.model.boxentities
import ch.wsl.box.jdbc.PostgresProfile.api._
import slick.model.ForeignKeyAction
import slick.collection.heterogeneous._
import slick.collection.heterogeneous.syntax._
/**
* Created by andre on 5/15/2017.
*/
object BoxLabels {
val profile = ch.wsl.box.jdbc.PostgresProfile
import profile._
case class BoxLabels_row(lang: String, key:String, label: Option[String] = None)
class BoxLabels(_tableTag: Tag) extends profile.api.Table[BoxLabels_row](_tableTag,BoxSchema.schema, "labels") {
def * = (lang, key, label) <> (BoxLabels_row.tupled, BoxLabels_row.unapply)
/** Maps whole row to an option. Useful for outer joins. */
val lang: Rep[String] = column[String]("lang")
val key: Rep[String] = column[String]("key")
val label: Rep[Option[String]] = column[Option[String]]("label", O.Default(None))
lazy val pk = primaryKey("labels_pk",(lang,key))
}
/** Collection-like TableQuery object for table Form */
lazy val BoxLabelsTable = new TableQuery(tag => new BoxLabels(tag))
}
| {
"content_hash": "69e0713b6c3d9ea3dc8dc6a9e83d924c",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 114,
"avg_line_length": 28.756756756756758,
"alnum_prop": 0.7058270676691729,
"repo_name": "Insubric/box",
"id": "afa6a2b2dc2f259a608283baab00ab8bfeb8768f",
"size": "1064",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/main/scala/ch/wsl/box/model/boxentities/BoxLabels.scala",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "7784"
},
{
"name": "JavaScript",
"bytes": "4223"
},
{
"name": "PLpgSQL",
"bytes": "98116"
},
{
"name": "Scala",
"bytes": "1481715"
}
],
"symlink_target": ""
} |
Networking part for Parse infomation App
## Installation
pod "AOInfoNetManager", :git => 'https://github.com/alekoleg/AOInfoNetManager.git'
## Author
Oleg Alekseenko, alekoleg@gmail.com
## License
| {
"content_hash": "f3fc22cbdb57468a6ba79ce5da8dae26",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 86,
"avg_line_length": 16,
"alnum_prop": 0.7355769230769231,
"repo_name": "alekoleg/AOInfoNetManager",
"id": "11f190ea9212273a12740ac38a8d3b3a9490c5fa",
"size": "243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "37012"
},
{
"name": "C++",
"bytes": "3534"
},
{
"name": "Mathematica",
"bytes": "278"
},
{
"name": "Objective-C",
"bytes": "567434"
},
{
"name": "Ruby",
"bytes": "849"
},
{
"name": "Shell",
"bytes": "3942"
}
],
"symlink_target": ""
} |
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.us.Common;
namespace OpenADK.Library.us.Instr{
/// <summary>A CreatorLearning</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
[Serializable]
public class CreatorLearning : SifKeyedElement
{
/// <summary>
/// Creates an instance of a CreatorLearning
/// </summary>
public CreatorLearning() : base ( InstrDTD.CREATORLEARNING ){}
/// <summary>
/// Constructor that accepts values for all mandatory fields
/// </summary>
///<param name="value">Gets or sets the content value of the &lt;CreatorLearning&gt; element</param>
///
public CreatorLearning( string value ) : base( InstrDTD.CREATORLEARNING )
{
this.Value = value;
}
/// <summary>
/// Constructor used by the .Net Serialization formatter
/// </summary>
[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
protected CreatorLearning( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
/// <summary>
/// Gets the metadata fields that make up the key of this object
/// </summary>
/// <value>
/// an array of metadata fields that make up the object's key
/// </value>
public override IElementDef[] KeyFields {
get { return new IElementDef[] { InstrDTD.CREATORLEARNING }; }
}
/// <summary>
/// Gets or sets the value of the <c><CreatorLearning></c> element.
/// </summary>
/// <value> The <c>Value</c> of the content of this object.</value>
/// <remarks>
/// <para>The SIF specification defines the meaning of this of the content as: "Gets or sets the content value of the &lt;CreatorLearning&gt; element"</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
public string Value
{
get
{
return (string) GetSifSimpleFieldValue( InstrDTD.CREATORLEARNING ) ;
}
set
{
SetFieldValue( InstrDTD.CREATORLEARNING, new SifString( value ), value );
}
}
/// <summary>
/// Gets or sets the value of the <c>Type</c> attribute.
/// </summary>
/// <value> The <c>Type</c> attribute of this object.</value>
/// <remarks>
/// <para>The SIF specification defines the meaning of this attribute as: "The object type of the object representing the Creator."</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
public string Type
{
get
{
return GetFieldValue( InstrDTD.CREATORLEARNING_TYPE );
}
set
{
SetField( InstrDTD.CREATORLEARNING_TYPE, value );
}
}
/// <summary>
/// Sets the value of the <c>Type</c> attribute.
/// </summary>
/// <param name="val">A TypeCreator object</param>
/// <remarks>
/// <para>The SIF specification defines the meaning of this attribute as: "The object type of the object representing the Creator."</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
public void SetType( TypeCreator val )
{
SetField( InstrDTD.CREATORLEARNING_TYPE, val );
}
/// <summary>
/// Gets or sets the value of the <c>SIF_RefId</c> attribute.
/// </summary>
/// <value> The <c>SIF_RefId</c> attribute of this object.</value>
/// <remarks>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
public string SIF_RefId
{
get
{
return (string) GetSifSimpleFieldValue( InstrDTD.CREATORLEARNING_SIF_REFID ) ;
}
set
{
SetFieldValue( InstrDTD.CREATORLEARNING_SIF_REFID, new SifString( value ), value );
}
}
}}
| {
"content_hash": "446dadaf2715c932ab85c3a7e3ff9b54",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 166,
"avg_line_length": 28.5748031496063,
"alnum_prop": 0.6737393221273078,
"repo_name": "open-adk/OpenADK-csharp",
"id": "49df1e764106f2952b0ddaa388a9692523ceed0f",
"size": "3792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/us/sdo/Instr/CreatorLearning.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "16903092"
}
],
"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 appscool.model;
/**
*
* @author Abibatou
*/
public class GradeModel {
private String periode;
private int tab;
private int noteCC;
private int noteComp;
private String appreciation;
private SubjectModel subject;
//Definition des getteurs
public String getPer(){
return periode;
}
public int getTab(){//type de tab à revoir
return tab;
}
public int getNC(){
return noteCC;
}
public int getNComp(){
return noteComp;
}
public String getApp(){
return appreciation;
}
public SubjectModel getSubject(){
return subject;
}
//Definition des setteurs
public void setPer(String per){
this.periode = per;
}
public void setTab(int tab){//type de tab à revoir
this.tab = tab;
}
public void setNC(int nCC){
this.noteCC = nCC;
}
public void setNComp(int nComp){
this.noteComp = nComp;
}
public void setApp(String App){
this.appreciation = App;
}
public void setSubject(SubjectModel subj){
this.subject = subj;
}
}
| {
"content_hash": "706557a4a9bcdf42981207979f58f05f",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 79,
"avg_line_length": 21.639344262295083,
"alnum_prop": 0.6181818181818182,
"repo_name": "akdiallo/AppScool",
"id": "8bbaec1f8dc593fc1ecf4f3fa4f50cd52b4cc4d4",
"size": "1322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/appscool/model/GradeModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1863"
},
{
"name": "Java",
"bytes": "54037"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Boston CSS Accessibility Workshop</title>
<meta name="description" content="Can you find the accessibility errors?">
<meta name="author" content="Ali Areskog">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/comecorrect.css?v=1.0">
</head>
<body>
<header>
<h1>Spot the Accessibility Errors Form</h1>
<img src="../imgs/challengeAccepted.png" alt="Challenge Accepted Meme"/>
</header>
<main>
<section class="left">
<h2>Customer Information <i class="fa fa-info-circle" aria-hidden="true"></i></h2>
<form action="" method="post">
<label>First Name<input type="text"></label><!-- With or Without For is fine bc it's wrapped-->
<label>Last Name<input type="text" /></label><!-- With or Without For is fine bc it's wrapped-->
<h4 id="shipping">Shipping Address</h4>
<label id="street1" name="shipping">Street</label>
<input type="text" aria-labelledby="shipping street1" name="shipping" />
<label id="street2" class="sr-only">Street Line 2</label>
<input type="text" aria-labelledby="shipping street2" name="shipping" />
<label for="city">City</label>
<input type="text" name="shipping" id="city" />
<label for="state">State</label>
<select class="inline" name="shipping" id="state" >
<option value="AL">AL</option>
<option value="TL">Too Long</option>
</select>
<label for="zip">Zip Code</label>
<input type="text" class="inline" name="shipping" id="zip" maxlength="5" />
<div id="verification">
<input type="checkbox" name="shipping" class="inline" id="verify" value="verified" /><label for="verify">I verify that all the information above is correct</label>
</div>
<div><div class="button" id="submit" role="button" tabindex="0">Add Customer</div></div>
</form>
</section>
<section class="right">
<h2>Customer Data <i class="fa fa-table" aria-hidden="true"></i></h2>
<div class="button" id="download" tabindex="0">
<span aria-label="Download"><i class="fa fa-download" aria-hidden="true"></i></span>
</div>
<table>
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Address Line 1</th>
<th scope="col">Address Line 2</th>
<th scope="col">City</th>
<th scope="col">State</th>
<th scope="col">Zip Code</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ali</td>
<td>Areskog</td>
<td>90 Fake St</td>
<td>#66</td>
<td>Boston</td>
<td>MA</td>
<td>02129</td>
</tr>
<tr>
<td>Bob</td>
<td>The Builder</td>
<td>9 Imaginary Lane</td>
<td></td>
<td>Wonderland</td>
<td>KS</td>
<td>55555</td>
</tr>
<tr>
<td>Banana</td>
<td>Fruitstein</td>
<td>4 Elliot St</td>
<td>Apt 6</td>
<td>Jamaica Plain</td>
<td>MA</td>
<td>02130</td>
</tr>
<tr>
<td>Aster P.</td>
<td>Dogg</td>
<td>78 Blanket Lane</td>
<td></td>
<td>Boston</td>
<td>MA</td>
<td>02129</td>
</tr>
</tbody>
</table>
</section>
</main>
</body>
</html> | {
"content_hash": "2db596652576962089c9a6ce9079f239",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 168,
"avg_line_length": 30.99047619047619,
"alnum_prop": 0.5946527350952674,
"repo_name": "saltavenger/accessibility",
"id": "0a7c04e37707a5802ca18d72a4874f8afdced774",
"size": "3254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "workshop/comecorrect.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "197267"
},
{
"name": "HTML",
"bytes": "73714"
},
{
"name": "JavaScript",
"bytes": "254227"
}
],
"symlink_target": ""
} |
package org.asynchttpclient.listener;
import org.asynchttpclient.AsyncCompletionHandlerBase;
import org.asynchttpclient.FluentCaseInsensitiveStringsMap;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.HttpResponseHeaders;
import org.asynchttpclient.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* A {@link org.asynchttpclient.AsyncHandler} that can be used to notify a set of {@link TransferListener}
* <p/>
* <blockquote>
*
* <pre>
* AsyncHttpClient client = new AsyncHttpClient();
* TransferCompletionHandler tl = new TransferCompletionHandler();
* tl.addTransferListener(new TransferListener() {
* <p/>
* public void onRequestHeadersSent(FluentCaseInsensitiveStringsMap headers) {
* }
* <p/>
* public void onResponseHeadersReceived(FluentCaseInsensitiveStringsMap headers) {
* }
* <p/>
* public void onBytesReceived(ByteBuffer buffer) {
* }
* <p/>
* public void onBytesSent(long amount, long current, long total) {
* }
* <p/>
* public void onRequestResponseCompleted() {
* }
* <p/>
* public void onThrowable(Throwable t) {
* }
* });
* <p/>
* Response response = httpClient.prepareGet("http://...").execute(tl).get();
* </pre>
*
* </blockquote>
*/
public class TransferCompletionHandler extends AsyncCompletionHandlerBase {
private final static Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
private final ConcurrentLinkedQueue<TransferListener> listeners = new ConcurrentLinkedQueue<>();
private final boolean accumulateResponseBytes;
private FluentCaseInsensitiveStringsMap headers;
// Netty 3 bug hack: last chunk is not notified, fixed in Netty 4
private boolean patchForNetty3;
private long expectedTotal;
private long seen;
/**
* Create a TransferCompletionHandler that will not accumulate bytes. The resulting {@link org.asynchttpclient.Response#getResponseBody()},
* {@link org.asynchttpclient.Response#getResponseBodyAsStream()} and {@link Response#getResponseBodyExcerpt(int)} will throw an IllegalStateException if called.
*/
public TransferCompletionHandler() {
this(false);
}
/**
* Create a TransferCompletionHandler that can or cannot accumulate bytes and make it available when {@link org.asynchttpclient.Response#getResponseBody()} get called. The
* default is false.
*
* @param accumulateResponseBytes
* true to accumulates bytes in memory.
*/
public TransferCompletionHandler(boolean accumulateResponseBytes) {
this.accumulateResponseBytes = accumulateResponseBytes;
}
public void patchForNetty3() {
this.patchForNetty3 = true;
}
/**
* Add a {@link TransferListener}
*
* @param t
* a {@link TransferListener}
* @return this
*/
public TransferCompletionHandler addTransferListener(TransferListener t) {
listeners.offer(t);
return this;
}
/**
* Remove a {@link TransferListener}
*
* @param t
* a {@link TransferListener}
* @return this
*/
public TransferCompletionHandler removeTransferListener(TransferListener t) {
listeners.remove(t);
return this;
}
/**
* Set headers to this listener.
*
* @param headers
* {@link FluentCaseInsensitiveStringsMap}
*/
public void headers(FluentCaseInsensitiveStringsMap headers) {
this.headers = headers;
if (patchForNetty3) {
String contentLength = headers.getFirstValue("Content-Length");
if (contentLength != null)
expectedTotal = Long.valueOf(contentLength);
}
}
@Override
public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
fireOnHeaderReceived(headers.getHeaders());
return super.onHeadersReceived(headers);
}
@Override
public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
STATE s = STATE.CONTINUE;
if (accumulateResponseBytes) {
s = super.onBodyPartReceived(content);
}
fireOnBytesReceived(content.getBodyPartBytes());
return s;
}
@Override
public Response onCompleted(Response response) throws Exception {
if (patchForNetty3) {
// some chunks weren't notified, probably the last one
if (seen < expectedTotal) {
// do once
fireOnBytesSent(expectedTotal - seen, expectedTotal, expectedTotal);
}
}
fireOnEnd();
return response;
}
@Override
public STATE onHeaderWriteCompleted() {
if (headers != null) {
fireOnHeadersSent(headers);
}
return STATE.CONTINUE;
}
@Override
public STATE onContentWriteProgress(long amount, long current, long total) {
if (patchForNetty3) {
seen += amount;
}
fireOnBytesSent(amount, current, total);
return STATE.CONTINUE;
}
@Override
public void onThrowable(Throwable t) {
fireOnThrowable(t);
}
private void fireOnHeadersSent(FluentCaseInsensitiveStringsMap headers) {
for (TransferListener l : listeners) {
try {
l.onRequestHeadersSent(headers);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnHeaderReceived(FluentCaseInsensitiveStringsMap headers) {
for (TransferListener l : listeners) {
try {
l.onResponseHeadersReceived(headers);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnEnd() {
for (TransferListener l : listeners) {
try {
l.onRequestResponseCompleted();
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnBytesReceived(byte[] b) {
for (TransferListener l : listeners) {
try {
l.onBytesReceived(b);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnBytesSent(long amount, long current, long total) {
for (TransferListener l : listeners) {
try {
l.onBytesSent(amount, current, total);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnThrowable(Throwable t) {
for (TransferListener l : listeners) {
try {
l.onThrowable(t);
} catch (Throwable t2) {
logger.warn("onThrowable", t2);
}
}
}
}
| {
"content_hash": "d82e41a19e5bbd8ade2836f3e805cf77",
"timestamp": "",
"source": "github",
"line_count": 230,
"max_line_length": 175,
"avg_line_length": 30.030434782608694,
"alnum_prop": 0.625018097582163,
"repo_name": "afelisatti/async-http-client",
"id": "73b4bbb11cddcc99ce58fbdc6fdb5d8777b38606",
"size": "7602",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/src/main/java/org/asynchttpclient/listener/TransferCompletionHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1925816"
}
],
"symlink_target": ""
} |
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import * as actions from '../actions';
class Header extends Component {
authButton() {
if (this.props.authenticated) {
return <button onClick={() => this.props.authenticate(false)}>Sign Out</button>
}
return <button onClick={() => this.props.authenticate(true)}>Sign In</button>
}
render() {
return (
<nav className="navbar navbar-light">
<ul className="nav navbar-nav">
<li className="nav-item">
<Link to="/">Home</Link>
</li>
<li className="nav-item">
<Link to="/resources">Resources</Link>
</li>
<li className="nav-item">
{this.authButton()}
</li>
</ul>
</nav>
);
}
}
const mapStateToProps = state => ({
authenticated: state.authenticated
});
export default connect(mapStateToProps, actions)(Header);
| {
"content_hash": "77174c6f6593ccbbe74b546986a52826",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 85,
"avg_line_length": 26.07894736842105,
"alnum_prop": 0.5761856710393541,
"repo_name": "ric9176/hoc",
"id": "48a23e48866fb62c2997802765681eb0730ebd1e",
"size": "991",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/header.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "474"
},
{
"name": "JavaScript",
"bytes": "5295"
}
],
"symlink_target": ""
} |
import org.marketcetera.event.AskEvent;
import org.marketcetera.strategy.java.Strategy;
/* $License$ */
/**
* Test strategy (part one of two parts) that tests what happens when a strategy helper-class is redefined.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: Part1.java 16154 2012-07-14 16:34:05Z colin $
* @since 1.0.0
*/
public class Part1
extends Strategy
{
private Helper helper;
/* (non-Javadoc)
* @see org.marketcetera.strategy.java.Strategy#onAsk(org.marketcetera.event.AskEvent)
*/
@Override
public void onAsk(AskEvent inAsk)
{
setProperty("ask" + this,
"part1");
}
/* (non-Javadoc)
* @see org.marketcetera.strategy.java.Strategy#onCallback(java.lang.Object)
*/
@Override
public void onCallback(Object inData)
{
long callbackCounter = Long.parseLong(getProperty("onCallback"));
callbackCounter += 1;
setProperty("onCallback",
Long.toString(callbackCounter));
setProperty("callback" + Long.toString(callbackCounter),
this.toString());
}
/* (non-Javadoc)
* @see org.marketcetera.strategy.java.Strategy#onStart()
*/
@Override
public void onStart()
{
String callbackCounter = getProperty("onCallback");
if(callbackCounter == null) {
setProperty("onCallback",
"0");
}
helper = new Helper();
helper.doSomethingCommon();
helper.doSomethingPart1();
}
/* (non-Javadoc)
* @see org.marketcetera.strategy.java.Strategy#onStop()
*/
@Override
public void onStop()
{
helper.doSomethingCommon();
helper.doSomethingPart1();
}
private static class Helper
{
private void doSomethingCommon()
{
}
private void doSomethingPart1()
{
}
}
}
| {
"content_hash": "fe69ea6dcc9d15d3cc958c059a12ad0c",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 108,
"avg_line_length": 27.095890410958905,
"alnum_prop": 0.5930232558139535,
"repo_name": "nagyist/marketcetera",
"id": "57c207c254048215b696689baf05c019e51b369c",
"size": "1978",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "trunk/modules/strategy/src/test/sample_data/inputs/Part1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3625095"
},
{
"name": "Ruby",
"bytes": "655"
}
],
"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>
<title>Uses of Class org.apache.poi.sl.usermodel.PresetColor (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.sl.usermodel.PresetColor (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/sl/usermodel//class-usePresetColor.html" target="_top">FRAMES</a></li>
<li><a href="PresetColor.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.poi.sl.usermodel.PresetColor" class="title">Uses of Class<br>org.apache.poi.sl.usermodel.PresetColor</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</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.apache.poi.sl.usermodel">org.apache.poi.sl.usermodel</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.poi.sl.usermodel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</a> in <a href="../../../../../../org/apache/poi/sl/usermodel/package-summary.html">org.apache.poi.sl.usermodel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/poi/sl/usermodel/package-summary.html">org.apache.poi.sl.usermodel</a> that return <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</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>static <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</a></code></td>
<td class="colLast"><span class="strong">PresetColor.</span><code><strong><a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</a></code></td>
<td class="colLast"><span class="strong">PresetColor.</span><code><strong><a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html#valueOfNativeId(int)">valueOfNativeId</a></strong>(int nativeId)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</a></code></td>
<td class="colLast"><span class="strong">PresetColor.</span><code><strong><a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html#valueOfOoxmlId(java.lang.String)">valueOfOoxmlId</a></strong>(java.lang.String ooxmlId)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">PresetColor</a>[]</code></td>
<td class="colLast"><span class="strong">PresetColor.</span><code><strong><a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/poi/sl/usermodel/PresetColor.html" title="enum in org.apache.poi.sl.usermodel">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/sl/usermodel//class-usePresetColor.html" target="_top">FRAMES</a></li>
<li><a href="PresetColor.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2016 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
| {
"content_hash": "5441f08a2deb9f74e0550a87309e3f12",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 330,
"avg_line_length": 45.172413793103445,
"alnum_prop": 0.6358778625954199,
"repo_name": "Aarhus-BSS/Aarhus-Research-Rebuilt",
"id": "55f1fb92076e26f625afe2d442e741449c624b68",
"size": "7860",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/poi-3.16-beta1/docs/apidocs/org/apache/poi/sl/usermodel/class-use/PresetColor.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25053"
},
{
"name": "HTML",
"bytes": "99455840"
},
{
"name": "Java",
"bytes": "12711046"
},
{
"name": "Lua",
"bytes": "152042"
},
{
"name": "Python",
"bytes": "8613"
},
{
"name": "R",
"bytes": "20655"
},
{
"name": "Shell",
"bytes": "913"
}
],
"symlink_target": ""
} |
<ion-header>
<ion-navbar>
<img src="assets/img/sarah-avatar.png" class="logo">
</ion-navbar>
</ion-header>
<ion-content>
<ion-list [virtualScroll]="aboutLists">
<ion-grid>
<ion-col col-12 col-md-6 align-self-stretch align-self-center *virtualItem="let aboutList" >
<img *ngIf="aboutList.img!=''" src="{{aboutList.img}}" class="img_padding">
<h3 class="h_padding">{{aboutList.title}}</h3>
<p class="p_padding">
<ion-icon *ngIf="aboutList.img == ''" name="pin" item-start></ion-icon>
{{aboutList.desc}}
</p>
</ion-col>
</ion-grid>
</ion-list>
</ion-content> | {
"content_hash": "48c6e89d1ec614dad29ce8337b2b25b5",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 98,
"avg_line_length": 32.05,
"alnum_prop": 0.5865834633385335,
"repo_name": "JasonZzs/myApp",
"id": "9b452275868abac3232c29687a8a8243aa211fa4",
"size": "641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/pages/about/about.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5469"
},
{
"name": "HTML",
"bytes": "11931"
},
{
"name": "JavaScript",
"bytes": "740"
},
{
"name": "TypeScript",
"bytes": "24539"
}
],
"symlink_target": ""
} |
def largest_integer(list_of_nums)
if list_of_nums.length == 0
return nil
else
num = list_of_nums.sort
p num[list_of_nums.length-1]
end
end
| {
"content_hash": "70ce35dc5f28bb73265900c843a7fe5e",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 33,
"avg_line_length": 18.75,
"alnum_prop": 0.6866666666666666,
"repo_name": "nowakoff/phase-0",
"id": "a896ecc97d1f2c1e10ddd2012d1f9984e9eeedb1",
"size": "556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week-4/largest-integer/my_solution.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3325"
},
{
"name": "HTML",
"bytes": "24325"
},
{
"name": "JavaScript",
"bytes": "32070"
},
{
"name": "Ruby",
"bytes": "105524"
}
],
"symlink_target": ""
} |
Titanium.UI.setBackgroundColor('#000');
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
title:'TOP',
backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'TOP',
window:win1
});
var label1 = Titanium.UI.createLabel({
color:'#999',
text:'トップ画面。',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win1.add(label1);
//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
title:'CHECK',
backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
icon:'KS_nav_ui.png',
title:'CHECK',
bottom:0,
window:win2
});
var label2 = Titanium.UI.createLabel({
color:'#999',
text:'確認画面。',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win2.add(label2);
//
// create controls tab and root window
//
var win3 = Titanium.UI.createWindow({ url: "Entry.js" });
var tab3 = Titanium.UI.createTab({
icon:'KS_nav_platform.png',
title:'ENTRY',
window:win3
});
//
// add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
tabGroup.addTab(tab3);
// open tab group
tabGroup.open(); | {
"content_hash": "0d76f2ebdbcdaa7691626b5408f6bb82",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 57,
"avg_line_length": 17.944444444444443,
"alnum_prop": 0.6493808049535603,
"repo_name": "snjkodo/titanium_WG",
"id": "12a4f26489176d6d45e3829dc377d1641be6269b",
"size": "1515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Resources/app.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3786"
},
{
"name": "JavaScript",
"bytes": "122102"
}
],
"symlink_target": ""
} |
layout: model
title: English BertForQuestionAnswering Uncased model (from Andaf)
author: John Snow Labs
name: bert_qa_uncased_finetuned_squad_indonesian
date: 2022-07-07
tags: [en, open_source, bert, question_answering]
task: Question Answering
language: en
edition: Spark NLP 4.0.0
spark_version: 3.0
supported: true
annotator: BertForQuestionAnswering
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---
## Description
Pretrained Question Answering model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `bert-uncased-finetuned-squad-indonesian` is a English model originally trained by `Andaf`.
{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/bert_qa_uncased_finetuned_squad_indonesian_en_4.0.0_3.0_1657188726851.zip){:.button.button-orange.button-orange-trans.arr.button-icon}
## How to use
<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = MultiDocumentAssembler() \
.setInputCols(["question", "context"]) \
.setOutputCols(["document_question", "document_context"])
spanClassifier = BertForQuestionAnswering.pretrained("bert_qa_uncased_finetuned_squad_indonesian","en") \
.setInputCols(["document_question", "document_context"]) \
.setOutputCol("answer")\
.setCaseSensitive(True)
pipeline = Pipeline(stages=[documentAssembler, spanClassifier])
data = spark.createDataFrame([["What is my name?", "My name is Clara and I live in Berkeley."]]).toDF("question", "context")
result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new MultiDocumentAssembler()
.setInputCols(Array("question", "context"))
.setOutputCols(Array("document_question", "document_context"))
val spanClassifer = BertForQuestionAnswering.pretrained("bert_qa_uncased_finetuned_squad_indonesian","en")
.setInputCols(Array("document", "token"))
.setOutputCol("answer")
.setCaseSensitive(true)
val pipeline = new Pipeline().setStages(Array(documentAssembler, spanClassifier))
val data = Seq("What is my name?", "My name is Clara and I live in Berkeley.").toDF("question", "context")
val result = pipeline.fit(data).transform(data)
```
</div>
{:.model-param}
## Model Information
{:.table-model}
|---|---|
|Model Name:|bert_qa_uncased_finetuned_squad_indonesian|
|Compatibility:|Spark NLP 4.0.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[document_question, document_context]|
|Output Labels:|[answer]|
|Language:|en|
|Size:|413.2 MB|
|Case sensitive:|false|
|Max sentence length:|512|
## References
- https://huggingface.co/Andaf/bert-uncased-finetuned-squad-indonesian | {
"content_hash": "c96ff04a6c00a9677fc16dd4e5aebf56",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 231,
"avg_line_length": 33.88235294117647,
"alnum_prop": 0.7482638888888888,
"repo_name": "JohnSnowLabs/spark-nlp",
"id": "5a2b5e27707225044936223720f650bc7697d860",
"size": "2884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_posts/murat-gunay/2022-07-07-bert_qa_uncased_finetuned_squad_indonesian_en_3_0.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "14452"
},
{
"name": "Java",
"bytes": "223289"
},
{
"name": "Makefile",
"bytes": "819"
},
{
"name": "Python",
"bytes": "1694517"
},
{
"name": "Scala",
"bytes": "4116435"
},
{
"name": "Shell",
"bytes": "5286"
}
],
"symlink_target": ""
} |
package org.apache.jsp.WEB_002dINF.views.modules.sys;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class userModifyPwd_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
static private org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0;
static {
_jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getAdminPath", com.dc.smarteam.common.config.Global.class, "getAdminPath", new Class[] {});
}
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList(5);
_jspx_dependants.add("/WEB-INF/views/include/taglib.jsp");
_jspx_dependants.add("/WEB-INF/tlds/shiros.tld");
_jspx_dependants.add("/WEB-INF/tlds/fns.tld");
_jspx_dependants.add("/WEB-INF/tlds/fnc.tld");
_jspx_dependants.add("/WEB-INF/tags/sys/message.tag");
}
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005fhidden_0026_005fpath_005fnobody;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005fhidden_0026_005fpath_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.release();
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction.release();
_005fjspx_005ftagPool_005fform_005fhidden_0026_005fpath_005fnobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write('\n');
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
if (_jspx_meth_c_005fset_005f0(_jspx_page_context))
return;
out.write('\n');
if (_jspx_meth_c_005fset_005f1(_jspx_page_context))
return;
out.write("\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("\t<title>修改密码</title>\n");
out.write("\t<meta name=\"decorator\" content=\"default\"/>\n");
out.write("\t<script type=\"text/javascript\">\n");
out.write("\t\t$(document).ready(function() {\n");
out.write("\t\t\t$(\"#oldPassword\").focus();\n");
out.write("\t\t\t$(\"#inputForm\").validate({\n");
out.write("\t\t\t\trules: {\n");
out.write("\t\t\t\t},\n");
out.write("\t\t\t\tmessages: {\n");
out.write("\t\t\t\t\tconfirmNewPassword: {equalTo: \"输入与上面相同的密码\"}\n");
out.write("\t\t\t\t},\n");
out.write("\t\t\t\tsubmitHandler: function(form){\n");
out.write("\t\t\t\t\tloading('正在提交,请稍等...');\n");
out.write("\t\t\t\t\tform.submit();\n");
out.write("\t\t\t\t},\n");
out.write("\t\t\t\terrorContainer: \"#messageBox\",\n");
out.write("\t\t\t\terrorPlacement: function(error, element) {\n");
out.write("\t\t\t\t\t$(\"#messageBox\").text(\"输入有误,请先更正。\");\n");
out.write("\t\t\t\t\tif (element.is(\":checkbox\")||element.is(\":radio\")||element.parent().is(\".input-append\")){\n");
out.write("\t\t\t\t\t\terror.appendTo(element.parent().parent());\n");
out.write("\t\t\t\t\t} else {\n");
out.write("\t\t\t\t\t\terror.insertAfter(element);\n");
out.write("\t\t\t\t\t}\n");
out.write("\t\t\t\t}\n");
out.write("\t\t\t});\n");
out.write("\t\t});\n");
out.write("\t</script>\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("\t<ul class=\"nav nav-tabs\">\n");
out.write("\t\t<li><a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/sys/user/info\">个人信息</a></li>\n");
out.write("\t\t<li class=\"active\"><a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/sys/user/modifyPwd\">修改密码</a></li>\n");
out.write("\t</ul><br/>\n");
out.write("\t");
if (_jspx_meth_form_005fform_005f0(_jspx_page_context))
return;
out.write("\n");
out.write("</body>\n");
out.write("</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_005fset_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_005fset_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fset_005f0.setParent(null);
// /WEB-INF/views/include/taglib.jsp(11,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f0.setVar("ctx");
// /WEB-INF/views/include/taglib.jsp(11,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}${fns:getAdminPath()}", java.lang.Object.class, (PageContext)_jspx_page_context, _jspx_fnmap_0, false));
int _jspx_eval_c_005fset_005f0 = _jspx_th_c_005fset_005f0.doStartTag();
if (_jspx_th_c_005fset_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
return true;
}
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
return false;
}
private boolean _jspx_meth_c_005fset_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_005fset_005f1.setPageContext(_jspx_page_context);
_jspx_th_c_005fset_005f1.setParent(null);
// /WEB-INF/views/include/taglib.jsp(12,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f1.setVar("ctxStatic");
// /WEB-INF/views/include/taglib.jsp(12,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}/static", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
int _jspx_eval_c_005fset_005f1 = _jspx_th_c_005fset_005f1.doStartTag();
if (_jspx_th_c_005fset_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
return true;
}
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
return false;
}
private boolean _jspx_meth_form_005fform_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:form
org.springframework.web.servlet.tags.form.FormTag _jspx_th_form_005fform_005f0 = (org.springframework.web.servlet.tags.form.FormTag) _005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction.get(org.springframework.web.servlet.tags.form.FormTag.class);
_jspx_th_form_005fform_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005fform_005f0.setParent(null);
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(38,1) name = id type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setId("inputForm");
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(38,1) name = modelAttribute type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setModelAttribute("user");
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(38,1) name = action type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setAction((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}/sys/user/modifyPwd", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(38,1) name = method type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setMethod("post");
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(38,1) null
_jspx_th_form_005fform_005f0.setDynamicAttribute(null, "class", new String("form-horizontal"));
int[] _jspx_push_body_count_form_005fform_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005fform_005f0 = _jspx_th_form_005fform_005f0.doStartTag();
if (_jspx_eval_form_005fform_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write('\n');
out.write(' ');
out.write(' ');
if (_jspx_meth_form_005fhidden_005f0(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return true;
out.write('\n');
out.write(' ');
out.write(' ');
if (_jspx_meth_sys_005fmessage_005f0(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return true;
out.write("\n");
out.write("\t\t<div class=\"control-group\">\n");
out.write("\t\t\t<label class=\"control-label\">旧密码:</label>\n");
out.write("\t\t\t<div class=\"controls\">\n");
out.write("\t\t\t\t<input id=\"oldPassword\" name=\"oldPassword\" type=\"password\" value=\"\" maxlength=\"50\" minlength=\"3\" class=\"required\"/>\n");
out.write("\t\t\t\t<span class=\"help-inline\"><font color=\"red\">*</font> </span>\n");
out.write("\t\t\t</div>\n");
out.write("\t\t</div>\n");
out.write("\t\t<div class=\"control-group\">\n");
out.write("\t\t\t<label class=\"control-label\">新密码:</label>\n");
out.write("\t\t\t<div class=\"controls\">\n");
out.write("\t\t\t\t<input id=\"newPassword\" name=\"newPassword\" type=\"password\" value=\"\" maxlength=\"50\" minlength=\"3\" class=\"required\"/>\n");
out.write("\t\t\t\t<span class=\"help-inline\"><font color=\"red\">*</font> </span>\n");
out.write("\t\t\t</div>\n");
out.write("\t\t</div>\n");
out.write("\t\t<div class=\"control-group\">\n");
out.write("\t\t\t<label class=\"control-label\">确认新密码:</label>\n");
out.write("\t\t\t<div class=\"controls\">\n");
out.write("\t\t\t\t<input id=\"confirmNewPassword\" name=\"confirmNewPassword\" type=\"password\" value=\"\" maxlength=\"50\" minlength=\"3\" class=\"required\" equalTo=\"#newPassword\"/>\n");
out.write("\t\t\t\t<span class=\"help-inline\"><font color=\"red\">*</font> </span>\n");
out.write("\t\t\t</div>\n");
out.write("\t\t</div>\n");
out.write("\t\t<div class=\"form-actions\">\n");
out.write("\t\t\t<input id=\"btnSubmit\" class=\"btn btn-primary\" type=\"submit\" value=\"保 存\"/>\n");
out.write("\t\t</div>\n");
out.write("\t");
int evalDoAfterBody = _jspx_th_form_005fform_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_form_005fform_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005fform_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005fform_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005fform_005f0.doFinally();
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction.reuse(_jspx_th_form_005fform_005f0);
}
return false;
}
private boolean _jspx_meth_form_005fhidden_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:hidden
org.springframework.web.servlet.tags.form.HiddenInputTag _jspx_th_form_005fhidden_005f0 = (org.springframework.web.servlet.tags.form.HiddenInputTag) _005fjspx_005ftagPool_005fform_005fhidden_0026_005fpath_005fnobody.get(org.springframework.web.servlet.tags.form.HiddenInputTag.class);
_jspx_th_form_005fhidden_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005fhidden_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(39,2) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fhidden_005f0.setPath("id");
int[] _jspx_push_body_count_form_005fhidden_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005fhidden_005f0 = _jspx_th_form_005fhidden_005f0.doStartTag();
if (_jspx_th_form_005fhidden_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005fhidden_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005fhidden_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005fhidden_005f0.doFinally();
_005fjspx_005ftagPool_005fform_005fhidden_0026_005fpath_005fnobody.reuse(_jspx_th_form_005fhidden_005f0);
}
return false;
}
private boolean _jspx_meth_sys_005fmessage_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sys:message
org.apache.jsp.tag.web.sys.message_tag _jspx_th_sys_005fmessage_005f0 = new org.apache.jsp.tag.web.sys.message_tag();
org.apache.jasper.runtime.AnnotationHelper.postConstruct(_jsp_annotationprocessor, _jspx_th_sys_005fmessage_005f0);
_jspx_th_sys_005fmessage_005f0.setJspContext(_jspx_page_context);
_jspx_th_sys_005fmessage_005f0.setParent(_jspx_th_form_005fform_005f0);
// /WEB-INF/views/modules/sys/userModifyPwd.jsp(40,2) name = content type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
_jspx_th_sys_005fmessage_005f0.setContent((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${message}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
_jspx_th_sys_005fmessage_005f0.doTag();
org.apache.jasper.runtime.AnnotationHelper.preDestroy(_jsp_annotationprocessor, _jspx_th_sys_005fmessage_005f0);
return false;
}
}
| {
"content_hash": "9690c0f5cc576b7b784de688776643df",
"timestamp": "",
"source": "github",
"line_count": 315,
"max_line_length": 301,
"avg_line_length": 60.615873015873014,
"alnum_prop": 0.6810516392584057,
"repo_name": "VincentFxz/EAM",
"id": "81b01b3d15165552f8c8a7ba1c5f905b91398d87",
"size": "19200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "target/tomcat/work/localEngine-8181/localhost/smarteam/org/apache/jsp/WEB_002dINF/views/modules/sys/userModifyPwd_jsp.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "3753"
},
{
"name": "ApacheConf",
"bytes": "1536"
},
{
"name": "Batchfile",
"bytes": "5759"
},
{
"name": "CSS",
"bytes": "2231708"
},
{
"name": "HTML",
"bytes": "3619034"
},
{
"name": "Java",
"bytes": "3326237"
},
{
"name": "JavaScript",
"bytes": "14365592"
},
{
"name": "PHP",
"bytes": "8060"
},
{
"name": "PLSQL",
"bytes": "66284"
}
],
"symlink_target": ""
} |
package hackerranksolutions.Java.Introduction.JavaDateandTime;
/* Author: George Ngandu
Github: github.com/gngandu
HackerRank: hackerrank.com/gngandu
*/
import java.util.*;
import java.time.*;
public class JavaDateandTime {
/*
Instructions:
--------------
The Calendar class is an abstract class that provides methods for converting
between a specific instant in time and a set of calendar fields such
as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar
fields, such as getting the date of the next week.
You are given a date. To simplify your task, we have provided a portion of the code
in the editor. You just need to write the method, which returns the day on that date.
For example, if you are given the date , the method should return as the day on that date.
Input Format:
-------------
A single line of input containing the space separated month, day and year,
respectively, in format.
Output Format:
--------------
Output the correct day in capital letters.
Sample Input:
-------------
08 05 2015
Sample Output:
--------------
WEDNESDAY
*/
public static void main(String[] args) {
String month;
String day;
String year;
try (Scanner sc = new Scanner(System.in)) {
month = sc.next();
day = sc.next();
year = sc.next();
sc.close();
}
String date = year + "-" + month + "-" + day;
LocalDate dt = LocalDate.parse(date);
System.out.println(dt.getDayOfWeek());
}
}
| {
"content_hash": "4ea313e975241f4273bde7b0341a8125",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 95,
"avg_line_length": 29.228070175438596,
"alnum_prop": 0.6002400960384153,
"repo_name": "gngandu/HackerRankSolutions",
"id": "161a1b0722782737b7a4fdd234d5d97b11bda0e1",
"size": "1666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/hackerranksolutions/Java/Introduction/JavaDateandTime/JavaDateandTime.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27037"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009, Whispersoft s.r.l.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Whispersoft s.r.l. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: Catalin Popescu
#include "common/base/types.h"
#include "common/base/log.h"
#include "common/base/system.h"
#include "common/base/gflags.h"
#include "net/http/http_header.h"
#include "common/io/file/file.h"
#include "common/io/file/file_input_stream.h"
#include "common/io/file/file_output_stream.h"
#include "common/io/buffer/memory_stream.h"
//////////////////////////////////////////////////////////////////////
DEFINE_string(data_file,
"",
"We test w/ headers from this file");
DEFINE_int32(memstream_bufsize,
128,
"We dimmensionate the MemoryStream buffer to "
"this value");
//////////////////////////////////////////////////////////////////////
struct TestData {
bool is_strict;
const char header[1024];
http::Header::ParseError expected_error;
const char test_field_name[256];
const char test_field_content[256];
};
const TestData test[] = {
{ true,
"GET /en-US/firefox/bookmarks/%0A HTTP/1.0\r\n"
"User-Agent: Wget/1.10.2\r\n"
" GIGI MARGA\r\n"
"Accept: */*\r\n"
"Host: en-us.add-ons.mozilla.com\r\n"
"Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n"
"Connection: Keep-Alive\r\n"
"\r\n",
http::Header::READ_OK,
"User-Agent", "Wget/1.10.2 GIGI MARGA"
}, {
false,
"GeT /en-US/firefox/bookmarks/%0A HTTP/1.0\r\n"
"Accept: */*\r\n"
"Host: en-us\0300.add-ons.mozilla.com\r\n"
" xxx abcd\r\n"
"Connection: Keep-Alive\r\n"
"\r\n",
http::Header::READ_BAD_FIELD_SPEC,
"Host", "en-us\0300.add-ons.mozilla.com xxx abcd"
}, {
true,
"GeT /en-US/firefox/bookmarks/%0A HTTP/1.0\r\n"
"Accept: */*\r\n"
"Host: en-us\0300.add-ons.mozilla.com\r\n"
" xxx abcd\r\n"
"Connection: Keep-Alive\r\n"
"\r\n",
http::Header::READ_BAD_FIELD_SPEC,
"Host", ""
}, {
false,
"GeT /en-US/firefox/bookmarks/%0A\r\n"
"Accept: */*\r\n"
"Host: en-us\0300.add-ons.mozilla.com\r\n"
"Connection: Keep-Alive\r\n"
"\r\n",
http::Header::READ_NO_REQUEST_VERSION,
"Host", "en-us\0300.add-ons.mozilla.com"
}, {
true,
"GET /en-US/firefox/bookmarks/%0A HTTP/1.0\r\n"
"User-Agent: Wget/1.10.2\r\n"
"Accept: */*\r\n"
"Host: en-us.add-ons.mozilla.com\r\n"
"Connection: Keep-Alive\r\n"
"User-Agent: GIGI MARGA\r\n"
"\r\n",
http::Header::READ_OK,
"User-Agent", "Wget/1.10.2, GIGI MARGA"
},
};
void RunSimpleTests() {
for ( int i = 0; i < NUMBEROF(test); ++i ) {
http::Header headers(test[i].is_strict);
LOG_INFO << " ======================================== \n"
<< " TEST " << i;
io::MemoryStream ms;
ms.Write(test[i].header);
headers.Clear();
CHECK(headers.ParseHttpRequest(&ms));
CHECK_EQ(headers.parse_error(), test[i].expected_error);
LOG_INFO << "==================\n"
<< headers.ToString();
string s;
if ( *test[i].test_field_content ) {
CHECK(headers.FindField(
string(test[i].test_field_name), &s));
CHECK_EQ(s, string(test[i].test_field_content));
} else {
CHECK(!headers.FindField(
string(test[i].test_field_name), &s));
}
}
}
int main(int argc, char* argv[]) {
common::Init(argc, argv);
http::Header htest(true);
io::MemoryStream mstest;
mstest.Write("GET /en-US/firefox/bookmarks/%0A HTTP/1.0\r\n"
"Date1: Sun, 06 Nov 1994 08:49:37 GMT\r\n"
"Date2: Sunday, 06-Nov-94 08:49:37 GMT\r\n"
"Date3: Sun Nov 6 08:49:37 1994\r\n"
"Transfer-Encoding: \tchunked\r\n"
"Accept-Charset: iso-8859-5, unicode-1-1;q=0.8\r\n"
"Accept: text/plain; q=0.5, text/html, \r\n"
" text/x-dvi; q=0.8, text/x-c,\r\n"
" audio/*; q=0.3, audio/mp3; q = 0.7 , */*; q=0.01\r\n"
"Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0\r\n"
"Host: en-us.add-ons.mozilla.com\r\n"
"Connection: Keep-Alive\r\n"
"\r\n");
CHECK(htest.ParseHttpRequest(&mstest));
CHECK_NE(htest.GetDateField("Date1"), 0);
CHECK_EQ(htest.GetDateField("Date1"), htest.GetDateField("Date2"));
// This can be in different time zone - just make sure divides by 3600
CHECK_EQ((htest.GetDateField("Date1") - htest.GetDateField("Date3")) % 3600, 0);
CHECK_EQ(htest.method(), http::METHOD_GET);
CHECK_EQ(htest.http_version(), http::VERSION_1_0);
CHECK(htest.IsChunkedTransfer());
float value;
value = htest.GetHeaderAcceptance(
http::kHeaderAccept, "text/plain", "text/*", "*/*");
CHECK_EQ(value, 0.5f);
value = htest.GetHeaderAcceptance(
http::kHeaderAccept, "gigi/marga", "gigi/*", "*/*");
CHECK_EQ(value, 0.01f);
value = htest.GetHeaderAcceptance(
http::kHeaderAccept, "text/x-dvi", "text/*", "*/*");
CHECK_EQ(value, 0.8f);
value = htest.GetHeaderAcceptance(
http::kHeaderAccept, "audio/x-dvi", "audio/*", "*/*");
CHECK_EQ(value, 0.3f);
value = htest.GetHeaderAcceptance(
http::kHeaderAccept, "audio/mp3", "audio/*", "*/*");
CHECK_EQ(value, 0.7f);
value = htest.GetHeaderAcceptance(
http::kHeaderAcceptCharset, "iso-8859-5", "", "*");
CHECK_EQ(value, 1.0f);
value = htest.GetHeaderAcceptance(
http::kHeaderAcceptCharset, "UNICODE-1-1", "", "*");
CHECK_EQ(value, 0.8f);
value = htest.GetHeaderAcceptance(
http::kHeaderAcceptEncoding, "deflate", "", "*");
CHECK_EQ(value, 0.0f);
value = htest.GetHeaderAcceptance(
http::kHeaderAcceptEncoding, "identity", "", "*");
CHECK_EQ(value, 0.5f);
CHECK(htest.IsGzipAcceptableEncoding());
CHECK(!htest.SetAuthorizationField("gigi_marga:", "zuzub0#$A"));
string user, passwd;
CHECK(!htest.GetAuthorizationField(&user, &passwd));
CHECK(htest.SetAuthorizationField("gigi_marga", "zuzub0#$A"));
CHECK(htest.GetAuthorizationField(&user, &passwd));
CHECK_EQ(user, string("gigi_marga"));
CHECK_EQ(passwd, string("zuzub0#$A"));
string ss = http::Header::NormalizeFieldName(
string(" ABC DEF \t "));
CHECK_EQ(ss, "Abc-Def");
ss = http::Header::NormalizeFieldName("GiGi--MarG A \t ");
CHECK_EQ(ss, "Gigi--Marg-A");
CHECK(!http::Header::IsValidFieldName(" \t Gigi Marga "));
CHECK(http::Header::IsValidFieldName("Gigi \t Marga "));
CHECK(!http::Header::IsValidFieldName("Gigi \t Ma\0340rga "));
CHECK(http::Header::IsValidFieldName("Content-Length"));
CHECK(!http::Header::IsValidFieldName("\t "));
CHECK(!http::Header::IsValidFieldName(""));
CHECK(!http::Header::IsValidFieldName("Content:Length"));
CHECK(!http::Header::IsValidFieldName("Content<Length"));
CHECK(http::Header::IsValidFieldContent(""));
CHECK(http::Header::IsValidFieldContent("\t sds "));
CHECK(!http::Header::IsValidFieldContent("\t sd\0300s "));
CHECK(http::Header::IsValidFieldContent(
"\t !@#$%^&*()_+{}[]|:;\"'\\<>,./?"));
RunSimpleTests();
if ( !FLAGS_data_file.empty() ) {
io::MemoryStream ms(FLAGS_memstream_bufsize);
ms.Write(io::FileInputStream::ReadFileOrDie(FLAGS_data_file.c_str()));
const int32 size = ms.Size();
http::Header headers(true);
int64 parsed_bytes = 0;
bool is_req = true;
while ( !ms.IsEmpty() ) {
int sz1 = ms.Size();
CHECK_EQ(sz1, ms.Size());
if ( is_req ) {
CHECK(headers.ParseHttpRequest(&ms));
} else {
CHECK(headers.ParseHttpReply(&ms));
}
parsed_bytes += headers.bytes_parsed();
CHECK_EQ(headers.parse_error(), http::Header::READ_OK);
io::MemoryStream ss;
string s;
headers.AppendToStream(&ss);
CHECK(ss.ReadString(&s));
LOG_INFO << " ======================================== \n"
<< s;
is_req = !is_req;
headers.Clear();
}
CHECK_EQ(parsed_bytes, size);
}
LOG_INFO << "PASS!";
}
| {
"content_hash": "3254b2b953e214fddee738319423ee69",
"timestamp": "",
"source": "github",
"line_count": 262,
"max_line_length": 82,
"avg_line_length": 35.961832061068705,
"alnum_prop": 0.6127149225217576,
"repo_name": "cpopescu/whispercast",
"id": "2b3cab2849830c26731c4af61419155131a204b5",
"size": "9422",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "whisperlib/net/http/test/http_header_test.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "5501"
},
{
"name": "C",
"bytes": "384162"
},
{
"name": "C++",
"bytes": "5162993"
},
{
"name": "JavaScript",
"bytes": "69451"
},
{
"name": "Objective-C",
"bytes": "14940"
},
{
"name": "PHP",
"bytes": "39739"
},
{
"name": "Python",
"bytes": "73884"
},
{
"name": "Shell",
"bytes": "68433"
}
],
"symlink_target": ""
} |
package com.jinwen.thread.multithread.synchronize.example8;
/**
* P72
* synchronized方法的弊端
*/
public class Run8_synchronized01 {
public static void main(String[] args) {
TaskA taskA = new TaskA();
MyThreadA thread1 = new MyThreadA(taskA);
thread1.setName("a");
thread1.start();
MyThreadA thread2 = new MyThreadA(taskA);
thread2.setName("b");
thread2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long beginTime = CommonUtils.beginTime2 < CommonUtils.beginTime1 ? CommonUtils.beginTime2 : CommonUtils.beginTime1;
long endTime = CommonUtils.endTime1 > CommonUtils.endTime2 ? CommonUtils.endTime1 : CommonUtils.endTime2;
System.out.println("耗时:" + (endTime - beginTime) / 1000);
}
}
/*
输出:
begin task
长时间处理任务后从远程返回的值1 threadName=a
长时间处理任务后从远程返回的值2 threadName=a
end task
begin task
长时间处理任务后从远程返回的值1 threadName=b
长时间处理任务后从远程返回的值2 threadName=b
end task
耗时:6
*/ | {
"content_hash": "f66fc5bc0d46c8b5c1fd21cc8311446a",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 123,
"avg_line_length": 23.84090909090909,
"alnum_prop": 0.6644423260247855,
"repo_name": "jinchen92/JavaBasePractice",
"id": "47d0afc917e33ed80255ee2dc3624a56f05b6b8c",
"size": "1197",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/jinwen/thread/multithread/synchronize/example8/Run8_synchronized01.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "429074"
}
],
"symlink_target": ""
} |
<?php
// The content of this file was automatically generated
namespace ProcessOut;
use ProcessOut\ProcessOut;
use ProcessOut\Networking\Request;
class Coupon implements \JsonSerializable
{
/**
* ProcessOut's client
* @var ProcessOut\ProcessOut
*/
protected $client;
/**
* ID of the coupon
* @var string
*/
protected $id;
/**
* Project to which the coupon belongs
* @var object
*/
protected $project;
/**
* ID of the project to which the coupon belongs
* @var string
*/
protected $projectId;
/**
* Amount to be removed from the subscription price
* @var decimal
*/
protected $amountOff;
/**
* Percent of the subscription amount to be removed (integer between 0 and 100)
* @var integer
*/
protected $percentOff;
/**
* Currency of the coupon amount_off
* @var string
*/
protected $currency;
/**
* Number billing cycles the coupon will last when applied to a subscription. If 0, will last forever
* @var integer
*/
protected $iterationCount;
/**
* Number of time the coupon can be redeemed. If 0, there's no limit
* @var integer
*/
protected $maxRedemptions;
/**
* Date at which the coupon will expire
* @var string
*/
protected $expiresAt;
/**
* Metadata related to the coupon, in the form of a dictionary (key-value pair)
* @var dictionary
*/
protected $metadata;
/**
* Number of times the coupon was already redeemed
* @var integer
*/
protected $redeemedNumber;
/**
* True if the coupon was created in the sandbox environment, false otherwise
* @var boolean
*/
protected $sandbox;
/**
* Date at which the coupon was created
* @var string
*/
protected $createdAt;
/**
* Coupon constructor
* @param ProcessOut\ProcessOut $client
* @param array|null $prefill
*/
public function __construct(ProcessOut $client, $prefill = array())
{
$this->client = $client;
$this->fillWithData($prefill);
}
/**
* Get Id
* ID of the coupon
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Set Id
* ID of the coupon
* @param string $value
* @return $this
*/
public function setId($value)
{
$this->id = $value;
return $this;
}
/**
* Get Project
* Project to which the coupon belongs
* @return object
*/
public function getProject()
{
return $this->project;
}
/**
* Set Project
* Project to which the coupon belongs
* @param object $value
* @return $this
*/
public function setProject($value)
{
if (is_object($value))
$this->project = $value;
else
{
$obj = new Project($this->client);
$obj->fillWithData($value);
$this->project = $obj;
}
return $this;
}
/**
* Get ProjectId
* ID of the project to which the coupon belongs
* @return string
*/
public function getProjectId()
{
return $this->projectId;
}
/**
* Set ProjectId
* ID of the project to which the coupon belongs
* @param string $value
* @return $this
*/
public function setProjectId($value)
{
$this->projectId = $value;
return $this;
}
/**
* Get AmountOff
* Amount to be removed from the subscription price
* @return string
*/
public function getAmountOff()
{
return $this->amountOff;
}
/**
* Set AmountOff
* Amount to be removed from the subscription price
* @param string $value
* @return $this
*/
public function setAmountOff($value)
{
$this->amountOff = $value;
return $this;
}
/**
* Get PercentOff
* Percent of the subscription amount to be removed (integer between 0 and 100)
* @return int
*/
public function getPercentOff()
{
return $this->percentOff;
}
/**
* Set PercentOff
* Percent of the subscription amount to be removed (integer between 0 and 100)
* @param int $value
* @return $this
*/
public function setPercentOff($value)
{
$this->percentOff = $value;
return $this;
}
/**
* Get Currency
* Currency of the coupon amount_off
* @return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Set Currency
* Currency of the coupon amount_off
* @param string $value
* @return $this
*/
public function setCurrency($value)
{
$this->currency = $value;
return $this;
}
/**
* Get IterationCount
* Number billing cycles the coupon will last when applied to a subscription. If 0, will last forever
* @return int
*/
public function getIterationCount()
{
return $this->iterationCount;
}
/**
* Set IterationCount
* Number billing cycles the coupon will last when applied to a subscription. If 0, will last forever
* @param int $value
* @return $this
*/
public function setIterationCount($value)
{
$this->iterationCount = $value;
return $this;
}
/**
* Get MaxRedemptions
* Number of time the coupon can be redeemed. If 0, there's no limit
* @return int
*/
public function getMaxRedemptions()
{
return $this->maxRedemptions;
}
/**
* Set MaxRedemptions
* Number of time the coupon can be redeemed. If 0, there's no limit
* @param int $value
* @return $this
*/
public function setMaxRedemptions($value)
{
$this->maxRedemptions = $value;
return $this;
}
/**
* Get ExpiresAt
* Date at which the coupon will expire
* @return string
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Set ExpiresAt
* Date at which the coupon will expire
* @param string $value
* @return $this
*/
public function setExpiresAt($value)
{
$this->expiresAt = $value;
return $this;
}
/**
* Get Metadata
* Metadata related to the coupon, in the form of a dictionary (key-value pair)
* @return array
*/
public function getMetadata()
{
return $this->metadata;
}
/**
* Set Metadata
* Metadata related to the coupon, in the form of a dictionary (key-value pair)
* @param array $value
* @return $this
*/
public function setMetadata($value)
{
$this->metadata = $value;
return $this;
}
/**
* Get RedeemedNumber
* Number of times the coupon was already redeemed
* @return int
*/
public function getRedeemedNumber()
{
return $this->redeemedNumber;
}
/**
* Set RedeemedNumber
* Number of times the coupon was already redeemed
* @param int $value
* @return $this
*/
public function setRedeemedNumber($value)
{
$this->redeemedNumber = $value;
return $this;
}
/**
* Get Sandbox
* True if the coupon was created in the sandbox environment, false otherwise
* @return bool
*/
public function getSandbox()
{
return $this->sandbox;
}
/**
* Set Sandbox
* True if the coupon was created in the sandbox environment, false otherwise
* @param bool $value
* @return $this
*/
public function setSandbox($value)
{
$this->sandbox = $value;
return $this;
}
/**
* Get CreatedAt
* Date at which the coupon was created
* @return string
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set CreatedAt
* Date at which the coupon was created
* @param string $value
* @return $this
*/
public function setCreatedAt($value)
{
$this->createdAt = $value;
return $this;
}
/**
* Fills the current object with the new values pulled from the data
* @param array $data
* @return Coupon
*/
public function fillWithData($data)
{
if(! empty($data['id']))
$this->setId($data['id']);
if(! empty($data['project']))
$this->setProject($data['project']);
if(! empty($data['project_id']))
$this->setProjectId($data['project_id']);
if(! empty($data['amount_off']))
$this->setAmountOff($data['amount_off']);
if(! empty($data['percent_off']))
$this->setPercentOff($data['percent_off']);
if(! empty($data['currency']))
$this->setCurrency($data['currency']);
if(! empty($data['iteration_count']))
$this->setIterationCount($data['iteration_count']);
if(! empty($data['max_redemptions']))
$this->setMaxRedemptions($data['max_redemptions']);
if(! empty($data['expires_at']))
$this->setExpiresAt($data['expires_at']);
if(! empty($data['metadata']))
$this->setMetadata($data['metadata']);
if(! empty($data['redeemed_number']))
$this->setRedeemedNumber($data['redeemed_number']);
if(! empty($data['sandbox']))
$this->setSandbox($data['sandbox']);
if(! empty($data['created_at']))
$this->setCreatedAt($data['created_at']);
return $this;
}
/**
* Implements the JsonSerializable interface
* @return object
*/
public function jsonSerialize() {
return array(
"id" => $this->getId(),
"project" => $this->getProject(),
"project_id" => $this->getProjectId(),
"amount_off" => $this->getAmountOff(),
"percent_off" => $this->getPercentOff(),
"currency" => $this->getCurrency(),
"iteration_count" => $this->getIterationCount(),
"max_redemptions" => $this->getMaxRedemptions(),
"expires_at" => $this->getExpiresAt(),
"metadata" => $this->getMetadata(),
"redeemed_number" => $this->getRedeemedNumber(),
"sandbox" => $this->getSandbox(),
"created_at" => $this->getCreatedAt(),
);
}
/**
* Get all the coupons.
* @param array $options
* @return array
*/
public function all($options = array())
{
$this->fillWithData($options);
$request = new Request($this->client);
$path = "/coupons";
$data = array(
);
$response = $request->get($path, $data, $options);
$returnValues = array();
// Handling for field coupons
$a = array();
$body = $response->getBody();
foreach($body['coupons'] as $v)
{
$tmp = new Coupon($this->client);
$tmp->fillWithData($v);
$a[] = $tmp;
}
$returnValues['Coupons'] = $a;
return array_values($returnValues)[0];
}
/**
* Create a new coupon.
* @param array $options
* @return $this
*/
public function create($options = array())
{
$this->fillWithData($options);
$request = new Request($this->client);
$path = "/coupons";
$data = array(
"id" => $this->getId(),
"amount_off" => $this->getAmountOff(),
"percent_off" => $this->getPercentOff(),
"currency" => $this->getCurrency(),
"iteration_count" => $this->getIterationCount(),
"max_redemptions" => $this->getMaxRedemptions(),
"expires_at" => $this->getExpiresAt(),
"metadata" => $this->getMetadata()
);
$response = $request->post($path, $data, $options);
$returnValues = array();
// Handling for field coupon
$body = $response->getBody();
$body = $body['coupon'];
$returnValues['create'] = $this->fillWithData($body);
return array_values($returnValues)[0];
}
/**
* Find a coupon by its ID.
* @param string $couponId
* @param array $options
* @return $this
*/
public function find($couponId, $options = array())
{
$this->fillWithData($options);
$request = new Request($this->client);
$path = "/coupons/" . urlencode($couponId) . "";
$data = array(
);
$response = $request->get($path, $data, $options);
$returnValues = array();
// Handling for field coupon
$body = $response->getBody();
$body = $body['coupon'];
$returnValues['find'] = $this->fillWithData($body);
return array_values($returnValues)[0];
}
/**
* Save the updated coupon attributes.
* @param array $options
* @return $this
*/
public function save($options = array())
{
$this->fillWithData($options);
$request = new Request($this->client);
$path = "/coupons/" . urlencode($this->getId()) . "";
$data = array(
"metadata" => $this->getMetadata()
);
$response = $request->put($path, $data, $options);
$returnValues = array();
// Handling for field coupon
$body = $response->getBody();
$body = $body['coupon'];
$returnValues['save'] = $this->fillWithData($body);
return array_values($returnValues)[0];
}
/**
* Delete the coupon.
* @param array $options
* @return bool
*/
public function delete($options = array())
{
$this->fillWithData($options);
$request = new Request($this->client);
$path = "/coupons/" . urlencode($this->getId()) . "";
$data = array(
);
$response = $request->delete($path, $data, $options);
$returnValues = array();
$returnValues['success'] = $response->isSuccess();
return array_values($returnValues)[0];
}
}
| {
"content_hash": "342ac35c55f5d03ded87290150aa3462",
"timestamp": "",
"source": "github",
"line_count": 626,
"max_line_length": 105,
"avg_line_length": 23.18849840255591,
"alnum_prop": 0.5316891705704051,
"repo_name": "ProcessOut/processout-php",
"id": "6a992a1baac30b2a94da83ca2ae995db607199e2",
"size": "14516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Coupon.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "257505"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.aws.secretsmanager.integration;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws.secretsmanager.SecretsManagerConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import software.amazon.awssdk.services.secretsmanager.model.CreateSecretResponse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@DisabledIfSystemProperty(named = "ci.env.name", matches = "github.com", disabledReason = "Flaky on Apache CI")
public class SecretsManagerCreateSecretProducerLocalstackIT extends AwsSecretsManagerBaseTest {
@EndpointInject("mock:result")
private MockEndpoint mock;
@Test
public void createSecretTest() {
mock.expectedMessageCount(1);
Exchange exchange = template.request("direct:createSecret", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(SecretsManagerConstants.SECRET_NAME, "TestSecret4");
exchange.getIn().setBody("Body");
}
});
CreateSecretResponse resultGet = (CreateSecretResponse) exchange.getIn().getBody();
assertNotNull(resultGet);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:createSecret")
.to("aws-secrets-manager://test?operation=createSecret")
.to("mock:result");
}
};
}
}
| {
"content_hash": "a39ae1ef91bc20ad4a40392f126285d9",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 111,
"avg_line_length": 36.57142857142857,
"alnum_prop": 0.6936383928571429,
"repo_name": "christophd/camel",
"id": "f433c74eb76c0fa0d92b265b92a97307d099d49e",
"size": "2594",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "components/camel-aws/camel-aws-secrets-manager/src/test/java/org/apache/camel/component/aws/secretsmanager/integration/SecretsManagerCreateSecretProducerLocalstackIT.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6695"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5676"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "405043"
},
{
"name": "HTML",
"bytes": "212954"
},
{
"name": "Java",
"bytes": "114730615"
},
{
"name": "JavaScript",
"bytes": "103655"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "Kotlin",
"bytes": "41869"
},
{
"name": "Mustache",
"bytes": "525"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "15327"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "699"
},
{
"name": "XSLT",
"bytes": "276597"
}
],
"symlink_target": ""
} |
type: risks
template: risks
title: Risks overview
slug: risk
year: 2016
The following table shows four selected risks:
* Open DNS
* Open NTP
* Open SSDP
* Spam (spam sending devices)
in absolute numbers, as well as an averaged score over all countries.
### The score
In tables and maps on this website, you will see that countries are assigned a score. The score is a value between 0 and 100, where a higher score means a worse performance; that is, a greater number of affected devices and a higher level of risk or infection. You can read more about the [score and how it is calculated on the about page](/about#score).
| {
"content_hash": "abc570591e93362005eccec0f1b2f7e8",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 354,
"avg_line_length": 35.27777777777778,
"alnum_prop": 0.7559055118110236,
"repo_name": "cybergreen-net/stats",
"id": "044ae1befc320f76b12c6b028f6fcd83eba8cac1",
"size": "635",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/pages/risk/index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "276490"
},
{
"name": "HTML",
"bytes": "40947"
},
{
"name": "JavaScript",
"bytes": "37572"
},
{
"name": "Python",
"bytes": "24332"
}
],
"symlink_target": ""
} |
using extensions::Extension;
// An InProcessBrowserTest for testing the ExtensionToolbarModel.
// TODO(erikkay) It's unfortunate that this needs to be an in-proc browser test.
// It would be nice to refactor things so that ExtensionService could run
// without so much of the browser in place.
class ExtensionToolbarModelTest : public ExtensionBrowserTest,
public ExtensionToolbarModel::Observer {
public:
virtual void SetUp() {
inserted_count_ = 0;
removed_count_ = 0;
moved_count_ = 0;
ExtensionBrowserTest::SetUp();
}
virtual void SetUpOnMainThread() OVERRIDE {
ExtensionService* service = browser()->profile()->GetExtensionService();
model_ = service->toolbar_model();
model_->AddObserver(this);
}
virtual void CleanUpOnMainThread() {
model_->RemoveObserver(this);
}
virtual void BrowserActionAdded(const Extension* extension, int index) {
inserted_count_++;
}
virtual void BrowserActionRemoved(const Extension* extension) {
removed_count_++;
}
virtual void BrowserActionMoved(const Extension* extension, int index) {
moved_count_++;
}
const Extension* ExtensionAt(int index) {
const extensions::ExtensionList& toolbar_items = model_->toolbar_items();
for (extensions::ExtensionList::const_iterator i = toolbar_items.begin();
i < toolbar_items.end(); ++i) {
if (index-- == 0)
return *i;
}
return NULL;
}
protected:
ExtensionToolbarModel* model_;
int inserted_count_;
int removed_count_;
int moved_count_;
};
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, Basic) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
// Load an extension with no browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("none")));
// This extension should not be in the model (has no browser action).
EXPECT_EQ(0, inserted_count_);
EXPECT_EQ(0u, model_->toolbar_items().size());
ASSERT_EQ(NULL, ExtensionAt(0));
// Load an extension with a browser action.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics")));
// We should now find our extension in the model.
EXPECT_EQ(1, inserted_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extension = ExtensionAt(0);
ASSERT_TRUE(NULL != extension);
EXPECT_STREQ("A browser action with no icon that makes the page red",
extension->name().c_str());
// Should be a no-op, but still fires the events.
model_->MoveBrowserAction(extension, 0);
EXPECT_EQ(1, moved_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extension2 = ExtensionAt(0);
EXPECT_EQ(extension, extension2);
UnloadExtension(extension->id());
EXPECT_EQ(1, removed_count_);
EXPECT_EQ(0u, model_->toolbar_items().size());
EXPECT_EQ(NULL, ExtensionAt(0));
}
IN_PROC_BROWSER_TEST_F(ExtensionToolbarModelTest, ReorderAndReinsert) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
// Load an extension with a browser action.
FilePath extension_a_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("basics"));
ASSERT_TRUE(LoadExtension(extension_a_path));
// First extension loaded.
EXPECT_EQ(1, inserted_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
const Extension* extensionA = ExtensionAt(0);
ASSERT_TRUE(NULL != extensionA);
EXPECT_STREQ("A browser action with no icon that makes the page red",
extensionA->name().c_str());
// Load another extension with a browser action.
FilePath extension_b_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("popup"));
ASSERT_TRUE(LoadExtension(extension_b_path));
// Second extension loaded.
EXPECT_EQ(2, inserted_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
const Extension* extensionB = ExtensionAt(1);
ASSERT_TRUE(NULL != extensionB);
EXPECT_STREQ("Popup tester", extensionB->name().c_str());
// Load yet another extension with a browser action.
FilePath extension_c_path(test_data_dir_.AppendASCII("api_test")
.AppendASCII("browser_action")
.AppendASCII("remove_popup"));
ASSERT_TRUE(LoadExtension(extension_c_path));
// Third extension loaded.
EXPECT_EQ(3, inserted_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
const Extension* extensionC = ExtensionAt(2);
ASSERT_TRUE(NULL != extensionC);
EXPECT_STREQ("A page action which removes a popup.",
extensionC->name().c_str());
// Order is now A, B, C. Let's put C first.
model_->MoveBrowserAction(extensionC, 0);
EXPECT_EQ(1, moved_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(extensionB, ExtensionAt(2));
EXPECT_EQ(NULL, ExtensionAt(3));
// Order is now C, A, B. Let's put A last.
model_->MoveBrowserAction(extensionA, 2);
EXPECT_EQ(2, moved_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionB, ExtensionAt(1));
EXPECT_EQ(extensionA, ExtensionAt(2));
EXPECT_EQ(NULL, ExtensionAt(3));
// Order is now C, B, A. Let's remove B.
std::string idB = extensionB->id();
UnloadExtension(idB);
EXPECT_EQ(1, removed_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Load extension B again.
ASSERT_TRUE(LoadExtension(extension_b_path));
// Extension B loaded again.
EXPECT_EQ(4, inserted_count_);
EXPECT_EQ(3u, model_->toolbar_items().size());
// Make sure it gets its old spot in the list. We should get the same
// extension again, otherwise the order has changed.
ASSERT_STREQ(idB.c_str(), ExtensionAt(1)->id().c_str());
// Unload B again.
UnloadExtension(idB);
EXPECT_EQ(2, removed_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionC, ExtensionAt(0));
EXPECT_EQ(extensionA, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Order is now C, A. Flip it.
model_->MoveBrowserAction(extensionA, 0);
EXPECT_EQ(3, moved_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(extensionC, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Move A to the location it already occupies.
model_->MoveBrowserAction(extensionA, 0);
EXPECT_EQ(4, moved_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(extensionC, ExtensionAt(1));
EXPECT_EQ(NULL, ExtensionAt(2));
// Order is now A, C. Remove C.
std::string idC = extensionC->id();
UnloadExtension(idC);
EXPECT_EQ(3, removed_count_);
EXPECT_EQ(1u, model_->toolbar_items().size());
EXPECT_EQ(extensionA, ExtensionAt(0));
EXPECT_EQ(NULL, ExtensionAt(1));
// Load extension C again.
ASSERT_TRUE(LoadExtension(extension_c_path));
// Extension C loaded again.
EXPECT_EQ(5, inserted_count_);
EXPECT_EQ(2u, model_->toolbar_items().size());
// Make sure it gets its old spot in the list (at the very end).
ASSERT_STREQ(idC.c_str(), ExtensionAt(1)->id().c_str());
}
| {
"content_hash": "f9e529ecb61a1ddcc1bb2e339d8215be",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 80,
"avg_line_length": 35.731818181818184,
"alnum_prop": 0.6529703600050885,
"repo_name": "junmin-zhu/chromium-rivertrail",
"id": "ddf0f6e859aa28627ccb588ac327d5a2f16b3749",
"size": "8394",
"binary": false,
"copies": "4",
"ref": "refs/heads/v8-binding",
"path": "chrome/browser/extensions/extension_toolbar_model_browsertest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1172794"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "75806807"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "145161929"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "1546515"
},
{
"name": "JavaScript",
"bytes": "18675242"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "6981387"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "926245"
},
{
"name": "Python",
"bytes": "8088373"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3239"
},
{
"name": "Shell",
"bytes": "1513486"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
],
"symlink_target": ""
} |
<?php
namespace backend\controllers;
use Yii;
use backend\models\IllegalKeyword;
use backend\models\IllegalKeywordSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* IllegalkeywordController implements the CRUD actions for IllegalKeyword model.
*/
class IllegalkeywordController extends BackendController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all IllegalKeyword models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new IllegalKeywordSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single IllegalKeyword model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new IllegalKeyword model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new IllegalKeyword();
if ($model->load(Yii::$app->request->post()) ) {
$model->created_at = time();
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing IllegalKeyword model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing IllegalKeyword model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the IllegalKeyword model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return IllegalKeyword the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = IllegalKeyword::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| {
"content_hash": "05d98fe2ab1aa3b8f9e9ad102e9e812d",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 85,
"avg_line_length": 26.548387096774192,
"alnum_prop": 0.5434386391251519,
"repo_name": "mianbao726/sunny",
"id": "4e16d31d0f46023336203d4bc8f99e819ab1c533",
"size": "3292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_protected/backend/controllers/IllegalkeywordController.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "578"
},
{
"name": "Batchfile",
"bytes": "1540"
},
{
"name": "CSS",
"bytes": "253526"
},
{
"name": "JavaScript",
"bytes": "782248"
},
{
"name": "PHP",
"bytes": "700324"
}
],
"symlink_target": ""
} |
/**
* Function that returns default values.
* Used because Object.assign does a shallow instead of a deep copy.
* Using [].push will add to the base array, so a require will alter
* the base array output.
*/
'use strict';
const path = require('path');
const srcPath = path.join(__dirname, '/../src');
const dfltPort = 8000;
/**
* Get the default modules object for webpack
* @return {Object}
*/
function getDefaultModules() {
return {
preLoaders: [
{
test: /\.(js|jsx)$/,
include: srcPath,
loader: 'eslint-loader'
}
],
loaders: [
{
test: /\.css$/,
loader: 'style-loader!css-loader!postcss-loader'
},
{
test: /\.sass/,
loader: 'style-loader!css-loader!sass-loader!postcss-loader?outputStyle=expanded&indentedSyntax'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!sass-loader!postcss-loader?outputStyle=expanded'
},
{
test: /\.less/,
loader: 'style-loader!css-loader!less-loader!postcss-loader'
},
{
test: /\.styl/,
loader: 'style-loader!css-loader!stylus-loader!postcss-loader'
},
{
test: /\.(png|jpg|gif|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.(mp4|ogg|svg)$/,
loader: 'file-loader'
}
]
};
}
module.exports = {
srcPath: srcPath,
publicPath: '/assets/',
port: dfltPort,
getDefaultModules: getDefaultModules
};
| {
"content_hash": "ed4a407a253ba014483ed0bbbabee1f3",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 104,
"avg_line_length": 23.75,
"alnum_prop": 0.5697368421052632,
"repo_name": "Aikk/gallery-by-react",
"id": "aabc0b4333d5f5e25e3d0bc9f541c50b2f010196",
"size": "1520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cfg/defaults.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3002"
},
{
"name": "HTML",
"bytes": "1109"
},
{
"name": "JavaScript",
"bytes": "19979"
}
],
"symlink_target": ""
} |
/**
* @file
* @brief ARM Cortex-M k_thread_abort() routine
*
* The ARM Cortex-M architecture provides its own k_thread_abort() to deal
* with different CPU modes (handler vs thread) when a thread aborts. When its
* entry point returns or when it aborts itself, the CPU is in thread mode and
* must call _Swap() (which triggers a service call), but when in handler
* mode, the CPU must exit handler mode to cause the context switch, and thus
* must queue the PendSV exception.
*/
#include <kernel.h>
#include <kernel_structs.h>
#include <toolchain.h>
#include <linker/sections.h>
#include <ksched.h>
#include <wait_q.h>
#include <misc/__assert.h>
extern void _k_thread_single_abort(struct k_thread *thread);
void _impl_k_thread_abort(k_tid_t thread)
{
unsigned int key;
key = irq_lock();
__ASSERT(!(thread->base.user_options & K_ESSENTIAL),
"essential thread aborted");
_k_thread_single_abort(thread);
_thread_monitor_exit(thread);
if (_current == thread) {
if ((SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) == 0) {
_Swap(key);
CODE_UNREACHABLE;
} else {
SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk;
}
}
/* The abort handler might have altered the ready queue. */
_reschedule_threads(key);
}
| {
"content_hash": "145257e4693d9bd4affa3d39cb50ed94",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 78,
"avg_line_length": 25.458333333333332,
"alnum_prop": 0.6890343698854338,
"repo_name": "aceofall/zephyr-iotos",
"id": "3d398a530760ded5908fe9298800ae82951888a3",
"size": "1317",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "arch/arm/core/thread_abort.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "407937"
},
{
"name": "C",
"bytes": "240981874"
},
{
"name": "C++",
"bytes": "2140671"
},
{
"name": "CMake",
"bytes": "244239"
},
{
"name": "Lex",
"bytes": "11299"
},
{
"name": "Makefile",
"bytes": "40445"
},
{
"name": "Objective-C",
"bytes": "17224"
},
{
"name": "Perl",
"bytes": "216930"
},
{
"name": "Python",
"bytes": "366266"
},
{
"name": "Shell",
"bytes": "39214"
},
{
"name": "Verilog",
"bytes": "6394"
},
{
"name": "Yacc",
"bytes": "15396"
}
],
"symlink_target": ""
} |
<?php
namespace app\lib\commands;
use app\lib\BaseCommand;
use yii\console\Exception;
use yii\helpers\Console;
use yii\helpers\FileHelper;
use Yii;
class RmdirCommand extends BaseCommand
{
/**
* @inheritdoc
*/
public function run(& $cmdParams, & $params)
{
$taskRunner = $this->taskRunner;
$path = (!empty($cmdParams[0]) ? $taskRunner->parsePath($cmdParams[0]) : '');
if (empty($path)) {
throw new Exception('rmdir: Path cannot be empty');
}
$this->controller->stdout('Removing directory: ' . $path);
if (!$this->controller->dryRun) {
FileHelper::removeDirectory($path);
} else {
$this->controller->stdout(' [dry run]', Console::FG_YELLOW);
}
$this->controller->stdout("\n");
return true;
}
} | {
"content_hash": "0dabbab7ff884b6cded85cf82fbd4b87",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 85,
"avg_line_length": 20.658536585365855,
"alnum_prop": 0.5714285714285714,
"repo_name": "giovdk21/deployii",
"id": "e649980972a238a0711acf3cde9d78df8fa97734",
"size": "1054",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/commands/RmdirCommand.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "184286"
},
{
"name": "Shell",
"bytes": "2077"
}
],
"symlink_target": ""
} |
package com.intellij.velocity.inspections;
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.ResolveState;
import com.intellij.psi.scope.BaseScopeProcessor;
import static com.intellij.velocity.VelocityBundle.message;
import com.intellij.velocity.psi.VtlElementTypes;
import com.intellij.velocity.psi.VtlExpression;
import com.intellij.velocity.psi.VtlMacro;
import com.intellij.velocity.psi.VtlParameterDeclaration;
import com.intellij.velocity.psi.directives.VtlMacroImpl;
import com.intellij.velocity.psi.directives.VtlParse;
import com.intellij.velocity.psi.files.VtlFile;
import org.jetbrains.annotations.NonNls;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Alexey Chmutov
*/
public class VtlMacroAnnotator implements Annotator {
@NonNls
private static final String V_IDENT = "([a-zA-Z_][a-zA-Z_0-9-]*)";
@NonNls
private static final Pattern WOULD_BE_MACRO_CALL_PATTERN = Pattern.compile("(#" + V_IDENT + ")|(#\\{" + V_IDENT + "\\})");
public void annotate(final PsiElement element, final AnnotationHolder holder) {
if (element instanceof VtlMacroImpl) {
final VtlMacroImpl macro = (VtlMacroImpl) element;
final VtlFile file = macro.getContainingFile();
String macroName = macro.getName();
if (macroName != null && file.getNumberOfMacros(macroName) > 1) {
holder.createErrorAnnotation(macro.getNameElementRange(), message("macro.is.already.defined", macroName, file.getName()));
}
} else if (element instanceof VtlParameterDeclaration) {
VtlParameterDeclaration param = (VtlParameterDeclaration) element;
String paramName = param.getName();
if (paramName == null) {
return;
}
PsiElement sibling = param.getPrevSibling();
while (sibling != null) {
if (sibling instanceof VtlParameterDeclaration
&& paramName.equals(((VtlParameterDeclaration) sibling).getName())) {
final String msg = message("duplicated.parameter.name", paramName);
holder.createErrorAnnotation(param.getTextRange(), msg);
holder.createErrorAnnotation(sibling.getTextRange(), msg);
}
sibling = sibling.getPrevSibling();
}
} else if (element instanceof VtlParse) {
final VtlParse parse = (VtlParse) element;
VtlFile parsedFile = parse.resolveFile();
if (parsedFile == null) {
return;
}
final VtlExpression parsedFileElement = parse.getArgumentList().getArguments()[0];
final VtlFile containingFile = parse.getContainingFile();
for (String macroName : containingFile.getDefinedMacroNames()) {
if (parsedFile.getNumberOfMacros(macroName) > 0) {
final String msg = message("macro.declaration.will.be.ignored", macroName, containingFile.getName(), parsedFile.getName());
holder.createWarningAnnotation(parsedFileElement, msg);
}
}
} else {
final ASTNode node = element.getNode();
if (node == null || node.getElementType() != VtlElementTypes.TEMPLATE_TEXT) {
return;
}
final Matcher matcher = WOULD_BE_MACRO_CALL_PATTERN.matcher(node.getText());
if (!matcher.find()) {
return;
}
final PsiFile file = element.getContainingFile();
if (!(file instanceof VtlFile)) {
return;
}
final VtlFile vtlFile = (VtlFile) file;
do {
int index = matcher.start(2) != -1 ? 2 : 4;
final String macroName = matcher.group(index);
final BaseScopeProcessor processor = new BaseScopeProcessor() {
public boolean execute(PsiElement element, ResolveState state) {
return !(element instanceof VtlMacro && macroName.equals(((VtlMacro) element).getName()));
}
};
if (!vtlFile.processAllMacrosInScope(processor, ResolveState.initial())) {
TextRange range = new TextRange(matcher.start(), matcher.end()).shiftRight(element.getTextOffset());
holder.createErrorAnnotation(range, message("will.be.considered.as.macro.call"));
}
} while (matcher.find());
}
}
} | {
"content_hash": "bfe1f35d865e4a9a99540281ac1cdbce",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 143,
"avg_line_length": 47.05882352941177,
"alnum_prop": 0.6220833333333333,
"repo_name": "consulo/consulo-apache-velocity",
"id": "ddaa3e51ba5fbeaba2ed113583ce3b6044eb92d2",
"size": "5400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/intellij/velocity/inspections/VtlMacroAnnotator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2349"
},
{
"name": "Java",
"bytes": "470778"
},
{
"name": "Lex",
"bytes": "14861"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>jsonld-java-integration</artifactId>
<groupId>com.github.jsonld-java</groupId>
<version>0.6.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jsonld-java-rdf2go</artifactId>
<name>JSONLD Java :: RDF2Go</name>
<description>JSON-LD Java integration module for RDF2Go</description>
<packaging>bundle</packaging>
<developers>
<developer>
<id>ismriv</id>
<name>Ismael Rivera</name>
<url>http://ismaelrivera.es</url>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jsonld-java</artifactId>
<version>${project.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jsonld-java</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.semweb4j</groupId>
<artifactId>rdf2go.api</artifactId>
<version>${rdf2go.version}</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.semweb4j</groupId>
<artifactId>rdf2go.impl.sesame</artifactId>
<version>${rdf2go.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "e310a2681a0fb211913738b789e79bfc",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 104,
"avg_line_length": 27.522727272727273,
"alnum_prop": 0.6862097440132122,
"repo_name": "westei/jsonld-java",
"id": "ee3f2bd0be9f035b56eb8ff042ed63c05f8e6bfd",
"size": "2422",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "integration/rdf2go/pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "515301"
},
{
"name": "Shell",
"bytes": "393"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Impact++ / Source: entities/particle-color.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="scripts/html5shiv.js"> </script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="styles/main.css">
</head>
<body data-spy="scroll" data-target="#navdoc">
<section>
<article>
<pre class="prettyprint source"><code>ig.module(
'plusplus.entities.particle-color'
)
.requires(
'plusplus.core.config',
'plusplus.abstractities.particle-fast'
)
.defines(function() {
"use strict";
var _c = ig.CONFIG;
/**
* Fast particle that looks like a simple colored square.
* <span class="alert"><strong>IMPORTANT:</strong> this entity has a defined size and animation sheet!</span>
* <br>- colored particle sprite sheet courtesy of Jesse Freeman
* @class
* @extends ig.ParticleFast
* @memberof ig
* @author Collin Hover - collinhover.com
* @author Jesse Freeman
**/
ig.EntityParticleColor = ig.global.EntityParticleColor = ig.ParticleFast.extend( /**@lends ig.EntityParticleColor.prototype */ {
/**
* @override
* @default 2x2
*/
size: {
x: 2,
y: 2
},
/**
* @override
* @default particles.png
*/
animSheet: new ig.AnimationSheet(_c.PATH_TO_MEDIA + 'particles.png', 2, 2),
/**
* @override
* @default
*/
animTileOffset: 0,
/**
* @override
* @default
*/
animSequenceCount: 7,
/**
* @override
* @default 50x50
*/
vel: {
x: 50,
y: 50
},
/**
* @override
* @default
*/
lifeDuration: 0.35,
/**
* @override
* @default
*/
fadeBeforeDeathDuration: 0.15,
// internal properties, do not modify
_animTileOffsetLast: -1,
/**
* Resets color particle visuals and randomizes slightly from offset.
* @override
**/
reset: function(x, y, settings) {
this.parent(x, y, settings);
if (this._animTileOffsetLast !== this.animTileOffset) {
this._animTileOffsetLast = this.animTileOffset;
this.addAnim("move", {
sequence: [Math.round(Math.random() * this.animSequenceCount) + (this.animTileOffset * (this.animSequenceCount + 1))],
frameTime: 1,
stop: true
});
}
}
});
/**
* Color offset map, based on {@link ig.EntityParticleColor#animSheet}
* @memberof ig.EntityParticleColor
* @property {Number} RED 0
* @property {Number} YELLOW 4
* @property {Number} GREEN 8
* @property {Number} BLUE 12
* @property {Number} PURPLE 16
* @property {Number} BROWN 20
* @property {Number} GRAY 24
* @property {Number} WHITE 28
*/
ig.EntityParticleColor.colorOffsets = {
RED: 0,
YELLOW: 4,
GREEN: 8,
BLUE: 12,
PURPLE: 16,
BROWN: 20,
GRAY: 24,
WHITE: 28
};
});
</code></pre>
</article>
</section>
<script src="scripts/linenumber.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="scripts/jquery-1.9.1.min.js"><\/script>')</script>
<script src="scripts/bootstrap.min.js"> </script>
<script src="scripts/main.js"> </script>
</body>
</html>
| {
"content_hash": "33fa9b61e96faa92b113783a98be774e",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 142,
"avg_line_length": 27.209580838323355,
"alnum_prop": 0.4977992957746479,
"repo_name": "modulexcite/impactplusplus",
"id": "b5734be218ed02bf073a389b92ab5874024fb4c1",
"size": "4544",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/particle-color.js.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2719"
},
{
"name": "JavaScript",
"bytes": "1506261"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.migrationhuborchestrator.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.migrationhuborchestrator.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetTemplateRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetTemplateRequestProtocolMarshaller implements Marshaller<Request<GetTemplateRequest>, GetTemplateRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/migrationworkflowtemplate/{id}").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false)
.serviceName("AWSMigrationHubOrchestrator").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetTemplateRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetTemplateRequest> marshall(GetTemplateRequest getTemplateRequest) {
if (getTemplateRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetTemplateRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
getTemplateRequest);
protocolMarshaller.startMarshalling();
GetTemplateRequestMarshaller.getInstance().marshall(getTemplateRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {
"content_hash": "4d288b7370114b3e6cd8b5bb4694748c",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 150,
"avg_line_length": 40.13461538461539,
"alnum_prop": 0.761379971250599,
"repo_name": "aws/aws-sdk-java",
"id": "7f95648a7d87b29b003f2cd381ad58f127ed7a8b",
"size": "2667",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-migrationhuborchestrator/src/main/java/com/amazonaws/services/migrationhuborchestrator/model/transform/GetTemplateRequestProtocolMarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
public class VerySecureEncryption {
public String encrypt(String message, int[] key, int K) {
if (K == 0) {
return message;
}
String scrambledMessage = new String();
for (int j = 0; j < K; j++) { //mix up k times
for (int w = 0; w < key.length; w++) { //go through 0 through n
for (int i = 0; i < key.length; i++) { //go through entire array key
if (key[i] == w) {
scrambledMessage += message.charAt(i);
}
}
}
message = scrambledMessage;
scrambledMessage = "";
}
return message;
}
}
| {
"content_hash": "4bc2481390ba4efe016b794ce6a11e3e",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 72,
"avg_line_length": 22.08,
"alnum_prop": 0.5634057971014492,
"repo_name": "emmasax1/LearningComputerScience",
"id": "fd33087eb370e5267768222ec85ae03e57587c5f",
"size": "552",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "preACM/src/VerySecureEncryption.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Clojure",
"bytes": "6162"
},
{
"name": "HTML",
"bytes": "93"
},
{
"name": "Java",
"bytes": "43769"
},
{
"name": "JavaScript",
"bytes": "6858"
},
{
"name": "Ruby",
"bytes": "53987"
},
{
"name": "Shell",
"bytes": "3689"
}
],
"symlink_target": ""
} |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EntryValidator.FormsPlugin.Abstractions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EntryValidator.FormsPlugin.Abstractions")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "eb91c69d4bfd7a41091812af9d483147",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 84,
"avg_line_length": 37.766666666666666,
"alnum_prop": 0.7528684907325685,
"repo_name": "wilsonvargas/EntryValidatorPlugin",
"id": "d4175114cd14f97a412a724a941bda9e28d78573",
"size": "1136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/EntryValidator/EntryValidator.FormsPlugin.Abstractions/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "108"
},
{
"name": "C#",
"bytes": "65463"
},
{
"name": "PowerShell",
"bytes": "7318"
},
{
"name": "Shell",
"bytes": "2936"
}
],
"symlink_target": ""
} |
package org.museautomation.builtins.tests;
import org.junit.jupiter.api.*;
import org.museautomation.builtins.value.*;
import org.museautomation.core.*;
import org.museautomation.core.context.*;
import org.museautomation.core.project.*;
import org.museautomation.core.resource.*;
import org.museautomation.core.values.*;
import org.museautomation.core.values.descriptor.*;
import org.museautomation.core.values.strings.*;
/**
* @author Christopher L Merrill (see LICENSE.txt for license details)
*/
class NameValuePairSourceTests
{
@Test
void returnValue() throws MuseInstantiationException, ValueSourceResolutionError
{
MuseValueSource source = _config.createSource(_project);
Object result = source.resolveValue(new ProjectExecutionContext(_project));
Assertions.assertTrue(result instanceof NameValuePair);
NameValuePair pair = (NameValuePair) result;
Assertions.assertEquals("name1", pair.getName());
Assertions.assertEquals("value1", pair.getValue());
}
@Test
void instanceDescription()
{
String description = new ValueSourceDescriptors(_project).get(_config).getInstanceDescription(_config, new RootStringExpressionContext(_project));
Assertions.assertTrue(description.contains("name1"));
Assertions.assertTrue(description.contains("value1"));
}
@BeforeEach
void setup()
{
_project = new SimpleProject();
_config = ValueSourceConfiguration.forType(NameValuePairSource.TYPE_ID);
_config.addSource(NameValuePairSource.NAME_PARAM, ValueSourceConfiguration.forValue("name1"));
_config.addSource(NameValuePairSource.VALUE_PARAM, ValueSourceConfiguration.forValue("value1"));
}
private ValueSourceConfiguration _config;
private MuseProject _project;
}
| {
"content_hash": "26a497fb9f39badd890c015166cf55ee",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 154,
"avg_line_length": 36.35294117647059,
"alnum_prop": 0.7243797195253506,
"repo_name": "ChrisLMerrill/muse",
"id": "0ae5b0c068f3cc717cd6391439327433a1a43485",
"size": "1854",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/org/museautomation/builtins/tests/NameValuePairSourceTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1354843"
},
{
"name": "JavaScript",
"bytes": "2748"
}
],
"symlink_target": ""
} |
<!--
Copyright 2021 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.
-->
<!DOCTYPE html>
<html>
<body>
<p>Cross-origin content</p>
</body>
</html>
| {
"content_hash": "f3954f7158ad3401db3430a252dc3155",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 72,
"avg_line_length": 19.153846153846153,
"alnum_prop": 0.6907630522088354,
"repo_name": "ChromeDevTools/devtools-frontend",
"id": "a716d5511f4c0ca66bfe06c89f000a15d772a9a1",
"size": "249",
"binary": false,
"copies": "9",
"ref": "refs/heads/main",
"path": "test/e2e/resources/issues/cross-origin-portal.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "615241"
},
{
"name": "Dart",
"bytes": "205"
},
{
"name": "HTML",
"bytes": "317251"
},
{
"name": "JavaScript",
"bytes": "1401177"
},
{
"name": "LLVM",
"bytes": "1918"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Python",
"bytes": "133111"
},
{
"name": "Shell",
"bytes": "1122"
},
{
"name": "TypeScript",
"bytes": "15230731"
},
{
"name": "WebAssembly",
"bytes": "921"
}
],
"symlink_target": ""
} |
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
package org.globus.cog.abstraction.impl.file.webdav;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.impl.common.task.SecurityContextImpl;
public class WebDAVSecurityContextImpl extends SecurityContextImpl {
private static Logger logger = Logger
.getLogger(WebDAVSecurityContextImpl.class.getName());
public WebDAVSecurityContextImpl() {
}
}
| {
"content_hash": "f79c5ee6d160e0a4544944d432cc9654",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 72,
"avg_line_length": 34.142857142857146,
"alnum_prop": 0.6122733612273361,
"repo_name": "ya7lelkom/swift-k",
"id": "4f77382bff8109a7a9de9fe793a92dd9d0d4713f",
"size": "1460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cogkit/modules/provider-webdav/src/org/globus/cog/abstraction/impl/file/webdav/WebDAVSecurityContextImpl.java",
"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": ""
} |
@interface CreateCourseViewController : UIViewController <CLLocationManagerDelegate,UIActionSheetDelegate>
- (IBAction)MenuButtonPressed:(id)sender;
@property (strong, nonatomic) CLLocationManager *LocationManager;
@property (strong, nonatomic) id<GMSMarker> CurrentLocation;
@property (strong,nonatomic) id<GMSPolyline> MapConnector;
@property (strong, nonatomic) NSDate *Time;
@property (nonatomic,strong) NSMutableArray *Questions;
@property (nonatomic,strong) NSMutableArray *Nodes;
@property (nonatomic) Boolean Satellite;
@property (nonatomic) double Latitude;
@property (nonatomic) double Longitude;
@end
| {
"content_hash": "2985dbb15b7b36e4e751c29883e6192b",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 106,
"avg_line_length": 36.294117647058826,
"alnum_prop": 0.813614262560778,
"repo_name": "martinborjesson/quizwalker",
"id": "2cb6db398334a151f0228d518ee6253ec6e4f34a",
"size": "906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quizwalker/CreateCourseViewController.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "152017"
}
],
"symlink_target": ""
} |
**This software is not ready for production! It is still being developed and it will change in the future.**
The goal is to have a starter project which can be used to quickly build an API with a frontend that are easily extended.
[](https://gitter.im/beeman/loopback-angular-admin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[](http://badge.fury.io/js/loopback-angular-admin)
[](https://david-dm.org/beeman/loopback-angular-admin)
[](https://www.codeship.io/projects/42207)
[](https://app.wercker.com/project/bykey/d5bf1a6b787b3c00633c02da0f9a48e5)
[](https://drone.io/github.com/beeman/loopback-angular-admin/latest)
## Try it now!
Deploy an instance on your Heroku account to play around with it!
[](https://heroku.com/deploy)
## Using Docker Compose
After install [Docker Compose](https://docs.docker.com/compose/), start up the container using:
docker-compose up
Browse your app by going to: [http://localhost:9000](http://localhost:9000)
Features:
* Live Reload of your angular application if changes made in client/
* Automatic restarting of the server application if changes made in common/ or server/ files.
## Users
After an installation the following users are created:
- **Admin user**: Email: ```admin@admin.com```, password: ```admin```
- **Regular user**: Email: ```user@user.com```:, password ```user```
Please note, at this moment there is no difference in permissions for admin users or regular users. This needs to change in the future!
## Features and implemented projects
- A LoopBack REST API with authentication enabled built on the [LoopBack Generator](https://www.npmjs.org/package/generator-loopback)
- A GUI built with AngularJS based on the [Angular Generator](https://github.com/yeoman/generator-angular)
- Angular UI-Router
- JSON-based based forms by [angular-formly](https://formly-js.github.io/angular-formly/)
- Notifications by [angular-toasty](https://github.com/Salakar/angular-toasty)
- File upload with [LoopBack storage services](https://github.com/strongloop/loopback-component-storage/)
- Admin template powered by [almasaeed2010/AdminLTE](https://github.com/almasaeed2010/AdminLTE)
- Markdown Editor with live preview with [angular-markdown-editor](https://github.com/JimLiu/angular-markdown-editor)
- Bunch of useful filters for AngularJS: [a8m/angular-filter](https://github.com/a8m/angular-filter)
- [t4t5/sweetalert](https://github.com/t4t5/sweetalert) provided by [oitozero/ngSweetAlert](https://github.com/oitozero/ngSweetAlert)
- Automatically growing textarea's by [monospaced/angular-elastic](https://github.com/monospaced/angular-elastic)
- Social authentication with [LoopBack passport](https://github.com/strongloop/loopback-component-passport/)
- Multi-language support by [rubenv/angular-gettext](https://github.com/rubenv/angular-gettext)
- User management
- Loading indicators [chieffancypants/angular-loading-bar](https://github.com/chieffancypants/angular-loading-bar)?
## Unit Testing using [Karma](http://karma-runner.github.io/0.12/index.html)/[Jasmine](http://jasmine.github.io/)
Initial unit tests are located in client/test, and may be executed via:
$ ```node_modules/.bin/karma start client/test/karma.conf.js```
INFO [karma]: Karma v0.12.31 server started at http://localhost:8080/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Linux)]: Connected on socket aLJmRuSNUH2rPfpWgS3l with id 89641972
PhantomJS 1.9.8 (Linux): Executed 1 of 1 SUCCESS (0.007 secs / 0.029 secs)
## TODO:
- Permissions on user actions (non-admins cannot access advanced functions)
- permissions on content items (non-admins can only edit own content, etc)
- Detect if API is online [HubSpot/offline](https://github.com/HubSpot/offline)?
- Map API roles to [Narzerus/angular-permission](https://github.com/Narzerus/angular-permission)
- Add tests
- Add Dockerfile
- Add Vagrantfile
[Tell me what we need more!](https://github.com/beeman/loopback-angular-admin/issues/new)
## Screenshots
#### Dashboard

#### Markdown Editor

#### SweetAlert

#### File uploads

#### Events

## Installation
### Dependencies
Installation depends on `node`/`npm` with `grunt` and `bower` installed globally.
$ npm install -g bower grunt-cli
### Checkout the project:
git clone https://github.com/beeman/loopback-angular-admin.git
### Install the Node packages:
npm install
### Clone, install and run in a oneliner
git clone https://github.com/beeman/loopback-angular-admin.git && cd loopback-angular-admin && npm install && npm start & grunt serve
## Running
The project is separated in a server and a client.
### Server
To run the server you issue the command:
npm start
Or to run it with nodemon (needs `nodemon` installed globally). This will
automatically restart the server when you change its code:
npm run dev
### Client
Rebuild the lb-services.js file with the correct `API_URL` for development.
API_URL=http://0.0.0.0:3000/api grunt
To run the client you issue the command:
grunt serve
It will open the project in your default browser with livereload enabled.
This will take care of reloading the page when you change your code.
## Connect to a database
You can specify the URL to the MongoDB database you want to use with the `MONGODB_URL` environment variable.
MONGODB_URL="mongodb://localhost:27017/loopback-angular-admin" npm start
Set `INITDB` to true if you want to load the initial dataset, which creates the admin user. The memory database (default) does this automatically.
INITDB=true MONGODB_URL="mongodb://localhost:27017/loopback-angular-admin" npm start
This also works with the free hosted MongoDB instances at [compose.io](https://www.compose.io) and [mongolab.com](https://mongolab.com)!
## Development
If you want to share your work through a Pull Request, be sure to make it a clean branch (one functionality per PR) and base it off master.
If you plan on making a big change or replace a core function with something else it is probably best to first open an issue to discuss it with me. This will enhance the chance of the eventual changes getting merged a lot :)
The API is built with [generator-loopback](https://www.npmjs.org/package/generator-loopback).
The GUI is built with [generator-angular](https://www.npmjs.org/package/generator-angular) but is no longer compatible due to refactoring the project into modules.
These should help you quickly add code to your project. Further details tailored to this project might follow in the future.
### Useful commits
These commits might be useful when extending the functionality.
- [Add support for MongoDB databases](https://github.com/beeman/loopback-angular-admin/commit/6b884e601d535ed64b4ef4f6f07e0f55d357a5b6)
- [Add custom method to the API](https://github.com/beeman/loopback-angular-admin/commit/eedbd03f755ddf2234872886ee390ac4f6753c64)
- [Rename a model](https://github.com/beeman/loopback-angular-admin/commit/88254ce59af29818aec900514693e3fe6c94acea)
### WebSockets / socket.io
At this moment there is no integration for socket.io or websockets, nor will there be in the near future. Once LoopBack has integrated support for it we will leverage from that.
Having that said, it's certainly possible to integrate socket.io, check [this](https://github.com/beeman/loopback-angular-admin/pull/44) pull request by [@movibe](https://github.com/movibe).
# Issues
If you have any problems please [contact me](https://github.com/beeman/loopback-angular-admin/issues/new).
| {
"content_hash": "637dd4f093cb81f6c8a82ce1ef29b23a",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 224,
"avg_line_length": 44.42780748663102,
"alnum_prop": 0.7643235435724602,
"repo_name": "drmikecrowe/loopback-angular-admin",
"id": "fb55681eb816a9153942e63e80c0427ef07eff74",
"size": "8334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "664619"
},
{
"name": "HTML",
"bytes": "3186752"
},
{
"name": "JavaScript",
"bytes": "3039588"
},
{
"name": "PHP",
"bytes": "1684"
},
{
"name": "Shell",
"bytes": "1243"
}
],
"symlink_target": ""
} |
package org.datavec.spark.transform;
import org.datavec.image.transform.ImageTransformProcess;
import org.datavec.spark.transform.model.Base64NDArrayBody;
import org.datavec.spark.transform.model.BatchImageRecord;
import org.datavec.spark.transform.model.SingleImageRecord;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.io.ClassPathResource;
import org.nd4j.serde.base64.Nd4jBase64;
import java.io.File;
import static org.junit.Assert.assertEquals;
/**
* Created by kepricon on 17. 5. 24.
*/
public class ImageSparkTransformTest {
@Rule
public TemporaryFolder testDir = new TemporaryFolder();
@Test
public void testSingleImageSparkTransform() throws Exception {
int seed = 12345;
File f1 = new ClassPathResource("datavec-spark-inference/testimages/class1/A.jpg").getFile();
SingleImageRecord imgRecord = new SingleImageRecord(f1.toURI());
ImageTransformProcess imgTransformProcess = new ImageTransformProcess.Builder().seed(seed)
.scaleImageTransform(10).cropImageTransform(5).build();
ImageSparkTransform imgSparkTransform = new ImageSparkTransform(imgTransformProcess);
Base64NDArrayBody body = imgSparkTransform.toArray(imgRecord);
INDArray fromBase64 = Nd4jBase64.fromBase64(body.getNdarray());
// System.out.println("Base 64ed array " + fromBase64);
assertEquals(1, fromBase64.size(0));
}
@Test
public void testBatchImageSparkTransform() throws Exception {
int seed = 12345;
File f0 = new ClassPathResource("datavec-spark-inference/testimages/class1/A.jpg").getFile();
File f1 = new ClassPathResource("datavec-spark-inference/testimages/class1/B.png").getFile();
File f2 = new ClassPathResource("datavec-spark-inference/testimages/class1/C.jpg").getFile();
BatchImageRecord batch = new BatchImageRecord();
batch.add(f0.toURI());
batch.add(f1.toURI());
batch.add(f2.toURI());
ImageTransformProcess imgTransformProcess = new ImageTransformProcess.Builder().seed(seed)
.scaleImageTransform(10).cropImageTransform(5).build();
ImageSparkTransform imgSparkTransform = new ImageSparkTransform(imgTransformProcess);
Base64NDArrayBody body = imgSparkTransform.toArray(batch);
INDArray fromBase64 = Nd4jBase64.fromBase64(body.getNdarray());
// System.out.println("Base 64ed array " + fromBase64);
assertEquals(3, fromBase64.size(0));
}
}
| {
"content_hash": "364967011128bb0baae7eb8308b365fa",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 101,
"avg_line_length": 37.48571428571429,
"alnum_prop": 0.7221798780487805,
"repo_name": "RobAltena/deeplearning4j",
"id": "c3474ab85c99b26c94bec5a745794e6c53902166",
"size": "3385",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datavec/datavec-spark-inference-parent/datavec-spark-inference-model/src/test/java/org/datavec/spark/transform/ImageSparkTransformTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2469"
},
{
"name": "C",
"bytes": "144275"
},
{
"name": "C#",
"bytes": "138404"
},
{
"name": "C++",
"bytes": "16954560"
},
{
"name": "CMake",
"bytes": "77377"
},
{
"name": "CSS",
"bytes": "10363"
},
{
"name": "Cuda",
"bytes": "2324886"
},
{
"name": "Dockerfile",
"bytes": "1329"
},
{
"name": "FreeMarker",
"bytes": "77045"
},
{
"name": "HTML",
"bytes": "38914"
},
{
"name": "Java",
"bytes": "36293636"
},
{
"name": "JavaScript",
"bytes": "436278"
},
{
"name": "PureBasic",
"bytes": "12256"
},
{
"name": "Python",
"bytes": "325018"
},
{
"name": "Ruby",
"bytes": "4558"
},
{
"name": "Scala",
"bytes": "355054"
},
{
"name": "Shell",
"bytes": "80490"
},
{
"name": "Smarty",
"bytes": "900"
},
{
"name": "Starlark",
"bytes": "931"
},
{
"name": "TypeScript",
"bytes": "80252"
}
],
"symlink_target": ""
} |
/***** includes *****/
#include "internal.h"
/****************************************************************************/
void test_lfds700_queue_bss_dequeuing()
{
enum lfds700_misc_validity
dvs = LFDS700_MISC_VALIDITY_VALID;
lfds700_pal_uint_t
loop;
struct lfds700_queue_bss_element
element_array[128];
struct lfds700_queue_bss_state
qs;
struct lfds700_misc_validation_info
vi;
void
*value;
/* TRD : create an empty queue
enqueue 128 elements
then dequeue the elements, in the same thread - we're API testing
it's a single producer queue, so we just do this in our current thread
since we're enqueuing and dequeuing in the same thread,
*/
internal_display_test_name( "Dequeuing" );
lfds700_queue_bss_init_valid_on_current_logical_core( &qs, element_array, 128, NULL );
for( loop = 0 ; loop < 127 ; loop++ )
lfds700_queue_bss_enqueue( &qs, NULL, (void *) loop );
for( loop = 0 ; loop < 127 ; loop++ )
{
lfds700_queue_bss_dequeue( &qs, NULL, &value );
if( (lfds700_pal_uint_t) value != 127 - loop )
dvs = LFDS700_MISC_VALIDITY_INVALID_TEST_DATA;
}
vi.min_elements = vi.max_elements = 0;
lfds700_queue_bss_query( &qs, LFDS700_QUEUE_BSS_QUERY_VALIDATE, &vi, &dvs );
lfds700_queue_bss_cleanup( &qs, NULL );
internal_display_test_result( 1, "queue_bss", dvs );
return;
}
| {
"content_hash": "57762ec09b9953c68a65e3204ce8d296",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 88,
"avg_line_length": 23.360655737704917,
"alnum_prop": 0.5971929824561404,
"repo_name": "mojmir-svoboda/BlackBoxTT",
"id": "971555c4436934cb9f36a84554f21f5636076136",
"size": "1425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "3rd_party/liblfds7.0.0/test/src/test_lfds700_queue_bounded_singleconsumer_singleproducer_dequeuing.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AutoHotkey",
"bytes": "1803"
},
{
"name": "BlitzBasic",
"bytes": "2646"
},
{
"name": "C",
"bytes": "419678"
},
{
"name": "C++",
"bytes": "1986927"
},
{
"name": "CMake",
"bytes": "55560"
},
{
"name": "HTML",
"bytes": "31452"
},
{
"name": "Lua",
"bytes": "2559"
},
{
"name": "Makefile",
"bytes": "1925"
},
{
"name": "NSIS",
"bytes": "21836"
},
{
"name": "Objective-C",
"bytes": "2988"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c50eeab6c52b4b6097af27a9e7e8f071",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "75cb1f2f4cd0e2f88189f3198b573254939b8429",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Rhododendron/Rhododendron rappardii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
FROM balenalib/kitra710-alpine:3.14-build
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk
ENV PATH $PATH:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin
RUN set -x \
&& apk add --no-cache \
openjdk8-jre \
&& [ "$JAVA_HOME" = "$(docker-java-home)" ]
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Alpine Linux 3.14 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v8-jre \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "8b019e9b1917001da8985866d7d7ce96",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 683,
"avg_line_length": 58,
"alnum_prop": 0.7,
"repo_name": "resin-io-library/base-images",
"id": "808340ce9f3708f1f3bcd8eb57802152c8935d9a",
"size": "1761",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/openjdk/kitra710/alpine/3.14/8-jre/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
`Daylilog` `Javascript` `Vue.js` `Links` `Design` `UX`
# Things Do Today:
- [x] Add new **Dailylog**
- [x] Started watch course Vue.js Mastering Web Apps :metal:
# Notes
- First Daily on Jun 2018
- Practice coding javascript.
- Started using Vue.js
## Links
[:movie_camera: Vue.js, Vuex e Single Source of Truth](https://www.youtube.com/watch?v=QIGFxhUQ_VM&t=432s)
[:newspaper: The technical designer](https://medium.com/envoy-design/the-technical-designer-2cb20fa5f108)
[:newspaper: Layouts of Tomorrow ](https://mxb.at/blog/layouts-of-tomorrow/)
# TIL - Today I Learned
- What is State on Vuex
> *"Um state __isolado de components__, no __nível da aplicação__ e __disponível para qualquer componente que tenha interesse__ na informação"*
| {
"content_hash": "10aa529a2803724f49a9a24a09584be5",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 145,
"avg_line_length": 32.95652173913044,
"alnum_prop": 0.712401055408971,
"repo_name": "wgoulart/dailylog",
"id": "2cc80f440f73a2e4a6a3df50a7d849aae3c27372",
"size": "788",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2018/06-Jun/log-18-06-2018.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
module.exports = function(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/login');
};
| {
"content_hash": "3e426ba0bce820c6649c54e911fb0780",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 43,
"avg_line_length": 17.142857142857142,
"alnum_prop": 0.6416666666666667,
"repo_name": "ziacik/eeechatx",
"id": "0aeaf99572e51c18d645e999e9a7ee49e28a25ec",
"size": "120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/policies/isAuthenticated.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "515"
},
{
"name": "JavaScript",
"bytes": "153438"
}
],
"symlink_target": ""
} |
/**
* Computes Euler's totient function
*
* @author Steven & Felix Halim
*/
package com.williamfiset.algorithms.math;
public class EulerTotientFunctionWithSieve {
// TODO(williamfiset): Refactor this class to accept a max value in the constructor.
// Set MAX to be the largest value you
// wish to compute the totient for.
private static int MAX = 1000000;
private static int[] PRIMES = sieve(MAX);
// Returns the value of Euler's totient/phi function
// which computes how many numbers are relativity
// prime to n less than or equal to n
public static int totient(int n) {
if (n >= MAX - 1) throw new IllegalStateException("MAX not large enough!");
int ans = n;
for (int i = 1, p = PRIMES[0]; p * p <= n; i++) {
if (n % p == 0) ans -= ans / p;
while (n % p == 0) n /= p;
p = PRIMES[i];
}
// Last factor
if (n != 1) ans -= ans / n;
return ans;
}
// Gets all primes up to, but NOT including limit (returned as a list of primes)
private static int[] sieve(int limit) {
if (limit <= 2) return new int[0];
// Find an upper bound on the number of primes below our limit.
// https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities
final int numPrimes = (int) (1.25506 * limit / Math.log((double) limit));
int[] primes = new int[numPrimes];
int index = 0;
boolean[] isComposite = new boolean[limit];
final int sqrtLimit = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrtLimit; i++) {
if (!isComposite[i]) {
primes[index++] = i;
for (int j = i * i; j < limit; j += i) isComposite[j] = true;
}
}
for (int i = sqrtLimit + 1; i < limit; i++) if (!isComposite[i]) primes[index++] = i;
return java.util.Arrays.copyOf(primes, index);
}
public static void main(String[] args) {
// Prints 8 because 1,2,4,7,8,11,13,14 are all
// less than 15 and relatively prime with 15
System.out.printf("phi(15) = %d\n", totient(15));
System.out.println();
for (int x = 1; x <= 11; x++) {
System.out.printf("phi(%d) = %d\n", x, totient(x));
}
}
}
| {
"content_hash": "52d2ed944e721ddd0294992e896c2215",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 89,
"avg_line_length": 30.014084507042252,
"alnum_prop": 0.6039418113561709,
"repo_name": "williamfiset/Algorithms",
"id": "e845fecb4b03e2a1315adf58e8aa5f6a6917138a",
"size": "2131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/williamfiset/algorithms/math/EulerTotientFunctionWithSieve.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1435029"
},
{
"name": "JavaScript",
"bytes": "9310"
},
{
"name": "Kotlin",
"bytes": "2635"
},
{
"name": "Python",
"bytes": "755"
}
],
"symlink_target": ""
} |
/**
* System module
* @module System
* @namespace RGPP.System
*/
(function(global) {
/* global RGPP */
"use strict";
var objName = "EventOperator";
/**
* Event Operator
* @class EventOperator
* @author arcsin
* @constructor
*/
var constructor = function(spec) {
var that = {};
// Reaction
that.reactionInRange = reactionInRange;
that.reactionByStateKey = reactionByStateKey;
that.reactionByEventID = reactionByEventID;
// Search
that.searchEventObjsByStateKey = searchEventObjsByStateKey;
// In Range
that.inRangeEvents = inRangeEvents;
that.isSpriteOnMouse = isSpriteOnMouse;
function searchEventObjsByStateKey(stateKey) {
var eom = RGPP.System.EventObjManager.getInstance();
var resultEventObjs = [];
var events = eom.getEvents();
for (var eventIndex = 0; eventIndex < events.length; ++eventIndex) {
if (events[eventIndex].currentStateKey() === stateKey) {
resultEventObjs.push(events[eventIndex]);
}
}
return resultEventObjs;
}
function reactionInRange(currentEvent, x, y, width, height) {
var eom = RGPP.System.EventObjManager.getInstance();
var events = eom.getEvents();
for (var eventIndex = 0; eventIndex < events.length; ++eventIndex) {
if (isSameEventObj(currentEvent, eventIndex)) {
continue;
}
var event = events[eventIndex];
var sprites = event.gameObjs("Sprite");
if (sprites.length > 0) {
var spr = sprites[RGPP.MW.RPG.CHARA_CHIP_OBJ_ID];
var inRangeFlag = spr.inRange(x, y, width, height);
if (inRangeFlag) {
events[eventIndex].reaction();
}
}
}
}
function reactionByStateKey(stateKey) {
var eom = RGPP.System.EventObjManager.getInstance();
var events = eom.getEvents();
for (var eventIndex = 0; eventIndex < events.length; ++eventIndex) {
var event = events[eventIndex];
if (event.currentStateKey() === stateKey) {
event.reaction();
}
}
}
function reactionByEventID(eventID) {
var eom = RGPP.System.EventObjManager.getInstance();
var events = eom.getEvents();
var currentMapPanel = RGPP.System.MapPanelList.getInstance().currentMapPanel();
var mapCategoryID = currentMapPanel.categoryID();
var mapDataID = currentMapPanel.id();
for (var eventIndex = 0; eventIndex < events.length; ++eventIndex) {
var event = events[eventIndex];
if (event.id() === eventID && event.initMapCategoryID() === mapCategoryID && event.initMapDataID() === mapDataID) {
event.reaction();
}
}
}
/**
* Return Range Events
*
* @method inRangeEvents
* @param currentEvent {Object} Event Object
* @param x {Number} Map Coordinate (Pixel)
* @param y {Number} Map Coordinate (Pixel)
* @param width {Number} Map Coordinate (Pixel)
* @param hegiht {Number} Map Coordinate (Pixel)
* @return {Object} event objects in range
*/
function inRangeEvents(currentEvent, x, y, width, height) {
var inRangeEvents = [];
var eom = RGPP.System.EventObjManager.getInstance();
var events = eom.getEvents();
for (var eventIndex = 0; eventIndex < events.length; eventIndex += 1) {
if (isSameEventObj(currentEvent, eventIndex)) {
continue;
}
var event = events[eventIndex];
var sprites = event.gameObjs("Sprite");
if (sprites.length > 0) {
var spr = sprites[RGPP.MW.RPG.CHARA_CHIP_OBJ_ID];
var inRangeFlag = spr.inRange(x, y, width, height);
if (inRangeFlag) {
inRangeEvents.push(event);
}
}
}
return inRangeEvents;
}
function isSpriteOnMouse(sprite, width, height) {
var spriteX = sprite.centerX() - width / 2;
var spriteY = sprite.centerY() - height / 2;
var cs = RGPP.System.CoordinateSystem.getInstance();
var cm = RGPP.System.ControlManager.getInstance();
var mouseMapX = cs.convertScreenToMapX(cm.getMouseX());
var mouseMapY = cs.convertScreenToMapY(cm.getMouseY());
if (spriteX < mouseMapX && mouseMapX < spriteX + width && spriteY < mouseMapY && mouseMapY < spriteY + height) {
return true;
}
return false;
}
var isSameEventObj = function(currentEventObj, anotherEventIndex) {
var eom = RGPP.System.EventObjManager.getInstance();
var events = eom.getEvents();
var anotherEvent = events[anotherEventIndex];
if (currentEventObj === anotherEvent) {
return true;
}
return false;
};
return that;
};
RGPP.System.exportsAsSingleton({
name: objName,
constructorFunc: constructor,
module: module
});
})((this || 0).self || global);
| {
"content_hash": "64f5ca7f072b23a8d6555a4a763b51c4",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 119,
"avg_line_length": 28.093167701863354,
"alnum_prop": 0.6681406146363034,
"repo_name": "arcsin037/RGPP",
"id": "7c0f030e5cd3f811edd0b95a6be05cb1fb309c56",
"size": "4523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/RGPP/MW/RPG/Script/EventOperator.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9336"
},
{
"name": "HTML",
"bytes": "9095"
},
{
"name": "JavaScript",
"bytes": "727477"
}
],
"symlink_target": ""
} |
Getting started
===============
This tutorial covers how to get started with the Cliche codebase.
Prerequisites
-------------
Cliche is made with the following softwares:
Python_ 3.3 or higher
Cliche is mostly written in Python language. It's a high-level scripting
language for general purpose.
Git_
We use Git for version control. We can track changes of Cliche source
code using it.
One of its main downsides is Windows support. If you're not using Mac
or Linux, it's hard to setup. We recommend you to simply use
`GitHub for Windows`_.
If you're using Mac you can find installers of these softwares in their
official websites.
If you're using Windows you can find CPython installer in Python_ website's
download page. For Git, install `GitHub for Windows`_ as mentioned above.
You can install these softwares using APT if you're on Ubuntu or Debian Linux:
.. sourcecode:: console
$ sudo apt-get install python3 git-core
There are other several third-party Python libraries as well, but you don't
have to install it by yourself. These can be automatically resolved.
.. _Python: http://www.python.org/
.. _Git: http://git-scm.org/
.. _GitHub for Windows: http://windows.github.com/
Check out the source code
-------------------------
Cliche codebase is managed under GitHub_, so you can clone it using Git_:
.. sourcecode:: console
$ git clone git@github.com:clicheio/cliche.git
$ cd cliche/
If you're using Windows, you can clone it using `GitHub for Windows`_ as well.
.. _GitHub: https://github.com/clicheio/cliche
Create an environment
---------------------
The next step is creating an environment for Cliche. This step should
be done first, and only once.
Each environment has its own directory for storing the :file:`site-packages`
folder, executable scripts, etc. Here we assume that the name of environment
folder is :file:`cliche-env`:
.. sourcecode:: console
$ pyvenv cliche-env
Enter the environment
---------------------
Each time you work on Cliche, you have to enter the created environment. It's
applied to each terminal session.
.. note::
If you're on Windows, you should *not* run the command prompt as
administrator.
We assume here that the environment name is :file:`cliche-env` and
the repository name is :file:`cliche`.
.. sourcecode:: console
$ . cliche-env/bin/activate
(cliche-env) $
.. note::
On Windows execute :program:`Scripts\\activate.bat` instead:
.. sourcecode:: text
C:\Users\John Doe> cliche-env\Scripts\activate.bat
(cliche-env) C:\Users\John Doe>
The prefix ``(cliche-env)`` of the prompt indicates you're in the environment.
And then install Cliche's dependencies in the environment (instead of
system-wide :file:`site-packages`).
.. sourcecode:: console
(cliche-env) $ cd cliche/
(cliche-env) cliche$ pip install -e .
Resolve dependencies
--------------------
Cliche depends on several third-party Python libraries, and these can be
automatically resolved through :program:`pip` command:
.. sourcecode:: console
$ pip install -e .
Finished processing dependencies for Cliche==0.0.0
Configuration
-------------
To run web server a configuration file is required. Here we assume
the filename we'll use is :file:`dev.cfg.py`. Configuration file is
an ordinary Python script. Create a new file and save::
DATABASE_URL = 'postgresql:///cliche_db'
Relational database
-------------------
Cliche stores data into a relational database through SQLAlchemy_.
In production we use PostgreSQL_ and it also works well with SQLite_.
Python ships with SQLite. There is no need to install it.
To use PostgreSQL, read :doc:`postgresql`.
Schema has to be created on the database. Use :program:`cliche upgrade`
command:
.. sourcecode:: console
$ cliche upgrade -c dev.cfg.py
.. _SQLAlchemy: http://www.sqlalchemy.org/
.. _PostgreSQL: http://www.postgresql.org/
.. _SQLite: http://sqlite.org/
| {
"content_hash": "18224ada0c3dc81f26e05a41a1fd110b",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 78,
"avg_line_length": 26.138157894736842,
"alnum_prop": 0.7072741001761893,
"repo_name": "clicheio/cliche",
"id": "e11fd0b59ac99a27dd213eb0e6d22cef13ec75fa",
"size": "3973",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/start.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2506"
},
{
"name": "HTML",
"bytes": "11847"
},
{
"name": "Io",
"bytes": "585"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "298946"
},
{
"name": "Shell",
"bytes": "2511"
}
],
"symlink_target": ""
} |
angular.module('memory')
.service('computerPlayerService', function($rootScope, $q, $timeout, localStorageService, deckService, playerService) {
'use strict';
var computer = {};
computer.isComputerTurn = localStorageService.get('mem.isComputerTurn') ? localStorageService.get('mem.isComputerTurn') : false;
computer.playComputerHand = function(revealedCards) {
if(revealedCards.length === 0 && playerService.matchesStack.length > 0 && playerService.matchesStack.length % 2 === 0){
computer.clickCard(playerService.matchesStack.pop());
} else if(revealedCards.length === 1 && playerService.matchesStack.length % 2 === 1){
computer.clickCard(playerService.matchesStack.pop());
} else {
computer.computerSelectCard();
}
};
computer.computerSelectCard = function() {
var deferred = $q.defer();
var card = null;
if(playerService.remainingCards.length < 20) {
playerService.resetRemainingCards();
}
for(var i = 0; i < playerService.remainingCards.length; i++) {
if(!playerService.remainingCards[i].visited && playerService.remainingCards[i].value
&& playerService.remainingCards[i].value !== 'null' && !playerService.remainingCards[i].removed) {
card = playerService.remainingCards[i];
break;
}
}
if(card) {
card.visited = true;
computer.clickCard(card).then(function() {
playerService.updateCardsVisitedMap(card).then(function() {
deferred.resolve();
});
});
} else {
deferred.resolve();
}
return deferred.promise;
};
computer.setComputerTurn = function(isOn) {
computer.isComputerTurn = isOn;
localStorageService.set('mem.isComputerTurn', isOn);
// score controller listening for this event
$rootScope.$broadcast('computerTurnUpdated');
};
computer.clickCard = function(card) {
// this pauses 1 second, then selects a card, then pauses for another second to simulate a real player selecting a card
// $timeout returns a promise
return $timeout(function() {
jQuery('#' + card.value + card.suitName).click();
}, 1000).then($timeout(function() {
}, 1000));
};
return computer;
});
| {
"content_hash": "12b3facaff488863753ead197590d1e9",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 132,
"avg_line_length": 35.753846153846155,
"alnum_prop": 0.6364027538726333,
"repo_name": "scottrice10/memory-card-game",
"id": "c23f574f005b83d5d6af2faa5db29e998f7ab183",
"size": "2324",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/computerPlayer/computerPlayer.service.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1107"
},
{
"name": "HTML",
"bytes": "3894"
},
{
"name": "JavaScript",
"bytes": "31401"
},
{
"name": "Shell",
"bytes": "180"
}
],
"symlink_target": ""
} |
/**
* @file
* Time.
*
*/
#ifndef NL_ER_TIME_H
#define NL_ER_TIME_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Represents a timeout that will never occur
*/
#define NLER_TIMEOUT_NEVER (nl_time_ms_t)-1
/** Represents a timeout that will happen immediately
*/
#define NLER_TIMEOUT_NOW 0
/** Time interval defined by the underlying runtime implementation.
* Applications should not attempt to interpret these values but they can be
* converted to and from milliseconds.
*/
typedef uint32_t nl_time_native_t;
/** Time interval specified in milliseconds.
*/
typedef uint32_t nl_time_ms_t;
/** Get current system time in native time units. One can expect this clock to
* wrap around at any time. All math done on time values must take this into
* account.
*
* @return the current system clock time in native time units
*/
nl_time_native_t nl_get_time_native(void);
/** Get current system time in native time units. One can expect this clock to
* wrap around at any time. All math done on time values must take this into
* account. This may be called in isr context.
*
* @return the current system clock time in native time units
*/
#if defined(NLER_BUILD_PLATFORM_FREERTOS)
nl_time_native_t nl_get_time_native_from_isr(void);
#endif
/** Convert time in milliseconds to native time units.
*
* Rounding behavior: For number of milliseconds shorter than 1 tick,
* the function will return 1 tick. NLER_TIMEOUT_NEVER milliseconds
* will be mapped onto appropriate internal value corresponding to
* TIMEOUT_NEVER. No overflow checking is performed: input
* millisecond values that would result in more than UINT32_MAX
* ticks, will produce erroneous results. For all other input
* values, the function rounds down.
*
* @param[in] aTime Time in milliseconds.
*
* @return Time in native units.
*/
nl_time_native_t nl_time_ms_to_time_native(nl_time_ms_t aTime);
/** Convert time in milliseconds to a delay value in native time units.
*
* Rounding behavior: The output is a value used for native delay APIs
* and is rounded up to the nearest native unit. Also, if the native
* unit is in ticks, an additional tick is added to account for the
* uncertainty of when in the current tick period the delay is being
* requested. The result is a guarantee that the delay will always be
* at least as long as the time in milliseconds and never early.
* NLER_TIMEOUT_NEVER milliseconds will be mapped onto appropriate
* internal value corresponding to TIMEOUT_NEVER. 0 milliseconds will
* be mapped onto appropriate internal value corresponding to no delay
* (e.g. non-blocking polling check only). No overflow checking
* is performed: input millisecond values that would result in more than
* UINT32_MAX ticks, will produce erroneous results.
*
* @param[in] aTime Time in milliseconds.
*
* @return Time in native units that guarantees a delay that is at
* least aTime milliseconds in duration.
*/
nl_time_native_t nl_time_ms_to_delay_time_native(nl_time_ms_t aTime);
/** Convert time in native time units to time in milliseconds.
*
* Rounding behavior: For input value corresponding to native
* TIMEOUT_NEVER, the function will result NLER_TIMEOUT_NEVER. No
* overflow checking is performed: input ticks that would result in
* more than UINT32_MAX milliseconds will produce erroneous results.
* For all other input values, the function rounds down.
*
* @param[in] aTime Time in native units.
*
* @return Time in milliseconds.
*/
nl_time_ms_t nl_time_native_to_time_ms(nl_time_native_t aTime);
#ifdef __cplusplus
}
#endif
#endif /* NL_ER_EVENT_QUEUE_SIM_H */
| {
"content_hash": "179f9bd124e0256935ebcf354979b3d5",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 78,
"avg_line_length": 33.5,
"alnum_prop": 0.7318860244233378,
"repo_name": "nestlabs/nler",
"id": "5faafaa5ad3eed6dca11e963bd0d5a6c5c4d9dcc",
"size": "4352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/nlertime.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "537145"
},
{
"name": "C++",
"bytes": "1081"
},
{
"name": "M4",
"bytes": "40922"
},
{
"name": "Makefile",
"bytes": "388726"
},
{
"name": "Shell",
"bytes": "4350"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>code</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../../";</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.api.uievent/KeyCode.KEY_X/code/#/PointingToDeclaration//-755115832">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.api.uievent</a>/<a href="../index.html">KeyCode</a>/<a href="index.html">KEY_X</a>/<a href="code.html">code</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>code</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">val <a href="code.html">code</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html">Int</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
<p class="paragraph">The unicode key code for the given key</p></div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
| {
"content_hash": "a2739f56b5741e775863104b901bb4e8",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 559,
"avg_line_length": 70.33333333333333,
"alnum_prop": 0.624756063562866,
"repo_name": "Hexworks/zircon",
"id": "3653c792d96f2f7435cbe207aa7f9e2174875741",
"size": "3588",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/2021.1.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.api.uievent/-key-code/-k-e-y_-x/code.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "121457"
},
{
"name": "Kotlin",
"bytes": "1792092"
},
{
"name": "Shell",
"bytes": "152"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Reflection;
using Bumblebee.Exceptions;
using Bumblebee.Extensions;
using Bumblebee.Interfaces;
using Bumblebee.Setup;
using FluentAssertions;
using NSubstitute;
using NUnit.Framework;
using OpenQA.Selenium;
// ReSharper disable InconsistentNaming
namespace Bumblebee.IntegrationTests.Extensions
{
[TestFixture]
public class VerificationTests
{
[TestCase(null, "Unable to verify.")]
[TestCase("", "Unable to verify.")]
[TestCase("Last name should equal 'Barson'.", "Unable to verify. Last name should equal 'Barson'.")]
public void Given_value_and_verification_and_predicate_that_fails_when_verifying_should_throw_exception_with_verification_message(string verification, string verificationMessage)
{
var value = new { FirstName = "Todd", LastName = "Meinershagen" };
Action action = () => value.Verify(verification, x => x.LastName == "Barson");
action.ShouldThrow<VerificationException>().WithMessage(verificationMessage);
}
[Test]
public void Given_value_and_verification_and_predicate_that_succeeds_when_verifying_should_return_original_value()
{
var value = new { FirstName = "Todd", LastName = "Meinershagen" };
var result = value.Verify("last name equals 'Meinershagen'", x => x.LastName == "Meinershagen");
result.Should().Be(value);
}
[Test]
public void Given_value_and_predicate_that_fails_when_verifying_should_throw_exception_with_standard_message()
{
var value = new { FirstName = "Todd", LastName = "Meinershagen" };
Action action = () => value.Verify(x => x.LastName.Equals("Barson"));
action
.ShouldThrow<VerificationException>()
.WithMessage("Unable to verify. Expected x.LastName.Equals(\"Barson\")");
}
[Test]
public void Given_value_and_predicate_that_succeeds_when_verifying_should_return_original_value()
{
var value = new { FirstName = "Todd", LastName = "Meinershagen" };
var result = value.Verify(x => x.LastName == "Meinershagen");
result.Should().Be(value);
}
[Test]
public void Given_assertion_that_fails_should_throw()
{
var value = new { };
const string expectedMessage = "This is the message.";
Action assertion = () =>
{
throw new AssertionException(expectedMessage);
};
Action action = () => value.VerifyThat(v => assertion());
action
.ShouldThrow<VerificationException>()
.WithMessage(string.Format("Unable to verify. {0}", expectedMessage))
.WithInnerException<AssertionException>()
.WithInnerMessage(expectedMessage);
}
[Test]
public void Given_assertion_that_does_not_fail_should_return_original_value()
{
var message = new { Name = "Todd" };
var result = message.VerifyThat(m => m.Name.Should().Be("Todd"));
result.Should().Be(message);
}
[TestCase(true)]
[TestCase(false)]
public void Given_selection_verification_passes_when_verifying_selected_should_return_element(bool expected)
{
var element = Substitute.For<ISelectable>();
element.Selected.Returns(expected);
var result = element.VerifySelected(expected);
result.Should().Be(element);
}
[TestCase(true)]
[TestCase(false)]
public void Given_selection_verification_fails_when_verifying_selected_should_throw_exception(bool expected)
{
var element = Substitute.For<ISelectable>();
element.Selected.Returns(!expected);
Action action = () => element.VerifySelected(expected);
action
.ShouldThrow<VerificationException>()
.WithMessage(String.Format("Selection verification failed. Expected: {0}, Actual: {1}.", expected, element.Selected));
}
[Test]
public void Given_verification_on_IClickable_and_take_screenshot_is_true_When_verification_fails_Then_screenshot_is_taken()
{
var driver = Substitute.For<IWebDriver>();
var driverEnvironment = Substitute.For<IDriverEnvironment>();
var settings = Substitute.For<ISettings>();
var session = Substitute.For<Session>(driverEnvironment);
var clickable = new TestClickable
{
Session = session,
Text = "Not the right text"
};
driverEnvironment.CreateWebDriver().Returns(driver);
settings.CaptureScreenOnVerificationFailure.Returns(true);
session.Settings.Returns(settings);
try
{
clickable.Verify(x => x.Text == "The right text");
}
catch (VerificationException)
{
}
session.Received().CaptureScreen(Path.Combine(Environment.CurrentDirectory, String.Format("{0}.png", MethodBase.GetCurrentMethod().GetFullName())));
session.End();
}
[Test]
public void Given_verification_on_IClickable_and_take_screenshot_is_true_When_verification_succeeds_Then_screenshot_is_not_taken()
{
var driver = Substitute.For<IWebDriver>();
var driverEnvironment = Substitute.For<IDriverEnvironment>();
var settings = Substitute.For<ISettings>();
var session = Substitute.For<Session>(driverEnvironment);
driverEnvironment.CreateWebDriver().Returns(driver);
settings.CaptureScreenOnVerificationFailure.Returns(true);
session.Settings.Returns(settings);
var clickable = new TestClickable
{
Session = session,
Text = "The right text"
};
clickable.Verify(x => x.Text == "The right text");
session.DidNotReceiveWithAnyArgs().CaptureScreen();
session.End();
}
[Test]
public void Given_verification_on_IClickable_and_take_screenshot_is_false_When_verification_fails_Then_screenshot_is_not_taken()
{
var driver = Substitute.For<IWebDriver>();
var driverEnvironment = Substitute.For<IDriverEnvironment>();
var settings = Substitute.For<ISettings>();
var session = Substitute.For<Session>(driverEnvironment);
driverEnvironment.CreateWebDriver().Returns(driver);
settings.CaptureScreenOnVerificationFailure.Returns(false);
session.Settings.Returns(settings);
var clickable = new TestClickable
{
Session = session,
Text = "Not the right text"
};
try
{
clickable.Verify(x => x.Text == "The right text");
}
catch (VerificationException)
{
}
session.DidNotReceive().CaptureScreen(Path.Combine(Environment.CurrentDirectory, String.Format("{0}.png", MethodBase.GetCurrentMethod().GetFullName())));
session.DidNotReceiveWithAnyArgs().CaptureScreen();
session.End();
}
[Test]
public void Given_verification_on_IClickable_and_take_screenshot_is_false_When_verification_succeeds_Then_screenshot_is_not_taken()
{
var driver = Substitute.For<IWebDriver>();
var driverEnvironment = Substitute.For<IDriverEnvironment>();
var settings = Substitute.For<ISettings>();
var session = Substitute.For<Session>(driverEnvironment);
driverEnvironment.CreateWebDriver().Returns(driver);
settings.CaptureScreenOnVerificationFailure.Returns(false);
session.Settings.Returns(settings);
var clickable = new TestClickable
{
Session = session,
Text = "The right text"
};
clickable.Verify(x => x.Text == "The right text");
session.DidNotReceiveWithAnyArgs().CaptureScreen();
session.End();
}
}
public class TestClickable : IClickable
{
public IWebElement Tag { get; set; }
public Session Session { get; set; }
public string Text { get; set; }
public TResult Click<TResult>() where TResult : IBlock
{
throw new NotImplementedException();
}
public IPerformsDragAndDrop GetDragAndDropPerformer()
{
throw new NotImplementedException();
}
}
}
| {
"content_hash": "d52509df6ca881013b543fb54accaac6",
"timestamp": "",
"source": "github",
"line_count": 261,
"max_line_length": 180,
"avg_line_length": 28.371647509578544,
"alnum_prop": 0.7138419986495611,
"repo_name": "qchicoq/Bumblebee",
"id": "068dd5150449820428291c35e94b89b82a583ea7",
"size": "7407",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Bumblebee.IntegrationTests/Extensions/VerificationTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "620"
},
{
"name": "C#",
"bytes": "138143"
},
{
"name": "HTML",
"bytes": "8374"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title>rtc.io</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!-- responsive -->
<link rel="stylesheet" media="screen and (max-width: 960px)" href="css/tablet.css">
<link rel="stylesheet" media="screen and (max-width: 710px)" href="css/phone.css">
<link rel="stylesheet" type="text/css" href="fonts/source-sans/stylesheet.css">
<link rel="stylesheet" type="text/css" href="css/code.css">
</head>
<body>
<a class="scroll-point pt-top" name="top"></a>
<header>
<a href="https://github.com/rtc-io/rtc-videoproc"><img class="fork" src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
<a class="scroll-point pt-top" name="top"></a>
<div class="site">
<div class="mascot">
<img src="images/artsio.png">
</div>
<div class="logo" data-subtext="OpenSource WebRTC">
<a href="index.html">rtc.io</a>
</div>
<nav>
<ul>
<li><a href="index.html">About</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="modules.html">Modules</a></li>
</ul>
</nav>
</div>
<div class="shadow"></div>
</header>
<div class="main" role="content"><h1 id="rtc-videoproc">rtc-videoproc</h1>
<p>This is a small helper module that allows you to substitute a video
element with a canvas element. This can be useful when you want to
do pixel manipulation of the rendered images, or in situations when
a video element does not behave as you expect.</p>
<p><a href="https://nodei.co/npm/rtc-videoproc/"><img src="https://nodei.co/npm/rtc-videoproc.png" alt="NPM"></a></p>
<p><a href="https://travis-ci.org/rtc-io/rtc-videoproc"><img src="https://img.shields.io/travis/rtc-io/rtc-videoproc.svg?branch=master" alt="Build Status"></a> <a href="https://github.com/dominictarr/stability#unstable"><img src="https://img.shields.io/badge/stability-unstable-yellowgreen.svg" alt="unstable"></a> </p>
<h2 id="example-usage">Example Usage</h2>
<div class="highlight"><pre><span class="kd">var</span> <span class="nx">crel</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'crel'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">videoproc</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'rtc-videoproc'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">video</span> <span class="o">=</span> <span class="nx">crel</span><span class="p">(</span><span class="s1">'video'</span><span class="p">,</span> <span class="p">{</span> <span class="nx">src</span><span class="o">:</span> <span class="s1">'../test/assets/tennis.webm'</span><span class="p">,</span> <span class="nx">autoplay</span><span class="o">:</span> <span class="kc">true</span> <span class="p">});</span>
<span class="kd">var</span> <span class="nx">canvas</span> <span class="o">=</span> <span class="nx">crel</span><span class="p">(</span><span class="s1">'canvas'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">processor</span> <span class="o">=</span> <span class="nx">videoproc</span><span class="p">(</span><span class="nx">video</span><span class="p">,</span> <span class="nx">canvas</span><span class="p">,</span> <span class="p">{</span>
<span class="nx">filter</span><span class="o">:</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'rtc-filter-grayscale'</span><span class="p">)</span>
<span class="p">});</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nx">canvas</span><span class="p">);</span>
</pre></div>
<h2 id="using-the-processing-pipeline">Using the Processing Pipeline</h2>
<p>A processing pipeline has been included to assist with
manipulating the canvas on the fly. To specify the filters to be used
in the processing pipeline, this is done in the options accepted by
videoproc. Either specifying an array of filters with the <code>filters</code> option
or a single filter function with the <code>filter</code> option is fine. If you use
both then the individual filter will be added filter list and used in
series.</p>
<div class="highlight"><pre><span class="nx">videoproc</span><span class="p">(</span><span class="nx">srcVideo</span><span class="p">,</span> <span class="nx">targetCanvas</span><span class="p">,</span> <span class="p">{</span>
<span class="nx">filters</span><span class="o">:</span> <span class="p">[</span>
<span class="nx">require</span><span class="p">(</span><span class="s1">'rtc-filter-grayscale'</span><span class="p">),</span>
<span class="nx">myCustomFilterFunction</span>
<span class="p">]</span>
<span class="p">});</span>
</pre></div>
<h2 id="writing-a-filter-function">Writing a Filter Function</h2>
<p>Writing a filter function is very simple, and they use the following
function signature:</p>
<div class="highlight"><pre><span class="kd">function</span> <span class="nx">filter</span><span class="p">(</span><span class="nx">imageData</span><span class="p">,</span> <span class="nx">tick</span><span class="p">)</span> <span class="p">{</span>
<span class="p">}</span>
</pre></div>
<p>The <code>imageData</code> arg is an
<a href="http://www.w3.org/TR/2dcontext/#imagedata">ImageData</a>, and the <code>tick</code>
argument refers to the tick that has been captured as part of the capture
loop (be aware that it could be a high resolution timer value if rAF is
being used).</p>
<p>If you are writing an analysis filter, then simply do what you need to do
and exit the function. If you have written a filter that modifies the pixel
data and you want this drawn back to the canvas then your <strong>filter must
return <code>true</code></strong> to tell <code>rtc-videoproc</code> that it should draw the imageData
back to the canvas.</p>
<h2 id="listening-for-custom-frame-events">Listening for custom <code>frame</code> events</h2>
<p>In addition to providing the opportunity to analyse and modify pixel data
the <code>rtc-videoproc</code> module also provides the a custom <code>frame</code> event for
detecting when a new frame has been drawn to the canvas.</p>
<p>A simple example can be found below:</p>
<div class="highlight"><pre><span class="kd">var</span> <span class="nx">videoproc</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'rtc-videoproc'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">crel</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'crel'</span><span class="p">);</span>
<span class="kd">var</span> <span class="nx">video</span> <span class="o">=</span> <span class="nx">crel</span><span class="p">(</span><span class="s1">'video'</span><span class="p">,</span> <span class="p">{</span> <span class="nx">src</span><span class="o">:</span> <span class="s1">'../test/assets/tennis.webm'</span><span class="p">,</span> <span class="nx">autoplay</span><span class="o">:</span> <span class="kc">true</span> <span class="p">});</span>
<span class="c1">// set up the video processing pipeline</span>
<span class="nx">videoproc</span><span class="p">(</span><span class="nx">video</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s1">'frame'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">tick</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">'captured frame at: '</span> <span class="o">+</span> <span class="nx">tick</span><span class="p">);</span>
<span class="p">});</span>
<span class="c1">// add the canvas to the dom</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nx">video</span><span class="p">);</span>
</pre></div>
<p>NOTE: The <code>frame</code> event occurs after the filter pipeline has been run and
and the imageData may have been modified from the original video frame.</p>
<h2 id="a-note-with-regards-to-cpu-usage">A Note with Regards to CPU Usage</h2>
<p>By default rtc-videoproc will draw at 25fps but this can be modified to capture
at a lower frame rate for slower devices, or increased if you have a
machine with plenty of grunt.</p>
<h2 id="reference">Reference</h2>
<h3 id="videoproc-src-target-opts-">videoproc(src, target, opts?)</h3>
<p>Create (or patch) a <code><canvas></code> element that will receive the video images
from a video element. The following options are supported.</p>
<ul>
<li><p><code>canvas</code> - the canvas to draw video data to. If not supplied a new
canvas element will be created.</p>
</li>
<li><p><code>video</code> - the video element that will be used as the source of the video.
If not supplied a new <code><video></code> element will be created.</p>
</li>
<li><p><code>fps</code> - the redraw rate of the fake video (default = 25)</p>
</li>
<li><p><code>greedy</code> - Specify <code>greedy: true</code> if you want the videoproc module to run
it's capture loop using setTimeout rather than <code>requestAnimationFrame</code>.
Doing this will mean you application will continue to capture and process
frames even when it's tab / window becomes inactive. This is usually the
desired behaviour with video conferencing applications.</p>
</li>
</ul>
<h2 id="license-s-">License(s)</h2>
<h3 id="apache-2-0">Apache 2.0</h3>
<p>Copyright 2014 National ICT Australia Limited (NICTA)</p>
<p> 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</p>
<pre><code> http://www.apache.org/licenses/LICENSE-2.0</code></pre>
<p> Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.</p>
</div>
<footer>
<p>
<a href="http://nicta.com.au">
<img src="images/nicta-logo.gif" alt="NICTA logo">
</a>© NICTA 2013 - 2014
</p>
<p class="license">Project source code is licensed under the <a href="https://github.com/rtc-io/rtc/blob/master/LICENSE">Apache 2.0</a>.</p>
<a class="closing" href="#top"></a>
</footer>
</body>
<script src="js/app.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-26567546-2', 'rtc.io');
ga('send', 'pageview');
</script>
</html>
| {
"content_hash": "4f0bf5853fa7eaa22e0eaf4ef440412c",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 473,
"avg_line_length": 67.79768786127168,
"alnum_prop": 0.6815585301389718,
"repo_name": "rtc-io/rtc.io-website",
"id": "f6d17ab48f3b99834ec987bfc92d36a6b8255393",
"size": "11730",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "module-rtc-videoproc.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "28047"
},
{
"name": "HTML",
"bytes": "327077"
},
{
"name": "JavaScript",
"bytes": "1313430"
},
{
"name": "Makefile",
"bytes": "2215"
}
],
"symlink_target": ""
} |
define(["sprd/view/ProductImage", "sprd/data/ImageService"], function (ProductImage, ImageService) {
return ProductImage.inherit("sprd.view.ArticleImage", {
_commitChangedAttributes: function (attributes) {
this.callBase();
if (attributes.hasOwnProperty('article')) {
this.set('loaded', false);
}
},
imageUrl: function () {
var url;
if (this.$.article && this.$.article.$.resources && this.$.article.$.resources.length) {
url = this.$.article.$.resources[0].href;
var id = this.$.article.$.id;
id = Math.floor(parseInt(id.substr(id.length - 2)) / 5);
url = url.replace(/:\/\/image/, '://image' + id);
if (this.$.type === ImageService.ProductImageType.COMPOSITION) {
url = url.replace("products", "compositions");
}
url = this.extendUrlWithSizes(url);
var mediaType = this.$.mediaType;
if (mediaType) {
url += "." + mediaType;
}
return url;
}
return this.callBase();
}.onChange("article").on(["article", "change:resources"]),
alt: function () {
return this.get("article.name");
}
});
}); | {
"content_hash": "c901e8b84d8928f8ab76c9e757fb750c",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 100,
"avg_line_length": 32.116279069767444,
"alnum_prop": 0.4887762490948588,
"repo_name": "spreadshirt/rAppid.js-sprd",
"id": "0116ecd25bc4f5839e1ab6b49bf98d6e8e962167",
"size": "1381",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "sprd/view/ArticleImage.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3404"
},
{
"name": "JavaScript",
"bytes": "1085309"
}
],
"symlink_target": ""
} |
import { isTextBlock } from './isTextBlock'
import { ElementRefType, StringElementRefType } from './types'
export function canFuse
( a: ElementRefType
): a is StringElementRefType {
return isTextBlock ( a.elem ) && a.path.length < 3
} | {
"content_hash": "edca3292bd5c24e9edfe32bfea3b6a0d",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 62,
"avg_line_length": 29.625,
"alnum_prop": 0.7341772151898734,
"repo_name": "luciditeam/lucidity",
"id": "77d8e7df63189dd16edc08602d171041b6855653",
"size": "237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OLD/packages/@lucidity/editor/src/modules/editor/lib/utils/canFuse.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27540"
},
{
"name": "HTML",
"bytes": "4284"
},
{
"name": "JavaScript",
"bytes": "38688"
},
{
"name": "Lua",
"bytes": "1492"
},
{
"name": "TypeScript",
"bytes": "482134"
}
],
"symlink_target": ""
} |
using UnityEngine;
using IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3;
using IBM.Watson.DeveloperCloud.Logging;
using IBM.Watson.DeveloperCloud.Utilities;
using System.Collections;
using IBM.Watson.DeveloperCloud.Connection;
using System.Collections.Generic;
public class ExamplePersonalityInsights : MonoBehaviour
{
private string _username = null;
private string _password = null;
private string _url = null;
private PersonalityInsights _personalityInsights;
private string _personalityInsightsVersionDate = "2017-05-26";
private string _testString = "The IBM Watson™ Personality Insights service provides a Representational State Transfer (REST) Application Programming Interface (API) that enables applications to derive insights from social media, enterprise data, or other digital communications. The service uses linguistic analytics to infer individuals' intrinsic personality characteristics, including Big Five, Needs, and Values, from digital communications such as email, text messages, tweets, and forum posts. The service can automatically infer, from potentially noisy social media, portraits of individuals that reflect their personality characteristics. The service can report consumption preferences based on the results of its analysis, and for JSON content that is timestamped, it can report temporal behavior.";
private string _dataPath;
private bool _getProfileTextTested = false;
private bool _getProfileJsonTested = false;
void Start()
{
LogSystem.InstallDefaultReactors();
// Create credential and instantiate service
Credentials credentials = new Credentials(_username, _password, _url);
_personalityInsights = new PersonalityInsights(credentials);
_personalityInsights.VersionDate = _personalityInsightsVersionDate;
_dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json";
Runnable.Run(Examples());
}
private IEnumerator Examples()
{
if (!_personalityInsights.GetProfile(OnGetProfileJson, OnFail, _dataPath, ContentType.TextHtml, ContentLanguage.English, ContentType.ApplicationJson, AcceptLanguage.English, true, true, true))
Log.Debug("ExamplePersonalityInsights.GetProfile()", "Failed to get profile!");
while (!_getProfileJsonTested)
yield return null;
if (!_personalityInsights.GetProfile(OnGetProfileText, OnFail, _testString, ContentType.TextHtml, ContentLanguage.English, ContentType.ApplicationJson, AcceptLanguage.English, true, true, true))
Log.Debug("ExamplePersonalityInsights.GetProfile()", "Failed to get profile!");
while (!_getProfileTextTested)
yield return null;
Log.Debug("ExamplePersonalityInsights.Examples()", "Personality insights examples complete.");
}
private void OnGetProfileText(Profile profile, Dictionary<string, object> customData)
{
Log.Debug("ExamplePersonaltyInsights.OnGetProfileText()", "Personality Insights - GetProfileText Response: {0}", customData["json"].ToString());
_getProfileTextTested = true;
}
private void OnGetProfileJson(Profile profile, Dictionary<string, object> customData)
{
Log.Debug("ExamplePersonaltyInsights.OnGetProfileJson()", "Personality Insights - GetProfileJson Response: {0}", customData["json"].ToString());
_getProfileJsonTested = true;
}
private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData)
{
Log.Error("ExamplePersonaltyInsights.OnFail()", "Error received: {0}", error.ToString());
}
}
| {
"content_hash": "ed40e7231974ba6f05bd4957049bb371",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 812,
"avg_line_length": 50.45205479452055,
"alnum_prop": 0.748303013847407,
"repo_name": "kimberlysiva/unity-sdk",
"id": "a8eb77299cf1154a608165bb2eb627c5eef45bde",
"size": "4290",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Examples/ServiceExamples/Scripts/ExamplePersonalityInsights.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1750038"
},
{
"name": "Shell",
"bytes": "7047"
}
],
"symlink_target": ""
} |
package com.joshstrohminger.stepbystep;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
public static final String ARG_SECTION_TITLE = "arg_section_title";
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position, true);
}
});
String[] names = new String[MainMobileActivity.SECTIONS.length];
for( int i = 0; i < MainMobileActivity.SECTIONS.length; i++) {
names[i] = getString(MainMobileActivity.SECTIONS[i].getFragmentName());
}
mDrawerListView.setAdapter(new ArrayAdapter<>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
names));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
// mDrawerToggle = new ActionBarDrawerToggle(
// getActivity(), /* host Activity */
// mDrawerLayout, /* DrawerLayout object */
// R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
// R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
// R.string.navigation_drawer_close /* "close drawer" description for accessibility */
// )
{
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
protected void setCurrentItemFromBackstack(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null && isDrawerOpen()) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
}
protected int getCurrentPosition() {
int pos = 0;
if(mDrawerListView != null) {
pos = mDrawerListView.getCheckedItemPosition();
if (pos == AdapterView.INVALID_POSITION) {
pos = 0;
}
}
return pos;
}
protected void selectItem(int position, boolean samenessMatters) {
boolean same = samenessMatters && position == mCurrentSelectedPosition;
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null && isDrawerOpen()) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null && !same) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
//inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an new item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(String title) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putString(ARG_SECTION_TITLE, title);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_placeholder, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainMobileActivity) activity).onSectionAttached(getArguments().getString(ARG_SECTION_TITLE));
}
}
}
| {
"content_hash": "2a3d2300189bf68e3c9cf226840e7b98",
"timestamp": "",
"source": "github",
"line_count": 337,
"max_line_length": 107,
"avg_line_length": 37.332344213649854,
"alnum_prop": 0.6463715125983626,
"repo_name": "KillerSpiders/StepByStep",
"id": "2b947ea11cf3044675b077228b70a83f3b686955",
"size": "12581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mobile/src/main/java/com/joshstrohminger/stepbystep/NavigationDrawerFragment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "73090"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ Copyright (c) 2011-2012 by Cornell University and the Cornell Research Foundation,
~ Inc. All Rights Reserved.
~
~ GobyWeb plugins are released under the LGPL3 license, unless otherwise specified
~ by the license of a specific plugin. See the file LGPL3.license in this distribution
~ for a copy of the LGPL license.
~
~ When a plugin is not released under the LGPL3 license, the comments at the top of
~ the plugin's config.xml will indicate how that specific plugin is released/licensed.
-->
<resourceConfig xsi:noNamespaceSchemaLocation="../../../schemas/plugins.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>Goby</name>
<id>GOBY</id>
<help>Goby framework and toolbox. See http://goby.campagnelab.org.</help>
<version>20120216154520</version>
<files>
<file>
<id>GOBY_JAR</id>
<filename>goby.jar</filename>
</file>
<file>
<id>SHELL_SCRIPT</id>
<filename>goby-script.sh</filename>
</file>
</files>
</resourceConfig>
| {
"content_hash": "991f76172e0560d5ebbe5edb030f9fca",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 131,
"avg_line_length": 40.535714285714285,
"alnum_prop": 0.654625550660793,
"repo_name": "CampagneLaboratory/gobyweb2-plugins",
"id": "6140aac699b8f8e852625e6275a79b9a39f8ca0c",
"size": "1135",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/resources/GOBY_1.9.8.3/config.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "261155"
},
{
"name": "Perl",
"bytes": "431585"
},
{
"name": "Python",
"bytes": "22176"
},
{
"name": "R",
"bytes": "52046"
},
{
"name": "Scala",
"bytes": "8281"
},
{
"name": "Shell",
"bytes": "300142"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>Webcode configuration files</title>
</head>
<body>
<h1>Configuration and sessions</h1>
<p>Ensembl has two different types of configuration: system and user.</p>
<h2>System configuration</h2>
<p>System settings are controlled by the administrator of Ensembl.</p>
<h3>Apache web server configuration</h3>
<p>The <code>SiteDefs.pm</code> Perl module holds the information required to build the <code>httpd.conf</code> file to configure Apache (i.e. port number, modules etc). Some knowledge of Perl is required to edit and maintain this file.</p>
<p>A SiteDefs object is instantiated by the parent Apache process, and is made available to all scripts served by a child process. The role of Apache in serving pages is discussed in <a href="apache_loop.html">Apache Loop</a>.</p>
<h3>Site configuration and species definitions</h3>
<p>A series of <code>.ini</code> files are used to specify virtually every other configurable section of Ensembl. These are easier to configure than a perl module and are only needed by the child processes. The <code>DEFAULTS.ini</code> and <code>MULTI.ini</code> files contains a set of default settings for all species, but each species appearing in Ensembl can augment or overwrite these settings with its own <code>.ini</code> file. All these files are located and parsed at server startup by <code>EnsEMBL::Web::SpeciesDefs.pm</code>.</p>
<p>Configuration options specified in the <code>.ini</code> files include (but are in no way limited to):</p>
<ul>
<li>Default database connection settings</li>
<li>Homology search settings</li>
<li>Paths to utilities used by the site</li>
<li>Parameters that control the look and feel of the site</li>
</ul>
<h3>Accessing system configurations</h3>
<p>As the information from <code>SiteDefs.pm</code> is pulled into <code>SpeciesDefs.pm</code>, all these settings (be they server, site or species) are accessible from the global package <code>SpeciesDefs</code>. No instantiation should be necessary to access the settings as the SpeciesDefs object is instantiated early by <code>EnsEMBL::Web::Page</code> and then passed around. </p>
<h2>User configuration</h2>
<p>Seperate from the actual system configuration, it is often helpful to store additional configuration information on a per user basis. For example, should a user elect to hide a number of tracks, it makes for a better user experience if Ensembl remembers those changes for subsequent visits to the site. Ensembl does this based on user sessions.</p>
<h3>Sessions</h3>
<p>Any time a user makes a configuration change to a view in Ensembl, a new user session is started. This links a particular browser to a particular Ensembl configuration, by storing a cookie containing a unique identification number in the browser.
The cookies are only created when needed, by <code>EnsEMBL::Document::WebPage</code>. They store an encrypted
version of the session ID from the <code>%ENV</code> variable (instantiated by the Post Read Request handler).</p>
<p>When a new session is started, a new entry is made in the optional WebUser database and all configuration changes are stored against it. This ensures that configuration changes are persistant per session. </p>
<h3>Accessing user configurations</h3>
<p>Two modules are used to maintain state in this way: <code>UserConfig</code> and <code>ScriptConfig</code>. Both use the same WebUser database for storing and trieving information, and both check and create session identifiers if necessary.</p>
<ul>
<li><code>UserConfig</code> is used to store information about a particular view's images. For example, which tracks are active.</li>
<li><code>ScriptConfig</code> stores options for a particular script or page. For example, the width of the page, which panels are visible and which are collapsed.</li>
</ul>
<p>Instead of saving all configuration options in the databse, these configuration modules actually store the difference from the default settings. With this implementation new default options will not be overridden by older session information.
</p>
<h2>Footnotes on ensembl_accounts</h2>
<ul>
<li>The <code>UserConfig</code> reads the session ID from the cookie and then looks up the session data in the
ensembl web user database (ensembl_accounts). If this database goes down, session data requests back up and
eventually the whole site does down.</li>
<li>Data is not deleted from the ensembl_accounts database.</li>
<li>The user logins system uses the same database but different tables.</li>
</ul>
</body>
</html>
| {
"content_hash": "55297a46a7b62a0c2812084890d62dc6",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 544,
"avg_line_length": 62.62162162162162,
"alnum_prop": 0.7619766940008632,
"repo_name": "muffato/public-plugins",
"id": "3ee6e1cdccf097e8ea3f49d63b70c72e74f8caf4",
"size": "4634",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/htdocs/info/docs/webcode/dev/configuration.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "186"
},
{
"name": "CSS",
"bytes": "164321"
},
{
"name": "CoffeeScript",
"bytes": "171316"
},
{
"name": "HTML",
"bytes": "1271868"
},
{
"name": "JavaScript",
"bytes": "1719676"
},
{
"name": "Perl",
"bytes": "1712523"
}
],
"symlink_target": ""
} |
package com.maxdemarzi.processing.pagerank;
import com.maxdemarzi.processing.NodeCounter;
import org.neo4j.collection.primitive.PrimitiveLongIterator;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import org.neo4j.kernel.api.ReadOperations;
import org.neo4j.kernel.api.exceptions.EntityNotFoundException;
import org.neo4j.kernel.impl.api.RelationshipVisitor;
import org.neo4j.kernel.impl.core.ThreadToStatementContextBridge;
import java.util.Arrays;
/**
* @author mh
* @since 28.03.15
*/
public class PageRankArrayStorageSPI implements PageRank {
private final GraphDatabaseAPI db;
private final int nodes;
private float[] dst;
public PageRankArrayStorageSPI(GraphDatabaseService db) {
this.db = (GraphDatabaseAPI) db;
this.nodes = new NodeCounter().getNodeCount(db);
}
@Override
public void compute(String label, String type, int iterations) {
float[] src = new float[nodes];
dst = new float[nodes];
try ( Transaction tx = db.beginTx()) {
ThreadToStatementContextBridge ctx = this.db.getDependencyResolver().resolveDependency(ThreadToStatementContextBridge.class);
ReadOperations ops = ctx.get().readOperations();
int labelId = ops.labelGetForName(label);
int typeId = ops.relationshipTypeGetForName(type);
int[] degrees = computeDegrees(ops,labelId, typeId);
RelationshipVisitor<RuntimeException> visitor = new RelationshipVisitor<RuntimeException>() {
public void visit(long relId, int relTypeId, long startNode, long endNode) throws RuntimeException {
if (relTypeId == typeId) {
dst[((int) endNode)] += src[(int) startNode];
}
}
};
for (int iteration = 0; iteration < iterations; iteration++) {
startIteration(src, dst, degrees);
PrimitiveLongIterator rels = ops.relationshipsGetAll();
while (rels.hasNext()) {
ops.relationshipVisit(rels.next(), visitor);
}
}
tx.success();
} catch (EntityNotFoundException e) {
e.printStackTrace();
}
}
private void startIteration(float[] src, float[] dst, int[] degrees) {
for (int node = 0; node < this.nodes; node++) {
if (degrees[node] == -1) continue;
src[node]= (float) (ALPHA * dst[node] / degrees[node]);
}
Arrays.fill(dst, (float) ONE_MINUS_ALPHA);
}
private int[] computeDegrees(ReadOperations ops, int labelId, int relationshipId) throws EntityNotFoundException {
int[] degrees = new int[nodes];
Arrays.fill(degrees,-1);
PrimitiveLongIterator nodes = ops.nodesGetForLabel(labelId);
while (nodes.hasNext()) {
long node = nodes.next();
degrees[((int)node)]= ops.nodeGetDegree(node, Direction.OUTGOING, relationshipId);
}
return degrees;
}
@Override
public double getResult(long node) {
return dst != null ? dst[((int) node)] : -1;
}
@Override
public long numberOfNodes() {
return nodes;
}
}
| {
"content_hash": "bb76d40406f2f9fd5c3827c951152db6",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 137,
"avg_line_length": 35.357894736842105,
"alnum_prop": 0.6338195891634415,
"repo_name": "maxdemarzi/graph_processing",
"id": "0d16903b77cb64a8b0cefd37ca777ff2fc2f87b6",
"size": "3359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/maxdemarzi/processing/pagerank/PageRankArrayStorageSPI.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "99793"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Http_Client
*/
// require_once 'Zend/Http/Client.php';
/**
* @see Zend_Http_CookieJar
*/
// require_once 'Zend/Http/CookieJar.php';
/**
* @see Zend_Oauth_Consumer
*/
// require_once 'Zend/Oauth/Consumer.php';
/**
* @see Zend_Oauth_Token_Access
*/
// require_once 'Zend/Oauth/Token/Access.php';
/**
* @see Zend_Service_Twitter_Response
*/
// require_once 'Zend/Service/Twitter/Response.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage Twitter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Twitter
{
/**
* Base URI for all API calls
*/
const API_BASE_URI = 'https://api.twitter.com/1.1/';
/**
* OAuth Endpoint
*/
const OAUTH_BASE_URI = 'https://api.twitter.com/oauth';
/**
* 246 is the current limit for a status message, 140 characters are displayed
* initially, with the remainder linked from the web UI or client. The limit is
* applied to a html encoded UTF-8 string (i.e. entities are counted in the limit
* which may appear unusual but is a security measure).
*
* This should be reviewed in the future...
*/
const STATUS_MAX_CHARACTERS = 246;
/**
* @var array
*/
protected $cookieJar;
/**
* Date format for 'since' strings
*
* @var string
*/
protected $dateFormat = 'D, d M Y H:i:s T';
/**
* @var Zend_Http_Client
*/
protected $httpClient = null;
/**
* Current method type (for method proxying)
*
* @var string
*/
protected $methodType;
/**
* Oauth Consumer
*
* @var Zend_Oauth_Consumer
*/
protected $oauthConsumer = null;
/**
* Types of API methods
*
* @var array
*/
protected $methodTypes = array(
'account',
'application',
'blocks',
'directmessages',
'favorites',
'friendships',
'search',
'statuses',
'users',
);
/**
* Options passed to constructor
*
* @var array
*/
protected $options = array();
/**
* Username
*
* @var string
*/
protected $username;
/**
* Constructor
*
* @param null|array|Zend_Config $options
* @param null|Zend_Oauth_Consumer $consumer
* @param null|Zend_Http_Client $httpClient
*/
public function __construct($options = null, Zend_Oauth_Consumer $consumer = null, Zend_Http_Client $httpClient = null)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (!is_array($options)) {
$options = array();
}
$this->options = $options;
if (isset($options['username'])) {
$this->setUsername($options['username']);
}
$accessToken = false;
if (isset($options['accessToken'])) {
$accessToken = $options['accessToken'];
} elseif (isset($options['access_token'])) {
$accessToken = $options['access_token'];
}
$oauthOptions = array();
if (isset($options['oauthOptions'])) {
$oauthOptions = $options['oauthOptions'];
} elseif (isset($options['oauth_options'])) {
$oauthOptions = $options['oauth_options'];
}
$oauthOptions['siteUrl'] = self::OAUTH_BASE_URI;
$httpClientOptions = array();
if (isset($options['httpClientOptions'])) {
$httpClientOptions = $options['httpClientOptions'];
} elseif (isset($options['http_client_options'])) {
$httpClientOptions = $options['http_client_options'];
}
// If we have an OAuth access token, use the HTTP client it provides
if ($accessToken && is_array($accessToken)
&& (isset($accessToken['token']) && isset($accessToken['secret']))
) {
$token = new Zend_Oauth_Token_Access();
$token->setToken($accessToken['token']);
$token->setTokenSecret($accessToken['secret']);
$accessToken = $token;
}
if ($accessToken && $accessToken instanceof Zend_Oauth_Token_Access) {
$oauthOptions['token'] = $accessToken;
$this->setHttpClient($accessToken->getHttpClient($oauthOptions, self::OAUTH_BASE_URI, $httpClientOptions));
return;
}
// See if we were passed an http client
if (isset($options['httpClient']) && null === $httpClient) {
$httpClient = $options['httpClient'];
} elseif (isset($options['http_client']) && null === $httpClient) {
$httpClient = $options['http_client'];
}
if ($httpClient instanceof Zend_Http_Client) {
$this->httpClient = $httpClient;
} else {
$this->setHttpClient(new Zend_Http_Client(null, $httpClientOptions));
}
// Set the OAuth consumer
if ($consumer === null) {
$consumer = new Zend_Oauth_Consumer($oauthOptions);
}
$this->oauthConsumer = $consumer;
}
/**
* Proxy service methods
*
* @param string $type
* @return Zend_Service_Twitter
* @throws Exception\DomainException If method not in method types list
*/
public function __get($type)
{
$type = strtolower((string) $type);
$type = str_replace((string) '_', '', $type);
if (!in_array($type, $this->methodTypes)) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Invalid method type "' . $type . '"'
);
}
$this->methodType = $type;
return $this;
}
/**
* Method overloading
*
* @param string $method
* @param array $params
* @return mixed
* @throws Exception\BadMethodCallException if unable to find method
*/
public function __call($method, $params)
{
if (method_exists($this->oauthConsumer, $method)) {
$return = call_user_func_array(array($this->oauthConsumer, $method), $params);
if ($return instanceof Zend_Oauth_Token_Access) {
$this->setHttpClient($return->getHttpClient($this->options));
}
return $return;
}
if (empty($this->methodType)) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Invalid method "' . $method . '"'
);
}
$test = str_replace((string) '_', '', strtolower((string) $method));
$test = $this->methodType . $test;
if (!method_exists($this, $test)) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Invalid method "' . $test . '"'
);
}
return call_user_func_array(array($this, $test), $params);
}
/**
* Set HTTP client
*
* @param Zend_Http_Client $client
* @return self
*/
public function setHttpClient(Zend_Http_Client $client)
{
$this->httpClient = $client;
$this->httpClient->setHeaders(array('Accept-Charset' => 'ISO-8859-1,utf-8'));
return $this;
}
/**
* Get the HTTP client
*
* Lazy loads one if none present
*
* @return Zend_Http_Client
*/
public function getHttpClient()
{
if (null === $this->httpClient) {
$this->setHttpClient(new Zend_Http_Client());
}
return $this->httpClient;
}
/**
* Retrieve username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set username
*
* @param string $value
* @return self
*/
public function setUsername($value)
{
$this->username = $value;
return $this;
}
/**
* Checks for an authorised state
*
* @return bool
*/
public function isAuthorised()
{
if ($this->getHttpClient() instanceof Zend_Oauth_Client) {
return true;
}
return false;
}
/**
* Verify Account Credentials
*
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function accountVerifyCredentials()
{
$this->init();
$response = $this->get('account/verify_credentials');
return new Zend_Service_Twitter_Response($response);
}
/**
* Returns the number of api requests you have left per hour.
*
* @todo Have a separate payload object to represent rate limits
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function applicationRateLimitStatus()
{
$this->init();
$response = $this->get('application/rate_limit_status');
return new Zend_Service_Twitter_Response($response);
}
/**
* Blocks the user specified in the ID parameter as the authenticating user.
* Destroys a friendship to the blocked user if it exists.
*
* @param integer|string $id The ID or screen name of a user to block.
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function blocksCreate($id)
{
$this->init();
$path = 'blocks/create';
$params = $this->createUserParameter($id, array());
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Un-blocks the user specified in the ID parameter for the authenticating user
*
* @param integer|string $id The ID or screen_name of the user to un-block.
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function blocksDestroy($id)
{
$this->init();
$path = 'blocks/destroy';
$params = $this->createUserParameter($id, array());
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Returns an array of user ids that the authenticating user is blocking
*
* @param integer $cursor Optional. Specifies the cursor position at which to begin listing ids; defaults to first "page" of results.
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function blocksIds($cursor = -1)
{
$this->init();
$path = 'blocks/ids';
$response = $this->get($path, array('cursor' => $cursor));
return new Zend_Service_Twitter_Response($response);
}
/**
* Returns an array of user objects that the authenticating user is blocking
*
* @param integer $cursor Optional. Specifies the cursor position at which to begin listing ids; defaults to first "page" of results.
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function blocksList($cursor = -1)
{
$this->init();
$path = 'blocks/list';
$response = $this->get($path, array('cursor' => $cursor));
return new Zend_Service_Twitter_Response($response);
}
/**
* Destroy a direct message
*
* @param int $id ID of message to destroy
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function directMessagesDestroy($id)
{
$this->init();
$path = 'direct_messages/destroy';
$params = array('id' => $this->validInteger($id));
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Retrieve direct messages for the current user
*
* $options may include one or more of the following keys
* - count: return page X of results
* - since_id: return statuses only greater than the one specified
* - max_id: return statuses with an ID less than (older than) or equal to that specified
* - include_entities: setting to false will disable embedded entities
* - skip_status:setting to true, "t", or 1 will omit the status in returned users
*
* @param array $options
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function directMessagesMessages(array $options = array())
{
$this->init();
$path = 'direct_messages';
$params = array();
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'count':
$params['count'] = (int) $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
case 'skip_status':
$params['skip_status'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Send a direct message to a user
*
* @param int|string $user User to whom to send message
* @param string $text Message to send to user
* @throws Exception\InvalidArgumentException if message is empty
* @throws Exception\OutOfRangeException if message is too long
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function directMessagesNew($user, $text)
{
$this->init();
$path = 'direct_messages/new';
$len = iconv_strlen($text, 'UTF-8');
if (0 == $len) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Direct message must contain at least one character'
);
} elseif (140 < $len) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Direct message must contain no more than 140 characters'
);
}
$params = $this->createUserParameter($user, array());
$params['text'] = $text;
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Retrieve list of direct messages sent by current user
*
* $options may include one or more of the following keys
* - count: return page X of results
* - page: return starting at page
* - since_id: return statuses only greater than the one specified
* - max_id: return statuses with an ID less than (older than) or equal to that specified
* - include_entities: setting to false will disable embedded entities
*
* @param array $options
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function directMessagesSent(array $options = array())
{
$this->init();
$path = 'direct_messages/sent';
$params = array();
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'count':
$params['count'] = (int) $value;
break;
case 'page':
$params['page'] = (int) $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Mark a status as a favorite
*
* @param int $id Status ID you want to mark as a favorite
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function favoritesCreate($id)
{
$this->init();
$path = 'favorites/create';
$params = array('id' => $this->validInteger($id));
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Remove a favorite
*
* @param int $id Status ID you want to de-list as a favorite
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function favoritesDestroy($id)
{
$this->init();
$path = 'favorites/destroy';
$params = array('id' => $this->validInteger($id));
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Fetch favorites
*
* $options may contain one or more of the following:
* - user_id: Id of a user for whom to fetch favorites
* - screen_name: Screen name of a user for whom to fetch favorites
* - count: number of tweets to attempt to retrieve, up to 200
* - since_id: return results only after the specified tweet id
* - max_id: return results with an ID less than (older than) or equal to the specified ID
* - include_entities: when set to false, entities member will be omitted
*
* @param array $params
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function favoritesList(array $options = array())
{
$this->init();
$path = 'favorites/list';
$params = array();
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'user_id':
$params['user_id'] = $this->validInteger($value);
break;
case 'screen_name':
$params['screen_name'] = $value;
break;
case 'count':
$params['count'] = (int) $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Create friendship
*
* @param int|string $id User ID or name of new friend
* @param array $params Additional parameters to pass
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function friendshipsCreate($id, array $params = array())
{
$this->init();
$path = 'friendships/create';
$params = $this->createUserParameter($id, $params);
$allowed = array(
'user_id' => null,
'screen_name' => null,
'follow' => null,
);
$params = array_intersect_key($params, $allowed);
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Destroy friendship
*
* @param int|string $id User ID or name of friend to remove
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function friendshipsDestroy($id)
{
$this->init();
$path = 'friendships/destroy';
$params = $this->createUserParameter($id, array());
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Search tweets
*
* $options may include any of the following:
* - geocode: a string of the form "latitude, longitude, radius"
* - lang: restrict tweets to the two-letter language code
* - locale: query is in the given two-letter language code
* - result_type: what type of results to receive: mixed, recent, or popular
* - count: number of tweets to return per page; up to 100
* - until: return tweets generated before the given date
* - since_id: return resutls with an ID greater than (more recent than) the given ID
* - max_id: return results with an ID less than (older than) the given ID
* - include_entities: whether or not to include embedded entities
*
* @param string $query
* @param array $options
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function searchTweets($query, array $options = array())
{
$this->init();
$path = 'search/tweets';
$len = iconv_strlen($query, 'UTF-8');
if (0 == $len) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Query must contain at least one character'
);
}
$params = array('q' => $query);
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'geocode':
if (!substr_count($value, ',') !== 2) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'"geocode" must be of the format "latitude,longitude,radius"'
);
}
list($latitude, $longitude, $radius) = explode(',', $value);
$radius = \trim((string) $radius);
if (!preg_match('/^\d+(mi|km)$/', $radius)) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Radius segment of "geocode" must be of the format "[unit](mi|km)"'
);
}
$latitude = (float) $latitude;
$longitude = (float) $longitude;
$params['geocode'] = $latitude . ',' . $longitude . ',' . $radius;
break;
case 'lang':
if (strlen((string) $value) > 2) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Query language must be a 2 character string'
);
}
$params['lang'] = strtolower((string) $value);
break;
case 'locale':
if (strlen((string) $value) > 2) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Query locale must be a 2 character string'
);
}
$params['locale'] = strtolower((string) $value);
break;
case 'result_type':
$value = strtolower((string) $value);
if (!in_array($value, array('mixed', 'recent', 'popular'))) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'result_type must be one of "mixed", "recent", or "popular"'
);
}
$params['result_type'] = $value;
break;
case 'count':
$value = (int) $value;
if (1 > $value || 100 < $value) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'count must be between 1 and 100'
);
}
$params['count'] = $value;
break;
case 'until':
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'"until" must be a date in the format YYYY-MM-DD'
);
}
$params['until'] = $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Destroy a status message
*
* @param int $id ID of status to destroy
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesDestroy($id)
{
$this->init();
$path = 'statuses/destroy/' . $this->validInteger($id);
$response = $this->post($path);
return new Zend_Service_Twitter_Response($response);
}
/**
* Friend Timeline Status
*
* $options may include one or more of the following keys
* - count: number of tweets to attempt to retrieve, up to 200
* - since_id: return results only after the specified tweet id
* - max_id: return results with an ID less than (older than) or equal to the specified ID
* - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
* - contributor_details: when set to true, includes screen_name of each contributor
* - include_entities: when set to false, entities member will be omitted
* - exclude_replies: when set to true, will strip replies appearing in the timeline
*
* @param array $params
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesHomeTimeline(array $options = array())
{
$this->init();
$path = 'statuses/home_timeline';
$params = array();
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'count':
$params['count'] = (int) $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'trim_user':
if (in_array($value, array(true, 'true', 't', 1, '1'))) {
$value = true;
} else {
$value = false;
}
$params['trim_user'] = $value;
break;
case 'contributor_details:':
$params['contributor_details:'] = (bool) $value;
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
case 'exclude_replies':
$params['exclude_replies'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Get status replies
*
* $options may include one or more of the following keys
* - count: number of tweets to attempt to retrieve, up to 200
* - since_id: return results only after the specified tweet id
* - max_id: return results with an ID less than (older than) or equal to the specified ID
* - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
* - contributor_details: when set to true, includes screen_name of each contributor
* - include_entities: when set to false, entities member will be omitted
*
* @param array $options
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesMentionsTimeline(array $options = array())
{
$this->init();
$path = 'statuses/mentions_timeline';
$params = array();
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'count':
$params['count'] = (int) $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'trim_user':
if (in_array($value, array(true, 'true', 't', 1, '1'))) {
$value = true;
} else {
$value = false;
}
$params['trim_user'] = $value;
break;
case 'contributor_details:':
$params['contributor_details:'] = (bool) $value;
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Public Timeline status
*
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesSample()
{
$this->init();
$path = 'statuses/sample';
$response = $this->get($path);
return new Zend_Service_Twitter_Response($response);
}
/**
* Show a single status
*
* @param int $id Id of status to show
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesShow($id)
{
$this->init();
$path = 'statuses/show/' . $this->validInteger($id);
$response = $this->get($path);
return new Zend_Service_Twitter_Response($response);
}
/**
* Update user's current status
*
* @todo Support additional parameters supported by statuses/update endpoint
* @param string $status
* @param null|int $inReplyToStatusId
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\OutOfRangeException if message is too long
* @throws Exception\InvalidArgumentException if message is empty
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesUpdate($status, $inReplyToStatusId = null)
{
$this->init();
$path = 'statuses/update';
$len = iconv_strlen(htmlspecialchars((string) $status, ENT_QUOTES, 'UTF-8'), 'UTF-8');
if ($len > self::STATUS_MAX_CHARACTERS) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Status must be no more than '
. self::STATUS_MAX_CHARACTERS
. ' characters in length'
);
} elseif (0 == $len) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Status must contain at least one character'
);
}
$params = array('status' => $status);
$inReplyToStatusId = $this->validInteger($inReplyToStatusId);
if ($inReplyToStatusId) {
$params['in_reply_to_status_id'] = $inReplyToStatusId;
}
$response = $this->post($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* User Timeline status
*
* $options may include one or more of the following keys
* - user_id: Id of a user for whom to fetch favorites
* - screen_name: Screen name of a user for whom to fetch favorites
* - count: number of tweets to attempt to retrieve, up to 200
* - since_id: return results only after the specified tweet id
* - max_id: return results with an ID less than (older than) or equal to the specified ID
* - trim_user: when set to true, "t", or 1, user object in tweets will include only author's ID.
* - exclude_replies: when set to true, will strip replies appearing in the timeline
* - contributor_details: when set to true, includes screen_name of each contributor
* - include_rts: when set to false, will strip native retweets
*
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function statusesUserTimeline(array $options = array())
{
$this->init();
$path = 'statuses/user_timeline';
$params = array();
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'user_id':
$params['user_id'] = $this->validInteger($value);
break;
case 'screen_name':
$params['screen_name'] = $this->validateScreenName($value);
break;
case 'count':
$params['count'] = (int) $value;
break;
case 'since_id':
$params['since_id'] = $this->validInteger($value);
break;
case 'max_id':
$params['max_id'] = $this->validInteger($value);
break;
case 'trim_user':
if (in_array($value, array(true, 'true', 't', 1, '1'))) {
$value = true;
} else {
$value = false;
}
$params['trim_user'] = $value;
break;
case 'contributor_details:':
$params['contributor_details:'] = (bool) $value;
break;
case 'exclude_replies':
$params['exclude_replies'] = (bool) $value;
break;
case 'include_rts':
$params['include_rts'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Search users
*
* $options may include any of the following:
* - page: the page of results to retrieve
* - count: the number of users to retrieve per page; max is 20
* - include_entities: if set to boolean true, include embedded entities
*
* @param string $query
* @param array $options
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function usersSearch($query, array $options = array())
{
$this->init();
$path = 'users/search';
$len = iconv_strlen($query, 'UTF-8');
if (0 == $len) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Query must contain at least one character'
);
}
$params = array('q' => $query);
foreach ($options as $key => $value) {
switch (strtolower((string) $key)) {
case 'count':
$value = (int) $value;
if (1 > $value || 20 < $value) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'count must be between 1 and 20'
);
}
$params['count'] = $value;
break;
case 'page':
$params['page'] = (int) $value;
break;
case 'include_entities':
$params['include_entities'] = (bool) $value;
break;
default:
break;
}
}
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Show extended information on a user
*
* @param int|string $id User ID or name
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @throws Exception\DomainException if unable to decode JSON payload
* @return Zend_Service_Twitter_Response
*/
public function usersShow($id)
{
$this->init();
$path = 'users/show';
$params = $this->createUserParameter($id, array());
$response = $this->get($path, $params);
return new Zend_Service_Twitter_Response($response);
}
/**
* Initialize HTTP authentication
*
* @return void
* @throws Exception\DomainException if unauthorised
*/
protected function init()
{
if (!$this->isAuthorised() && $this->getUsername() !== null) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Twitter session is unauthorised. You need to initialize '
. __CLASS__ . ' with an OAuth Access Token or use '
. 'its OAuth functionality to obtain an Access Token before '
. 'attempting any API actions that require authorisation'
);
}
$client = $this->getHttpClient();
$client->resetParameters();
if (null === $this->cookieJar) {
$cookieJar = $client->getCookieJar();
if (null === $cookieJar) {
$cookieJar = new Zend_Http_CookieJar();
}
$this->cookieJar = $cookieJar;
$this->cookieJar->reset();
} else {
$client->setCookieJar($this->cookieJar);
}
}
/**
* Protected function to validate that the integer is valid or return a 0
*
* @param $int
* @throws Zend_Http_Client_Exception if HTTP request fails or times out
* @return integer
*/
protected function validInteger($int)
{
if (preg_match("/(\d+)/", (string) $int)) {
return $int;
}
return 0;
}
/**
* Validate a screen name using Twitter rules
*
* @param string $name
* @return string
* @throws Exception\InvalidArgumentException
*/
protected function validateScreenName($name)
{
if (!preg_match('/^[a-zA-Z0-9_]{0,20}$/', $name)) {
// require_once 'Zend/Service/Twitter/Exception.php';
throw new Zend_Service_Twitter_Exception(
'Screen name, "' . $name
. '" should only contain alphanumeric characters and'
. ' underscores, and not exceed 15 characters.');
}
return $name;
}
/**
* Call a remote REST web service URI
*
* @param string $path The path to append to the URI
* @param Zend_Http_Client $client
* @throws Zend_Http_Client_Exception
* @return void
*/
protected function prepare($path, Zend_Http_Client $client)
{
$client->setUri(self::API_BASE_URI . $path . '.json');
/**
* Do this each time to ensure oauth calls do not inject new params
*/
$client->resetParameters();
}
/**
* Performs an HTTP GET request to the $path.
*
* @param string $path
* @param array $query Array of GET parameters
* @throws Zend_Http_Client_Exception
* @return Zend_Http_Response
*/
protected function get($path, array $query = array())
{
$client = $this->getHttpClient();
$this->prepare($path, $client);
$client->setParameterGet($query);
$response = $client->request(Zend_Http_Client::GET);
return $response;
}
/**
* Performs an HTTP POST request to $path.
*
* @param string $path
* @param mixed $data Raw data to send
* @throws Zend_Http_Client_Exception
* @return Zend_Http_Response
*/
protected function post($path, $data = null)
{
$client = $this->getHttpClient();
$this->prepare($path, $client);
$response = $this->performPost(Zend_Http_Client::POST, $data, $client);
return $response;
}
/**
* Perform a POST or PUT
*
* Performs a POST or PUT request. Any data provided is set in the HTTP
* client. String data is pushed in as raw POST data; array or object data
* is pushed in as POST parameters.
*
* @param mixed $method
* @param mixed $data
* @return Zend_Http_Response
*/
protected function performPost($method, $data, Zend_Http_Client $client)
{
if (is_string($data)) {
$client->setRawData($data);
} elseif (is_array($data) || is_object($data)) {
$client->setParameterPost((array) $data);
}
return $client->request($method);
}
/**
* Create a parameter representing the user
*
* Determines if $id is an integer, and, if so, sets the "user_id" parameter.
* If not, assumes the $id is the "screen_name".
*
* @param int|string $id
* @param array $params
* @return array
*/
protected function createUserParameter($id, array $params)
{
if ($this->validInteger($id)) {
$params['user_id'] = $id;
return $params;
}
$params['screen_name'] = $this->validateScreenName($id);
return $params;
}
}
| {
"content_hash": "a862d5845dd0142219588e91341f2e84",
"timestamp": "",
"source": "github",
"line_count": 1288,
"max_line_length": 139,
"avg_line_length": 35.56987577639752,
"alnum_prop": 0.5391146811018466,
"repo_name": "holtkamp/zf1",
"id": "6e4360643633af8727fe19f916e9599b8ad6a2c0",
"size": "46530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/zend-service-twitter/library/Zend/Service/Twitter.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1036"
},
{
"name": "HTML",
"bytes": "90766"
},
{
"name": "Hack",
"bytes": "7"
},
{
"name": "JavaScript",
"bytes": "1588"
},
{
"name": "PHP",
"bytes": "29840536"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Roff",
"bytes": "307"
},
{
"name": "Shell",
"bytes": "3011"
},
{
"name": "TSQL",
"bytes": "1167"
}
],
"symlink_target": ""
} |
<?php
defined( 'ABSPATH' ) || exit;
class PMW_Register_Register {
/**
* @since 20170227
* @var string
*/
protected static $option = 'plugin_option_slug';
/**
* @since 20170318
* @var string class trait added
*/
protected static $php_vers = '5.3.6';
/**
* @since 20170227
* @var string Option slug prefix.
*/
protected static $prefix = 'option_prefix_';
/**
* @since 20200406
* @var string Name of class.
*/
protected static $register = 'PMW_Register_Register';
/**
* @since 20170318
* @var string Plugin title.
*/
protected static $title = 'Plugin Name';
/**
* @since 20170318
* @var string get_theme_file_uri() added
*/
protected static $wp_vers = '4.7.0';
/**
* Provide an email address.
*
* @since 20170214
*/
private static $our_site = '<a href="rtcenterprises.net" target="rtc">%s</a>';
private static $rc_email = '<a href="mailto:richard.coffee@rtcenterprises.net">%s</a>';
// private static $jg_email = '<a href="mailto:cableman371@gmail.com">%s</a>';
// private static function our_email() { return ( ( mt_rand( 1, 10 ) > 5 ) ? self::$rc_email : self::$jg_email ); }
public static function our_email() { return self::$rc_email; }
/**
* Preforms preliminary version checks.
*
* @since 20170214
*/
public static function activate() {
if ( ! static::php_version_check() ) {
wp_die( esc_html( static::php_bad_version_text() ) . self::return_link() );
}
if ( ! static::wp_version_check() ) {
wp_die( esc_html( static::wp_bad_version_text() ) . self::return_link() );
}
static::activate_tasks();
}
/**
* Should be overridden in child class. Performs all tasks required when activating the plugin.
*
* @since 20170501
*/
protected static function activate_tasks() { }
/** Dependency Checking - Will It Work?
*
* @link https://github.com/GlotPress/GlotPress-WP/blob/develop/glotpress.php
* @link https://pento.net/2014/02/18/dont-let-your-plugin-be-activated-on-incompatible-sites/
* @link https://buddypress.trac.wordpress.org/attachment/ticket/7196/7196.diff
*/
/** PHP version check **/
/**
* Returns the PHP version required.
*
* @since 20170318
* @return string PHP version string.
*/
protected static function php_version_required() {
return static::$php_vers;
}
/**
* Do the PHP version check.
*
* @since 20170318
* @return bool Result of the version check.
*/
public static function php_version_check() {
if ( version_compare( phpversion(), static::php_version_required(), '<' ) ) {
add_action( 'admin_notices', [ static::$register, 'unsupported_php_version' ], 10, 2 );
return false;
}
return true;
}
/**
* Handles bad PHP versions.
*
* @since 20170318
*/
public static function unsupported_php_version() {
$short = __( 'You are running an unsupported version of PHP.', 'privacy-my-way' );
$long = static::php_bad_version_text();
self::display_admin_notice( '— ' . $short, $long );
}
/**
* Returns the string for bad PHP version.
*
* @since 20170318
* @return string Text for bad PHP version.
*/
protected static function php_bad_version_text() {
return sprintf(
_x(
'%1$s requires PHP version %2$s, version %3$s detected. Please upgrade your PHP before attempting to use this plugin. ',
'1: Plugin name 2: php version required 3: php version detected',
'privacy-my-way'
),
static::$title,
static::$php_vers,
phpversion()
);
}
/** WordPress version check **/
/**
* Return the WP version required.
*
* @since 20170318
* @return string Required WP version.
*/
protected static function wp_version_required() {
return static::$wp_vers;
}
/**
* Handles the WP version check.
*
* @since 20170318
* @return bool Success/failure of version check.
*/
public static function wp_version_check() {
global $wp_version;
if ( version_compare( $wp_version, static::wp_version_required(), '<' ) ) {
add_action( 'admin_notices', [ static::$register, 'unsupported_wp_version' ], 10, 2 );
return false;
}
return true;
}
/**
* Handles bad wp version.
*
* @since 20170318
*/
public static function unsupported_wp_version() {
$short = __( 'You are running an unsupported version of WordPress.', 'privacy-my-way' );
$long = static::wp_bad_version_text();
self::display_admin_notice( '— ' . $short, $long );
}
/**
* Returns text for bad WP version.
*
* @since 20170318
* @return string Text.
*/
protected static function wp_bad_version_text() {
global $wp_version;
return sprintf(
_x(
'%1$s requires WordPress %2$s or later and has detected you are running %3$s. Upgrade your WordPress install before using this plugin.',
'1: Plugin name 2: Required version of WordPress 3: Current version of WordPress',
'privacy-my-way'
),
static::$title,
static::wp_version_required(),
$wp_version
);
}
/**
* Handles displaying the admin notice.
*
* @since 20170318
* @param string Notice title message.
* @param string Notice body message.
*/
private static function display_admin_notice( $short, $long ) {
$screen = get_current_screen();
if ( 'plugins' !== $screen->id ) {
return;
} ?>
<div class="notice notice-error">
<p style="max-width:800px;">
<b><?php echo esc_html( sprintf( _x( '%s can not be activated.', 'Plugin title', 'privacy-my-way' ), static::$title ) ); ?></b>
<?php echo esc_html( $short ); ?>
</p>
<p style="max-width:800px;">
<?php echo esc_html( $long ); ?>
</p>
</div><?php
}
/**
* Gives return anchor link for plugin install page.
*
* @since 20170501
* @return string HTML for anchor link.
*/
private static function return_link() {
ob_start(); ?>
<p>
<a href="<?php echo esc_url( get_site_url() . '/wp-admin/plugins.php' ); ?>">
<?php esc_html_e( 'Return to plugin page.' ); ?>
</a>
</p><?php
return ob_get_clean();
}
/** Turn things on **/
/**
* Creates a new page, or modifies a current page.
*
* @todo This function needs more testing before using it.
* @since 20170214
* @param array Post array.
* @param bool If true, will overwrite existing page.
*/
protected static function create_new_page( $new = array(), $overwrite = false ) {
if ( $new ) {
$page = false;
if ( ! empty( $new['post_name'] ) ) {
global $wpdb;
$page_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM posts WHERE post_name = %s AND post_type = 'page'", $new['post_name'] ) );
if ( $page_id ) {
$page = get_post( $page_id );
}
}
if ( ( ! $page ) && array_key_exists( 'post_title', $new ) && $new['post_title'] ) {
$page = get_page_by_title( $new['post_title'] );
}
if ( $page ) {
$new = array_merge( (array) $page, $new );
}
if ( $overwrite && array_key_exists( 'ID', $new ) && $new['ID'] ) {
wp_update_post( $new );
} else {
unset( $new['ID'] );
wp_insert_post( $new );
}
}
}
/** Turn things off **/
/**
* Removes plugin options from database on plugin deactivation.
*
* @since 20170111
* @param string Option slug.
*/
public static function deactivate( $option = '' ) {
if ( current_user_can( 'activate_plugins' ) ) {
$option = self::verify_option( $option );
if ( $option ) {
self::delete_blog_options( 'deactive', $option );
if ( is_multisite() && is_main_site() ) {
self::delete_site_options( 'deactive', $option );
}
flush_rewrite_rules();
}
}
}
/**
* Removes plugin options from the wp database when uninstalling plugin.
*
* @since 20170111
* @param string Option slug.
*/
public static function uninstall( $option = '' ) {
if ( current_user_can( 'activate_plugins' ) ) {
$option = self::verify_option( $option );
if ( $option ) {
self::delete_blog_options( 'uninstall', $option );
if ( is_multisite() && is_main_site() ) {
self::delete_site_options( 'uninstall', $option );
}
}
}
}
/**
* Provides for default value of option slug. Does not actually 'verify' anything.
*
* @since 20170227
* @param string Option slug.
* @return string Options slug.
*/
private static function verify_option( $option ) {
$option = ( $option )
? $option
: ( static::$option )
? static::$option
: null;
return $option;
}
/**
* Delete options for a multi-site blog.
*
* @since 20170227
* @param string Action to take.
* @param string Option slug.
*/
protected static function delete_blog_options( $action, $option ) {
$blog_id = get_current_blog_id();
$opt_slug = static::$prefix . $option;
$options = ( is_multisite() ) ? get_blog_option( $blog_id, $opt_slug, array() ) : get_option( $opt_slug, array() );
if ( $options ) {
if ( array_key_exists( 'deledata', $options ) && ( $options['deledata'] === $action ) ) {
if ( is_multisite() ) {
delete_blog_option( $blog_id, $opt_slug );
} else {
delete_option( $opt_slug );
}
}
}
}
/**
* Delete single site option.
*
* @since 20170227
* @param string Actino to take.
* @param string Option slug.
*/
protected static function delete_site_options( $action, $option ) {
$opt_slug = static::$prefix . $option;
$options = get_site_option( $opt_slug, array() );
if ( $options ) {
if ( array_key_exists( 'deledata', $options ) && ( $options['deledata'] === $action ) ) {
delete_site_option( $opt_slug );
}
}
}
}
| {
"content_hash": "3b8459b84d276288558241c8d577e8ff",
"timestamp": "",
"source": "github",
"line_count": 367,
"max_line_length": 140,
"avg_line_length": 25.96185286103542,
"alnum_prop": 0.607367758186398,
"repo_name": "RichardCoffee/privacy-my-way",
"id": "83ec37da0a0e4fb7a0c79eb763f91d99eae1507b",
"size": "9868",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/Register/Register.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "839"
},
{
"name": "JavaScript",
"bytes": "971"
},
{
"name": "PHP",
"bytes": "147335"
}
],
"symlink_target": ""
} |
using namespace std;
typedef actionlib::SimpleActionClient<control_msgs::JointTrajectoryAction> TrajClient;
class ArmControllerTester {
private:
ros::NodeHandle nh;
ros::NodeHandle pnh;
auto_ptr<message_filters::Subscriber<humanoid_catching::MovementGoal> > movementGoalSub;
ros::Publisher movementGoalMetricsPub;
ros::Publisher movementPlanMetricsPub;
string endEffector;
string arm;
string commandTopic;
robot_model::JointModelGroup* jointModelGroup;
robot_state::RobotStatePtr kinematicState;
auto_ptr<TrajClient> trajectoryClient;
auto_ptr<moveit::planning_interface::MoveGroup> moveGroup;
public:
ArmControllerTester() :
pnh("~")
{
if (!pnh.getParam("end_effector", endEffector))
{
ROS_ERROR("End effector name must be specified");
}
else {
ROS_INFO("Configuring for end effector: [%s]", endEffector.c_str());
}
if (!pnh.getParam("arm", arm))
{
ROS_ERROR("Arm name must be specified");
}
else {
ROS_INFO("Configuring for arm: [%s]", arm.c_str());
}
if (!pnh.getParam("command_topic", commandTopic))
{
ROS_ERROR("Command topic must be specified");
}
else {
ROS_INFO("Subscribing to topic: [%s]", commandTopic.c_str());
}
// Setup the subscriber
movementGoalSub.reset(new message_filters::Subscriber<humanoid_catching::MovementGoal>(nh,commandTopic, 1000));
movementGoalSub->registerCallback(boost::bind(&ArmControllerTester::goalCallback, this, _1));
// Setup the publisher
movementGoalMetricsPub = nh.advertise<humanoid_catching::DurationStamped>("movement_execute_metric", 100000, true);
movementPlanMetricsPub = nh.advertise<humanoid_catching::DurationStamped>("movement_plan_metric", 100000, true);
robot_model_loader::RobotModelLoader robotModelLoader("robot_description");
robot_model::RobotModelPtr kinematicModel = robotModelLoader.getModel();
kinematicState.reset(new robot_state::RobotState(kinematicModel));
kinematicState->setToDefaultValues();
jointModelGroup = kinematicModel->getJointModelGroup(arm);
trajectoryClient.reset(new TrajClient(arm == "left" ? "l_arm_controller/joint_trajectory_action" : "r_arm_controller/joint_trajectory_action", true));
ROS_INFO("Waiting for the joint_trajectory_action server");
if(!trajectoryClient->waitForServer(ros::Duration(30))){
ROS_ERROR("joint trajectory server could not be found");
}
ROS_INFO("joint_trajectory_action server is up");
moveGroup.reset(new moveit::planning_interface::MoveGroup(arm));
}
private:
static double distance(const geometry_msgs::Pose& pose1, const geometry_msgs::Pose& pose2) {
return sqrt(pow(pose2.position.x - pose1.position.x, 2) + pow(pose2.position.y - pose1.position.y, 2) + pow(pose2.position.z - pose1.position.z, 2));
}
void goalCallback(const humanoid_catching::MovementGoalConstPtr movementGoal) {
ROS_INFO("Receive a goal callback");
setArmToStart(movementGoal->jointAngles);
moveGroup->setGoalPositionTolerance(0.01);
moveGroup->setGoalOrientationTolerance(0.01);
moveGroup->setPoseTarget(movementGoal->pose);
moveGroup->setPlanningTime(1.0);
moveGroup->allowLooking(false);
moveGroup->allowReplanning(false);
ros::WallTime startMove = ros::WallTime::now();
ros::Time startMoveRos = ros::Time::now();
if (moveGroup->asyncMove() == -1) {
ROS_WARN("Failed to start movement");
return;
}
ROS_INFO("Polling for result");
bool succeeded = false;
while (ros::Duration(0.001).sleep() && ros::Time::now() - startMoveRos < ros::Duration(5)) {
const geometry_msgs::PoseStamped& pose = moveGroup->getCurrentPose();
ROS_INFO("Current position [%f %f %f]", pose.pose.position.x, pose.pose.position.y, pose.pose.position.z);
ROS_INFO("Desired position [%f %f %f]", movementGoal->pose.position.x, movementGoal->pose.position.y, movementGoal->pose.position.z);
double current = distance(pose.pose, movementGoal->pose);
ROS_INFO("Current distance: [%f]", current);
// TODO: Add orientation
if (current <= 0.01) {
ROS_INFO("Reached goal");
succeeded = true;
break;
}
}
ROS_INFO("Finished polling for result");
if (!succeeded) {
ROS_WARN("Failed to reach goal");
return;
}
ROS_INFO("Succeeded!");
{
humanoid_catching::DurationStamped msg;
msg.arm = arm;
msg.header = movementGoal->header;
msg.duration = ros::Duration((ros::WallTime::now() - startMove).toSec());
ROS_INFO("Duration of move was [%f]", msg.duration.toSec());
movementGoalMetricsPub.publish(msg);
}
ROS_INFO("Exiting goal callback");
}
void setArmToStart(const vector<double>& positions) {
control_msgs::JointTrajectoryGoal goal;
goal.trajectory.header.stamp = ros::Time::now();
if (arm == "left") {
goal.trajectory.joint_names.push_back("l_shoulder_pan_joint");
goal.trajectory.joint_names.push_back("l_shoulder_lift_joint");
goal.trajectory.joint_names.push_back("l_upper_arm_roll_joint");
goal.trajectory.joint_names.push_back("l_elbow_flex_joint");
goal.trajectory.joint_names.push_back("l_forearm_roll_joint");
goal.trajectory.joint_names.push_back("l_wrist_flex_joint");
goal.trajectory.joint_names.push_back("l_wrist_roll_joint");
}
else {
goal.trajectory.joint_names.push_back("r_shoulder_pan_joint");
goal.trajectory.joint_names.push_back("r_shoulder_lift_joint");
goal.trajectory.joint_names.push_back("r_upper_arm_roll_joint");
goal.trajectory.joint_names.push_back("r_elbow_flex_joint");
goal.trajectory.joint_names.push_back("r_forearm_roll_joint");
goal.trajectory.joint_names.push_back("r_wrist_flex_joint");
goal.trajectory.joint_names.push_back("r_wrist_roll_joint");
}
goal.trajectory.points.resize(1);
goal.trajectory.points[0].positions = positions;
goal.trajectory.points[0].velocities.resize(7);
goal.trajectory.points[0].velocities[0] = 0.0;
goal.trajectory.points[0].time_from_start = ros::Duration(0.5);
trajectoryClient->sendGoal(goal);
ROS_INFO("Sent goal to reset arm positions");
// Wait for the action to return
if (trajectoryClient->waitForResult(ros::Duration(30.0))) {
actionlib::SimpleClientGoalState state = trajectoryClient->getState();
ROS_INFO("Action finished: %s", state.toString().c_str());
}
else {
ROS_WARN("Failed to move to base position");
}
}
};
int main(int argc, char **argv) {
ros::init(argc, argv, "arm_controller_tester");
ArmControllerTester act;
ros::spin();
return 0;
}
| {
"content_hash": "9fb7800ca81ef1ab4c73feffa90d12a7",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 158,
"avg_line_length": 39.59139784946237,
"alnum_prop": 0.6250678978815861,
"repo_name": "PositronicsLab/humanoid_catching",
"id": "0d6697b0eaa3ebcf32584c1e1631178614634d6f",
"size": "7814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/arm_controller_tester.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "222270"
},
{
"name": "CMake",
"bytes": "15454"
},
{
"name": "Shell",
"bytes": "3066"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.