code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
body {
color: #2a2d2b;
background-color: lightgrey;
}
h1 {
color: #2a2d2b;
}
h2 {
color: #336699;
}
h3 {
color: #2a2d2b;
}
.link {
color: #336699;
}
a:hover, .link:hover {
font-weight: bold;
text-decoration: underline;
}
ul {
padding-left: 5px;
}
div#header {
background-color: #fff;
padding: 15px 15px;
color: #2a2d2b;
}
button, div#header button {
color: #ffffff;
}
.btn, div#header .btn, div#content div#sidebar .btn, ul.dropdown-menu {
font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
}
div#header .alert {
margin: 5px 0px;
text-align: left;
}
.alert {
color: #fff;
}
.alert-info, .alert-success, .brand-info, .btn-success {
background-color: #4a9e43;
}
.alert-danger, .brand-danger {
background-color: #ff2a00;
}
.brand-primary, .btn-primary {
background-color: #336699;
}
.btn {
color: #fff;
}
.btn-default {
background-color: #444547;
}
.btn-default:hover {
background-color: #444547;
border-color: #2a2d2b;
color: #fff;
}
.sycned {
color: #4a9e43;
}
.unsycned {
color: #ff2a00;
}
div#message {
margin: 0px 5px;
}
.divider {
border: 10px solid #2a2d2b;
}
#content {
min-height: 450px;
padding: 0px;
box-shadow: 0px 5px 5px #888888;
background-color: #fff;
}
#content .divider {
border: 3px solid #2a2d2b;
margin: 20px -50px;
}
#content h2, #content li>h3, #content li>h4 {
display: inline-block;
margin-right: 10px;
}
#content .btn {
vertical-align: baseline;
}
#footer {
font-size: 12px;
text-align: center;
margin: 10px 0px;
}
ul.alert {
padding-left: 30px;
}
.spacing-top {
margin-top: 10px;
}
div#sitemenu {
text-align: right;
color: #ffffff;
}
button#headerDropdownMenu {
background-color: #404040;
border: 0px;
color: #ffffff;
}
div#sidebar {
background-color: #444547;
min-height: 450px;
}
div#sidebar h1, div#sidebar h2, div#sidebar h3, div#sidebar a {
color: #fff;
}
li>h1, li>h2, li>h3, li>h4 {
margin-top: 5px;
margin-bottom: 5px;
}
div#center {
background-color: #fff;
min-height: 450px;
padding: 30px 50px;
}
div.button-group-center {
text-align: center;
margin: 30px;
}
div.button-group-right {
float: right;
}
.modal-footer {
border-top: 0px;
}
.fa {
margin-right: 10px;
font-size: 24px;
}
li.folder, li.file {
list-style: none;
margin-left: 36px;
}
.row-flex {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
ul.abn-tree {
padding-left: 30px;
}
ul.abn-tree li.abn-tree-row a {
color: #2a2d2b;
font-size: 18px;
}
ul.nav.abn-tree i {
font-size: 18px;
}
.spinner {
float: right;
position: relative;
left: -50%;
text-align: left;
z-index: 1000;
color: #ff2a00;
}
.spinner > .child {
position: relative;
left: 50%;
float: right;
z-index: 1000;
}
.fa-spin {
font-size: 80px;
width: 0px;
margin: 0px;
}
.nav, .pagination, .carousel, .panel-title a {
cursor: pointer;
}
#progressBar {
background-color: #444547;
display: table;
height: 450px;
width: 100%;
}
#progressBar > div {
display: table-cell;
vertical-align: middle;
}
#progressBar > div {
margin-left: auto;
margin-right: auto;
width: 200px;
}
.progress {
height: 30px;
}
.progress span {
font-size: 25px;
line-height: 20px;
}
.progress-bar {
padding: 3px;
}
.deploy-errors {
border: 2px solid red;
padding: 10px;
background-color: #333;
color: white;
}
.deploy-errors h3 {
color: white;
margin: 0px 0px 10px 0px;
}
.error-msg {
font-weight: bold;
}
.error-loc {
margin-left: 20px;
}
.modal-sm {
width: 600px;
}
.modal-content {
width:inherit;
height:inherit;
margin: 0 auto;
}
.tree-scroller-cust1 {
height: 200px;
overflow-y: auto;
border-color: #ddd;
}
/* The starting CSS styles for the enter animation */
.fade.ng-enter {
transition:0.5s linear all;
opacity:0;
}
/* The finishing CSS styles for the enter animation */
.fade.ng-enter.ng-enter-active {
opacity:1;
}
/* now the element will fade out before it is removed from the DOM */
.fade.ng-leave {
transition:0.5s linear all;
opacity:1;
}
.fade.ng-leave.ng-leave-active {
opacity:0;
}
.caption {
font-style: italic;
font-weight: normal;
}
.hint {
color: #666;
}
.code {
font-weight: normal;
font-family: sans-serif;
}
.copy-icon {
font-size: 14px;
margin-left: 10px;
cursor: pointer;
}
.code textarea {
border: none;
width: 100%;
resize: none;
}
.code textarea:focus {
outline: none;
}
section {
border: 1px solid #ccc;
padding: 6px 12px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
}
.navbar-default {
background-color: #2a2d2b;
color: white;
}
/* This is specifically for Swagger UI */
.swagger-validator {
display: none;
}
div.api-doc > div {
padding: 15px;
}
#img_logo {
margin: 0pt 10px;
height: 50px;
}
| paxtonhare/marklogic-data-hub | quick-start/src/main/resources/static/css/quick-start.css | CSS | apache-2.0 | 5,187 |
<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="800px" height="600px" id="silverlightObject">
<param name="source" value="static/sl/Overlay.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="windowless" value="false" />
<!--
<param name="background" value="transparent" />
<param name="windowless" value="true" />
-->
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<param name="onLoad" value="pluginLoaded" />
<!--a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none" />
</a-->
</object>
</div>
| StackableRegiments/analyticalmetlx | src/main/webapp/_inkOverlay.html | HTML | apache-2.0 | 927 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
from google.analytics.data_v1alpha.types import analytics_data_api
from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO
from .grpc import AlphaAnalyticsDataGrpcTransport
class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport):
"""gRPC AsyncIO backend transport for AlphaAnalyticsData.
Google Analytics reporting data service.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
_grpc_channel: aio.Channel
_stubs: Dict[str, Callable] = {}
@classmethod
def create_channel(
cls,
host: str = "analyticsdata.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
aio.Channel: A gRPC AsyncIO channel object.
"""
return grpc_helpers_async.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
)
def __init__(
self,
*,
host: str = "analyticsdata.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
channel (Optional[aio.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for the grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure a mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
# Ignore credentials if a channel was passed.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
)
if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
self._host,
credentials=self._credentials,
credentials_file=credentials_file,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Wrap messages. This must be done after self._grpc_channel exists
self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
"""Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
"""
# Return the channel from cache.
return self._grpc_channel
@property
def run_report(
self,
) -> Callable[
[analytics_data_api.RunReportRequest],
Awaitable[analytics_data_api.RunReportResponse],
]:
r"""Return a callable for the run report method over gRPC.
Returns a customized report of your Google Analytics
event data. Reports contain statistics derived from data
collected by the Google Analytics tracking code. The
data returned from the API is as a table with columns
for the requested dimensions and metrics. Metrics are
individual measurements of user activity on your
property, such as active users or event count.
Dimensions break down metrics across some common
criteria, such as country or event name.
Returns:
Callable[[~.RunReportRequest],
Awaitable[~.RunReportResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "run_report" not in self._stubs:
self._stubs["run_report"] = self.grpc_channel.unary_unary(
"/google.analytics.data.v1alpha.AlphaAnalyticsData/RunReport",
request_serializer=analytics_data_api.RunReportRequest.serialize,
response_deserializer=analytics_data_api.RunReportResponse.deserialize,
)
return self._stubs["run_report"]
@property
def run_pivot_report(
self,
) -> Callable[
[analytics_data_api.RunPivotReportRequest],
Awaitable[analytics_data_api.RunPivotReportResponse],
]:
r"""Return a callable for the run pivot report method over gRPC.
Returns a customized pivot report of your Google
Analytics event data. Pivot reports are more advanced
and expressive formats than regular reports. In a pivot
report, dimensions are only visible if they are included
in a pivot. Multiple pivots can be specified to further
dissect your data.
Returns:
Callable[[~.RunPivotReportRequest],
Awaitable[~.RunPivotReportResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "run_pivot_report" not in self._stubs:
self._stubs["run_pivot_report"] = self.grpc_channel.unary_unary(
"/google.analytics.data.v1alpha.AlphaAnalyticsData/RunPivotReport",
request_serializer=analytics_data_api.RunPivotReportRequest.serialize,
response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize,
)
return self._stubs["run_pivot_report"]
@property
def batch_run_reports(
self,
) -> Callable[
[analytics_data_api.BatchRunReportsRequest],
Awaitable[analytics_data_api.BatchRunReportsResponse],
]:
r"""Return a callable for the batch run reports method over gRPC.
Returns multiple reports in a batch. All reports must
be for the same Entity.
Returns:
Callable[[~.BatchRunReportsRequest],
Awaitable[~.BatchRunReportsResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "batch_run_reports" not in self._stubs:
self._stubs["batch_run_reports"] = self.grpc_channel.unary_unary(
"/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunReports",
request_serializer=analytics_data_api.BatchRunReportsRequest.serialize,
response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize,
)
return self._stubs["batch_run_reports"]
@property
def batch_run_pivot_reports(
self,
) -> Callable[
[analytics_data_api.BatchRunPivotReportsRequest],
Awaitable[analytics_data_api.BatchRunPivotReportsResponse],
]:
r"""Return a callable for the batch run pivot reports method over gRPC.
Returns multiple pivot reports in a batch. All
reports must be for the same Entity.
Returns:
Callable[[~.BatchRunPivotReportsRequest],
Awaitable[~.BatchRunPivotReportsResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "batch_run_pivot_reports" not in self._stubs:
self._stubs["batch_run_pivot_reports"] = self.grpc_channel.unary_unary(
"/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunPivotReports",
request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize,
response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize,
)
return self._stubs["batch_run_pivot_reports"]
@property
def get_metadata(
self,
) -> Callable[
[analytics_data_api.GetMetadataRequest], Awaitable[analytics_data_api.Metadata]
]:
r"""Return a callable for the get metadata method over gRPC.
Returns metadata for dimensions and metrics available in
reporting methods. Used to explore the dimensions and metrics.
In this method, a Google Analytics GA4 Property Identifier is
specified in the request, and the metadata response includes
Custom dimensions and metrics as well as Universal metadata.
For example if a custom metric with parameter name
``levels_unlocked`` is registered to a property, the Metadata
response will contain ``customEvent:levels_unlocked``. Universal
metadata are dimensions and metrics applicable to any property
such as ``country`` and ``totalUsers``.
Returns:
Callable[[~.GetMetadataRequest],
Awaitable[~.Metadata]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_metadata" not in self._stubs:
self._stubs["get_metadata"] = self.grpc_channel.unary_unary(
"/google.analytics.data.v1alpha.AlphaAnalyticsData/GetMetadata",
request_serializer=analytics_data_api.GetMetadataRequest.serialize,
response_deserializer=analytics_data_api.Metadata.deserialize,
)
return self._stubs["get_metadata"]
@property
def run_realtime_report(
self,
) -> Callable[
[analytics_data_api.RunRealtimeReportRequest],
Awaitable[analytics_data_api.RunRealtimeReportResponse],
]:
r"""Return a callable for the run realtime report method over gRPC.
The Google Analytics Realtime API returns a
customized report of realtime event data for your
property. These reports show events and usage from the
last 30 minutes.
Returns:
Callable[[~.RunRealtimeReportRequest],
Awaitable[~.RunRealtimeReportResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "run_realtime_report" not in self._stubs:
self._stubs["run_realtime_report"] = self.grpc_channel.unary_unary(
"/google.analytics.data.v1alpha.AlphaAnalyticsData/RunRealtimeReport",
request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize,
response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize,
)
return self._stubs["run_realtime_report"]
__all__ = ("AlphaAnalyticsDataGrpcAsyncIOTransport",)
| googleapis/python-analytics-data | google/analytics/data_v1alpha/services/alpha_analytics_data/transports/grpc_asyncio.py | Python | apache-2.0 | 19,474 |
/**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.politaktiv.map.model.impl;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import org.politaktiv.map.model.Layer;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Date;
/**
* The cache model class for representing Layer in entity cache.
*
* @author Paul Butenko
* @see Layer
* @generated
*/
public class LayerCacheModel implements CacheModel<Layer>, Externalizable {
@Override
public String toString() {
StringBundler sb = new StringBundler(11);
sb.append("{layerId=");
sb.append(layerId);
sb.append(", createDate=");
sb.append(createDate);
sb.append(", label=");
sb.append(label);
sb.append(", userId=");
sb.append(userId);
sb.append(", portletInstance=");
sb.append(portletInstance);
sb.append("}");
return sb.toString();
}
@Override
public Layer toEntityModel() {
LayerImpl layerImpl = new LayerImpl();
layerImpl.setLayerId(layerId);
if (createDate == Long.MIN_VALUE) {
layerImpl.setCreateDate(null);
}
else {
layerImpl.setCreateDate(new Date(createDate));
}
if (label == null) {
layerImpl.setLabel(StringPool.BLANK);
}
else {
layerImpl.setLabel(label);
}
layerImpl.setUserId(userId);
if (portletInstance == null) {
layerImpl.setPortletInstance(StringPool.BLANK);
}
else {
layerImpl.setPortletInstance(portletInstance);
}
layerImpl.resetOriginalValues();
return layerImpl;
}
@Override
public void readExternal(ObjectInput objectInput) throws IOException {
layerId = objectInput.readLong();
createDate = objectInput.readLong();
label = objectInput.readUTF();
userId = objectInput.readLong();
portletInstance = objectInput.readUTF();
}
@Override
public void writeExternal(ObjectOutput objectOutput)
throws IOException {
objectOutput.writeLong(layerId);
objectOutput.writeLong(createDate);
if (label == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(label);
}
objectOutput.writeLong(userId);
if (portletInstance == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(portletInstance);
}
}
public long layerId;
public long createDate;
public String label;
public long userId;
public String portletInstance;
} | PolitAktiv/politaktiv-map2-portlet | docroot/WEB-INF/src/org/politaktiv/map/model/impl/LayerCacheModel.java | Java | apache-2.0 | 3,021 |
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/optimizers/rmsprop_op.h"
namespace paddle {
namespace operators {
class RmspropOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE_EQ(ctx->HasInput("Param"), true,
platform::errors::NotFound(
"Input(Param) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasInput("MeanSquare"), true,
platform::errors::NotFound(
"Input(MeanSquare) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasInput("LearningRate"), true,
platform::errors::NotFound(
"Input(LearningRate) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(ctx->HasInput("Grad"), true,
platform::errors::NotFound(
"Input(Grad) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(ctx->HasInput("Moment"), true,
platform::errors::NotFound(
"Input(Moment) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(ctx->GetInputsVarType("Param").front(),
framework::proto::VarType::LOD_TENSOR,
platform::errors::InvalidArgument(
"The input var's type in RmspropOp should be "
"LoDTensor, but the received is %s",
ctx->GetInputsVarType("Param").front()));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("ParamOut"), true,
platform::errors::NotFound(
"Output(param_out) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("MomentOut"), true,
platform::errors::NotFound(
"Output(MomentOut) of RmspropOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("MeanSquareOut"), true,
platform::errors::NotFound(
"Output(MeanSquareOut) of RmspropOp should not be null."));
if (ctx->Attrs().Get<bool>("centered")) {
PADDLE_ENFORCE_EQ(
ctx->HasOutput("MeanGradOut"), true,
platform::errors::NotFound(
"Output(MeanGradOut) of RmspropOp should not be null."));
}
auto param_dim = ctx->GetInputDim("Param");
PADDLE_ENFORCE_EQ(
param_dim, ctx->GetInputDim("Grad"),
platform::errors::InvalidArgument(
"Param and grad input of RmspropOp should have the same dimension. "
"But received Param's dim [%s] and Grad's dim [%s].",
param_dim, ctx->GetInputDim("Grad")));
PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("Moment"),
platform::errors::InvalidArgument(
"Param and Momentum input of RmspropOp "
"should have the same dimension. But received "
"Param's dim [%s] and Moment [%s]",
param_dim, ctx->GetInputDim("Moment")));
PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("MeanSquare"),
platform::errors::InvalidArgument(
"Param and Momentum input of RmspropOp "
"should have the same dimension. But received "
"Param's dim [%s] and MeanSquare [%s]",
param_dim, ctx->GetInputDim("MeanSquare")));
auto lr_dim = ctx->GetInputDim("LearningRate");
PADDLE_ENFORCE_EQ(phi::product(lr_dim), 1,
platform::errors::InvalidArgument(
"Learning Rate of RmspropOp should be a scalar. But "
"received LearningRate's dim [%s]",
phi::product(lr_dim)));
ctx->SetOutputDim("ParamOut", param_dim);
ctx->SetOutputDim("MomentOut", param_dim);
ctx->SetOutputDim("MeanSquareOut", param_dim);
if (ctx->Attrs().Get<bool>("centered")) {
ctx->SetOutputDim("MeanGradOut", param_dim);
}
}
};
class RmspropOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("Param",
"(Tensor, default Tensor<float>) "
"Input parameter value that has to be updated.");
AddInput("MeanSquare",
"(Tensor, default Tensor<float>)"
" The mean square value that gets updated.");
AddInput("MeanGrad",
"(Tensor, default Tensor<float>)"
" The moving average of gradient")
.AsDispensable();
AddInput("LearningRate",
"(Tensor, default Tensor<float>) "
"The learning rate should be a tensor of size 1.");
AddInput("Grad",
"(Tensor, default Tensor<float>) "
"Input gradient of the parameter.");
AddInput("Moment",
"(Tensor, default Tensor<float>) The moment that gets updated.");
AddOutput("ParamOut", "(Tensor) Output updated parameter value.");
AddOutput("MomentOut", "(Tensor) Output updated moment.");
AddOutput("MeanSquareOut", "(Tensor) Output Mean squared updated value.");
AddOutput("MeanGradOut",
"(Tensor) Output moving average of gradient updated value.");
AddAttr<float>("epsilon",
"(float, default 1e-10) Constant "
"for numerical stability.")
.SetDefault(1.0e-10f);
AddAttr<float>("decay",
"(float, default 0.9) "
"Discounting factor for coming gradient.")
.SetDefault(0.9f);
AddAttr<float>("momentum", "(float, default 0.0) Constant value.")
.SetDefault(0.0f);
AddAttr<bool>("centered", "(bool, default false) use centered rmsprop.")
.SetDefault(false);
AddComment(R"DOC(
Rmsprop Optimizer.
$$
MeanSquareOut = decay * MeanSquare + (1 - decay) * Grad * Grad \\
MomentOut = momentum * Moment +
\frac{LearningRate * Grad}{\sqrt{MeanSquareOut + epsilon}} \\
ParamOut = Param - MomentOut
$$
if centered is true:
mean_grad = decay * mean_square{t-1} + (1-decay) * gradient
mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2
mom = momentum * mom{t-1} + learning_rate * g_t /
sqrt(mean_square - mean_grad**2 + epsilon)
param -= mom
The original slides that proposed Rmsprop: Slide 29 of
http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(rmsprop, ops::RmspropOp, ops::RmspropOpMaker);
REGISTER_OP_CPU_KERNEL(
rmsprop, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, float>,
ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, double>);
| PaddlePaddle/Paddle | paddle/fluid/operators/optimizers/rmsprop_op.cc | C++ | apache-2.0 | 7,369 |
package main
import (
"encoding/json"
"fmt"
"github.com/codegangsta/cli"
"github.com/olekukonko/tablewriter"
"github.com/zero-os/0-core/base/pm"
"gopkg.in/yaml.v2"
"os"
"sort"
"strconv"
"strings"
)
type containerData struct {
Container struct {
Arguments struct {
Root string `json:"root"`
Hostname string `json:"hostname"`
Tags []string `json:"tags"`
} `json:"arguments"`
PID int `json:"pid"`
Root string `json:"root"`
} `json:"container"`
}
func containers(t Transport, c *cli.Context) {
var tags []string
if c.Args().Present() {
tags = append(tags, c.Args().First())
tags = append(tags, c.Args().Tail()...)
}
response, err := t.Run(Command{
Sync: true,
Content: pm.Command{
Command: "corex.find",
Arguments: pm.MustArguments(M{
"tags": tags,
}),
},
})
if err != nil {
log.Fatal(err)
}
response.ValidateResultOrExit()
var containers map[string]containerData
if err := json.Unmarshal([]byte(response.Data), &containers); err != nil {
log.Fatal(err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetBorders(tablewriter.Border{})
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeader([]string{"ID", "FLIST", "HOSTNAME", "TAGS"})
ids := make([]int, 0, len(containers))
for id := range containers {
iid, _ := strconv.ParseInt(id, 10, 32)
ids = append(ids, int(iid))
}
sort.Ints(ids)
for _, id := range ids {
sid := fmt.Sprintf("%d", id)
container := containers[sid]
table.Append([]string{
sid,
container.Container.Arguments.Root,
container.Container.Arguments.Hostname,
strings.Join(container.Container.Arguments.Tags, ", "),
})
}
table.Render()
}
func containerInspect(t Transport, c *cli.Context) {
id := c.Args().First()
if id == "" {
log.Fatal("missing container id")
}
response, err := t.Run(Command{
Sync: true,
Content: pm.Command{
Command: "corex.list",
Arguments: pm.MustArguments(M{}),
},
})
if err != nil {
log.Fatal(err)
}
response.ValidateResultOrExit()
var containers map[string]interface{}
if err := json.Unmarshal([]byte(response.Data), &containers); err != nil {
log.Fatal(err)
}
container, ok := containers[id]
if !ok {
log.Fatalf("no container with id: %s", id)
}
data, _ := yaml.Marshal(container)
fmt.Println(string(data))
}
| g8os/core0 | apps/corectl/container.go | GO | apache-2.0 | 2,323 |
package org.poormanscastle.studies.compilers.grammar.grammar3_1.astparser.ast;
import org.poormanscastle.studies.compilers.utils.grammartools.ast.CodePosition;
/**
* Created by georg on 15.01.16.
*/
public class OperatorExpression extends AbstractAstItem implements Expression {
private final Expression leftOperand, rightOperand;
private final Operator operator;
public OperatorExpression(CodePosition codePosition, Expression leftOperand, Operator operator, Expression rightOperand) {
super(codePosition);
this.leftOperand = leftOperand;
this.rightOperand = rightOperand;
this.operator = operator;
}
public Expression getLeftOperand() {
return leftOperand;
}
public Expression getRightOperand() {
return rightOperand;
}
public Operator getOperator() {
return operator;
}
@Override
public boolean handleProceedWith(AstItemVisitor visitor) {
return visitor.proceedWithOperatorExpression(this);
}
@Override
public void accept(AstItemVisitor visitor) {
visitor.visitOperatorExpression(this);
if (leftOperand.handleProceedWith(visitor)) {
leftOperand.accept(visitor);
}
if (rightOperand.handleProceedWith(visitor)) {
rightOperand.accept(visitor);
}
visitor.leaveOperatorExpression(this);
}
}
| georgfedermann/compilers | straightline/src/main/java/org/poormanscastle/studies/compilers/grammar/grammar3_1/astparser/ast/OperatorExpression.java | Java | apache-2.0 | 1,401 |
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
namespace OAuth.AspNet.AuthServer
{
/// <summary>
/// Provides context information used in handling an OAuth resource owner grant.
/// </summary>
public class OAuthGrantResourceOwnerCredentialsContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthGrantResourceOwnerCredentialsContext"/> class
/// </summary>
/// <param name="context"></param>
/// <param name="options"></param>
/// <param name="clientId"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="scope"></param>
public OAuthGrantResourceOwnerCredentialsContext(HttpContext context, OAuthAuthorizationServerOptions options, string clientId, string userName, string password, IList<string> scope) : base(context, options, null)
{
ClientId = clientId;
UserName = userName;
Password = password;
Scope = scope;
}
/// <summary>
/// OAuth client id.
/// </summary>
public string ClientId { get; private set; }
/// <summary>
/// Resource owner username.
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// Resource owner password.
/// </summary>
public string Password { get; private set; }
/// <summary>
/// List of scopes allowed by the resource owner.
/// </summary>
public IList<string> Scope { get; private set; }
}
}
| XacronDevelopment/oauth-aspnet | src/OAuth.AspNet.AuthServer/OAuth/AspNet/AuthServer/OAuthGrantResourceOwnerCredentialsContext.cs | C# | apache-2.0 | 1,705 |
# Generated by Django 2.1.7 on 2019-04-30 13:20
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='publishablemodel',
name='id',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
]
| flavoi/diventi | diventi/core/migrations/0002_auto_20190430_1520.py | Python | apache-2.0 | 446 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Thu Mar 26 16:48:34 UTC 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
com.hazelcast.queue.impl.operations (Hazelcast Root 3.4.2 API)
</TITLE>
<META NAME="date" CONTENT="2015-03-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../com/hazelcast/queue/impl/operations/package-summary.html" target="classFrame">com.hazelcast.queue.impl.operations</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="AddAllBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">AddAllBackupOperation</A>
<BR>
<A HREF="AddAllOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">AddAllOperation</A>
<BR>
<A HREF="CheckAndEvictOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">CheckAndEvictOperation</A>
<BR>
<A HREF="ClearBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">ClearBackupOperation</A>
<BR>
<A HREF="ClearOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">ClearOperation</A>
<BR>
<A HREF="CompareAndRemoveBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">CompareAndRemoveBackupOperation</A>
<BR>
<A HREF="CompareAndRemoveOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">CompareAndRemoveOperation</A>
<BR>
<A HREF="ContainsOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">ContainsOperation</A>
<BR>
<A HREF="DrainBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">DrainBackupOperation</A>
<BR>
<A HREF="DrainOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">DrainOperation</A>
<BR>
<A HREF="IsEmptyOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">IsEmptyOperation</A>
<BR>
<A HREF="IteratorOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">IteratorOperation</A>
<BR>
<A HREF="OfferBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">OfferBackupOperation</A>
<BR>
<A HREF="OfferOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">OfferOperation</A>
<BR>
<A HREF="PeekOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">PeekOperation</A>
<BR>
<A HREF="PollBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">PollBackupOperation</A>
<BR>
<A HREF="PollOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">PollOperation</A>
<BR>
<A HREF="QueueBackupAwareOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">QueueBackupAwareOperation</A>
<BR>
<A HREF="QueueOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">QueueOperation</A>
<BR>
<A HREF="QueueReplicationOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">QueueReplicationOperation</A>
<BR>
<A HREF="RemainingCapacityOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">RemainingCapacityOperation</A>
<BR>
<A HREF="RemoveBackupOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">RemoveBackupOperation</A>
<BR>
<A HREF="RemoveOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">RemoveOperation</A>
<BR>
<A HREF="SizeOperation.html" title="class in com.hazelcast.queue.impl.operations" target="classFrame">SizeOperation</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| akiskip/KoDeMat-Collaboration-Platform-Application | KoDeMat_TouchScreen/lib/hazelcast-3.4.2/hazelcast-3.4.2/docs/javadoc/com/hazelcast/queue/impl/operations/package-frame.html | HTML | apache-2.0 | 4,188 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:25 EEST 2014 -->
<title>Uses of Interface net.sf.jasperreports.engine.util.BigDecimalHandler (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<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 Interface net.sf.jasperreports.engine.util.BigDecimalHandler (JasperReports 5.6.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">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?net/sf/jasperreports/engine/util/class-use/BigDecimalHandler.html" target="_top">Frames</a></li>
<li><a href="BigDecimalHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface net.sf.jasperreports.engine.util.BigDecimalHandler" class="title">Uses of Interface<br>net.sf.jasperreports.engine.util.BigDecimalHandler</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="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">BigDecimalHandler</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="#net.sf.jasperreports.engine.util">net.sf.jasperreports.engine.util</a></td>
<td class="colLast">
<div class="block">Contains utility classes for the core library.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sf.jasperreports.engine.util">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">BigDecimalHandler</a> in <a href="../../../../../../net/sf/jasperreports/engine/util/package-summary.html">net.sf.jasperreports.engine.util</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/engine/util/package-summary.html">net.sf.jasperreports.engine.util</a> that implement <a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">BigDecimalHandler</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/util/Java14BigDecimalHandler.html" title="class in net.sf.jasperreports.engine.util">Java14BigDecimalHandler</a></strong></code>
<div class="block"><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util"><code>BigDecimalHandler</code></a> implementation used on Java 1.4.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/util/Java15BigDecimalHandler.html" title="class in net.sf.jasperreports.engine.util">Java15BigDecimalHandler</a></strong></code>
<div class="block"><a href="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util"><code>BigDecimalHandler</code></a> implementation used on Java 1.5 or newer.</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="../../../../../../net/sf/jasperreports/engine/util/BigDecimalHandler.html" title="interface in net.sf.jasperreports.engine.util">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?net/sf/jasperreports/engine/util/class-use/BigDecimalHandler.html" target="_top">Frames</a></li>
<li><a href="BigDecimalHandler.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>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
| phurtado1112/cnaemvc | lib/JasperReport__5.6/docs/api/net/sf/jasperreports/engine/util/class-use/BigDecimalHandler.html | HTML | apache-2.0 | 7,579 |
package uk.ac.ebi.ddi.extservices.entrez.ncbiresult;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author Yasset Perez-Riverol ([email protected])
* @date 18/05/2015
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class NCBITaxResult {
@JsonProperty("header")
NCBIHeader header;
@JsonProperty("esearchresult")
NCBIEResult result;
public NCBIHeader getHeader() {
return header;
}
public void setHeader(NCBIHeader header) {
this.header = header;
}
public NCBIEResult getResult() {
return result;
}
public void setResult(NCBIEResult result) {
this.result = result;
}
public String[] getNCBITaxonomy() {
if (getResult() != null && getResult().getIdList() != null && getResult().getIdList().length == 1) {
return getResult().getIdList();
}
return null;
}
}
| BD2K-DDI/ddi-annotation | src/main/java/uk/ac/ebi/ddi/extservices/entrez/ncbiresult/NCBITaxResult.java | Java | apache-2.0 | 974 |
// Copyright 2018, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "opencensus/stats/internal/measure_data.h"
#include <algorithm>
#include <cmath>
#include <numeric>
#include <vector>
#include "absl/types/span.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "opencensus/stats/bucket_boundaries.h"
#include "opencensus/stats/distribution.h"
#include "opencensus/stats/testing/test_utils.h"
namespace opencensus {
namespace stats {
namespace {
TEST(MeasureDataTest, SmallSequence) {
MeasureData data({});
data.Add(-6);
data.Add(0);
data.Add(3);
EXPECT_EQ(data.count(), 3);
EXPECT_DOUBLE_EQ(data.sum(), -3);
}
TEST(MeasureDataTest, MultipleHistograms) {
std::vector<BucketBoundaries> buckets = {BucketBoundaries::Explicit({0, 10}),
BucketBoundaries::Explicit({}),
BucketBoundaries::Explicit({5})};
MeasureData data(buckets);
data.Add(-1);
data.Add(1);
data.Add(8);
Distribution distribution1 =
testing::TestUtils::MakeDistribution(&buckets[0]);
data.AddToDistribution(&distribution1);
EXPECT_THAT(distribution1.bucket_counts(), ::testing::ElementsAre(1, 2, 0));
Distribution distribution2 =
testing::TestUtils::MakeDistribution(&buckets[2]);
data.AddToDistribution(&distribution2);
EXPECT_THAT(distribution2.bucket_counts(), ::testing::ElementsAre(2, 1));
}
TEST(MeasureDataTest, DistributionStatistics) {
BucketBoundaries buckets = BucketBoundaries::Explicit({});
MeasureData data(absl::MakeSpan(&buckets, 1));
const std::vector<int> samples{91, 18, 63, 98, 87, 77, 14, 97, 10, 35,
12, 5, 75, 41, 49, 38, 40, 20, 55, 83};
const double expected_mean =
static_cast<double>(std::accumulate(samples.begin(), samples.end(), 0)) /
samples.size();
double expected_sum_of_squared_deviation = 0;
for (const auto sample : samples) {
data.Add(sample);
expected_sum_of_squared_deviation += pow(sample - expected_mean, 2);
}
Distribution distribution = testing::TestUtils::MakeDistribution(&buckets);
data.AddToDistribution(&distribution);
EXPECT_EQ(distribution.count(), samples.size());
EXPECT_DOUBLE_EQ(distribution.mean(), expected_mean);
EXPECT_DOUBLE_EQ(distribution.sum_of_squared_deviation(),
expected_sum_of_squared_deviation);
EXPECT_DOUBLE_EQ(distribution.min(),
*std::min_element(samples.begin(), samples.end()));
EXPECT_DOUBLE_EQ(distribution.max(),
*std::max_element(samples.begin(), samples.end()));
}
TEST(MeasureDataTest, BatchedAddToDistribution) {
// Tests that batching values in the MeasureData is equivalent to sequentially
// adding to the distribution.
BucketBoundaries buckets = BucketBoundaries::Exponential(7, 2, 2);
MeasureData data(absl::MakeSpan(&buckets, 1));
Distribution base_distribution =
testing::TestUtils::MakeDistribution(&buckets);
// Add some preexisting data to fully test the merge.
testing::TestUtils::AddToDistribution(&base_distribution, 20);
testing::TestUtils::AddToDistribution(&base_distribution, 10);
Distribution expected_distribution = base_distribution;
const double tolerance = 1.0 / 1000000000;
const int max = 100;
for (int i = 0; i <= max; ++i) {
data.Add(i);
testing::TestUtils::AddToDistribution(&expected_distribution, i);
Distribution actual_distribution = base_distribution;
data.AddToDistribution(&actual_distribution);
EXPECT_EQ(expected_distribution.count(), actual_distribution.count());
EXPECT_DOUBLE_EQ(expected_distribution.mean(), actual_distribution.mean());
EXPECT_NEAR(expected_distribution.sum_of_squared_deviation(),
actual_distribution.sum_of_squared_deviation(), tolerance);
EXPECT_DOUBLE_EQ(expected_distribution.min(), actual_distribution.min());
EXPECT_DOUBLE_EQ(expected_distribution.max(), actual_distribution.max());
EXPECT_THAT(
actual_distribution.bucket_counts(),
::testing::ElementsAreArray(expected_distribution.bucket_counts()));
}
}
TEST(MeasureDataDeathTest, AddToDistributionWithUnknownBuckets) {
BucketBoundaries buckets = BucketBoundaries::Explicit({0, 10});
MeasureData data(absl::MakeSpan(&buckets, 1));
data.Add(1);
BucketBoundaries distribution_buckets = BucketBoundaries::Explicit({0});
Distribution distribution =
testing::TestUtils::MakeDistribution(&distribution_buckets);
EXPECT_DEBUG_DEATH(
{
data.AddToDistribution(&distribution);
EXPECT_THAT(distribution.bucket_counts(), ::testing::ElementsAre(1, 0));
},
"No matching BucketBoundaries in AddToDistribution");
}
} // namespace
} // namespace stats
} // namespace opencensus
| census-instrumentation/opencensus-cpp | opencensus/stats/internal/measure_data_test.cc | C++ | apache-2.0 | 5,320 |
package peng.zhang.mobilesafe01.servicer;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSService extends Service {
private LocationManager lm;
private MyLocationListener listener;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
lm=(LocationManager) getSystemService(LOCATION_SERVICE);
/**
* List<String> providers=lm.getAllProviders();
for(String pv :providers){
Log.d(TAG, pv);
}
*/
//ΪÄÚÈÝÌṩÕßÉèÖÃÌõ¼þ
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//ÉèÖòÎÊýϸ»¯£º
//criteria.setAccuracy(Criteria.ACCURACY_FINE);//ÉèÖÃΪ×î´ó¾«¶È
//criteria.setAltitudeRequired(false);//²»ÒªÇ󺣰ÎÐÅÏ¢
//criteria.setBearingRequired(false);//²»ÒªÇó·½Î»ÐÅÏ¢
//criteria.setCostAllowed(true);//ÊÇ·ñÔÊÐí¸¶·Ñ
//criteria.setPowerRequirement(Criteria.POWER_LOW);//¶ÔµçÁ¿µÄÒªÇó
//ÉèÖÃλÖøüмàÌýÆ÷£¬ÐèÒª´«Èë²ÎÊýΪ¶¨Î»·½Ê½¡¢¸üÐÂʱ¼ä£¨Ò»°ãÒ»·ÖÖÓ£©£¬¸üоàÀ루һ°ã50Ã×£©£¬¼àÌýÆ÷
//ÉèÖûñÈ¡×îºÃµÄλÖÃÌṩÆ÷
listener =new MyLocationListener();
String provider=lm.getBestProvider(criteria, true);
lm.requestLocationUpdates(provider,0, 0, listener);
Log.d("Location", "Location0"+"Æô¶¯·þÎñ");
}
//·þÎñÏú»Ù£¬È¡Ïû×¢²á
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
lm.removeUpdates(listener);
listener=null;
}
class MyLocationListener implements LocationListener{
/**
* µ±Î»ÖøıäµÄʱºò»Øµ÷
*/
@Override
public void onLocationChanged(Location location) {
Log.d("Location", "Location1"+"MyLocationListenerÖ´ÐÐÁË");
String longitude = "jj:" + location.getLongitude() + "\n";
String latitude = "w:" + location.getLatitude() + "\n";
String accuracy = "a" + location.getAccuracy() + "\n";
Log.d("Location", "Location1"+longitude);
//½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê
//ʵÀý»¯ModifyOffsetÐèÒªÊäÈëÒ»¸öÊäÈëÁ÷£¬Õâ¸öÊäÈëÁ÷¼ÈÊǶÁÈ¡Êý¾Ý¿âÁ÷
// InputStream in = null;
// try {
// in=getResources().getAssets().open("axisoffset.dat");
// ModifyOffset offset=ModifyOffset.getInstance(in);
// //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê
// PointDouble double1=offset.s2c(new PointDouble(location.getLongitude(), location.getLatitude()));
// //ת»»Íê³É£¬È¡³ö×ø±ê
// longitude ="j:" + offset.X+ "\n";
// latitude = "w:" +offset.Y+ "\n";
// } catch (IOException e) {
// e.printStackTrace();
// } catch (Exception e) {
// e.printStackTrace();
// }
//¶ÔµÃµ½µÄ¾Î³¶È½øÐб£´æ
SharedPreferences sp=getSharedPreferences("config", MODE_PRIVATE);
Editor editor=sp.edit();
editor.putString("lastlocation", longitude + latitude + accuracy);
editor.commit();
}
/**
* µ±×´Ì¬·¢Éú¸Ä±äµÄʱºò»Øµ÷ ¿ªÆô--¹Ø±Õ £»¹Ø±Õ--¿ªÆô
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
/**
* ijһ¸öλÖÃÌṩÕß¿ÉÒÔʹÓÃÁË
*/
@Override
public void onProviderEnabled(String provider) {
}
/**
* ijһ¸öλÖÃÌṩÕß²»¿ÉÒÔʹÓÃÁË
*/
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
| yongyu0102/MobileSafe | src/peng/zhang/mobilesafe01/servicer/GPSService.java | Java | apache-2.0 | 3,609 |
package com.ty.activity;
import com.ty.app.R;
import com.ty.service.AutoUpdateService;
import com.ty.util.HttpCallbackListener;
import com.ty.util.HttpUtil;
import com.ty.util.Utility;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WeatherActivity extends Activity implements OnClickListener{
private LinearLayout weatherInfoLayout;
/**
* 用于显示城市名
*/
private TextView cityNameText;
/**
* 用于显示发布时间
*/
private TextView publishText;
/**
* 用于显示天气描述信息
*/
private TextView weatherDespText;
/**
* 用于显示气温1
*/
private TextView temp1Text;
/**
* 用于显示气温2
*/
private TextView temp2Text;
/**
* 用于显示当前日期
*/
private TextView currentDateText;
/**
* 切换城市按钮
*/
private Button switchCity;
/**
* 更新天气按钮
*/
private Button refreshWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.weather_layout);
// 初始化各控件
weatherInfoLayout = (LinearLayout) findViewById(R.id.tyweather_info_layout);
cityNameText = (TextView) findViewById(R.id.tycity_name);
publishText = (TextView) findViewById(R.id.typublish_text);
weatherDespText = (TextView) findViewById(R.id.tyweather_desp);
temp1Text = (TextView) findViewById(R.id.tytemp1);
temp2Text = (TextView) findViewById(R.id.tytemp2);
currentDateText = (TextView) findViewById(R.id.tycurrent_date);
switchCity = (Button) findViewById(R.id.tyswitch_city);
refreshWeather = (Button) findViewById(R.id.tyrefresh_weather);
String countyCode = getIntent().getStringExtra("county_code");
if (!TextUtils.isEmpty(countyCode)) {
// 有县级代号时就去查询天气
publishText.setText("同步中...");
weatherInfoLayout.setVisibility(View.INVISIBLE);
cityNameText.setVisibility(View.INVISIBLE);
queryWeatherCode(countyCode);
} else {
// 没有县级代号时就直接显示本地天气
showWeather();
}
switchCity.setOnClickListener(this);
refreshWeather.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tycity_name:
Intent intent = new Intent(this, ChooseAreaActivity.class);
intent.putExtra("from_weather_activity", true);
startActivity(intent);
finish();
break;
case R.id.tyrefresh_weather:
publishText.setText("同步中...");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherCode = prefs.getString("weather_code", "");
if (!TextUtils.isEmpty(weatherCode)) {
queryWeatherInfo(weatherCode);
}
break;
default:
break;
}
}
/**
* 查询县级代号所对应的天气代号。
*/
private void queryWeatherCode(String countyCode) {
String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml";
queryFromServer(address, "countyCode");
}
/**
* 查询天气代号所对应的天气。
*/
private void queryWeatherInfo(String weatherCode) {
String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html";
queryFromServer(address, "weatherCode");
}
/**
* 根据传入的地址和类型去向服务器查询天气代号或者天气信息。
*/
private void queryFromServer(final String address, final String type) {
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(final String response) {
if ("countyCode".equals(type)) {
if (!TextUtils.isEmpty(response)) {
// 从服务器返回的数据中解析出天气代号
String[] array = response.split("\\|");
if (array != null && array.length == 2) {
String weatherCode = array[1];
queryWeatherInfo(weatherCode);
}
}
} else if ("weatherCode".equals(type)) {
// 处理服务器返回的天气信息
Utility.handleWeatherResponse(WeatherActivity.this, response);
runOnUiThread(new Runnable() {
@Override
public void run() {
showWeather();
}
});
}
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
publishText.setText("同步失败");
}
});
}
});
}
/**
* 从SharedPreferences文件中读取存储的天气信息,并显示到界面上。
*/
private void showWeather() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
cityNameText.setText( prefs.getString("city_name", ""));
temp1Text.setText(prefs.getString("temp1", ""));
temp2Text.setText(prefs.getString("temp2", ""));
weatherDespText.setText(prefs.getString("weather_desp", ""));
publishText.setText("今天" + prefs.getString("publish_time", "") + "发布");
currentDateText.setText(prefs.getString("current_date", ""));
weatherInfoLayout.setVisibility(View.VISIBLE);
cityNameText.setVisibility(View.VISIBLE);
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
}
} | tanqii/weather | src/com/ty/activity/WeatherActivity.java | Java | apache-2.0 | 5,476 |
# Coprotus dhofarensis Gené, El Shafie & Guarro SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycotaxon 46: 276 (1993)
#### Original name
Coprotus dhofarensis Gené, El Shafie & Guarro
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Leotiomycetes/Thelebolales/Thelebolaceae/Coprotus/Coprotus dhofarensis/README.md | Markdown | apache-2.0 | 241 |
// Generated from /POI/java/org/apache/poi/hssf/record/DBCellRecord.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <org/apache/poi/util/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/StandardRecord.hpp>
#include <java/lang/Cloneable.hpp>
struct default_init_tag;
class poi::hssf::record::DBCellRecord final
: public StandardRecord
, public ::java::lang::Cloneable
{
public:
typedef StandardRecord super;
static constexpr int16_t sid { int16_t(215) };
static constexpr int32_t BLOCK_SIZE { int32_t(32) };
private:
int32_t field_1_row_offset { };
::int16_tArray* field_2_cell_offsets { };
protected:
void ctor(int32_t rowOffset, ::int16_tArray* cellOffsets);
void ctor(RecordInputStream* in);
public:
::java::lang::String* toString() override;
void serialize(::poi::util::LittleEndianOutput* out) override;
public: /* protected */
int32_t getDataSize() override;
public:
int16_t getSid() override;
DBCellRecord* clone() override;
// Generated
public: /* package */
DBCellRecord(int32_t rowOffset, ::int16_tArray* cellOffsets);
public:
DBCellRecord(RecordInputStream* in);
protected:
DBCellRecord(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
int32_t serialize(int32_t offset, ::int8_tArray* data);
::int8_tArray* serialize();
private:
virtual ::java::lang::Class* getClass0();
friend class DBCellRecord_Builder;
};
| pebble2015/cpoi | src/org/apache/poi/hssf/record/DBCellRecord.hpp | C++ | apache-2.0 | 1,539 |
<HTML>
<HEAD>
<meta charset="UTF-8">
<title>Box2DLevel.engine - core</title>
<link rel="stylesheet" href="..\..\..\style.css">
</HEAD>
<BODY>
<a href="../../index.html">core</a> / <a href="../index.html">io.github.restioson.kettle.level</a> / <a href="index.html">Box2DLevel</a> / <a href=".">engine</a><br/>
<br/>
<h1>engine</h1>
<a name="io.github.restioson.kettle.level.Box2DLevel$engine"></a>
<code><span class="keyword">val </span><span class="identifier">engine</span><span class="symbol">: </span><span class="identifier">Kettle</span></code> <a href="https://github.com/Restioson/kettle-engine/tree/master/core/src/kotlin/io/github/restioson/kettle/level/Box2DLevel.kt#L10">(source)</a>
</BODY>
</HTML>
| Restioson/restioson.github.io | docs/kettle-engine/core/io.github.restioson.kettle.level/-box2-d-level/engine.html | HTML | apache-2.0 | 754 |
import { Pipe, PipeTransform } from '@angular/core';
import { Project } from 'app/models/project';
@Pipe({
name: 'operatorFilter'
})
export class OperatorFilterPipe implements PipeTransform {
transform(value: Project[], q: string) {
if (!q) {
return value;
}
return value.filter(item => -1 < item.operator.toLowerCase().indexOf(q.toLowerCase()));
}
}
| asanchezr/mem-mmti-public | src/app/operator-filter.pipe.ts | TypeScript | apache-2.0 | 378 |
//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with code generation of C++ declarations
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
#include "CGCXXABI.h"
#include "CGObjCRuntime.h"
#include "CGOpenMPRuntime.h"
#include "clang/Basic/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/Path.h"
using namespace clang;
using namespace CodeGen;
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
ConstantAddress DeclPtr) {
assert(
(D.hasGlobalStorage() ||
(D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
"VarDecl must have global or local (in the case of OpenCL) storage!");
assert(!D.getType()->isReferenceType() &&
"Should not call EmitDeclInit on a reference!");
QualType type = D.getType();
LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
const Expr *Init = D.getInit();
switch (CGF.getEvaluationKind(type)) {
case TEK_Scalar: {
CodeGenModule &CGM = CGF.CGM;
if (lv.isObjCStrong())
CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
DeclPtr, D.getTLSKind());
else if (lv.isObjCWeak())
CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
DeclPtr);
else
CGF.EmitScalarInit(Init, &D, lv, false);
return;
}
case TEK_Complex:
CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
return;
case TEK_Aggregate:
CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased,
AggValueSlot::DoesNotOverlap));
return;
}
llvm_unreachable("bad evaluation kind");
}
/// Emit code to cause the destruction of the given variable with
/// static storage duration.
static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
ConstantAddress Addr) {
// Honor __attribute__((no_destroy)) and bail instead of attempting
// to emit a reference to a possibly nonexistent destructor, which
// in turn can cause a crash. This will result in a global constructor
// that isn't balanced out by a destructor call as intended by the
// attribute. This also checks for -fno-c++-static-destructors and
// bails even if the attribute is not present.
if (D.isNoDestroy(CGF.getContext()))
return;
CodeGenModule &CGM = CGF.CGM;
// FIXME: __attribute__((cleanup)) ?
QualType Type = D.getType();
QualType::DestructionKind DtorKind = Type.isDestructedType();
switch (DtorKind) {
case QualType::DK_none:
return;
case QualType::DK_cxx_destructor:
break;
case QualType::DK_objc_strong_lifetime:
case QualType::DK_objc_weak_lifetime:
case QualType::DK_nontrivial_c_struct:
// We don't care about releasing objects during process teardown.
assert(!D.getTLSKind() && "should have rejected this");
return;
}
llvm::FunctionCallee Func;
llvm::Constant *Argument;
// Special-case non-array C++ destructors, if they have the right signature.
// Under some ABIs, destructors return this instead of void, and cannot be
// passed directly to __cxa_atexit if the target does not allow this
// mismatch.
const CXXRecordDecl *Record = Type->getAsCXXRecordDecl();
bool CanRegisterDestructor =
Record && (!CGM.getCXXABI().HasThisReturn(
GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
CGM.getCXXABI().canCallMismatchedFunctionType());
// If __cxa_atexit is disabled via a flag, a different helper function is
// generated elsewhere which uses atexit instead, and it takes the destructor
// directly.
bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
if (Record && (CanRegisterDestructor || UsingExternalHelper)) {
assert(!Record->hasTrivialDestructor());
CXXDestructorDecl *Dtor = Record->getDestructor();
Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete));
Argument = llvm::ConstantExpr::getBitCast(
Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo());
// Otherwise, the standard logic requires a helper function.
} else {
Func = CodeGenFunction(CGM)
.generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind),
CGF.needsEHCleanup(DtorKind), &D);
Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
}
CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
}
/// Emit code to cause the variable at the given address to be considered as
/// constant from this point onwards.
static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
llvm::Constant *Addr) {
return CGF.EmitInvariantStart(
Addr, CGF.getContext().getTypeSizeInChars(D.getType()));
}
void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) {
// Do not emit the intrinsic if we're not optimizing.
if (!CGM.getCodeGenOpts().OptimizationLevel)
return;
// Grab the llvm.invariant.start intrinsic.
llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
// Overloaded address space type.
llvm::Type *ObjectPtr[1] = {Int8PtrTy};
llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr);
// Emit a call with the size in bytes of the object.
uint64_t Width = Size.getQuantity();
llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(Int64Ty, Width),
llvm::ConstantExpr::getBitCast(Addr, Int8PtrTy)};
Builder.CreateCall(InvariantStart, Args);
}
void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
llvm::Constant *DeclPtr,
bool PerformInit) {
const Expr *Init = D.getInit();
QualType T = D.getType();
// The address space of a static local variable (DeclPtr) may be different
// from the address space of the "this" argument of the constructor. In that
// case, we need an addrspacecast before calling the constructor.
//
// struct StructWithCtor {
// __device__ StructWithCtor() {...}
// };
// __device__ void foo() {
// __shared__ StructWithCtor s;
// ...
// }
//
// For example, in the above CUDA code, the static local variable s has a
// "shared" address space qualifier, but the constructor of StructWithCtor
// expects "this" in the "generic" address space.
unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
if (ActualAddrSpace != ExpectedAddrSpace) {
llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T);
llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
}
ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D));
if (!T->isReferenceType()) {
if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
D.hasAttr<OMPThreadPrivateDeclAttr>()) {
(void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
&D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
PerformInit, this);
}
if (PerformInit)
EmitDeclInit(*this, D, DeclAddr);
if (CGM.isTypeConstant(D.getType(), true))
EmitDeclInvariant(*this, D, DeclPtr);
else
EmitDeclDestroy(*this, D, DeclAddr);
return;
}
assert(PerformInit && "cannot have constant initializer which needs "
"destruction for reference");
RValue RV = EmitReferenceBindingToExpr(Init);
EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
}
/// Create a stub function, suitable for being passed to atexit,
/// which passes the given address to the given destructor function.
llvm::Function *CodeGenFunction::createAtExitStub(const VarDecl &VD,
llvm::FunctionCallee dtor,
llvm::Constant *addr) {
// Get the destructor function type, void(*)(void).
llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
SmallString<256> FnName;
{
llvm::raw_svector_ostream Out(FnName);
CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
}
const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
ty, FnName.str(), FI, VD.getLocation());
CodeGenFunction CGF(CGM);
CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit),
CGM.getContext().VoidTy, fn, FI, FunctionArgList());
llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
// Make sure the call and the callee agree on calling convention.
if (llvm::Function *dtorFn =
dyn_cast<llvm::Function>(dtor.getCallee()->stripPointerCasts()))
call->setCallingConv(dtorFn->getCallingConv());
CGF.FinishFunction();
return fn;
}
/// Register a global destructor using the C atexit runtime function.
void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
llvm::FunctionCallee dtor,
llvm::Constant *addr) {
// Create a function which calls the destructor.
llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
registerGlobalDtorWithAtExit(dtorStub);
}
void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
// extern "C" int atexit(void (*f)(void));
llvm::FunctionType *atexitTy =
llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
llvm::FunctionCallee atexit =
CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
/*Local=*/true);
if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
atexitFn->setDoesNotThrow();
EmitNounwindRuntimeCall(atexit, dtorStub);
}
void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
llvm::GlobalVariable *DeclPtr,
bool PerformInit) {
// If we've been asked to forbid guard variables, emit an error now.
// This diagnostic is hard-coded for Darwin's use case; we can find
// better phrasing if someone else needs it.
if (CGM.getCodeGenOpts().ForbidGuardVariables)
CGM.Error(D.getLocation(),
"this initialization requires a guard variable, which "
"the kernel does not support");
CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
}
void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
llvm::BasicBlock *InitBlock,
llvm::BasicBlock *NoInitBlock,
GuardKind Kind,
const VarDecl *D) {
assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
// A guess at how many times we will enter the initialization of a
// variable, depending on the kind of variable.
static const uint64_t InitsPerTLSVar = 1024;
static const uint64_t InitsPerLocalVar = 1024 * 1024;
llvm::MDNode *Weights;
if (Kind == GuardKind::VariableGuard && !D->isLocalVarDecl()) {
// For non-local variables, don't apply any weighting for now. Due to our
// use of COMDATs, we expect there to be at most one initialization of the
// variable per DSO, but we have no way to know how many DSOs will try to
// initialize the variable.
Weights = nullptr;
} else {
uint64_t NumInits;
// FIXME: For the TLS case, collect and use profiling information to
// determine a more accurate brach weight.
if (Kind == GuardKind::TlsGuard || D->getTLSKind())
NumInits = InitsPerTLSVar;
else
NumInits = InitsPerLocalVar;
// The probability of us entering the initializer is
// 1 / (total number of times we attempt to initialize the variable).
llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Weights = MDHelper.createBranchWeights(1, NumInits - 1);
}
Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
}
llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
SourceLocation Loc, bool TLS) {
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Name, &getModule());
if (!getLangOpts().AppleKext && !TLS) {
// Set the section if needed.
if (const char *Section = getTarget().getStaticInitSectionSpecifier())
Fn->setSection(Section);
}
SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Fn->setCallingConv(getRuntimeCC());
if (!getLangOpts().Exceptions)
Fn->setDoesNotThrow();
if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
!isInSanitizerBlacklist(SanitizerKind::Address, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
!isInSanitizerBlacklist(SanitizerKind::KernelAddress, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
!isInSanitizerBlacklist(SanitizerKind::HWAddress, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
!isInSanitizerBlacklist(SanitizerKind::KernelHWAddress, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
!isInSanitizerBlacklist(SanitizerKind::Thread, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeThread);
if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
!isInSanitizerBlacklist(SanitizerKind::Memory, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
!isInSanitizerBlacklist(SanitizerKind::KernelMemory, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
!isInSanitizerBlacklist(SanitizerKind::SafeStack, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::SafeStack);
if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
!isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc))
Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
auto RASignKind = getCodeGenOpts().getSignReturnAddress();
if (RASignKind != CodeGenOptions::SignReturnAddressScope::None) {
Fn->addFnAttr("sign-return-address",
RASignKind == CodeGenOptions::SignReturnAddressScope::All
? "all"
: "non-leaf");
auto RASignKey = getCodeGenOpts().getSignReturnAddressKey();
Fn->addFnAttr("sign-return-address-key",
RASignKey == CodeGenOptions::SignReturnAddressKeyValue::AKey
? "a_key"
: "b_key");
}
if (getCodeGenOpts().BranchTargetEnforcement)
Fn->addFnAttr("branch-target-enforcement");
return Fn;
}
/// Create a global pointer to a function that will initialize a global
/// variable. The user has requested that this pointer be emitted in a specific
/// section.
void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
llvm::GlobalVariable *GV,
llvm::Function *InitFunc,
InitSegAttr *ISA) {
llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
TheModule, InitFunc->getType(), /*isConstant=*/true,
llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
PtrArray->setSection(ISA->getSection());
addUsedGlobal(PtrArray);
// If the GV is already in a comdat group, then we have to join it.
if (llvm::Comdat *C = GV->getComdat())
PtrArray->setComdat(C);
}
void
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
llvm::GlobalVariable *Addr,
bool PerformInit) {
// According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
// __constant__ and __shared__ variables defined in namespace scope,
// that are of class type, cannot have a non-empty constructor. All
// the checks have been done in Sema by now. Whatever initializers
// are allowed are empty and we just need to ignore them here.
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
(D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
D->hasAttr<CUDASharedAttr>()))
return;
if (getLangOpts().OpenMP &&
getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit))
return;
// Check if we've already initialized this decl.
auto I = DelayedCXXInitPosition.find(D);
if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
return;
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
SmallString<256> FnName;
{
llvm::raw_svector_ostream Out(FnName);
getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
}
// Create a variable initialization function.
llvm::Function *Fn =
CreateGlobalInitOrDestructFunction(FTy, FnName.str(),
getTypes().arrangeNullaryFunction(),
D->getLocation());
auto *ISA = D->getAttr<InitSegAttr>();
CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
PerformInit);
llvm::GlobalVariable *COMDATKey =
supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
if (D->getTLSKind()) {
// FIXME: Should we support init_priority for thread_local?
// FIXME: We only need to register one __cxa_thread_atexit function for the
// entire TU.
CXXThreadLocalInits.push_back(Fn);
CXXThreadLocalInitVars.push_back(D);
} else if (PerformInit && ISA) {
EmitPointerToInitFunc(D, Addr, Fn, ISA);
} else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
} else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) ||
getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR) {
// C++ [basic.start.init]p2:
// Definitions of explicitly specialized class template static data
// members have ordered initialization. Other class template static data
// members (i.e., implicitly or explicitly instantiated specializations)
// have unordered initialization.
//
// As a consequence, we can put them into their own llvm.global_ctors entry.
//
// If the global is externally visible, put the initializer into a COMDAT
// group with the global being initialized. On most platforms, this is a
// minor startup time optimization. In the MS C++ ABI, there are no guard
// variables, so this COMDAT key is required for correctness.
AddGlobalCtor(Fn, 65535, COMDATKey);
if (getTarget().getCXXABI().isMicrosoft() && COMDATKey) {
// In The MS C++, MS add template static data member in the linker
// drective.
addUsedGlobal(COMDATKey);
}
} else if (D->hasAttr<SelectAnyAttr>()) {
// SelectAny globals will be comdat-folded. Put the initializer into a
// COMDAT group associated with the global, so the initializers get folded
// too.
AddGlobalCtor(Fn, 65535, COMDATKey);
} else {
I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
if (I == DelayedCXXInitPosition.end()) {
CXXGlobalInits.push_back(Fn);
} else if (I->second != ~0U) {
assert(I->second < CXXGlobalInits.size() &&
CXXGlobalInits[I->second] == nullptr);
CXXGlobalInits[I->second] = Fn;
}
}
// Remember that we already emitted the initializer for this global.
DelayedCXXInitPosition[D] = ~0U;
}
void CodeGenModule::EmitCXXThreadLocalInitFunc() {
getCXXABI().EmitThreadLocalInitFuncs(
*this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
CXXThreadLocalInits.clear();
CXXThreadLocalInitVars.clear();
CXXThreadLocals.clear();
}
void
CodeGenModule::EmitCXXGlobalInitFunc() {
while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
CXXGlobalInits.pop_back();
if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
return;
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
// Create our global initialization function.
if (!PrioritizedCXXGlobalInits.empty()) {
SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
PrioritizedCXXGlobalInits.end());
// Iterate over "chunks" of ctors with same priority and emit each chunk
// into separate function. Note - everything is sorted first by priority,
// second - by lex order, so we emit ctor functions in proper order.
for (SmallVectorImpl<GlobalInitData >::iterator
I = PrioritizedCXXGlobalInits.begin(),
E = PrioritizedCXXGlobalInits.end(); I != E; ) {
SmallVectorImpl<GlobalInitData >::iterator
PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
LocalCXXGlobalInits.clear();
unsigned Priority = I->first.priority;
// Compute the function suffix from priority. Prepend with zeroes to make
// sure the function names are also ordered as priorities.
std::string PrioritySuffix = llvm::utostr(Priority);
// Priority is always <= 65535 (enforced by sema).
PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
FTy, "_GLOBAL__I_" + PrioritySuffix, FI);
for (; I < PrioE; ++I)
LocalCXXGlobalInits.push_back(I->second);
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
AddGlobalCtor(Fn, Priority);
}
PrioritizedCXXGlobalInits.clear();
}
// Include the filename in the symbol name. Including "sub_" matches gcc and
// makes sure these symbols appear lexicographically behind the symbols with
// priority emitted above.
SmallString<128> FileName = llvm::sys::path::filename(getModule().getName());
if (FileName.empty())
FileName = "<null>";
for (size_t i = 0; i < FileName.size(); ++i) {
// Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
// to be the set of C preprocessing numbers.
if (!isPreprocessingNumberBody(FileName[i]))
FileName[i] = '_';
}
llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
FTy, llvm::Twine("_GLOBAL__sub_I_", FileName), FI);
CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
AddGlobalCtor(Fn);
// In OpenCL global init functions must be converted to kernels in order to
// be able to launch them from the host.
// FIXME: Some more work might be needed to handle destructors correctly.
// Current initialization function makes use of function pointers callbacks.
// We can't support function pointers especially between host and device.
// However it seems global destruction has little meaning without any
// dynamic resource allocation on the device and program scope variables are
// destroyed by the runtime when program is released.
if (getLangOpts().OpenCL) {
GenOpenCLArgMetadata(Fn);
Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
}
CXXGlobalInits.clear();
}
void CodeGenModule::EmitCXXGlobalDtorFunc() {
if (CXXGlobalDtors.empty())
return;
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
// Create our global destructor function.
const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
llvm::Function *Fn =
CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a", FI);
CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
AddGlobalDtor(Fn);
}
/// Emit the code necessary to initialize the given global variable.
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
const VarDecl *D,
llvm::GlobalVariable *Addr,
bool PerformInit) {
// Check if we need to emit debug info for variable initializer.
if (D->hasAttr<NoDebugAttr>())
DebugInfo = nullptr; // disable debug info indefinitely for this function
CurEHLocation = D->getBeginLoc();
StartFunction(GlobalDecl(D, DynamicInitKind::Initializer),
getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
FunctionArgList(), D->getLocation(),
D->getInit()->getExprLoc());
// Use guarded initialization if the global variable is weak. This
// occurs for, e.g., instantiated static data members and
// definitions explicitly marked weak.
//
// Also use guarded initialization for a variable with dynamic TLS and
// unordered initialization. (If the initialization is ordered, the ABI
// layer will guard the whole-TU initialization for us.)
if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage() ||
(D->getTLSKind() == VarDecl::TLS_Dynamic &&
isTemplateInstantiation(D->getTemplateSpecializationKind()))) {
EmitCXXGuardedInit(*D, Addr, PerformInit);
} else {
EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
}
FinishFunction();
}
void
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
ArrayRef<llvm::Function *> Decls,
ConstantAddress Guard) {
{
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
getTypes().arrangeNullaryFunction(), FunctionArgList());
// Emit an artificial location for this function.
auto AL = ApplyDebugLocation::CreateArtificial(*this);
llvm::BasicBlock *ExitBlock = nullptr;
if (Guard.isValid()) {
// If we have a guard variable, check whether we've already performed
// these initializations. This happens for TLS initialization functions.
llvm::Value *GuardVal = Builder.CreateLoad(Guard);
llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
"guard.uninitialized");
llvm::BasicBlock *InitBlock = createBasicBlock("init");
ExitBlock = createBasicBlock("exit");
EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
GuardKind::TlsGuard, nullptr);
EmitBlock(InitBlock);
// Mark as initialized before initializing anything else. If the
// initializers use previously-initialized thread_local vars, that's
// probably supposed to be OK, but the standard doesn't say.
Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
// The guard variable can't ever change again.
EmitInvariantStart(
Guard.getPointer(),
CharUnits::fromQuantity(
CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
}
RunCleanupsScope Scope(*this);
// When building in Objective-C++ ARC mode, create an autorelease pool
// around the global initializers.
if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
llvm::Value *token = EmitObjCAutoreleasePoolPush();
EmitObjCAutoreleasePoolCleanup(token);
}
for (unsigned i = 0, e = Decls.size(); i != e; ++i)
if (Decls[i])
EmitRuntimeCall(Decls[i]);
Scope.ForceCleanup();
if (ExitBlock) {
Builder.CreateBr(ExitBlock);
EmitBlock(ExitBlock);
}
}
FinishFunction();
}
void CodeGenFunction::GenerateCXXGlobalDtorsFunc(
llvm::Function *Fn,
const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
llvm::Constant *>> &DtorsAndObjects) {
{
auto NL = ApplyDebugLocation::CreateEmpty(*this);
StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
getTypes().arrangeNullaryFunction(), FunctionArgList());
// Emit an artificial location for this function.
auto AL = ApplyDebugLocation::CreateArtificial(*this);
// Emit the dtors, in reverse order from construction.
for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
llvm::FunctionType *CalleeTy;
llvm::Value *Callee;
llvm::Constant *Arg;
std::tie(CalleeTy, Callee, Arg) = DtorsAndObjects[e - i - 1];
llvm::CallInst *CI = Builder.CreateCall(CalleeTy, Callee, Arg);
// Make sure the call and the callee agree on calling convention.
if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
CI->setCallingConv(F->getCallingConv());
}
}
FinishFunction();
}
/// generateDestroyHelper - Generates a helper function which, when
/// invoked, destroys the given object. The address of the object
/// should be in global memory.
llvm::Function *CodeGenFunction::generateDestroyHelper(
Address addr, QualType type, Destroyer *destroyer,
bool useEHCleanupForArray, const VarDecl *VD) {
FunctionArgList args;
ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy,
ImplicitParamDecl::Other);
args.push_back(&Dst);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
CurEHLocation = VD->getBeginLoc();
StartFunction(VD, getContext().VoidTy, fn, FI, args);
emitDestroy(addr, type, destroyer, useEHCleanupForArray);
FinishFunction();
return fn;
}
| apple/swift-clang | lib/CodeGen/CGDeclCXX.cpp | C++ | apache-2.0 | 30,989 |
# Builders
ARG BUNDLE_IMAGE=fission-workflows-bundle
ARG BUNDLE_TAG=latest
ARG FISSION_BUILDER_IMAGE=fission/builder
ARG FISSION_TAG=latest
FROM $BUNDLE_IMAGE:$BUNDLE_TAG as workflows-bundle
FROM scratch
COPY --from=workflows-bundle /fission-workflows-bundle /fission-workflows-bundle
EXPOSE 8888
EXPOSE 8080
ENV FNENV_FISSION_CONTROLLER http://controller.fission
ENV FNENV_FISSION_EXECUTOR http://executor.fission
ENV ES_NATS_URL nats://[email protected]:4222
ENV ES_NATS_CLUSTER fissionMQTrigger
# Remove APIs when components stabilize
ENTRYPOINT ["/fission-workflows-bundle", \
"--nats", \
"--fission", \
"--internal", \
"--controller", \
"--api-http", \
"--api-workflow-invocation", \
"--api-workflow", \
"--api-admin", \
"--metrics"] | fission/fission-workflows | build/runtime-env/Dockerfile | Dockerfile | apache-2.0 | 880 |
# Dilsea californica (J. Agardh) Kuntze SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Rhodophyta/Florideophyceae/Gigartinales/Dumontiaceae/Dilsea/Dilsea californica/README.md | Markdown | apache-2.0 | 195 |
# Penicillium rufulum (Bainier) Sacc. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Syll. fung. (Abellini) 22: 1275 (1913)
#### Original name
Scopulariopsis rufulus Bainier
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Eurotiomycetes/Eurotiales/Trichocomaceae/Penicillium/Penicillium rufulum/README.md | Markdown | apache-2.0 | 228 |
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package m3ql
//go:generate peg -inline -switch src/query/parser/m3ql/grammar.peg
import (
"fmt"
"io"
"math"
"os"
"sort"
"strconv"
)
const endSymbol rune = 1114112
/* The rule types inferred from the grammar are below. */
type pegRule uint8
const (
ruleUnknown pegRule = iota
ruleGrammar
ruleMacroDef
rulePipeline
ruleExpression
ruleFunctionCall
ruleArgument
ruleKeywordSpecifier
ruleNesting
ruleSpacing
ruleSpace
ruleEOL
ruleComment
ruleCommentStart
ruleIdentifier
ruleIdentifierStart
ruleIdentifierChars
ruleOperator
ruleOperatorSymbols
ruleBoolean
ruleTrue
ruleFalse
ruleNumber
ruleIntegralNumber
ruleFloatingNumber
ruleMinus
ruleStringLiteral
ruleQuoteChar
rulePattern
rulePatternChars
ruleGlobSymbols
ruleSemicolon
ruleEquals
rulePipe
ruleLParenthesis
ruleRParenthesis
ruleColon
ruleEOF
ruleAction0
ruleAction1
ruleAction2
ruleAction3
ruleAction4
ruleAction5
ruleAction6
ruleAction7
ruleAction8
ruleAction9
rulePegText
)
var rul3s = [...]string{
"Unknown",
"Grammar",
"MacroDef",
"Pipeline",
"Expression",
"FunctionCall",
"Argument",
"KeywordSpecifier",
"Nesting",
"Spacing",
"Space",
"EOL",
"Comment",
"CommentStart",
"Identifier",
"IdentifierStart",
"IdentifierChars",
"Operator",
"OperatorSymbols",
"Boolean",
"True",
"False",
"Number",
"IntegralNumber",
"FloatingNumber",
"Minus",
"StringLiteral",
"QuoteChar",
"Pattern",
"PatternChars",
"GlobSymbols",
"Semicolon",
"Equals",
"Pipe",
"LParenthesis",
"RParenthesis",
"Colon",
"EOF",
"Action0",
"Action1",
"Action2",
"Action3",
"Action4",
"Action5",
"Action6",
"Action7",
"Action8",
"Action9",
"PegText",
}
type token32 struct {
pegRule
begin, end uint32
}
func (t *token32) String() string {
return fmt.Sprintf("\x1B[34m%v\x1B[m %v %v", rul3s[t.pegRule], t.begin, t.end)
}
type node32 struct {
token32
up, next *node32
}
func (node *node32) print(w io.Writer, pretty bool, buffer string) {
var print func(node *node32, depth int)
print = func(node *node32, depth int) {
for node != nil {
for c := 0; c < depth; c++ {
fmt.Printf(" ")
}
rule := rul3s[node.pegRule]
quote := strconv.Quote(string(([]rune(buffer)[node.begin:node.end])))
if !pretty {
fmt.Fprintf(w, "%v %v\n", rule, quote)
} else {
fmt.Fprintf(w, "\x1B[34m%v\x1B[m %v\n", rule, quote)
}
if node.up != nil {
print(node.up, depth+1)
}
node = node.next
}
}
print(node, 0)
}
func (node *node32) Print(w io.Writer, buffer string) {
node.print(w, false, buffer)
}
func (node *node32) PrettyPrint(w io.Writer, buffer string) {
node.print(w, true, buffer)
}
type tokens32 struct {
tree []token32
}
func (t *tokens32) Trim(length uint32) {
t.tree = t.tree[:length]
}
func (t *tokens32) Print() {
for _, token := range t.tree {
fmt.Println(token.String())
}
}
func (t *tokens32) AST() *node32 {
type element struct {
node *node32
down *element
}
tokens := t.Tokens()
var stack *element
for _, token := range tokens {
if token.begin == token.end {
continue
}
node := &node32{token32: token}
for stack != nil && stack.node.begin >= token.begin && stack.node.end <= token.end {
stack.node.next = node.up
node.up = stack.node
stack = stack.down
}
stack = &element{node: node, down: stack}
}
if stack != nil {
return stack.node
}
return nil
}
func (t *tokens32) PrintSyntaxTree(buffer string) {
t.AST().Print(os.Stdout, buffer)
}
func (t *tokens32) WriteSyntaxTree(w io.Writer, buffer string) {
t.AST().Print(w, buffer)
}
func (t *tokens32) PrettyPrintSyntaxTree(buffer string) {
t.AST().PrettyPrint(os.Stdout, buffer)
}
func (t *tokens32) Add(rule pegRule, begin, end, index uint32) {
if tree := t.tree; int(index) >= len(tree) {
expanded := make([]token32, 2*len(tree))
copy(expanded, tree)
t.tree = expanded
}
t.tree[index] = token32{
pegRule: rule,
begin: begin,
end: end,
}
}
func (t *tokens32) Tokens() []token32 {
return t.tree
}
type m3ql struct {
scriptBuilder
Buffer string
buffer []rune
rules [49]func() bool
parse func(rule ...int) error
reset func()
Pretty bool
tokens32
}
func (p *m3ql) Parse(rule ...int) error {
return p.parse(rule...)
}
func (p *m3ql) Reset() {
p.reset()
}
type textPosition struct {
line, symbol int
}
type textPositionMap map[int]textPosition
func translatePositions(buffer []rune, positions []int) textPositionMap {
length, translations, j, line, symbol := len(positions), make(textPositionMap, len(positions)), 0, 1, 0
sort.Ints(positions)
search:
for i, c := range buffer {
if c == '\n' {
line, symbol = line+1, 0
} else {
symbol++
}
if i == positions[j] {
translations[positions[j]] = textPosition{line, symbol}
for j++; j < length; j++ {
if i != positions[j] {
continue search
}
}
break search
}
}
return translations
}
type parseError struct {
p *m3ql
max token32
}
func (e *parseError) Error() string {
tokens, error := []token32{e.max}, "\n"
positions, p := make([]int, 2*len(tokens)), 0
for _, token := range tokens {
positions[p], p = int(token.begin), p+1
positions[p], p = int(token.end), p+1
}
translations := translatePositions(e.p.buffer, positions)
format := "parse error near %v (line %v symbol %v - line %v symbol %v):\n%v\n"
if e.p.Pretty {
format = "parse error near \x1B[34m%v\x1B[m (line %v symbol %v - line %v symbol %v):\n%v\n"
}
for _, token := range tokens {
begin, end := int(token.begin), int(token.end)
error += fmt.Sprintf(format,
rul3s[token.pegRule],
translations[begin].line, translations[begin].symbol,
translations[end].line, translations[end].symbol,
strconv.Quote(string(e.p.buffer[begin:end])))
}
return error
}
func (p *m3ql) PrintSyntaxTree() {
if p.Pretty {
p.tokens32.PrettyPrintSyntaxTree(p.Buffer)
} else {
p.tokens32.PrintSyntaxTree(p.Buffer)
}
}
func (p *m3ql) WriteSyntaxTree(w io.Writer) {
p.tokens32.WriteSyntaxTree(w, p.Buffer)
}
func (p *m3ql) Execute() {
buffer, _buffer, text, begin, end := p.Buffer, p.buffer, "", 0, 0
for _, token := range p.Tokens() {
switch token.pegRule {
case rulePegText:
begin, end = int(token.begin), int(token.end)
text = string(_buffer[begin:end])
case ruleAction0:
p.newMacro(text)
case ruleAction1:
p.newPipeline()
case ruleAction2:
p.endPipeline()
case ruleAction3:
p.newExpression(text)
case ruleAction4:
p.endExpression()
case ruleAction5:
p.newBooleanArgument(text)
case ruleAction6:
p.newNumericArgument(text)
case ruleAction7:
p.newPatternArgument(text)
case ruleAction8:
p.newStringLiteralArgument(text)
case ruleAction9:
p.newKeywordArgument(text)
}
}
_, _, _, _, _ = buffer, _buffer, text, begin, end
}
func (p *m3ql) Init() {
var (
max token32
position, tokenIndex uint32
buffer []rune
)
p.reset = func() {
max = token32{}
position, tokenIndex = 0, 0
p.buffer = []rune(p.Buffer)
if len(p.buffer) == 0 || p.buffer[len(p.buffer)-1] != endSymbol {
p.buffer = append(p.buffer, endSymbol)
}
buffer = p.buffer
}
p.reset()
_rules := p.rules
tree := tokens32{tree: make([]token32, math.MaxInt16)}
p.parse = func(rule ...int) error {
r := 1
if len(rule) > 0 {
r = rule[0]
}
matches := p.rules[r]()
p.tokens32 = tree
if matches {
p.Trim(tokenIndex)
return nil
}
return &parseError{p, max}
}
add := func(rule pegRule, begin uint32) {
tree.Add(rule, begin, position, tokenIndex)
tokenIndex++
if begin != position && position > max.end {
max = token32{rule, begin, position}
}
}
matchDot := func() bool {
if buffer[position] != endSymbol {
position++
return true
}
return false
}
/*matchChar := func(c byte) bool {
if buffer[position] == c {
position++
return true
}
return false
}*/
/*matchRange := func(lower byte, upper byte) bool {
if c := buffer[position]; c >= lower && c <= upper {
position++
return true
}
return false
}*/
_rules = [...]func() bool{
nil,
/* 0 Grammar <- <(Spacing (MacroDef Semicolon)* Pipeline EOF)> */
func() bool {
position0, tokenIndex0 := position, tokenIndex
{
position1 := position
if !_rules[ruleSpacing]() {
goto l0
}
l2:
{
position3, tokenIndex3 := position, tokenIndex
{
position4 := position
if !_rules[ruleIdentifier]() {
goto l3
}
{
add(ruleAction0, position)
}
{
position6 := position
if buffer[position] != rune('=') {
goto l3
}
position++
if !_rules[ruleSpacing]() {
goto l3
}
add(ruleEquals, position6)
}
if !_rules[rulePipeline]() {
goto l3
}
add(ruleMacroDef, position4)
}
{
position7 := position
if buffer[position] != rune(';') {
goto l3
}
position++
if !_rules[ruleSpacing]() {
goto l3
}
add(ruleSemicolon, position7)
}
goto l2
l3:
position, tokenIndex = position3, tokenIndex3
}
if !_rules[rulePipeline]() {
goto l0
}
{
position8 := position
{
position9, tokenIndex9 := position, tokenIndex
if !matchDot() {
goto l9
}
goto l0
l9:
position, tokenIndex = position9, tokenIndex9
}
add(ruleEOF, position8)
}
add(ruleGrammar, position1)
}
return true
l0:
position, tokenIndex = position0, tokenIndex0
return false
},
/* 1 MacroDef <- <(Identifier Action0 Equals Pipeline)> */
nil,
/* 2 Pipeline <- <(Action1 Expression (Pipe Expression)* Action2)> */
func() bool {
position11, tokenIndex11 := position, tokenIndex
{
position12 := position
{
add(ruleAction1, position)
}
if !_rules[ruleExpression]() {
goto l11
}
l14:
{
position15, tokenIndex15 := position, tokenIndex
{
position16 := position
if buffer[position] != rune('|') {
goto l15
}
position++
if !_rules[ruleSpacing]() {
goto l15
}
add(rulePipe, position16)
}
if !_rules[ruleExpression]() {
goto l15
}
goto l14
l15:
position, tokenIndex = position15, tokenIndex15
}
{
add(ruleAction2, position)
}
add(rulePipeline, position12)
}
return true
l11:
position, tokenIndex = position11, tokenIndex11
return false
},
/* 3 Expression <- <(FunctionCall / Nesting)> */
func() bool {
position18, tokenIndex18 := position, tokenIndex
{
position19 := position
{
position20, tokenIndex20 := position, tokenIndex
{
position22 := position
{
position23, tokenIndex23 := position, tokenIndex
if !_rules[ruleIdentifier]() {
goto l24
}
goto l23
l24:
position, tokenIndex = position23, tokenIndex23
{
position25 := position
{
position26 := position
{
position27 := position
{
position28, tokenIndex28 := position, tokenIndex
if buffer[position] != rune('<') {
goto l29
}
position++
if buffer[position] != rune('=') {
goto l29
}
position++
goto l28
l29:
position, tokenIndex = position28, tokenIndex28
if buffer[position] != rune('>') {
goto l30
}
position++
if buffer[position] != rune('=') {
goto l30
}
position++
goto l28
l30:
position, tokenIndex = position28, tokenIndex28
{
switch buffer[position] {
case '>':
if buffer[position] != rune('>') {
goto l21
}
position++
break
case '!':
if buffer[position] != rune('!') {
goto l21
}
position++
if buffer[position] != rune('=') {
goto l21
}
position++
break
case '=':
if buffer[position] != rune('=') {
goto l21
}
position++
if buffer[position] != rune('=') {
goto l21
}
position++
break
default:
if buffer[position] != rune('<') {
goto l21
}
position++
break
}
}
}
l28:
add(ruleOperatorSymbols, position27)
}
add(rulePegText, position26)
}
if !_rules[ruleSpacing]() {
goto l21
}
add(ruleOperator, position25)
}
}
l23:
{
add(ruleAction3, position)
}
l33:
{
position34, tokenIndex34 := position, tokenIndex
{
position35 := position
{
position36, tokenIndex36 := position, tokenIndex
{
position38 := position
if !_rules[ruleIdentifier]() {
goto l36
}
{
add(ruleAction9, position)
}
{
position40 := position
if buffer[position] != rune(':') {
goto l36
}
position++
if !_rules[ruleSpacing]() {
goto l36
}
add(ruleColon, position40)
}
add(ruleKeywordSpecifier, position38)
}
goto l37
l36:
position, tokenIndex = position36, tokenIndex36
}
l37:
{
position41, tokenIndex41 := position, tokenIndex
{
position43 := position
{
position44 := position
{
position45, tokenIndex45 := position, tokenIndex
{
position47 := position
{
position48, tokenIndex48 := position, tokenIndex
if buffer[position] != rune('t') {
goto l49
}
position++
goto l48
l49:
position, tokenIndex = position48, tokenIndex48
if buffer[position] != rune('T') {
goto l46
}
position++
}
l48:
{
position50, tokenIndex50 := position, tokenIndex
if buffer[position] != rune('r') {
goto l51
}
position++
goto l50
l51:
position, tokenIndex = position50, tokenIndex50
if buffer[position] != rune('R') {
goto l46
}
position++
}
l50:
{
position52, tokenIndex52 := position, tokenIndex
if buffer[position] != rune('u') {
goto l53
}
position++
goto l52
l53:
position, tokenIndex = position52, tokenIndex52
if buffer[position] != rune('U') {
goto l46
}
position++
}
l52:
{
position54, tokenIndex54 := position, tokenIndex
if buffer[position] != rune('e') {
goto l55
}
position++
goto l54
l55:
position, tokenIndex = position54, tokenIndex54
if buffer[position] != rune('E') {
goto l46
}
position++
}
l54:
add(ruleTrue, position47)
}
goto l45
l46:
position, tokenIndex = position45, tokenIndex45
{
position56 := position
{
position57, tokenIndex57 := position, tokenIndex
if buffer[position] != rune('f') {
goto l58
}
position++
goto l57
l58:
position, tokenIndex = position57, tokenIndex57
if buffer[position] != rune('F') {
goto l42
}
position++
}
l57:
{
position59, tokenIndex59 := position, tokenIndex
if buffer[position] != rune('a') {
goto l60
}
position++
goto l59
l60:
position, tokenIndex = position59, tokenIndex59
if buffer[position] != rune('A') {
goto l42
}
position++
}
l59:
{
position61, tokenIndex61 := position, tokenIndex
if buffer[position] != rune('l') {
goto l62
}
position++
goto l61
l62:
position, tokenIndex = position61, tokenIndex61
if buffer[position] != rune('L') {
goto l42
}
position++
}
l61:
{
position63, tokenIndex63 := position, tokenIndex
if buffer[position] != rune('s') {
goto l64
}
position++
goto l63
l64:
position, tokenIndex = position63, tokenIndex63
if buffer[position] != rune('S') {
goto l42
}
position++
}
l63:
{
position65, tokenIndex65 := position, tokenIndex
if buffer[position] != rune('e') {
goto l66
}
position++
goto l65
l66:
position, tokenIndex = position65, tokenIndex65
if buffer[position] != rune('E') {
goto l42
}
position++
}
l65:
add(ruleFalse, position56)
}
}
l45:
add(rulePegText, position44)
}
{
position67, tokenIndex67 := position, tokenIndex
if !_rules[rulePatternChars]() {
goto l67
}
goto l42
l67:
position, tokenIndex = position67, tokenIndex67
}
if !_rules[ruleSpacing]() {
goto l42
}
add(ruleBoolean, position43)
}
{
add(ruleAction5, position)
}
goto l41
l42:
position, tokenIndex = position41, tokenIndex41
{
position70 := position
{
position71 := position
{
position72, tokenIndex72 := position, tokenIndex
{
position74 := position
if buffer[position] != rune('-') {
goto l72
}
position++
add(ruleMinus, position74)
}
goto l73
l72:
position, tokenIndex = position72, tokenIndex72
}
l73:
{
position75, tokenIndex75 := position, tokenIndex
{
position77 := position
{
position78, tokenIndex78 := position, tokenIndex
if !_rules[ruleIntegralNumber]() {
goto l78
}
goto l79
l78:
position, tokenIndex = position78, tokenIndex78
}
l79:
if buffer[position] != rune('.') {
goto l76
}
position++
if !_rules[ruleIntegralNumber]() {
goto l76
}
add(ruleFloatingNumber, position77)
}
goto l75
l76:
position, tokenIndex = position75, tokenIndex75
if !_rules[ruleIntegralNumber]() {
goto l69
}
}
l75:
add(rulePegText, position71)
}
{
position80, tokenIndex80 := position, tokenIndex
if !_rules[rulePatternChars]() {
goto l80
}
goto l69
l80:
position, tokenIndex = position80, tokenIndex80
}
if !_rules[ruleSpacing]() {
goto l69
}
add(ruleNumber, position70)
}
{
add(ruleAction6, position)
}
goto l41
l69:
position, tokenIndex = position41, tokenIndex41
{
switch buffer[position] {
case '(':
if !_rules[ruleNesting]() {
goto l34
}
break
case '"':
{
position83 := position
if !_rules[ruleQuoteChar]() {
goto l34
}
{
position84 := position
l85:
{
position86, tokenIndex86 := position, tokenIndex
{
position87, tokenIndex87 := position, tokenIndex
if buffer[position] != rune('"') {
goto l87
}
position++
goto l86
l87:
position, tokenIndex = position87, tokenIndex87
}
if !matchDot() {
goto l86
}
goto l85
l86:
position, tokenIndex = position86, tokenIndex86
}
add(rulePegText, position84)
}
if !_rules[ruleQuoteChar]() {
goto l34
}
if !_rules[ruleSpacing]() {
goto l34
}
add(ruleStringLiteral, position83)
}
{
add(ruleAction8, position)
}
break
default:
{
position89 := position
{
position90 := position
if !_rules[rulePatternChars]() {
goto l34
}
l91:
{
position92, tokenIndex92 := position, tokenIndex
if !_rules[rulePatternChars]() {
goto l92
}
goto l91
l92:
position, tokenIndex = position92, tokenIndex92
}
add(rulePegText, position90)
}
if !_rules[ruleSpacing]() {
goto l34
}
add(rulePattern, position89)
}
{
add(ruleAction7, position)
}
break
}
}
}
l41:
add(ruleArgument, position35)
}
goto l33
l34:
position, tokenIndex = position34, tokenIndex34
}
{
add(ruleAction4, position)
}
add(ruleFunctionCall, position22)
}
goto l20
l21:
position, tokenIndex = position20, tokenIndex20
if !_rules[ruleNesting]() {
goto l18
}
}
l20:
add(ruleExpression, position19)
}
return true
l18:
position, tokenIndex = position18, tokenIndex18
return false
},
/* 4 FunctionCall <- <((Identifier / Operator) Action3 Argument* Action4)> */
nil,
/* 5 Argument <- <(KeywordSpecifier? ((Boolean Action5) / (Number Action6) / ((&('(') Nesting) | (&('"') (StringLiteral Action8)) | (&('$' | '*' | ',' | '-' | '.' | '/' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '?' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '[' | '\\' | ']' | '^' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z' | '{' | '}') (Pattern Action7)))))> */
nil,
/* 6 KeywordSpecifier <- <(Identifier Action9 Colon)> */
nil,
/* 7 Nesting <- <(LParenthesis Pipeline RParenthesis)> */
func() bool {
position98, tokenIndex98 := position, tokenIndex
{
position99 := position
{
position100 := position
if buffer[position] != rune('(') {
goto l98
}
position++
if !_rules[ruleSpacing]() {
goto l98
}
add(ruleLParenthesis, position100)
}
if !_rules[rulePipeline]() {
goto l98
}
{
position101 := position
if buffer[position] != rune(')') {
goto l98
}
position++
if !_rules[ruleSpacing]() {
goto l98
}
add(ruleRParenthesis, position101)
}
add(ruleNesting, position99)
}
return true
l98:
position, tokenIndex = position98, tokenIndex98
return false
},
/* 8 Spacing <- <((&('#') Comment) | (&('\n' | '\r') EOL) | (&('\t' | ' ') Space))*> */
func() bool {
{
position103 := position
l104:
{
position105, tokenIndex105 := position, tokenIndex
{
switch buffer[position] {
case '#':
{
position107 := position
{
position108 := position
if buffer[position] != rune('#') {
goto l105
}
position++
add(ruleCommentStart, position108)
}
l109:
{
position110, tokenIndex110 := position, tokenIndex
{
position111, tokenIndex111 := position, tokenIndex
if !_rules[ruleEOL]() {
goto l111
}
goto l110
l111:
position, tokenIndex = position111, tokenIndex111
}
if !matchDot() {
goto l110
}
goto l109
l110:
position, tokenIndex = position110, tokenIndex110
}
add(ruleComment, position107)
}
break
case '\n', '\r':
if !_rules[ruleEOL]() {
goto l105
}
break
default:
{
position112 := position
{
position113, tokenIndex113 := position, tokenIndex
if buffer[position] != rune(' ') {
goto l114
}
position++
goto l113
l114:
position, tokenIndex = position113, tokenIndex113
if buffer[position] != rune('\t') {
goto l105
}
position++
}
l113:
add(ruleSpace, position112)
}
break
}
}
goto l104
l105:
position, tokenIndex = position105, tokenIndex105
}
add(ruleSpacing, position103)
}
return true
},
/* 9 Space <- <(' ' / '\t')> */
nil,
/* 10 EOL <- <(('\r' '\n') / '\n' / '\r')> */
func() bool {
position116, tokenIndex116 := position, tokenIndex
{
position117 := position
{
position118, tokenIndex118 := position, tokenIndex
if buffer[position] != rune('\r') {
goto l119
}
position++
if buffer[position] != rune('\n') {
goto l119
}
position++
goto l118
l119:
position, tokenIndex = position118, tokenIndex118
if buffer[position] != rune('\n') {
goto l120
}
position++
goto l118
l120:
position, tokenIndex = position118, tokenIndex118
if buffer[position] != rune('\r') {
goto l116
}
position++
}
l118:
add(ruleEOL, position117)
}
return true
l116:
position, tokenIndex = position116, tokenIndex116
return false
},
/* 11 Comment <- <(CommentStart (!EOL .)*)> */
nil,
/* 12 CommentStart <- <'#'> */
nil,
/* 13 Identifier <- <(<(IdentifierStart IdentifierChars*)> Spacing)> */
func() bool {
position123, tokenIndex123 := position, tokenIndex
{
position124 := position
{
position125 := position
if !_rules[ruleIdentifierStart]() {
goto l123
}
l126:
{
position127, tokenIndex127 := position, tokenIndex
if !_rules[ruleIdentifierChars]() {
goto l127
}
goto l126
l127:
position, tokenIndex = position127, tokenIndex127
}
add(rulePegText, position125)
}
if !_rules[ruleSpacing]() {
goto l123
}
add(ruleIdentifier, position124)
}
return true
l123:
position, tokenIndex = position123, tokenIndex123
return false
},
/* 14 IdentifierStart <- <((&('_') '_') | (&('A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z') [A-Z]) | (&('a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z') [a-z]))> */
func() bool {
position128, tokenIndex128 := position, tokenIndex
{
position129 := position
{
switch buffer[position] {
case '_':
if buffer[position] != rune('_') {
goto l128
}
position++
break
case 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z':
if c := buffer[position]; c < rune('A') || c > rune('Z') {
goto l128
}
position++
break
default:
if c := buffer[position]; c < rune('a') || c > rune('z') {
goto l128
}
position++
break
}
}
add(ruleIdentifierStart, position129)
}
return true
l128:
position, tokenIndex = position128, tokenIndex128
return false
},
/* 15 IdentifierChars <- <((&('\\') '\\') | (&('/') '/') | (&('-') '-') | (&('.') '.') | (&('0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9') [0-9]) | (&('A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z') IdentifierStart))> */
func() bool {
position131, tokenIndex131 := position, tokenIndex
{
position132 := position
{
switch buffer[position] {
case '\\':
if buffer[position] != rune('\\') {
goto l131
}
position++
break
case '/':
if buffer[position] != rune('/') {
goto l131
}
position++
break
case '-':
if buffer[position] != rune('-') {
goto l131
}
position++
break
case '.':
if buffer[position] != rune('.') {
goto l131
}
position++
break
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
if c := buffer[position]; c < rune('0') || c > rune('9') {
goto l131
}
position++
break
default:
if !_rules[ruleIdentifierStart]() {
goto l131
}
break
}
}
add(ruleIdentifierChars, position132)
}
return true
l131:
position, tokenIndex = position131, tokenIndex131
return false
},
/* 16 Operator <- <(<OperatorSymbols> Spacing)> */
nil,
/* 17 OperatorSymbols <- <(('<' '=') / ('>' '=') / ((&('>') '>') | (&('!') ('!' '=')) | (&('=') ('=' '=')) | (&('<') '<')))> */
nil,
/* 18 Boolean <- <(<(True / False)> !PatternChars Spacing)> */
nil,
/* 19 True <- <(('t' / 'T') ('r' / 'R') ('u' / 'U') ('e' / 'E'))> */
nil,
/* 20 False <- <(('f' / 'F') ('a' / 'A') ('l' / 'L') ('s' / 'S') ('e' / 'E'))> */
nil,
/* 21 Number <- <(<(Minus? (FloatingNumber / IntegralNumber))> !PatternChars Spacing)> */
nil,
/* 22 IntegralNumber <- <[0-9]+> */
func() bool {
position140, tokenIndex140 := position, tokenIndex
{
position141 := position
if c := buffer[position]; c < rune('0') || c > rune('9') {
goto l140
}
position++
l142:
{
position143, tokenIndex143 := position, tokenIndex
if c := buffer[position]; c < rune('0') || c > rune('9') {
goto l143
}
position++
goto l142
l143:
position, tokenIndex = position143, tokenIndex143
}
add(ruleIntegralNumber, position141)
}
return true
l140:
position, tokenIndex = position140, tokenIndex140
return false
},
/* 23 FloatingNumber <- <(IntegralNumber? '.' IntegralNumber)> */
nil,
/* 24 Minus <- <'-'> */
nil,
/* 25 StringLiteral <- <(QuoteChar <(!'"' .)*> QuoteChar Spacing)> */
nil,
/* 26 QuoteChar <- <'"'> */
func() bool {
position147, tokenIndex147 := position, tokenIndex
{
position148 := position
if buffer[position] != rune('"') {
goto l147
}
position++
add(ruleQuoteChar, position148)
}
return true
l147:
position, tokenIndex = position147, tokenIndex147
return false
},
/* 27 Pattern <- <(<PatternChars+> Spacing)> */
nil,
/* 28 PatternChars <- <(IdentifierChars / GlobSymbols)> */
func() bool {
position150, tokenIndex150 := position, tokenIndex
{
position151 := position
{
position152, tokenIndex152 := position, tokenIndex
if !_rules[ruleIdentifierChars]() {
goto l153
}
goto l152
l153:
position, tokenIndex = position152, tokenIndex152
{
position154 := position
{
switch buffer[position] {
case '$':
if buffer[position] != rune('$') {
goto l150
}
position++
break
case '^':
if buffer[position] != rune('^') {
goto l150
}
position++
break
case ',':
if buffer[position] != rune(',') {
goto l150
}
position++
break
case '?':
if buffer[position] != rune('?') {
goto l150
}
position++
break
case '*':
if buffer[position] != rune('*') {
goto l150
}
position++
break
case ']':
if buffer[position] != rune(']') {
goto l150
}
position++
break
case '[':
if buffer[position] != rune('[') {
goto l150
}
position++
break
case '}':
if buffer[position] != rune('}') {
goto l150
}
position++
break
default:
if buffer[position] != rune('{') {
goto l150
}
position++
break
}
}
add(ruleGlobSymbols, position154)
}
}
l152:
add(rulePatternChars, position151)
}
return true
l150:
position, tokenIndex = position150, tokenIndex150
return false
},
/* 29 GlobSymbols <- <((&('$') '$') | (&('^') '^') | (&(',') ',') | (&('?') '?') | (&('*') '*') | (&(']') ']') | (&('[') '[') | (&('}') '}') | (&('{') '{'))> */
nil,
/* 30 Semicolon <- <(';' Spacing)> */
nil,
/* 31 Equals <- <('=' Spacing)> */
nil,
/* 32 Pipe <- <('|' Spacing)> */
nil,
/* 33 LParenthesis <- <('(' Spacing)> */
nil,
/* 34 RParenthesis <- <(')' Spacing)> */
nil,
/* 35 Colon <- <(':' Spacing)> */
nil,
/* 36 EOF <- <!.> */
nil,
/* 38 Action0 <- <{ p.newMacro(text) }> */
nil,
/* 39 Action1 <- <{ p.newPipeline() }> */
nil,
/* 40 Action2 <- <{ p.endPipeline() }> */
nil,
/* 41 Action3 <- <{ p.newExpression(text) }> */
nil,
/* 42 Action4 <- <{ p.endExpression() }> */
nil,
/* 43 Action5 <- <{ p.newBooleanArgument(text) }> */
nil,
/* 44 Action6 <- <{ p.newNumericArgument(text) }> */
nil,
/* 45 Action7 <- <{ p.newPatternArgument(text) }> */
nil,
/* 46 Action8 <- <{ p.newStringLiteralArgument(text) }> */
nil,
/* 47 Action9 <- <{ p.newKeywordArgument(text) }> */
nil,
nil,
}
p.rules = _rules
}
| m3db/m3db | src/query/parser/m3ql/grammar.peg.go | GO | apache-2.0 | 37,003 |
<?php
/**
* The Campaigns endpoint. This is a campaign of type SMS.
*
* @link https://github.com/PortaText/docs/wiki/REST-API#api_campaigns Campaigns endpoint.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0
* @author Marcelo Gornstein <[email protected]>
* @copyright 2015 PortaText
*/
namespace PortaText\Command\Api;
use PortaText\Command\Base;
/**
* The Campaigns endpoint. This is a campaign of type SMS.
*/
class SmsCampaign extends Campaigns
{
/**
* Specifies source sms service.
*
* @param string $serviceId SMS Service ID.
*
* @return PortaText\Command\ICommand
*/
public function fromService($serviceId)
{
return $this->setArgument("service_id", $serviceId);
}
/**
* Sets the template id to use.
*
* @param integer $templateId Use the given template as the message body.
* @param array $variables Variables to use in template.
*
* @return PortaText\Command\ICommand
*/
public function useTemplate($templateId, array $variables = array())
{
$this->setSetting("template_id", $templateId);
return $this->setSetting("variables", $variables);
}
/**
* Sets the message text.
*
* @param string $text Message text.
*
* @return PortaText\Command\ICommand
*/
public function text($text)
{
return $this->setSetting("text", $text);
}
/**
* Standard constructor.
*
*/
public function __construct()
{
parent::__construct();
$this->setArgument("type", "sms");
}
}
| PortaText/php-sdk | src/PortaText/Command/Api/SmsCampaign.php | PHP | apache-2.0 | 1,615 |
/**
Copyright 2017 Andrea "Stock" Stocchero
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* Contains the {@link org.pepstock.charba.client.annotation.AnnotationPlugin#ID} plugin elements interfaces to use in the callbacks and events.
*
* @author Andrea "Stock" Stocchero
*
*/
package org.pepstock.charba.client.annotation.elements; | pepstock-org/Charba | src/org/pepstock/charba/client/annotation/elements/package-info.java | Java | apache-2.0 | 881 |
#
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module DTK::Client; class Operation::Service::TaskStatus::StreamMode
class Element
class TaskStart < self
def self.get(task_status_handle, opts = {})
opts_get = {
:start_index => 0,
:end_index => 0
}.merge(opts)
get_task_status_elements(task_status_handle, :task_start, opts_get)
end
def render
return if @ignore_stage_level_info
msg = "start '#{field?(:display_name) || 'Workflow'}'"
render_line msg, :bracket => true, :started_at => field?(:started_at)
render_empty_lines 2
end
end
end
end; end
| dtk/dtk-client | lib/client/operation/service/task_status/stream_mode/element/task_start.rb | Ruby | apache-2.0 | 1,243 |
/*
Copyright 2016, 2020 Nationale-Nederlanden, 2020-2021 WeAreFrank!
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.adapterframework.pipes;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.Adapter;
import nl.nn.adapterframework.core.PipeLineSession;
import nl.nn.adapterframework.core.PipeRunException;
import nl.nn.adapterframework.core.PipeRunResult;
import nl.nn.adapterframework.doc.IbisDoc;
import nl.nn.adapterframework.http.RestListenerUtils;
import nl.nn.adapterframework.soap.WsdlGenerator;
import nl.nn.adapterframework.stream.Message;
import nl.nn.adapterframework.util.StreamUtil;
/**
* Generate WSDL of parent or specified adapter.
*
* @author Jaco de Groot
*/
public class WsdlGeneratorPipe extends FixedForwardPipe {
private String from = "parent";
@Override
public void configure() throws ConfigurationException {
super.configure();
if (!"parent".equals(getFrom()) && !"input".equals(getFrom())) {
throw new ConfigurationException("from should either be parent or input");
}
}
@Override
public PipeRunResult doPipe(Message message, PipeLineSession session) throws PipeRunException {
String result = null;
Adapter adapter;
try {
if ("input".equals(getFrom())) {
String adapterName = message.asString();
adapter = getAdapter().getConfiguration().getIbisManager().getRegisteredAdapter(adapterName);
if (adapter == null) {
throw new PipeRunException(this, "Could not find adapter: " + adapterName);
}
} else {
adapter = getPipeLine().getAdapter();
}
} catch (IOException e) {
throw new PipeRunException(this, "Could not determine adapter name", e);
}
try {
String generationInfo = "at " + RestListenerUtils.retrieveRequestURL(session);
WsdlGenerator wsdl = new WsdlGenerator(adapter.getPipeLine(), generationInfo);
wsdl.init();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wsdl.wsdl(outputStream, null);
result = outputStream.toString(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING);
} catch (Exception e) {
throw new PipeRunException(this, "Could not generate WSDL for adapter [" + adapter.getName() + "]", e);
}
return new PipeRunResult(getSuccessForward(), result);
}
public String getFrom() {
return from;
}
@IbisDoc({"either parent (adapter of pipeline which contains this pipe) or input (name of adapter specified by input of pipe)", "parent"})
public void setFrom(String from) {
this.from = from;
}
} | ibissource/iaf | core/src/main/java/nl/nn/adapterframework/pipes/WsdlGeneratorPipe.java | Java | apache-2.0 | 3,096 |
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.dianaui.universal.core.client.ui.html;
import com.dianaui.universal.core.client.ui.base.AbstractTextWidget;
import com.dianaui.universal.core.client.ui.constants.ElementTags;
import com.google.gwt.dom.client.Document;
/**
* Simple {@code <strong>} tag to emphasize words
*
* @author Joshua Godi
*/
public class Strong extends AbstractTextWidget {
public Strong() {
super(Document.get().createElement(ElementTags.STRONG));
}
public Strong(final String text) {
this();
setHTML(text);
}
}
| dianaui/dianaui-universal | core/src/main/java/com/dianaui/universal/core/client/ui/html/Strong.java | Java | apache-2.0 | 1,186 |
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.dianaui.universal.core.client.ui.constants;
import com.dianaui.universal.core.client.ui.base.helper.EnumHelper;
import com.google.gwt.dom.client.Style;
/**
* Only relevant to horizontal forms
*
* @author Xiaodong Sun
*/
public enum FormGroupSize implements Size, Style.HasCssName {
LARGE("form-group-lg"),
DEFAULT(""),
SMALL("form-group-sm"),;
private final String cssClass;
private FormGroupSize(final String cssClass) {
this.cssClass = cssClass;
}
@Override
public String getCssName() {
return cssClass;
}
public static FormGroupSize fromStyleName(final String styleName) {
return EnumHelper.fromStyleName(styleName, FormGroupSize.class, DEFAULT);
}
}
| dianaui/dianaui-universal | core/src/main/java/com/dianaui/universal/core/client/ui/constants/FormGroupSize.java | Java | apache-2.0 | 1,385 |
# frozen_string_literal: true
require 'github_request'
class GithubPostReceiveHook
SUBSCRIBE_NAME = "web"
def initialize(repository, oauth_token)
@repository = repository
@oauth_token = oauth_token
@root_url = "#{repository.base_api_url}/hooks"
@hook_url = "#{repository.base_api_url}/hooks/#{repository.github_post_receive_hook_id}"
@receive_url = Rails.application.routes.url_helpers.pull_request_build_url
@interested_events = @repository.interested_github_events
@subscribe_args = {:name => "web", :config => {:url => @receive_url}, :events => @interested_events, :active => true}
end
def subscribe!
if @repository.github_post_receive_hook_id
update_repository_hook!
else
synchronize_or_create!
end
end
private
def update_repository_hook!
begin
GithubRequest.patch(@hook_url, @subscribe_args, @oauth_token)
rescue GithubRequest::ResponseError => e
if e.response.class == Net::HTTPNotFound
create_hook
else
raise e
end
end
end
def synchronize_or_create!
begin
response_body = GithubRequest.get(@root_url, @oauth_token)
existing_hooks = JSON.parse(response_body)
existing_subscription = existing_hooks.detect do |hook|
hook["active"] && hook["events"] == @interested_events && hook["config"]["url"] == @receive_url
end
if existing_subscription
@repository.update_attributes(:github_post_receive_hook_id => existing_subscription["id"])
return response_body
end
rescue GithubRequest::ResponseError
Rails.logger.info("Failed to get hooks for #{@root_url}")
end
create_hook
end
def create_hook
GithubRequest.post(@root_url, @subscribe_args, @oauth_token)
end
end
| square/kochiku | lib/github_post_receive_hook.rb | Ruby | apache-2.0 | 1,783 |
package org.swtk.commons.dict.wiktionary.generated.a.u.v; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryAUV000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("auvergne", "{\"term\":\"auvergne\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{rfe|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A region and historical province of France\", \"priority\":1}]}, \"synonyms\":{}}");
} private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } } | torrances/swtk-commons | commons-dict-wiktionary/src/main/java/org/swtk/commons/dict/wiktionary/generated/a/u/v/WiktionaryAUV000.java | Java | apache-2.0 | 967 |
# frozen_string_literal: true
# rubocop:disable Layout/LineLength
# == Schema Information
#
# Table name: form_items
#
# id :uuid not null, primary key
# all_levels_required :boolean default(FALSE), not null
# ancestry :text
# ancestry_depth :integer not null
# default :string
# disabled :boolean default(FALSE), not null
# display_if :string default("always"), not null
# group_hint_translations :jsonb
# group_item_name_translations :jsonb
# group_name_translations :jsonb
# hidden :boolean default(FALSE), not null
# one_screen :boolean
# rank :integer not null
# read_only :boolean
# repeatable :boolean
# required :boolean default(FALSE), not null
# type :string(255) not null
# created_at :datetime not null
# updated_at :datetime not null
# form_id :uuid not null
# form_old_id :integer
# mission_id :uuid
# old_id :integer
# question_id :uuid
# question_old_id :integer
#
# Indexes
#
# index_form_items_on_ancestry (ancestry)
# index_form_items_on_form_id (form_id)
# index_form_items_on_form_id_and_question_id (form_id,question_id) UNIQUE
# index_form_items_on_mission_id (mission_id)
# index_form_items_on_question_id (question_id)
#
# Foreign Keys
#
# form_items_form_id_fkey (form_id => forms.id) ON DELETE => restrict ON UPDATE => restrict
# form_items_mission_id_fkey (mission_id => missions.id) ON DELETE => restrict ON UPDATE => restrict
# form_items_question_id_fkey (question_id => questions.id) ON DELETE => restrict ON UPDATE => restrict
#
# rubocop:enable Layout/LineLength
require "rails_helper"
describe Questioning do
it "mission should get copied from question on creation" do
f = create(:form, question_types: %w[integer], mission: get_mission)
expect(f.questionings[0].mission).to eq(get_mission)
end
describe "normalization" do
# Run valid? to trigger normalization
let(:q_attrs) { {} }
let(:question) { create(:question, q_attrs) }
let(:qing) { build(:questioning, submitted.merge(question: question)).tap(&:valid?) }
subject { submitted.keys.index_with { |k| qing.send(k) }.to_h }
describe "hidden/disabled/required/read_only" do
context do
let(:submitted) { {hidden: true, disabled: false, required: true, read_only: false} }
it { is_expected.to eq(hidden: true, disabled: false, required: false, read_only: false) }
end
context do
let(:submitted) { {hidden: false, disabled: true, required: true, read_only: false} }
it { is_expected.to eq(hidden: false, disabled: true, required: true, read_only: false) }
end
context do
let(:submitted) { {hidden: true, disabled: true, required: false, read_only: false} }
it { is_expected.to eq(hidden: true, disabled: true, required: false, read_only: false) }
end
context do
let(:submitted) { {hidden: false, disabled: false, required: true, read_only: false} }
it { is_expected.to eq(hidden: false, disabled: false, required: true, read_only: false) }
end
context do
let(:submitted) { {hidden: false, disabled: false, required: true, read_only: true} }
it { is_expected.to eq(hidden: false, disabled: false, required: false, read_only: true) }
end
context do
let(:submitted) { {hidden: false, disabled: false, required: false, read_only: true} }
it { is_expected.to eq(hidden: false, disabled: false, required: false, read_only: true) }
end
end
describe "preload_last_saved and default" do
context do
let(:submitted) { {preload_last_saved: false, default: "foo"} }
it { is_expected.to eq(preload_last_saved: false, default: "foo") }
end
context do
let(:submitted) { {preload_last_saved: true, default: "foo"} }
it { is_expected.to eq(preload_last_saved: true, default: nil) }
end
end
describe "question metadata and hidden/disabled/required" do
context do
let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} }
let(:submitted) { {required: true, hidden: false, disabled: false} }
it { is_expected.to eq(required: false, hidden: true, disabled: false) }
end
context do
let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} }
let(:submitted) { {required: "", hidden: true, disabled: true} }
it { is_expected.to eq(required: false, hidden: true, disabled: true) }
end
context do
let(:q_attrs) { {qtype_name: "datetime", metadata_type: ""} }
let(:submitted) { {required: true, disabled: false} }
it { is_expected.to eq(required: true, disabled: false) }
end
end
describe "question metadata and condition" do
let(:condition) { build(:condition) }
context "not adding a metadata_type" do
let(:q_attrs) { {qtype_name: "datetime", metadata_type: nil} }
let(:submitted) { {display_conditions: [condition]} }
it "should not destroy existing conditions" do
is_expected.to eq(display_conditions: [condition])
end
end
context "add a metadata_type with an existing condition" do
let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} }
let(:submitted) { {display_conditions: [condition]} }
it "should destroy existing conditions" do
is_expected.to eq(display_conditions: [])
expect(condition).to be_destroyed
end
end
context "add a metadata_type with no existing conditions" do
let(:q_attrs) { {qtype_name: "datetime", metadata_type: "formstart"} }
let(:submitted) { {display_conditions: []} }
it "should not change the display conditions" do
is_expected.to eq(display_conditions: [])
end
end
end
describe "all_levels_required" do
let(:question) { form.c[0].question }
context "multilevel, required question" do
let(:form) { create(:form, question_types: %w[multilevel_select_one]) }
let(:submitted) { {all_levels_required: true, required: true} }
it "should leave all_levels_required alone" do
is_expected.to eq(all_levels_required: true, required: true)
end
end
context "multilevel, non-required question" do
let(:form) { create(:form, question_types: %w[multilevel_select_one]) }
let(:submitted) { {all_levels_required: true, required: false} }
it "should reset all_levels_required" do
is_expected.to eq(all_levels_required: false, required: false)
end
end
context "non-multilevel question" do
let(:form) { create(:form, question_types: %w[select_one]) }
let(:submitted) { {all_levels_required: true, required: true} }
it "should reset all_levels_required" do
is_expected.to eq(all_levels_required: false, required: true)
end
end
context "non-select question" do
let(:form) { create(:form, question_types: %w[integer]) }
let(:submitted) { {all_levels_required: true, required: true} }
it "should reset all_levels_required" do
is_expected.to eq(all_levels_required: false, required: true)
end
end
end
end
describe "validation" do
let(:questioning) { build(:questioning, default: "Item: calc($Foo + 4) ") }
# Detailed testing of this validator is in own file.
describe "DynamicPatternValidator" do
it "is hooked up properly" do
expect(questioning).to be_invalid
expect(questioning.errors[:default].join).to match(/must surround/)
end
end
it "should fail properly when there is no qtype" do
questioning.qtype_name = nil
expect { questioning.save }.not_to raise_error
end
end
end
| thecartercenter/elmo | spec/models/questioning_spec.rb | Ruby | apache-2.0 | 8,424 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package fixture.simple;
import java.util.List;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Named;
import org.apache.isis.applib.annotation.Prototype;
import org.apache.isis.applib.fixturescripts.FixtureResult;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.apache.isis.applib.fixturescripts.SimpleFixtureScript;
/**
* Enables fixtures to be installed from the application.
*/
@Named("Prototyping")
@DomainService(menuOrder = "20")
public class SimpleObjectsFixturesService extends FixtureScripts {
public SimpleObjectsFixturesService() {
super("fixture.simple");
}
//@Override // compatibility with core 1.5.0
public FixtureScript default0RunFixtureScript() {
return findFixtureScriptFor(SimpleFixtureScript.class);
}
/**
* Raising visibility to <tt>public</tt> so that choices are available for first param
* of {@link #runFixtureScript(FixtureScript, String)}.
*/
@Override
public List<FixtureScript> choices0RunFixtureScript() {
return super.choices0RunFixtureScript();
}
// //////////////////////////////////////
@Prototype
@MemberOrder(sequence="20")
public Object installFixturesAndReturnFirst() {
final List<FixtureResult> run = findFixtureScriptFor(SimpleObjectsFixture.class).run(null);
return run.get(0).getObject();
}
@Prototype
@MemberOrder(sequence="20")
public Object instalarFixturesAlumnos() {
final List<FixtureResult> run = findFixtureScriptFor(AlumnosFixture.class).run(null);
return run.get(0).getObject();
}
@Prototype
@MemberOrder(sequence="20")
public Object instalarFixturesCursos() {
final List<FixtureResult> run = findFixtureScriptFor(CursosFixture.class).run(null);
return run.get(0).getObject();
}
}
| leanddrot/isis-asistencia | fixture/src/main/java/fixture/simple/SimpleObjectsFixturesService.java | Java | apache-2.0 | 2,843 |
package org.qcri.rheem.basic.operators;
import org.apache.commons.lang3.Validate;
import org.qcri.rheem.core.api.Configuration;
import org.qcri.rheem.core.function.DistinctPredicateDescriptor;
import org.qcri.rheem.core.function.PredicateDescriptor;
import org.qcri.rheem.core.optimizer.OptimizationContext;
import org.qcri.rheem.core.optimizer.ProbabilisticDoubleInterval;
import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimate;
import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator;
import org.qcri.rheem.core.optimizer.cardinality.DefaultCardinalityEstimator;
import org.qcri.rheem.core.plan.rheemplan.UnaryToUnaryOperator;
import org.qcri.rheem.core.types.DataSetType;
import java.util.Optional;
/**
* This operator returns the distinct elements in this dataset.
*/
public class DistinctOperator<Type> extends UnaryToUnaryOperator<Type, Type> {
protected final DistinctPredicateDescriptor<Type> predicateDescriptor;
/**
* Creates a new instance.
*
* @param type type of the dataunit elements
*/
public DistinctOperator(DataSetType<Type> type) {
super(type, type, false);
this.predicateDescriptor = null;
}
public DistinctOperator(DataSetType<Type> type, DistinctPredicateDescriptor<Type> predicateDescriptor) {
super(type, type, false);
this.predicateDescriptor = predicateDescriptor;
}
/**
* Creates a new instance.
*
* @param typeClass type of the dataunit elements
*/
public DistinctOperator(Class<Type> typeClass) {
this(DataSetType.createDefault(typeClass));
}
/**
* Copies an instance (exclusive of broadcasts).
*
* @param that that should be copied
*/
public DistinctOperator(DistinctOperator<Type> that) {
super(that);
this.predicateDescriptor = that.getPredicateDescriptor();
}
public DistinctPredicateDescriptor<Type> getPredicateDescriptor() {
return this.predicateDescriptor;
}
public String getSelectKeyString(){
if (this.getPredicateDescriptor() != null && this.getPredicateDescriptor().getUdfSelectivity() != null){
return this.getPredicateDescriptor().getUdfSelectivityKeyString();
} else {
return "";
}
}
// // Assume with a confidence of 0.7 that 70% of the data quanta are pairwise distinct.
// return Optional.of(new DefaultCardinalityEstimator(0.7d, 1, this.isSupportingBroadcastInputs(),
// inputCards -> (long) (inputCards[0] * 0.7d))); // TODO JRK: Do not make baseline worse
@Override
public Optional<org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator> createCardinalityEstimator(
final int outputIndex,
final Configuration configuration) {
Validate.inclusiveBetween(0, this.getNumOutputs() - 1, outputIndex);
return Optional.of(new DistinctOperator.CardinalityEstimator(configuration));
}
private class CardinalityEstimator implements org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator {
/**
* The expected selectivity to be applied in this instance.
*/
private final ProbabilisticDoubleInterval selectivity;
Configuration configuration;
public CardinalityEstimator(Configuration configuration) {
this.selectivity = configuration.getUdfSelectivityProvider().provideFor(DistinctOperator.this.predicateDescriptor);
this.configuration = configuration;
}
@Override
public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) {
Validate.isTrue(inputEstimates.length == DistinctOperator.this.getNumInputs());
final CardinalityEstimate inputEstimate = inputEstimates[0];
String mode = this.configuration.getStringProperty("rheem.optimizer.sr.mode", "best");
if (mode.equals("best")){
mode = this.selectivity.getBest();
}
if (mode.equals("lin")) {
return new CardinalityEstimate(
(long) Math.max(0, ((inputEstimate.getLowerEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getLowerEstimate())),
(long) Math.max(0, ((inputEstimate.getUpperEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getUpperEstimate())),
inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability()
);
} else if (mode.equals("log")) {
return new CardinalityEstimate(
(long) Math.max(0, ((Math.log(inputEstimate.getLowerEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getLowerEstimate())),
(long) Math.max(0, ((Math.log(inputEstimate.getUpperEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getUpperEstimate())),
inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability()
);
} else {
return new CardinalityEstimate(
(long) Math.max(0, (inputEstimate.getLowerEstimate() * this.selectivity.getLowerEstimate())),
(long) Math.max(0, (inputEstimate.getUpperEstimate() * this.selectivity.getUpperEstimate())),
inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability()
);
}
}
}
}
| jonasrk/rheem | rheem-basic/src/main/java/org/qcri/rheem/basic/operators/DistinctOperator.java | Java | apache-2.0 | 5,747 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.phonemetra.turbo.launcher;
import com.phonemetra.turbo.launcher.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.widget.TextView;
public class BubbleTextView extends TextView {
static final float SHADOW_LARGE_RADIUS = 4.0f;
static final float SHADOW_SMALL_RADIUS = 1.75f;
static final float SHADOW_Y_OFFSET = 2.0f;
static final int SHADOW_LARGE_COLOUR = 0xDD000000;
static final int SHADOW_SMALL_COLOUR = 0xCC000000;
static final float PADDING_H = 8.0f;
static final float PADDING_V = 3.0f;
private int mPrevAlpha = -1;
private HolographicOutlineHelper mOutlineHelper;
private final Canvas mTempCanvas = new Canvas();
private final Rect mTempRect = new Rect();
private boolean mDidInvalidateForPressedState;
private Bitmap mPressedOrFocusedBackground;
private int mFocusedOutlineColor;
private int mFocusedGlowColor;
private int mPressedOutlineColor;
private int mPressedGlowColor;
private int mTextColor;
private boolean mShadowsEnabled = true;
private boolean mIsTextVisible;
private boolean mBackgroundSizeChanged;
private Drawable mBackground;
private boolean mStayPressed;
private CheckLongPressHelper mLongPressHelper;
public BubbleTextView(Context context) {
super(context);
init();
}
public BubbleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void onFinishInflate() {
super.onFinishInflate();
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx);
setTextColor(getResources().getColor(R.color.workspace_icon_text_color));
}
private void init() {
mLongPressHelper = new CheckLongPressHelper(this);
mBackground = getBackground();
mOutlineHelper = HolographicOutlineHelper.obtain(getContext());
final Resources res = getContext().getResources();
mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor =
res.getColor(R.color.outline_color);
setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
}
public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Bitmap b = info.getIcon(iconCache);
setCompoundDrawables(null,
Utilities.createIconDrawable(b), null, null);
setCompoundDrawablePadding(grid.iconDrawablePaddingPx);
setText(info.title);
setTag(info);
}
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
if (getLeft() != left || getRight() != right || getTop() != top || getBottom() != bottom) {
mBackgroundSizeChanged = true;
}
return super.setFrame(left, top, right, bottom);
}
@Override
protected boolean verifyDrawable(Drawable who) {
return who == mBackground || super.verifyDrawable(who);
}
@Override
public void setTag(Object tag) {
if (tag != null) {
LauncherModel.checkItemInfo((ItemInfo) tag);
}
super.setTag(tag);
}
@Override
protected void drawableStateChanged() {
if (isPressed()) {
// In this case, we have already created the pressed outline on ACTION_DOWN,
// so we just need to do an invalidate to trigger draw
if (!mDidInvalidateForPressedState) {
setCellLayoutPressedOrFocusedIcon();
}
} else {
// Otherwise, either clear the pressed/focused background, or create a background
// for the focused state
final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null;
if (!mStayPressed) {
mPressedOrFocusedBackground = null;
}
if (isFocused()) {
if (getLayout() == null) {
// In some cases, we get focus before we have been layed out. Set the
// background to null so that it will get created when the view is drawn.
mPressedOrFocusedBackground = null;
} else {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor);
}
mStayPressed = false;
setCellLayoutPressedOrFocusedIcon();
}
final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null;
if (!backgroundEmptyBefore && backgroundEmptyNow) {
setCellLayoutPressedOrFocusedIcon();
}
}
Drawable d = mBackground;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
super.drawableStateChanged();
}
/**
* Draw this BubbleTextView into the given Canvas.
*
* @param destCanvas the canvas to draw on
* @param padding the horizontal and vertical padding to use when drawing
*/
private void drawWithPadding(Canvas destCanvas, int padding) {
final Rect clipRect = mTempRect;
getDrawingRect(clipRect);
// adjust the clip rect so that we don't include the text label
clipRect.bottom =
getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0);
// Draw the View into the bitmap.
// The translate of scrollX and scrollY is necessary when drawing TextViews, because
// they set scrollX and scrollY to large values to achieve centered text
destCanvas.save();
destCanvas.scale(getScaleX(), getScaleY(),
(getWidth() + padding) / 2, (getHeight() + padding) / 2);
destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2);
destCanvas.clipRect(clipRect, Op.REPLACE);
draw(destCanvas);
destCanvas.restore();
}
public void setGlowColor(int color) {
mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = color;
}
/**
* Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
* Responsibility for the bitmap is transferred to the caller.
*/
private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) {
final int padding = mOutlineHelper.mMaxOuterBlurRadius;
final Bitmap b = Bitmap.createBitmap(
getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
drawWithPadding(canvas, padding);
mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor);
canvas.setBitmap(null);
return b;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Call the superclass onTouchEvent first, because sometimes it changes the state to
// isPressed() on an ACTION_UP
boolean result = super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// So that the pressed outline is visible immediately when isPressed() is true,
// we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time
// to create it)
if (mPressedOrFocusedBackground == null) {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mPressedGlowColor, mPressedOutlineColor);
}
// Invalidate so the pressed state is visible, or set a flag so we know that we
// have to call invalidate as soon as the state is "pressed"
if (isPressed()) {
mDidInvalidateForPressedState = true;
setCellLayoutPressedOrFocusedIcon();
} else {
mDidInvalidateForPressedState = false;
}
mLongPressHelper.postCheckForLongPress();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// If we've touched down and up on an item, and it's still not "pressed", then
// destroy the pressed outline
if (!isPressed()) {
mPressedOrFocusedBackground = null;
}
mLongPressHelper.cancelLongPress();
break;
}
return result;
}
void setStayPressed(boolean stayPressed) {
mStayPressed = stayPressed;
if (!stayPressed) {
mPressedOrFocusedBackground = null;
}
setCellLayoutPressedOrFocusedIcon();
}
void setCellLayoutPressedOrFocusedIcon() {
if (getParent() instanceof ShortcutAndWidgetContainer) {
ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) getParent();
if (parent != null) {
CellLayout layout = (CellLayout) parent.getParent();
layout.setPressedOrFocusedIcon((mPressedOrFocusedBackground != null) ? this : null);
}
}
}
void clearPressedOrFocusedBackground() {
mPressedOrFocusedBackground = null;
setCellLayoutPressedOrFocusedIcon();
}
Bitmap getPressedOrFocusedBackground() {
return mPressedOrFocusedBackground;
}
int getPressedOrFocusedBackgroundPadding() {
return mOutlineHelper.mMaxOuterBlurRadius / 2;
}
@Override
public void draw(Canvas canvas) {
if (!mShadowsEnabled) {
super.draw(canvas);
return;
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = getScrollX();
final int scrollY = getScrollY();
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, getRight() - getLeft(), getBottom() - getTop());
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// If text is transparent, don't draw any shadow
if (getCurrentTextColor() == getResources().getColor(android.R.color.transparent)) {
getPaint().clearShadowLayer();
super.draw(canvas);
return;
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(getScrollX(), getScrollY() + getExtendedPaddingTop(),
getScrollX() + getWidth(),
getScrollY() + getHeight(), Region.Op.INTERSECT);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mBackground != null) mBackground.setCallback(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mBackground != null) mBackground.setCallback(null);
}
@Override
public void setTextColor(int color) {
mTextColor = color;
super.setTextColor(color);
}
public void setShadowsEnabled(boolean enabled) {
mShadowsEnabled = enabled;
getPaint().clearShadowLayer();
invalidate();
}
public void setTextVisibility(boolean visible) {
Resources res = getResources();
if (visible) {
super.setTextColor(mTextColor);
} else {
super.setTextColor(res.getColor(android.R.color.transparent));
}
mIsTextVisible = visible;
}
public boolean isTextVisible() {
return mIsTextVisible;
}
@Override
protected boolean onSetAlpha(int alpha) {
if (mPrevAlpha != alpha) {
mPrevAlpha = alpha;
super.onSetAlpha(alpha);
}
return true;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mLongPressHelper.cancelLongPress();
}
}
| Phonemetra/TurboLauncher | app/src/main/java/com/phonemetra/turbo/launcher/BubbleTextView.java | Java | apache-2.0 | 13,912 |
# Scutellaria ovata subsp. bracteata (Benth.) Epling SUBSPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Scutellaria/Scutellaria ovata/Scutellaria ovata bracteata/README.md | Markdown | apache-2.0 | 211 |
/*
* Licensed to Crate.IO GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.operation.merge;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.SettableFuture;
import io.crate.core.collections.ArrayBucket;
import io.crate.core.collections.Bucket;
import io.crate.core.collections.BucketPage;
import io.crate.core.collections.Row;
import io.crate.core.collections.Row1;
import io.crate.core.collections.SingleRowBucket;
import io.crate.operation.PageConsumeListener;
import io.crate.operation.projectors.RowReceiver;
import io.crate.test.integration.CrateUnitTest;
import io.crate.testing.CollectingRowReceiver;
import io.crate.testing.TestingHelpers;
import org.elasticsearch.common.breaker.CircuitBreakingException;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.Mockito;
import javax.annotation.Nonnull;
import java.util.concurrent.Executor;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class IteratorPageDownstreamTest extends CrateUnitTest {
public static final PageConsumeListener PAGE_CONSUME_LISTENER = new PageConsumeListener() {
@Override
public void needMore() {
}
@Override
public void finish() {
}
};
@Mock
PagingIterator<Row> mockedPagingIterator;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testMergeOnPagingIteratorIsCalledAfterALLBucketsAreReady() throws Exception {
IteratorPageDownstream downstream = new IteratorPageDownstream(
new CollectingRowReceiver(), mockedPagingIterator, Optional.<Executor>absent());
SettableFuture<Bucket> b1 = SettableFuture.create();
SettableFuture<Bucket> b2 = SettableFuture.create();
downstream.nextPage(new BucketPage(ImmutableList.of(b1, b2)), PAGE_CONSUME_LISTENER);
verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any());
b1.set(Bucket.EMPTY);
verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any());
b2.set(Bucket.EMPTY);
verify(mockedPagingIterator, times(1)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any());
}
@Test
public void testFailingNextRowIsHandled() throws Exception {
expectedException.expect(CircuitBreakingException.class);
class FailingRowReceiver extends CollectingRowReceiver {
@Override
public boolean setNextRow(Row row) {
throw new CircuitBreakingException("foo");
}
}
CollectingRowReceiver rowReceiver = new FailingRowReceiver();
IteratorPageDownstream downstream = new IteratorPageDownstream(
rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent());
SettableFuture<Bucket> b1 = SettableFuture.create();
downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER);
b1.set(new SingleRowBucket(new Row1(42)));
rowReceiver.result();
}
@Test
public void testBucketFailureIsPassedToDownstream() throws Exception {
IllegalStateException dummy = new IllegalStateException("dummy");
expectedException.expect(IllegalStateException.class);
CollectingRowReceiver rowReceiver = new CollectingRowReceiver();
IteratorPageDownstream downstream = new IteratorPageDownstream(
rowReceiver, mockedPagingIterator, Optional.<Executor>absent());
SettableFuture<Bucket> b1 = SettableFuture.create();
downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER);
b1.setException(dummy);
rowReceiver.result();
}
@Test
public void testMultipleFinishPropagatesOnlyOnceToDownstream() throws Exception {
RowReceiver rowReceiver = mock(RowReceiver.class);
IteratorPageDownstream downstream = new IteratorPageDownstream(
rowReceiver, mockedPagingIterator, Optional.<Executor>absent());
downstream.finish();
downstream.finish();
verify(rowReceiver, times(1)).finish();
}
@Test
public void testFinishDoesNotEmitRemainingRow() throws Exception {
CollectingRowReceiver rowReceiver = CollectingRowReceiver.withLimit(1);
IteratorPageDownstream downstream = new IteratorPageDownstream(
rowReceiver,
PassThroughPagingIterator.<Row>oneShot(),
Optional.<Executor>absent()
);
SettableFuture<Bucket> b1 = SettableFuture.create();
b1.set(new ArrayBucket(
new Object[][]{
new Object[]{"a"},
new Object[]{"b"},
new Object[]{"c"}
}
));
downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER);
downstream.finish();
assertThat(rowReceiver.result().size(), is(1));
}
@Test
public void testRejectedExecutionDoesNotCauseBucketMergerToGetStuck() throws Exception {
expectedException.expect(EsRejectedExecutionException.class);
final CollectingRowReceiver rowReceiver = new CollectingRowReceiver();
IteratorPageDownstream pageDownstream = new IteratorPageDownstream(
rowReceiver,
PassThroughPagingIterator.<Row>oneShot(),
Optional.<Executor>of(new Executor() {
@Override
public void execute(@Nonnull Runnable command) {
throw new EsRejectedExecutionException("HAHA !");
}
}));
SettableFuture<Bucket> b1 = SettableFuture.create();
b1.set(Bucket.EMPTY);
pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), new PageConsumeListener() {
@Override
public void needMore() {
rowReceiver.finish();
}
@Override
public void finish() {
rowReceiver.finish();
}
});
rowReceiver.result();
}
@Test
public void testRepeat() throws Exception {
CollectingRowReceiver rowReceiver = new CollectingRowReceiver();
IteratorPageDownstream pageDownstream = new IteratorPageDownstream(
rowReceiver,
PassThroughPagingIterator.<Row>repeatable(),
Optional.<Executor>absent());
SettableFuture<Bucket> b1 = SettableFuture.create();
b1.set(new ArrayBucket(
new Object[][] {
new Object[] {"a"},
new Object[] {"b"},
new Object[] {"c"}
}
));
pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER);
pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER);
pageDownstream.finish();
rowReceiver.repeatUpstream();
pageDownstream.finish();
assertThat(TestingHelpers.printedTable(rowReceiver.result()), is(
"a\n" +
"b\n" +
"c\n" +
"a\n" +
"b\n" +
"c\n" +
"a\n" +
"b\n" +
"c\n" +
"a\n" +
"b\n" +
"c\n"));
}
@Test
public void testPauseAndResume() throws Exception {
CollectingRowReceiver rowReceiver = CollectingRowReceiver.withPauseAfter(2);
IteratorPageDownstream pageDownstream = new IteratorPageDownstream(
rowReceiver,
PassThroughPagingIterator.<Row>repeatable(),
Optional.<Executor>absent());
SettableFuture<Bucket> b1 = SettableFuture.create();
b1.set(new ArrayBucket(
new Object[][] {
new Object[] {"a"},
new Object[] {"b"},
new Object[] {"c"}
}
));
pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER);
assertThat(rowReceiver.rows.size(), is(2));
rowReceiver.resumeUpstream(false);
assertThat(rowReceiver.rows.size(), is(3));
pageDownstream.finish();
rowReceiver.repeatUpstream();
assertThat(TestingHelpers.printedTable(rowReceiver.result()), is(
"a\n" +
"b\n" +
"c\n" +
"a\n" +
"b\n" +
"c\n"));
}
} | aslanbekirov/crate | sql/src/test/java/io/crate/operation/merge/IteratorPageDownstreamTest.java | Java | apache-2.0 | 9,970 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.frauddetector.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.frauddetector.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteEventsByEventTypeRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteEventsByEventTypeRequestProtocolMarshaller implements Marshaller<Request<DeleteEventsByEventTypeRequest>, DeleteEventsByEventTypeRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AWSHawksNestServiceFacade.DeleteEventsByEventType").serviceName("AmazonFraudDetector").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteEventsByEventTypeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteEventsByEventTypeRequest> marshall(DeleteEventsByEventTypeRequest deleteEventsByEventTypeRequest) {
if (deleteEventsByEventTypeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteEventsByEventTypeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, deleteEventsByEventTypeRequest);
protocolMarshaller.startMarshalling();
DeleteEventsByEventTypeRequestMarshaller.getInstance().marshall(deleteEventsByEventTypeRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/transform/DeleteEventsByEventTypeRequestProtocolMarshaller.java | Java | apache-2.0 | 2,836 |
import Future = require("fibers/future");
import * as npm from "npm";
interface INpmOpts {
config?: any;
subCommandName?: string;
path?: string;
}
export class NodePackageManager implements INodePackageManager {
constructor(private $childProcess: IChildProcess,
private $logger: ILogger,
private $options: IOptions) { }
public getCache(): string {
return npm.cache;
}
public load(config?: any): IFuture<void> {
if (npm.config.loaded) {
let data = npm.config.sources.cli.data;
Object.keys(data).forEach(k => delete data[k]);
if (config) {
_.assign(data, config);
}
return Future.fromResult();
} else {
let future = new Future<void>();
npm.load(config, (err: Error) => {
if (err) {
future.throw(err);
} else {
future.return();
}
});
return future;
}
}
public install(packageName: string, pathToSave: string, config?: any): IFuture<any> {
return (() => {
if (this.$options.disableNpmInstall) {
return;
}
if (this.$options.ignoreScripts) {
config = config || {};
config["ignore-scripts"] = true;
}
try {
return this.loadAndExecute("install", [pathToSave, packageName], { config: config }).wait();
} catch (err) {
if (err.code === "EPEERINVALID") {
// Not installed peer dependencies are treated by npm 2 as errors, but npm 3 treats them as warnings.
// We'll show them as warnings and let the user install them in case they are needed.
// The strucutre of the error object in such case is:
// { [Error: The package @angular/[email protected] does not satisfy its siblings' peerDependencies requirements!]
// code: 'EPEERINVALID',
// packageName: '@angular/core',
// packageVersion: '2.1.0-beta.0',
// peersDepending:
// { '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@angular/[email protected]': '2.1.0-beta.0',
// '@ngrx/[email protected]': '^2.0.0',
// '@ngrx/[email protected]': '^2.0.0',
// '[email protected]': '~2.0.0' } }
this.$logger.warn(err.message);
this.$logger.trace("Required peerDependencies are: ", err.peersDepending);
} else {
// All other errors should be handled by the caller code.
throw err;
}
}
}).future<any>()();
}
public uninstall(packageName: string, config?: any, path?: string): IFuture<any> {
return this.loadAndExecute("uninstall", [[packageName]], { config, path });
}
public search(filter: string[], silent: boolean): IFuture<any> {
let args = (<any[]>([filter] || [])).concat(silent);
return this.loadAndExecute("search", args);
}
public cache(packageName: string, version: string, config?: any): IFuture<IDependencyData> {
// function cache (pkg, ver, where, scrub, cb)
return this.loadAndExecute("cache", [packageName, version, undefined, false], { subCommandName: "add", config: config });
}
public cacheUnpack(packageName: string, version: string, unpackTarget?: string): IFuture<void> {
// function unpack (pkg, ver, unpackTarget, dMode, fMode, uid, gid, cb)
return this.loadAndExecute("cache", [packageName, version, unpackTarget, null, null, null, null], { subCommandName: "unpack" });
}
public view(packageName: string, propertyName: string): IFuture<any> {
return this.loadAndExecute("view", [[packageName, propertyName], [false]]);
}
public executeNpmCommand(npmCommandName: string, currentWorkingDirectory: string): IFuture<any> {
return this.$childProcess.exec(npmCommandName, { cwd: currentWorkingDirectory });
}
private loadAndExecute(commandName: string, args: any[], opts?: INpmOpts): IFuture<any> {
return (() => {
opts = opts || {};
this.load(opts.config).wait();
return this.executeCore(commandName, args, opts).wait();
}).future<any>()();
}
private executeCore(commandName: string, args: any[], opts?: INpmOpts): IFuture<any> {
let future = new Future<any>();
let oldNpmPath: string = undefined;
let callback = (err: Error, data: any) => {
if (oldNpmPath) {
npm.prefix = oldNpmPath;
}
if (err) {
future.throw(err);
} else {
future.return(data);
}
};
args.push(callback);
if (opts && opts.path) {
oldNpmPath = npm.prefix;
npm.prefix = opts.path;
}
let subCommandName: string = opts.subCommandName;
let command = subCommandName ? npm.commands[commandName][subCommandName] : npm.commands[commandName];
command.apply(this, args);
return future;
}
}
$injector.register("npm", NodePackageManager);
| tsvetie/nativescript-cli | lib/node-package-manager.ts | TypeScript | apache-2.0 | 4,909 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.sling;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import javax.jcr.Repository;
import org.apache.jackrabbit.oak.api.ContentRepository;
import org.apache.jackrabbit.oak.spi.security.SecurityProvider;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
public class Activator implements BundleActivator, ServiceTrackerCustomizer {
private BundleContext context;
private ScheduledExecutorService executor;
private SecurityProvider securityProvider;
private ServiceTracker tracker;
private final Map<ServiceReference, ServiceRegistration> jcrRepositories =
new HashMap<ServiceReference, ServiceRegistration>();
private final Map<ServiceReference, ServiceRegistration> slingRepositories =
new HashMap<ServiceReference, ServiceRegistration>();
//-----------------------------------------------------< BundleActivator >--
@Override
public void start(BundleContext bundleContext) throws Exception {
context = bundleContext;
executor = Executors.newScheduledThreadPool(1);
securityProvider = null; // TODO
tracker = new ServiceTracker(
context, ContentRepository.class.getName(), this);
tracker.open();
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
tracker.close();
executor.shutdown();
}
//--------------------------------------------< ServiceTrackerCustomizer >--
@Override
public Object addingService(ServiceReference reference) {
Object service = context.getService(reference);
if (service instanceof ContentRepository) {
SlingRepository repository = new SlingRepositoryImpl(
(ContentRepository) service, executor, securityProvider);
jcrRepositories.put(reference, context.registerService(
Repository.class.getName(),
repository, new Properties()));
slingRepositories.put(reference, context.registerService(
SlingRepository.class.getName(),
repository, new Properties()));
return service;
} else {
context.ungetService(reference);
return null;
}
}
@Override
public void modifiedService(ServiceReference reference, Object service) {
}
@Override
public void removedService(ServiceReference reference, Object service) {
slingRepositories.get(reference).unregister();
jcrRepositories.get(reference).unregister();
context.ungetService(reference);
}
}
| tteofili/jackrabbit-oak | oak-sling/src/main/java/org/apache/jackrabbit/oak/sling/Activator.java | Java | apache-2.0 | 3,841 |
/*
* Copyright 1999-2101 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastjson.parser;
/**
* @author wenshao[[email protected]]
*/
public class JSONToken {
//
public final static int ERROR = 1;
//
public final static int LITERAL_INT = 2;
//
public final static int LITERAL_FLOAT = 3;
//
public final static int LITERAL_STRING = 4;
//
public final static int LITERAL_ISO8601_DATE = 5;
public final static int TRUE = 6;
//
public final static int FALSE = 7;
//
public final static int NULL = 8;
//
public final static int NEW = 9;
//
public final static int LPAREN = 10; // ("("),
//
public final static int RPAREN = 11; // (")"),
//
public final static int LBRACE = 12; // ("{"),
//
public final static int RBRACE = 13; // ("}"),
//
public final static int LBRACKET = 14; // ("["),
//
public final static int RBRACKET = 15; // ("]"),
//
public final static int COMMA = 16; // (","),
//
public final static int COLON = 17; // (":"),
//
public final static int IDENTIFIER = 18;
//
public final static int FIELD_NAME = 19;
public final static int EOF = 20;
public final static int SET = 21;
public final static int TREE_SET = 22;
public final static int UNDEFINED = 23; // undefined
public static String name(int value) {
switch (value) {
case ERROR:
return "error";
case LITERAL_INT:
return "int";
case LITERAL_FLOAT:
return "float";
case LITERAL_STRING:
return "string";
case LITERAL_ISO8601_DATE:
return "iso8601";
case TRUE:
return "true";
case FALSE:
return "false";
case NULL:
return "null";
case NEW:
return "new";
case LPAREN:
return "(";
case RPAREN:
return ")";
case LBRACE:
return "{";
case RBRACE:
return "}";
case LBRACKET:
return "[";
case RBRACKET:
return "]";
case COMMA:
return ",";
case COLON:
return ":";
case IDENTIFIER:
return "ident";
case FIELD_NAME:
return "fieldName";
case EOF:
return "EOF";
case SET:
return "Set";
case TREE_SET:
return "TreeSet";
case UNDEFINED:
return "undefined";
default:
return "Unkown";
}
}
}
| xiepengchong/FactoryZxing | src/com/alibaba/fastjson/parser/JSONToken.java | Java | apache-2.0 | 3,656 |
package com.github.obourgain.elasticsearch.http.response.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.common.xcontent.XContentParser;
import com.github.obourgain.elasticsearch.http.response.entity.Indices;
import com.github.obourgain.elasticsearch.http.response.entity.ShardFailure;
import com.github.obourgain.elasticsearch.http.response.entity.Shards;
import lombok.Getter;
@Getter
public class IndicesParser {
private static List<ShardFailure> failures;
public static Indices parse(XContentParser parser) {
Map<String, Shards> result = new HashMap<>();
try {
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
failures = ShardFailure.parse(parser);
} else if (token == XContentParser.Token.START_OBJECT) {
Shards shards = new Shards().parse(parser);
result.put(currentFieldName, shards);
}
}
return Indices.fromMap(result);
} catch (IOException e) {
throw new RuntimeException("Unable to parse source", e);
}
}
}
| obourgain/elasticsearch-http | src/main/java/com/github/obourgain/elasticsearch/http/response/parser/IndicesParser.java | Java | apache-2.0 | 1,496 |
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.carlomicieli.nerdmovies.controllers;
import com.github.carlomicieli.nerdmovies.services.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author Carlo Micieli
*/
@Controller
@RequestMapping("/")
public class HomeController {
private MovieService movieService;
@Autowired
public HomeController(MovieService movieService) {
this.movieService = movieService;
}
@RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET)
public String index(Model model) {
model.addAttribute("movies", movieService.getRecentMovies(10));
return "home/index";
}
@RequestMapping(value = "/about", method = RequestMethod.GET)
public String about() {
return "home/about";
}
@RequestMapping(value = "/default", method = RequestMethod.GET)
public String defaultPage() {
return "home/index";
}
}
| CarloMicieli/spring-mvc-movies | src/main/java/com/github/carlomicieli/nerdmovies/controllers/HomeController.java | Java | apache-2.0 | 1,759 |
package com.camillepradel.movierecommender.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
public class CsvToMySql {
static final String pathToCsvFiles = "D:\\MovieRecommender\\src\\main\\java\\com\\camillepradel\\movierecommender\\utils\\";
static final String usersCsvFile = pathToCsvFiles + "users.csv";
static final String moviesCsvFile = pathToCsvFiles + "movies.csv";
static final String genresCsvFile = pathToCsvFiles + "genres.csv";
static final String movGenreCsvFile = pathToCsvFiles + "mov_genre.csv";
static final String ratingsCsvFile = pathToCsvFiles + "ratings.csv";
static final String friendsCsvFile = pathToCsvFiles + "friends.csv";
static final String cvsSplitBy = ",";
private static void commitUsers(Connection connection) throws SQLException {
System.out.println(usersCsvFile);
// create table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (\n"
+ " id int(11) NOT NULL AUTO_INCREMENT,\n"
+ " age int(11) NOT NULL,\n"
+ " sex varchar(1) NOT NULL,\n"
+ " occupation varchar(60) NOT NULL,\n"
+ " zip varchar(6) NOT NULL,\n"
+ " PRIMARY KEY (`id`)\n"
+ ");");
// populate table
try (BufferedReader br = new BufferedReader(new FileReader(usersCsvFile))) {
String insertQuery = "INSERT INTO users (id, age, sex, occupation, zip) VALUES (?, ?, ?, ?, ?)";
PreparedStatement insertUsers = null;
try {
connection.setAutoCommit(false);
insertUsers = connection.prepareStatement(insertQuery);
String line;
br.readLine(); // skip first line
while ((line = br.readLine()) != null) {
String[] values = line.split(cvsSplitBy);
insertUsers.setInt(1, Integer.parseInt(values[0]));
insertUsers.setInt(2, Integer.parseInt(values[1]));
insertUsers.setString(3, values[2]);
insertUsers.setString(4, values[3]);
insertUsers.setString(5, values[4]);
insertUsers.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (insertUsers != null) {
insertUsers.close();
}
connection.setAutoCommit(true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void commitMovies(Connection connection) throws SQLException {
// movies.csv
System.out.println(moviesCsvFile);
// create table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS movies (\n"
+ " id int(11) NOT NULL AUTO_INCREMENT,\n"
+ " title varchar(200) NOT NULL,\n"
+ " date date NOT NULL,\n"
+ " PRIMARY KEY (`id`)\n"
+ ");");
// populate table
try (BufferedReader br = new BufferedReader(new FileReader(moviesCsvFile))) {
String insertQuery = "INSERT INTO movies (id, title, date) VALUES (?, ?, ?)";
PreparedStatement insertMovies = null;
try {
connection.setAutoCommit(false);
insertMovies = connection.prepareStatement(insertQuery);
String line;
br.readLine(); // skip first line
while ((line = br.readLine()) != null) {
String[] values = line.split(cvsSplitBy);
int movieId = Integer.parseInt(values[0]);
String title = String.join(",", Arrays.copyOfRange(values, 1, values.length - 1));
Date date = new Date(Long.parseLong(values[values.length - 1]) * 1000);
insertMovies.setInt(1, movieId);
insertMovies.setString(2, title);
insertMovies.setDate(3, date);
insertMovies.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (insertMovies != null) {
insertMovies.close();
}
connection.setAutoCommit(true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void commitGenres(Connection connection) throws SQLException {
// genres.csv
System.out.println(genresCsvFile);
// create table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS genres (\n"
+ " name varchar(60) NOT NULL,\n"
+ " id int(11) NOT NULL AUTO_INCREMENT,\n"
+ " PRIMARY KEY (`id`)\n"
+ ");");
// necessary to make mySQL accept 0 as a valid id value for genre unknown
statement.execute("SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';");
// populate table
try (BufferedReader br = new BufferedReader(new FileReader(genresCsvFile))) {
String insertQuery = "INSERT INTO genres (name, id) VALUES (?, ?)";
PreparedStatement insertGenres = null;
try {
connection.setAutoCommit(false);
insertGenres = connection.prepareStatement(insertQuery);
String line;
br.readLine(); // skip first line
while ((line = br.readLine()) != null) {
String[] values = line.split(cvsSplitBy);
String name = values[0];
int genreId = Integer.parseInt(values[1]);
insertGenres.setString(1, name);
insertGenres.setInt(2, genreId);
insertGenres.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (insertGenres != null) {
insertGenres.close();
}
connection.setAutoCommit(true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void commitMovieGenre(Connection connection) throws SQLException {
// mov_genre.csv
System.out.println(movGenreCsvFile);
// create table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS movie_genre (\n"
+ " movie_id int(11) NOT NULL,\n"
+ " genre_id int(11) NOT NULL,\n"
+ " KEY movie_id (movie_id),\n"
+ " KEY genre_id (genre_id)\n"
+ ");");
statement.executeUpdate("ALTER TABLE movie_genre\n"
+ " ADD CONSTRAINT movie_genre_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n");
statement.executeUpdate("ALTER TABLE movie_genre\n"
+ " ADD CONSTRAINT movie_genre_to_genre FOREIGN KEY (genre_id) REFERENCES genres(id) ON DELETE CASCADE ON UPDATE CASCADE;\n");
// populate table
try (BufferedReader br = new BufferedReader(new FileReader(movGenreCsvFile))) {
String insertQuery = "INSERT INTO movie_genre (movie_id, genre_id) VALUES (?, ?)";
PreparedStatement insertMovieGenre = null;
try {
connection.setAutoCommit(false);
insertMovieGenre = connection.prepareStatement(insertQuery);
String line;
br.readLine(); // skip first line
while ((line = br.readLine()) != null) {
String[] values = line.split(cvsSplitBy);
int movieId = Integer.parseInt(values[0]);
int genreId = Integer.parseInt(values[1]);
insertMovieGenre.setInt(1, movieId);
insertMovieGenre.setInt(2, genreId);
insertMovieGenre.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (insertMovieGenre != null) {
insertMovieGenre.close();
}
connection.setAutoCommit(true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void commitRatings(Connection connection) throws SQLException {
// ratings.csv
System.out.println(ratingsCsvFile);
// create table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS ratings (\n"
+ " user_id int(11) NOT NULL,\n"
+ " movie_id int(11) NOT NULL,\n"
+ " rating int(11) NOT NULL,\n"
+ " date date NOT NULL,\n"
+ " KEY user_id (user_id),\n"
+ " KEY movie_id (movie_id)\n"
+ ");");
statement.executeUpdate("ALTER TABLE ratings\n"
+ " ADD CONSTRAINT ratings_to_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n");
statement.executeUpdate("ALTER TABLE ratings\n"
+ " ADD CONSTRAINT ratings_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n");
statement.executeUpdate("ALTER TABLE ratings\n"
+ " ADD UNIQUE unique_index(user_id, movie_id);\n");
// populate table
try (BufferedReader br = new BufferedReader(new FileReader(ratingsCsvFile))) {
String insertQuery = "INSERT INTO ratings (user_id, movie_id, rating, date) VALUES (?, ?, ?, ?)";
PreparedStatement insertRatings = null;
try {
connection.setAutoCommit(false);
insertRatings = connection.prepareStatement(insertQuery);
String line;
br.readLine(); // skip first line
while ((line = br.readLine()) != null) {
String[] values = line.split(cvsSplitBy);
int userId = Integer.parseInt(values[0]);
int movieId = Integer.parseInt(values[1]);
int ratingValue = Integer.parseInt(values[2]);
Date date = new Date(Long.parseLong(values[3]) * 1000);
insertRatings.setInt(1, userId);
insertRatings.setInt(2, movieId);
insertRatings.setInt(3, ratingValue);
insertRatings.setDate(4, date);
insertRatings.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (insertRatings != null) {
insertRatings.close();
}
connection.setAutoCommit(true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void commitFriends(Connection connection) throws SQLException {
// friends.csv
System.out.println(friendsCsvFile);
// create table
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS friends (\n"
+ " user1_id int(11) NOT NULL,\n"
+ " user2_id int(11) NOT NULL,\n"
+ " KEY user1_id (user1_id),\n"
+ " KEY user2_id (user2_id)\n"
+ ");");
statement.executeUpdate("ALTER TABLE friends\n"
+ " ADD CONSTRAINT friends_to_user1 FOREIGN KEY (user1_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n");
statement.executeUpdate("ALTER TABLE friends\n"
+ " ADD CONSTRAINT friends_to_user2 FOREIGN KEY (user2_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n");
// populate table
try (BufferedReader br = new BufferedReader(new FileReader(friendsCsvFile))) {
String insertQuery = "INSERT INTO friends (user1_id, user2_id) VALUES (?, ?)";
PreparedStatement insertFriends = null;
try {
connection.setAutoCommit(false);
insertFriends = connection.prepareStatement(insertQuery);
String line;
br.readLine(); // skip first line
while ((line = br.readLine()) != null) {
String[] values = line.split(cvsSplitBy);
int user1Id = Integer.parseInt(values[0]);
int user2Id = Integer.parseInt(values[1]);
insertFriends.setInt(1, user1Id);
insertFriends.setInt(2, user2Id);
insertFriends.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (insertFriends != null) {
insertFriends.close();
}
connection.setAutoCommit(true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// load JDBC driver
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// db connection info
String url = "jdbc:mysql://localhost:3306"
+ "?zeroDateTimeBehavior=convertToNull&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
String login = "admin";
String password = "Q86PhnJRiEa7";
Connection connection = null;
try {
connection = DriverManager.getConnection(url, login, password);
Statement statement = connection.createStatement();
// create database
statement.executeUpdate("DROP DATABASE IF EXISTS movie_recommender;");
statement.executeUpdate("CREATE DATABASE movie_recommender;");
statement.executeUpdate("USE movie_recommender;");
commitUsers(connection);
commitMovies(connection);
commitGenres(connection);
commitMovieGenre(connection);
commitRatings(connection);
commitFriends(connection);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
// exception occured while closing connexion -> nothing else can be done
}
}
}
System.out.println("done");
}
}
| Camille31/MovieRecommender | src/main/java/com/camillepradel/movierecommender/utils/CsvToMySql.java | Java | apache-2.0 | 17,630 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.cache.EntryDestroyedException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.query.AmbiguousNameException;
import org.apache.geode.cache.query.FunctionDomainException;
import org.apache.geode.cache.query.NameResolutionException;
import org.apache.geode.cache.query.QueryInvocationTargetException;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.TypeMismatchException;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.pdx.PdxInstance;
import org.apache.geode.pdx.PdxSerializationException;
import org.apache.geode.pdx.internal.InternalPdxInstance;
import org.apache.geode.pdx.internal.PdxString;
/**
* Class Description
*
* @version $Revision: 1.1 $
*/
public class CompiledOperation extends AbstractCompiledValue {
private final CompiledValue receiver; // may be null if implicit to scope
private final String methodName;
private final List args;
@MakeNotStatic
private static final ConcurrentMap cache = new ConcurrentHashMap();
// receiver is an ID or PATH that contains the operation name
public CompiledOperation(CompiledValue receiver, String methodName, List args) {
this.receiver = receiver;
this.methodName = methodName;
this.args = args;
}
@Override
public List getChildren() {
List list = new ArrayList();
if (this.receiver != null) {
list.add(this.receiver);
}
list.addAll(this.args);
return list;
}
public String getMethodName() {
return this.methodName;
}
public List getArguments() {
return this.args;
}
@Override
public int getType() {
return METHOD_INV;
}
public CompiledValue getReceiver(ExecutionContext cxt) {
// receiver may be cached in execution context
if (this.receiver == null && cxt != null) {
return (CompiledValue) cxt.cacheGet(this);
}
return this.receiver;
}
@Override
public boolean hasIdentifierAtLeafNode() {
if (this.receiver.getType() == Identifier) {
return true;
} else {
return this.receiver.hasIdentifierAtLeafNode();
}
}
@Override
public CompiledValue getReceiver() {
return this.getReceiver(null);
}
@Override
public Object evaluate(ExecutionContext context) throws FunctionDomainException,
TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
CompiledValue rcvr = getReceiver(context);
Object result;
Object evalRcvr;
if (rcvr == null) { // must be intended as implicit iterator operation
// see if it's an implicit operation name
RuntimeIterator rcvrItr =
context.resolveImplicitOperationName(this.methodName, this.args.size(), true);
evalRcvr = rcvrItr.evaluate(context);
/*
* // evaluate on current iteration of collection if (rcvrItr != null) { result =
* eval0(rcvrItr.evaluate(context), rcvrItr.getElementType().resolveClass(), context); }
*
* // function call: no functions implemented except keywords in the grammar throw new
* TypeMismatchException("Could not resolve method named 'xyz'")
*/
} else {
// if not null, then explicit receiver
evalRcvr = rcvr.evaluate(context);
}
// short circuit null immediately
if (evalRcvr == null) {
return QueryService.UNDEFINED;
}
if (context.isCqQueryContext() && evalRcvr instanceof Region.Entry) {
Region.Entry re = (Region.Entry) evalRcvr;
if (re.isDestroyed()) {
return QueryService.UNDEFINED;
}
try {
evalRcvr = re.getValue();
} catch (EntryDestroyedException ede) {
// Even though isDestory() check is made, the entry could
// throw EntryDestroyedException if the value becomes null.
return QueryService.UNDEFINED;
}
}
// check if the receiver is the iterator, in which
// case we resolve the method on the constraint rather
// than the runtime type of the receiver
Class resolveClass = null;
// commented out because we currently always resolve the method
// on the runtime types
// CompiledValue rcvrVal = rcvrPath.getReceiver();
// if (rcvrVal.getType() == ID)
// {
// CompiledValue resolvedID = context.resolve(((CompiledID)rcvrVal).getId());
// if (resolvedID.getType() == ITERATOR)
// {
// resolveClass = ((RuntimeIterator)resolvedID).getBaseCollection().getConstraint();
// }
// }
// if (resolveClass == null)
if (evalRcvr instanceof PdxInstance) {
String className = ((PdxInstance) evalRcvr).getClassName();
try {
resolveClass = InternalDataSerializer.getCachedClass(className);
} catch (ClassNotFoundException cnfe) {
throw new QueryInvocationTargetException(cnfe);
}
} else if (evalRcvr instanceof PdxString) {
resolveClass = String.class;
} else {
resolveClass = evalRcvr.getClass();
}
result = eval0(evalRcvr, resolveClass, context);
// }
// check for PR substitution
// check for BucketRegion substitution
PartitionedRegion pr = context.getPartitionedRegion();
if (pr != null && (result instanceof Region)) {
if (pr.getFullPath().equals(((Region) result).getFullPath())) {
result = context.getBucketRegion();
}
}
return result;
}
@Override
public Set computeDependencies(ExecutionContext context)
throws TypeMismatchException, AmbiguousNameException, NameResolutionException {
List args = this.args;
Iterator i = args.iterator();
while (i.hasNext()) {
context.addDependencies(this, ((CompiledValue) i.next()).computeDependencies(context));
}
CompiledValue rcvr = getReceiver(context);
if (rcvr == null) // implicit iterator operation
{
// see if it's an implicit operation name
RuntimeIterator rcvrItr =
context.resolveImplicitOperationName(this.methodName, this.args.size(), true);
if (rcvrItr == null) { // no receiver resolved
// function call: no functions implemented except keywords in the grammar
throw new TypeMismatchException(
String.format("Could not resolve method named ' %s '",
this.methodName));
}
// cache the receiver so we don't have to resolve it again
context.cachePut(this, rcvrItr);
return context.addDependency(this, rcvrItr);
}
// receiver is explicit
return context.addDependencies(this, rcvr.computeDependencies(context));
}
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED",
justification = "Does not matter if the methodDispatch that isn't stored in the map is used")
private Object eval0(Object receiver, Class resolutionType, ExecutionContext context)
throws TypeMismatchException, FunctionDomainException, NameResolutionException,
QueryInvocationTargetException {
if (receiver == null || receiver == QueryService.UNDEFINED)
return QueryService.UNDEFINED;
List args = new ArrayList();
List argTypes = new ArrayList();
Iterator i = this.args.iterator();
while (i.hasNext()) {
CompiledValue arg = (CompiledValue) i.next();
Object o = arg.evaluate(context);
// undefined arg produces undefines method result
if (o == QueryService.UNDEFINED)
return QueryService.UNDEFINED;
args.add(o);
// pass in null for the type if the runtime value is null
if (o == null)
argTypes.add(null);
// commented out because we currently always use the runtime type for args
// else if (arg.getType() == Identifier)
// {
// CompiledValue resolved = context.resolve(((CompiledID)arg).getId());
// if (resolved != null && resolved.getType() == ITERATOR)
// argTypes.add(((RuntimeIterator)resolved).getBaseCollection().getConstraint());
// else
// argTypes.add(o.getClass());
// }
else
argTypes.add(o.getClass()); // otherwise use the runtime type
}
// see if in cache
MethodDispatch methodDispatch;
List key = Arrays.asList(new Object[] {resolutionType, this.methodName, argTypes});
methodDispatch = (MethodDispatch) CompiledOperation.cache.get(key);
if (methodDispatch == null) {
try {
methodDispatch =
new MethodDispatch(context.getCache().getQueryService().getMethodInvocationAuthorizer(),
resolutionType, this.methodName, argTypes);
} catch (NameResolutionException nre) {
if (!org.apache.geode.cache.query.Struct.class.isAssignableFrom(resolutionType)
&& (DefaultQueryService.QUERY_HETEROGENEOUS_OBJECTS
|| DefaultQueryService.TEST_QUERY_HETEROGENEOUS_OBJECTS)) {
return QueryService.UNDEFINED;
} else {
throw nre;
}
}
// cache
CompiledOperation.cache.putIfAbsent(key, methodDispatch);
}
if (receiver instanceof InternalPdxInstance) {
try {
receiver = ((InternalPdxInstance) receiver).getCachedObject();
} catch (PdxSerializationException ex) {
throw new QueryInvocationTargetException(ex);
}
} else if (receiver instanceof PdxString) {
receiver = ((PdxString) receiver).toString();
}
return methodDispatch.invoke(receiver, args);
}
// Asif :Function for generating from clause
@Override
public void generateCanonicalizedExpression(StringBuilder clauseBuffer, ExecutionContext context)
throws AmbiguousNameException, TypeMismatchException, NameResolutionException {
// Asif: if the method name starts with getABC & argument list is empty
// then canonicalize it to aBC
int len;
if (this.methodName.startsWith("get") && (len = this.methodName.length()) > 3
&& (this.args == null || this.args.isEmpty())) {
clauseBuffer.insert(0, len > 4 ? this.methodName.substring(4) : "");
clauseBuffer.insert(0, Character.toLowerCase(this.methodName.charAt(3)));
} else if (this.args == null || this.args.isEmpty()) {
clauseBuffer.insert(0, "()").insert(0, this.methodName);
} else {
// The method contains arguments which need to be canonicalized
clauseBuffer.insert(0, ')');
CompiledValue cv = null;
for (int j = this.args.size(); j > 0;) {
cv = (CompiledValue) this.args.get(--j);
cv.generateCanonicalizedExpression(clauseBuffer, context);
clauseBuffer.insert(0, ',');
}
clauseBuffer.deleteCharAt(0).insert(0, '(').insert(0, this.methodName);
}
clauseBuffer.insert(0, '.');
CompiledValue rcvr = this.receiver;
if (rcvr == null) {
// must be intended as implicit iterator operation
// see if it's an implicit operation name. The receiver will now be RuntimeIterator
rcvr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true);
}
rcvr.generateCanonicalizedExpression(clauseBuffer, context);
}
}
| PurelyApplied/geode | geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledOperation.java | Java | apache-2.0 | 12,213 |
package com.turlir.abakgists.allgists.view.listing;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
abstract class ModelViewHolder<T> extends RecyclerView.ViewHolder {
ModelViewHolder(View itemView) {
super(itemView);
}
abstract void bind(T model);
}
| iljaosintsev/Apress-Gists | app/src/main/java/com/turlir/abakgists/allgists/view/listing/ModelViewHolder.java | Java | apache-2.0 | 305 |
package com.zuoqing.demo.entity;
/**
* http 请求返回的最外层对象
*/
public class Result<T> {
private Integer code;
private String msg;
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
| zuoqing135du/SpringBoot | src/main/java/com/zuoqing/demo/entity/Result.java | Java | apache-2.0 | 569 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package libthrift091;
public interface TEnum {
public int getValue();
}
| XiaoMi/galaxy-sdk-java | galaxy-thrift-api/src/main/java/libthrift091/TEnum.java | Java | apache-2.0 | 880 |
@*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*@
@import iht.models.RegistrationDetails
@import iht.models.application.tnrb._
@import iht.utils._
@import iht.utils.tnrb.TnrbHelperFixture
@import iht.models.application.tnrb.TnrbEligibiltyModel
@import iht.models.application.tnrb.WidowCheck
@import iht.config.AppConfig
@this(
implicit val appConfig: AppConfig,
form: FormWithCSRF,
ihtMainTemplateApplication: iht_main_template_application,
errorSummary: ihtHelpers.custom.error_summary,
inputYesNoRadioGroup: ihtHelpers.standard.input_yes_no_radio_group
)
@(partnerLivingInUkForm:Form[TnrbEligibiltyModel],
tnrbModel: TnrbEligibiltyModel,
widowCheck: WidowCheck,
cancelUrl:Call, registrationDetails: RegistrationDetails)(implicit request:Request[_], messages: Messages)
@deceasedName() = @{CommonHelper.getOrException(registrationDetails.deceasedDetails).name}
@partnerName() = @{TnrbHelperFixture().spouseOrCivilPartnerLabelGenitive(tnrbModel, widowCheck, deceasedName, true)}
@ihtMainTemplateApplication(
title = "",
browserTitle = Some(Messages("iht.registration.deceased.locationOfPermanentHome")),
cancelLabel=Some(Messages("page.iht.application.tnrb.returnToIncreasingThreshold")),
cancelUrl = Some(cancelUrl)
){
@errorSummary(partnerLivingInUkForm)
@form(action = iht.controllers.application.tnrb.routes.PermanentHomeController.onSubmit,'autoComplete -> "off") {
@inputYesNoRadioGroup(
partnerLivingInUkForm("isPartnerLivingInUk"),
'_hintText -> Html(Messages("page.iht.application.tnrb.permanentHome.question.hint")),
'_divClass -> Some("form-group"),
'_legend -> Messages("iht.estateReport.tnrb.permanentHome.question",partnerName),
'_legendClass -> Some("legend-with-heading"),
'_legendIsHeading -> true,
'_headingClass -> "heading-large"
)
<div id="action-button" class="form-group">
<button class="button" id="save-continue" name="action" value="save">@Messages("iht.saveAndContinue")</button>
</div>
}
}
| hmrc/iht-frontend | app/iht/views/application/tnrb/permanent_home.scala.html | HTML | apache-2.0 | 2,657 |
/*
* Copyright (c) 2013 EMBL - European Bioinformatics Institute
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
var lodeNamespacePrefixes = {
rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
owl: 'http://www.w3.org/2002/07/owl#',
dc: 'http://purl.org/dc/elements/1.1/',
dcterms: 'http://purl.org/dc/terms/',
obo: 'http://purl.obolibrary.org/obo/',
efo: 'http://www.ebi.ac.uk/efo/',
'biosd-terms': 'http://rdf.ebi.ac.uk/terms/biosd/',
pav: 'http://purl.org/pav/2.0/',
prov: 'http://www.w3.org/ns/prov#',
foaf: 'http://xmlns.com/foaf/0.1/',
sio: 'http://semanticscience.org/resource/',
atlas: 'http://rdf.ebi.ac.uk/terms/atlas/',
oac: 'http://www.openannotation.org/ns/'
};
| EBIBioSamples/lodestar | web-ui/src/main/webapp/scripts/namespaces.js | JavaScript | apache-2.0 | 1,394 |
package utils
import java.io.{BufferedReader, File, InputStreamReader}
import scala.io.Source
/**
* Created by yujieshui on 2016/8/30.
*/
object NextLine {
type NextLine = () => String
def fromSystemIn(): NextLine = {
val bi = new BufferedReader(new InputStreamReader(System.in))
() => bi.readLine()
}
def fromFile(file: File): NextLine = {
fromSeq(Source.fromFile(file).getLines().toSeq)
}
def fromSeq(seq: Seq[String]): NextLine = {
var list = seq
() => {
val r = list.head
list = list.tail
r
}
}
} | 1178615156/hackerrank | src/main/scala/utils/NextLine.scala | Scala | apache-2.0 | 568 |
/*
* Copyright to the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rioproject.tools.cli;
import java.io.BufferedReader;
import java.io.PrintStream;
/**
* Define plugin interface for CLI option handlers. An OptionHandler is
* responsible for providing a option, or activity, that will be used through
* the CLI.
*
* @author Dennis Reedy
*/
public interface OptionHandler {
/**
* Process the option.
*
* @param input Parameters for the option, may be null
* @param br An optional BufferdReader, used if the option requires input.
* if this is null, the option handler may create a BufferedReader to
* handle the input
* @param out The PrintStream to use if the option prints results or
* choices for the user. Must not be null
*
* @return The result of the action.
*/
String process(String input, BufferedReader br, PrintStream out);
/**
* Get the usage of the command
*
* @return Command usage
*/
String getUsage();
}
| dreedyman/Rio | rio-tools/rio-cli/src/main/java/org/rioproject/tools/cli/OptionHandler.java | Java | apache-2.0 | 1,583 |
package com.eric.drools_demo;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 54070356/sample | drools-demo/src/test/java/com/eric/drools_demo/AppTest.java | Java | apache-2.0 | 648 |
// -----------------------------------------------------------------------------
// Copyright 2011-2012 Patrick Näf ([email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -----------------------------------------------------------------------------
// Project includes
#include "TableViewCellFactory.h"
// -----------------------------------------------------------------------------
/// @brief The UiUtilities class is a container for various utility functions
/// related to UI controls.
///
/// All functions in UiUtilities are class methods, so there is no need to
/// create an instance of UiUtilities.
// -----------------------------------------------------------------------------
@interface UiUtilities : NSObject
{
}
+ (double) radians:(double)degrees;
+ (CGFloat) tableView:(UITableView*)tableView heightForCellOfType:(enum TableViewCellType)type withText:(NSString*)text hasDisclosureIndicator:(bool)hasDisclosureIndicator;
+ (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;
+ (void) createTableViewWithStyle:(UITableViewStyle)tableViewStyle forController:(UIViewController*)viewController;
+ (void) addGroupTableViewBackgroundToView:(UIView*)view;
+ (UIImage*) gradientImageWithSize:(CGSize)size startColor:(UIColor*)startColor endColor:(UIColor*)endColor;
+ (void) drawLinearGradientWithContext:(CGContextRef)context rect:(CGRect)rect startColor:(CGColorRef)startColor endColor:(CGColorRef)endColor;
@end
| gcao/littlego_old | src/ui/UiUtilities.h | C | apache-2.0 | 1,994 |
package com.cognitionis.nlp_files;
import java.io.*;
import java.util.regex.*;
/**
*
* @author Héctor Llorens
* @since 2011
*/
public class TreebankFile extends NLPFile {
public TreebankFile(String filename) {
super(filename);
}
@Override
public Boolean isWellFormatted() {
int par_level = 0;
try {
if (super.getFile()==null) {
throw new Exception("No file loaded in NLPFile object");
}
BufferedReader reader = new BufferedReader(new FileReader(this.f));
try {
String line = null;
int linen = 0;
Pattern p = Pattern.compile("[\\(\\)]");
while ((line = reader.readLine()) != null) {
linen++; //System.getProperty("line.separator")
if (line.matches("\\s*[^\\(\\s].*")) {
throw new Exception("Treebank format error: line " + linen + " not begining with \\s*(");
}
Matcher m = p.matcher(line);
while (m.find()) {
if (m.group().equals("(")) {
par_level++;
} else {
par_level--;
if (par_level < 0) {
throw new Exception("Treebank format error: par_level lower than 0");
}
}
}
//System.out.println(linen+": "+line+" - parlevel="+ par_level);
}
} finally {
reader.close();
}
if (par_level != 0) {
throw new Exception("Treebank format error: positive unbalancement, par_level=" + par_level);
}
} catch (Exception e) {
System.err.println("Errors found ("+this.getClass().getSimpleName()+"):\n\t" + e.toString() + "\n");
if(System.getProperty("DEBUG")!=null && System.getProperty("DEBUG").equalsIgnoreCase("true")){e.printStackTrace(System.err);}
return false;
}
return true;
}
public String toPlain(String filename){
// one token, one space, one token, one space... (end of sentence -> \n)
return this.getFile().toString();
}
}
| hllorens/cognitionis-nlp-libraries | nlp-files/src/main/java/com/cognitionis/nlp_files/TreebankFile.java | Java | apache-2.0 | 2,385 |
package com.kashukov.convert;
/**
* Convert short to any primitive data type
*/
public class Short {
/**
* Convert short to boolean
*
* @param input short
* @return boolean
*/
public static boolean shortToBoolean(short input) {
return input != 0;
}
/**
* Convert short to byte
*
* @param input short
* @return byte
*/
public static byte shortToByte(short input) {
return (byte) input;
}
/**
* Convert short to byte[]
*
* @param input short
* @return byte[]
*/
public static byte[] shortToByteArray(short input) {
return new byte[]{
(byte) (input >>> 8),
(byte) input};
}
/**
* Convert short to char
*
* @param input short
* @return char
*/
public static char shortToChar(short input) {
return (char) input;
}
/**
* Convert short to double
*
* @param input short
* @return double
*/
public static double shortToDouble(short input) {
return (double) input;
}
/**
* Convert short to float
*
* @param input short
* @return float
*/
public static float shortToFloat(short input) {
return (float) input;
}
/**
* Convert short to int
*
* @param input short
* @return int
*/
public static int shortToInt(short input) {
return (int) input;
}
/**
* Convert short to long
*
* @param input short
* @return long
*/
public static long shortToLong(short input) {
return (long) input;
}
/**
* Convert short to String
*
* @param input short
* @return String
*/
public static java.lang.String shortToString(short input) {
return java.lang.Short.toString(input);
}
} | kashukov/convert | src/main/java/com/kashukov/convert/Short.java | Java | apache-2.0 | 1,895 |
<?php
/**
* PluginOp2CommunityEventMember form.
*
* @package opMTViewerPlugin
* @subpackage form
* @author Kimura Youichi <[email protected]>
*/
abstract class PluginOp2CommunityEventMemberForm extends BaseOp2CommunityEventMemberForm
{
}
| upsilon/opMTViewerPlugin | lib/form/doctrine/PluginOp2CommunityEventMemberForm.class.php | PHP | apache-2.0 | 256 |
package be.dnsbelgium.rdap.sample.parser;
import be.dnsbelgium.rdap.sample.dto.Contact;
import be.dnsbelgium.rdap.sample.dto.DnsSecKey;
import be.dnsbelgium.rdap.sample.dto.SimpleContact;
public enum WhoisKeyBlock {
MAIN(),
DOMAIN(),
REGISTRAR(),
REGISTRANT(),
ADMIN(Contact.class),
TECH(Contact.class),
DNSSEC(),
DNSSECKEY(DnsSecKey.class, true),
HOST(),
SIMPLE_ADMIN(SimpleContact.class),
SIMPLE_TECH(SimpleContact.class);
private Class repeatClass = null;
private boolean hasIndexSuffix = false;
WhoisKeyBlock() {
}
WhoisKeyBlock(Class repeatClass) {
this.repeatClass = repeatClass;
}
WhoisKeyBlock(Class repeatClass, boolean hasIndexSuffix) {
this.repeatClass = repeatClass;
this.hasIndexSuffix = hasIndexSuffix;
}
public Class getRepeatClass() {
return repeatClass;
}
public boolean hasIndexSuffix() {
return hasIndexSuffix;
}
public boolean isRepeatable() {
return repeatClass != null;
}
}
| DNSBelgium/rdap-server-sample-gtld | src/main/java/be/dnsbelgium/rdap/sample/parser/WhoisKeyBlock.java | Java | apache-2.0 | 981 |
package com.github.hadoop.maven.plugin;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
/**
* Writes jars.
*
*
*/
public class JarWriter {
/**
* Given a root directory, this writes the contents of the same as a jar file.
* The path to files inside the jar are relative paths, relative to the root
* directory specified.
*
* @param jarRootDir
* Root Directory that serves as an input to writing the jars.
* @param os
* OutputStream to which the jar is to be packed
* @throws FileNotFoundException
* @throws IOException
*/
public void packToJar(File jarRootDir, OutputStream os)
throws FileNotFoundException, IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(os, manifest);
for (File nestedFile : jarRootDir.listFiles())
add(jarRootDir.getPath().replace("\\", "/"), nestedFile, target);
target.close();
}
private void add(String prefix, File source, JarOutputStream target)
throws IOException {
BufferedInputStream in = null;
try {
if (source.isDirectory()) {
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty()) {
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name.substring(prefix.length() + 1));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile : source.listFiles())
add(prefix, nestedFile, target);
return;
}
String jarentryName = source.getPath().replace("\\", "/").substring(
prefix.length() + 1);
JarEntry entry = new JarEntry(jarentryName);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
} finally {
if (in != null)
in.close();
}
}
}
| akkumar/maven-hadoop | src/main/java/com/github/hadoop/maven/plugin/JarWriter.java | Java | apache-2.0 | 2,529 |
package dbtarzan.gui.table
import scalafx.scene.control.{TableView, TableColumn}
import scala.util.Random
import scalafx.Includes._
import dbtarzan.gui.util.JFXUtil
import dbtarzan.db._
object TableColumnsFitter {
/* a logistic (sigmoid) function, almost linear, returns max 50 */
def logistic(x : Double) : Double =
50.0 / (1.0 + 10.0 * scala.math.exp(-.1 * x))
}
class TableColumnsFitter[S](table : TableView[S], columns : List[Field]) {
private val maxSizes = new TableColumnsMaxSizes(columns, new Random())
private val charSize = JFXUtil.averageCharacterSize()
private def resizeColumn(column : TableColumn[S, _], size : Int) : Unit = {
val x = TableColumnsFitter.logistic((size+2))
column.prefWidth = x * charSize
}
def addRows(rows : List[Row]) : Unit = {
val columns = table.columns.drop(1)
maxSizes.addRows(rows)
val newSizes = maxSizes.maxLengths
// println("newSizes "+newSizes)
columns.zip(newSizes).foreach({
case (column, size) => resizeColumn(column, size)
})
}
} | aferrandi/dbtarzan | src/main/scala/dbtarzan/gui/table/TableColumnsFitter.scala | Scala | apache-2.0 | 1,092 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.transfer.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum HomeDirectoryType {
PATH("PATH"),
LOGICAL("LOGICAL");
private String value;
private HomeDirectoryType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return HomeDirectoryType corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static HomeDirectoryType fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (HomeDirectoryType enumEntry : HomeDirectoryType.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| aws/aws-sdk-java | aws-java-sdk-transfer/src/main/java/com/amazonaws/services/transfer/model/HomeDirectoryType.java | Java | apache-2.0 | 1,790 |
package com.ilad.teamwork;
import org.openqa.selenium.WebElement;
import io.appium.java_client.android.AndroidDriver;
public class TabsMenu extends AbstractTeamWork {
public TabsMenu(AndroidDriver<WebElement> driver) {
super(driver);
}
public AllProjectsPage goToProjects() {
driver.findElementByXPath("//android.widget.TextView[@text='Projects']").click();
return new AllProjectsPage(driver);
}
}
| Solomon1732/infinity-labs-repository | TeamWorkAndroid/src/main/java/com/ilad/teamwork/TabsMenu.java | Java | apache-2.0 | 414 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_32965_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=10994#src-10994" >testAbaNumberCheck_32965_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:22
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_32965_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=12585#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | dcarda/aba.route.validator | target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_32965_good_9pl.html | HTML | apache-2.0 | 9,181 |
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
require 'spec_helper'
RSpec.describe OneviewSDK::API2200::C7000::VolumeTemplate do
include_context 'shared context'
it 'inherits from OneviewSDK::API2000::C7000::VolumeTemplate' do
expect(described_class).to be < OneviewSDK::API2000::C7000::VolumeTemplate
end
end
| HewlettPackard/oneview-sdk-ruby | spec/unit/resource/api2200/c7000/volume_template_spec.rb | Ruby | apache-2.0 | 876 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202111;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Gets an {@link ActivityGroupPage} of {@link ActivityGroup} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ActivityGroup#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link ActivityGroup#name}</td>
* </tr>
* <tr>
* <td>{@code impressionsLookback}</td>
* <td>{@link ActivityGroup#impressionsLookback}</td>
* </tr>
* <tr>
* <td>{@code clicksLookback}</td>
* <td>{@link ActivityGroup#clicksLookback}</td>
* </tr>
* <tr>
* <td>{@code status}</td>
* <td>{@link ActivityGroup#status}</td>
* </tr>
* </table>
*
* @param filterStatement a statement used to filter a set of activity groups
* @return the activity groups that match the given filter
*
*
* <p>Java class for getActivityGroupsByStatement element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getActivityGroupsByStatement">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202111}Statement" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"filterStatement"
})
@XmlRootElement(name = "getActivityGroupsByStatement")
public class ActivityGroupServiceInterfacegetActivityGroupsByStatement {
protected Statement filterStatement;
/**
* Gets the value of the filterStatement property.
*
* @return
* possible object is
* {@link Statement }
*
*/
public Statement getFilterStatement() {
return filterStatement;
}
/**
* Sets the value of the filterStatement property.
*
* @param value
* allowed object is
* {@link Statement }
*
*/
public void setFilterStatement(Statement value) {
this.filterStatement = value;
}
}
| googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/ActivityGroupServiceInterfacegetActivityGroupsByStatement.java | Java | apache-2.0 | 3,560 |
package vnetpeering
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-11-01/network"
"github.com/giantswarm/microerror"
"github.com/giantswarm/operatorkit/v4/pkg/controller/context/reconciliationcanceledcontext"
"github.com/giantswarm/to"
"github.com/giantswarm/azure-operator/v5/service/controller/key"
)
const (
ProvisioningStateDeleting = "Deleting"
)
// This resource manages the VNet peering between the control plane and tenant cluster.
func (r *Resource) EnsureCreated(ctx context.Context, obj interface{}) error {
cr, err := key.ToCustomResource(obj)
if err != nil {
return microerror.Mask(err)
}
var tcVnet network.VirtualNetwork
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Checking if TC virtual network %#q exists in resource group %#q", key.VnetName(cr), key.ResourceGroupName(cr)))
virtualNetworksClient, err := r.clientFactory.GetVirtualNetworksClient(ctx, cr.ObjectMeta)
if err != nil {
return microerror.Mask(err)
}
tcVnet, err = virtualNetworksClient.Get(ctx, key.ResourceGroupName(cr), key.VnetName(cr), "")
if IsNotFound(err) {
r.logger.LogCtx(ctx, "level", "debug", "message", "TC Virtual network does not exist in resource group")
reconciliationcanceledcontext.SetCanceled(ctx)
r.logger.LogCtx(ctx, "level", "debug", "message", "canceling reconciliation")
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.LogCtx(ctx, "level", "debug", "message", "TC Virtual network exists in resource group")
}
var cpVnet network.VirtualNetwork
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Checking if CP virtual network %#q exists in resource group %#q", r.mcVirtualNetworkName, r.mcResourceGroup))
cpVnet, err = r.cpAzureClientSet.VirtualNetworkClient.Get(ctx, r.mcResourceGroup, r.mcVirtualNetworkName, "")
if IsNotFound(err) {
r.logger.LogCtx(ctx, "level", "debug", "message", "CP Virtual network does not exist in resource group")
reconciliationcanceledcontext.SetCanceled(ctx)
r.logger.LogCtx(ctx, "level", "debug", "message", "canceling reconciliation")
return nil
} else if err != nil {
return microerror.Mask(err)
}
r.logger.LogCtx(ctx, "level", "debug", "message", "CP Virtual network exists")
}
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Ensuring vnet peering %#q exists on the tenant cluster vnet %#q in resource group %#q", r.mcVirtualNetworkName, key.VnetName(cr), key.ResourceGroupName(cr)))
vnetPeeringsClient, err := r.clientFactory.GetVnetPeeringsClient(ctx, cr.ObjectMeta)
if err != nil {
return microerror.Mask(err)
}
tcPeering := r.getTCVnetPeering(*cpVnet.ID)
_, err = vnetPeeringsClient.CreateOrUpdate(ctx, key.ResourceGroupName(cr), key.VnetName(cr), r.mcVirtualNetworkName, tcPeering)
if err != nil {
return microerror.Mask(err)
}
}
{
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("Ensuring vnet peering %#q exists on the control plane vnet %#q in resource group %#q", key.ResourceGroupName(cr), r.mcVirtualNetworkName, r.mcResourceGroup))
cpPeering := r.getCPVnetPeering(*tcVnet.ID)
_, err = r.cpAzureClientSet.VnetPeeringClient.CreateOrUpdate(ctx, r.mcResourceGroup, r.mcVirtualNetworkName, key.ResourceGroupName(cr), cpPeering)
if err != nil {
return microerror.Mask(err)
}
}
return nil
}
func (r *Resource) getCPVnetPeering(vnetId string) network.VirtualNetworkPeering {
peering := network.VirtualNetworkPeering{
VirtualNetworkPeeringPropertiesFormat: &network.VirtualNetworkPeeringPropertiesFormat{
AllowVirtualNetworkAccess: to.BoolP(true),
AllowForwardedTraffic: to.BoolP(false),
AllowGatewayTransit: to.BoolP(false),
UseRemoteGateways: to.BoolP(false),
RemoteVirtualNetwork: &network.SubResource{
ID: &vnetId,
},
},
}
return peering
}
func (r *Resource) getTCVnetPeering(vnetId string) network.VirtualNetworkPeering {
peering := network.VirtualNetworkPeering{
VirtualNetworkPeeringPropertiesFormat: &network.VirtualNetworkPeeringPropertiesFormat{
AllowVirtualNetworkAccess: to.BoolP(true),
AllowForwardedTraffic: to.BoolP(false),
AllowGatewayTransit: to.BoolP(false),
UseRemoteGateways: to.BoolP(false),
RemoteVirtualNetwork: &network.SubResource{
ID: &vnetId,
},
},
}
return peering
}
| giantswarm/azure-operator | service/controller/azureconfig/handler/vnetpeering/create.go | GO | apache-2.0 | 4,401 |
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.ObservableCollection;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
@SuppressWarnings("unused")
public class ImportVmModel extends ListWithDetailsModel {
boolean sameSelectedDestinationStorage = false;
ArrayList<storage_domains> uniqueDestStorages;
ArrayList<storage_domains> allDestStorages;
storage_domains selectedDestinationStorage;
HashMap<Guid, ArrayList<Guid>> templateGuidUniqueStorageDomainDic;
HashMap<Guid, ArrayList<Guid>> templateGuidAllStorageDomainDic;
HashMap<Guid, ArrayList<DiskImage>> templateGuidDiskImagesDic;
VmImportDiskListModel importDiskListModel;
ArrayList<storage_domains> allStorageDomains;
int uniqueDomains;
Guid templateGuid;
private storage_domain_static privateSourceStorage;
public storage_domain_static getSourceStorage() {
return privateSourceStorage;
}
public void setSourceStorage(storage_domain_static value) {
privateSourceStorage = value;
}
private storage_pool privateStoragePool;
public storage_pool getStoragePool() {
return privateStoragePool;
}
public void setStoragePool(storage_pool value) {
privateStoragePool = value;
}
private ListModel privateDestinationStorage;
public ListModel getDestinationStorage() {
return privateDestinationStorage;
}
private void setDestinationStorage(ListModel value) {
privateDestinationStorage = value;
}
private ListModel privateAllDestinationStorage;
public ListModel getAllDestinationStorage() {
return privateAllDestinationStorage;
}
private void setAllDestinationStorage(ListModel value) {
privateAllDestinationStorage = value;
}
private ListModel privateCluster;
public ListModel getCluster() {
return privateCluster;
}
private void setCluster(ListModel value) {
privateCluster = value;
}
private ListModel privateSystemDiskFormat;
public ListModel getSystemDiskFormat() {
return privateSystemDiskFormat;
}
private void setSystemDiskFormat(ListModel value) {
privateSystemDiskFormat = value;
}
private ListModel privateDataDiskFormat;
public ListModel getDataDiskFormat() {
return privateDataDiskFormat;
}
private void setDataDiskFormat(ListModel value) {
privateDataDiskFormat = value;
}
private EntityModel collapseSnapshots;
public EntityModel getCollapseSnapshots() {
return collapseSnapshots;
}
public void setCollapseSnapshots(EntityModel value) {
this.collapseSnapshots = value;
}
private boolean isMissingStorages;
public boolean getIsMissingStorages() {
return isMissingStorages;
}
public void setIsMissingStorages(boolean value) {
if (isMissingStorages != value) {
isMissingStorages = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsMissingStorages"));
}
}
private String nameAndDescription;
private AsyncQuery onCollapseSnapshotsChangedFinish;
public String getNameAndDescription() {
return nameAndDescription;
}
public void setNameAndDescription(String value) {
if (!StringHelper.stringsEqual(nameAndDescription, value)) {
nameAndDescription = value;
OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription"));
}
}
private java.util.List<VM> problematicItems;
public java.util.List<VM> getProblematicItems() {
return problematicItems;
}
public void setProblematicItems(java.util.List<VM> value) {
if (problematicItems != value) {
problematicItems = value;
OnPropertyChanged(new PropertyChangedEventArgs("ProblematicItems"));
}
}
private EntityModel privateIsSingleDestStorage;
public EntityModel getIsSingleDestStorage() {
return privateIsSingleDestStorage;
}
public void setIsSingleDestStorage(EntityModel value) {
privateIsSingleDestStorage = value;
}
private ListModel privateStorageDoamins;
public ListModel getStorageDoamins() {
return privateStorageDoamins;
}
private void setStorageDoamins(ListModel value) {
privateStorageDoamins = value;
}
private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap;
public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap()
{
return privateDiskStorageMap;
}
public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value)
{
privateDiskStorageMap = value;
}
@Override
public void setSelectedItem(Object value) {
super.setSelectedItem(value);
OnEntityChanged();
}
public ImportVmModel() {
setProblematicItems(new ArrayList<VM>());
setCollapseSnapshots(new EntityModel());
getCollapseSnapshots().setEntity(false);
getCollapseSnapshots().getPropertyChangedEvent().addListener(
new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender,
EventArgs args) {
OnCollapseSnapshotsChanged();
}
});
setDestinationStorage(new ListModel());
getDestinationStorage().getSelectedItemChangedEvent().addListener(
new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender,
EventArgs args) {
DestinationStorage_SelectedItemChanged();
}
});
setCluster(new ListModel());
setSystemDiskFormat(new ListModel());
setDataDiskFormat(new ListModel());
setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>());
setIsSingleDestStorage(new EntityModel());
getIsSingleDestStorage().setEntity(true);
setAllDestinationStorage(new ListModel());
}
public void OnCollapseSnapshotsChanged(AsyncQuery _asyncQuery) {
this.onCollapseSnapshotsChangedFinish = _asyncQuery;
OnCollapseSnapshotsChanged();
}
public void initStorageDomains() {
templateGuidUniqueStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>();
templateGuidAllStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>();
templateGuidDiskImagesDic = new java.util.HashMap<Guid, ArrayList<DiskImage>>();
uniqueDomains = 0;
for (Object item : getItems()) {
VM vm = (VM) item;
templateGuid = vm.getvmt_guid();
if (templateGuid.equals(NGuid.Empty)) {
uniqueDomains++;
templateGuidUniqueStorageDomainDic.put(templateGuid, null);
templateGuidAllStorageDomainDic.put(templateGuid, null);
} else {
AsyncDataProvider.GetTemplateDiskList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
ImportVmModel importVmModel = (ImportVmModel) target;
ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue;
ArrayList<ArrayList<Guid>> allSourceStorages = new ArrayList<ArrayList<Guid>>();
for (DiskImage disk : disks) {
allSourceStorages.add(disk.getstorage_ids());
}
ArrayList<Guid> intersectStorageDomains = Linq.Intersection(allSourceStorages);
ArrayList<Guid> unionStorageDomains = Linq.Union(allSourceStorages);
uniqueDomains++;
templateGuidUniqueStorageDomainDic.put(importVmModel.templateGuid,
intersectStorageDomains);
templateGuidAllStorageDomainDic.put(importVmModel.templateGuid,
unionStorageDomains);
templateGuidDiskImagesDic.put(importVmModel.templateGuid, disks);
importVmModel.postInitStorageDomains();
}
}),
templateGuid);
}
}
postInitStorageDomains();
}
protected void postInitStorageDomains() {
if (templateGuidUniqueStorageDomainDic.size() != uniqueDomains) {
return;
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.Model = this;
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object returnValue) {
allStorageDomains = (ArrayList<storage_domains>) returnValue;
OnCollapseSnapshotsChanged();
initDiskStorageMap();
}
};
AsyncDataProvider.GetDataDomainsListByDomain(_asyncQuery, this.getSourceStorage().getId());
}
private void initDiskStorageMap() {
for (Object item : getItems()) {
VM vm = (VM) item;
for (DiskImage disk : vm.getDiskMap().values()) {
if (NGuid.Empty.equals(vm.getvmt_guid())) {
Guid storageId = !allDestStorages.isEmpty() ?
allDestStorages.get(0).getId() : new Guid();
addToDiskStorageMap(vm.getId(), disk, storageId);
}
else {
ArrayList<Guid> storageIds =
templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid());
Guid storageId = storageIds != null ?
templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()).get(0) : new Guid();
addToDiskStorageMap(vm.getId(), disk, storageId);
}
}
}
}
public void OnCollapseSnapshotsChanged() {
if (this.getItems() == null || allStorageDomains == null) {
return;
}
selectedDestinationStorage = null;
sameSelectedDestinationStorage = false;
uniqueDestStorages = new ArrayList<storage_domains>();
allDestStorages = new ArrayList<storage_domains>();
setIsMissingStorages(false);
if (getDestinationStorage().getSelectedItem() != null) {
selectedDestinationStorage = (storage_domains) getDestinationStorage().getSelectedItem();
}
for (storage_domains domain : allStorageDomains) {
boolean addStorage = false;
if (Linq.IsDataActiveStorageDomain(domain)) {
allDestStorages.add(domain);
if (((Boolean) getCollapseSnapshots().getEntity()).equals(true)) {
addStorage = true;
}
else {
for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidUniqueStorageDomainDic.entrySet())
{
if (NGuid.Empty.equals(keyValuePair.getKey())) {
addStorage = true;
} else {
addStorage = false;
for (Guid storageDomainId : keyValuePair.getValue()) {
if (storageDomainId.equals(domain.getId()))
{
addStorage = true;
break;
}
}
}
if (addStorage == false) {
break;
}
}
}
}
else {
for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidAllStorageDomainDic.entrySet())
{
if (!NGuid.Empty.equals(keyValuePair.getKey())) {
for (Guid storageDomainId : keyValuePair.getValue()) {
if (storageDomainId.equals(domain.getId()))
{
setIsMissingStorages(true);
break;
}
}
}
}
}
if (addStorage) {
uniqueDestStorages.add(domain);
if (sameSelectedDestinationStorage == false && domain.equals(selectedDestinationStorage)) {
sameSelectedDestinationStorage = true;
selectedDestinationStorage = domain;
}
}
}
getAllDestinationStorage().setItems(allDestStorages);
getDestinationStorage().setItems(uniqueDestStorages);
if (sameSelectedDestinationStorage) {
getDestinationStorage().setSelectedItem(selectedDestinationStorage);
} else {
getDestinationStorage().setSelectedItem(Linq.FirstOrDefault(uniqueDestStorages));
}
if (getDetailModels() != null
&& getActiveDetailModel() instanceof VmImportDiskListModel) {
VmImportDiskListModel detailModel = (VmImportDiskListModel) getActiveDetailModel();
detailModel
.setCollapseSnapshots((Boolean) getCollapseSnapshots()
.getEntity());
}
if (onCollapseSnapshotsChangedFinish != null) {
onCollapseSnapshotsChangedFinish.asyncCallback.OnSuccess(
onCollapseSnapshotsChangedFinish.getModel(), null);
onCollapseSnapshotsChangedFinish = null;
}
}
@Override
protected void ActiveDetailModelChanged() {
super.ActiveDetailModelChanged();
OnCollapseSnapshotsChanged();
}
@Override
protected void InitDetailModels() {
super.InitDetailModels();
importDiskListModel = new VmImportDiskListModel();
ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
list.add(new VmGeneralModel());
list.add(new VmImportInterfaceListModel());
list.add(importDiskListModel);
list.add(new VmAppListModel());
setDetailModels(list);
}
public boolean Validate() {
getDestinationStorage().ValidateSelectedItem(
new IValidation[] { new NotEmptyValidation() });
getCluster().ValidateSelectedItem(
new IValidation[] { new NotEmptyValidation() });
return getDestinationStorage().getIsValid()
&& getCluster().getIsValid();
}
@Override
protected void OnSelectedItemChanged() {
super.OnSelectedItemChanged();
if (getSelectedItem() != null) {
VM vm = (VM) getSelectedItem();
setNameAndDescription(StringFormat.format("%1$s%2$s",
vm.getvm_name(),
!StringHelper.isNullOrEmpty(vm.getvm_description()) ? " ["
+ vm.getvm_description() + "]" : ""));
} else {
setNameAndDescription("");
}
}
public void setItems(Iterable value)
{
super.setItems(value);
for (Object vm : getItems()) {
getDiskStorageMap().put(((VM) vm).getId(), new HashMap<Guid, Guid>());
}
initStorageDomains();
}
@Override
protected String getListName() {
return "ImportVmModel";
}
public void setSelectedVMsCount(int size) {
importDiskListModel.setSelectedVMsCount(((List) getItems()).size());
}
storage_domains currStorageDomain = null;
private void DestinationStorage_SelectedItemChanged() {
storage_domains selectedStorageDomain = (storage_domains) getDestinationStorage().getSelectedItem();
List destinationStorageDomains = ((List) getDestinationStorage().getItems());
if (selectedStorageDomain == null && !destinationStorageDomains.isEmpty()) {
selectedStorageDomain = (storage_domains) destinationStorageDomains.get(0);
}
if (currStorageDomain == null || selectedStorageDomain == null
|| !currStorageDomain.getQueryableId().equals(selectedStorageDomain.getQueryableId())) {
currStorageDomain = selectedStorageDomain;
UpdateImportWarnings();
}
}
public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) {
VM item = (VM) getSelectedItem();
addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId());
}
public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) {
HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId);
vmDiskStorageMap.put(disk.getId(), storageId);
}
private storage_domains getStorageDomainByName(String storageDomainName) {
storage_domains storage = null;
for (Object storageDomain : getDestinationStorage().getItems()) {
storage = (storage_domains) storageDomain;
if (storageDomainName.equals(storage.getstorage_name())) {
break;
}
}
return storage;
}
@Override
protected void ItemsChanged() {
super.ItemsChanged();
UpdateImportWarnings();
}
public VmImportDiskListModel getImportDiskListModel() {
return importDiskListModel;
}
private void UpdateImportWarnings() {
// Clear problematic state.
getProblematicItems().clear();
if (getItems() == null) {
return;
}
storage_domains destinationStorage = (storage_domains) getDestinationStorage()
.getSelectedItem();
for (Object item : getItems()) {
VM vm = (VM) item;
if (vm.getDiskMap() != null) {
for (java.util.Map.Entry<String, DiskImage> pair : vm
.getDiskMap().entrySet()) {
DiskImage disk = pair.getValue();
if (disk.getvolume_type() == VolumeType.Sparse
&& disk.getvolume_format() == VolumeFormat.RAW
&& destinationStorage != null
&& (destinationStorage.getstorage_type() == StorageType.ISCSI || destinationStorage
.getstorage_type() == StorageType.FCP)) {
getProblematicItems().add(vm);
}
}
}
}
// Decide what to do with the CollapseSnapshots option.
if (problematicItems.size() > 0) {
if (problematicItems.size() == Linq.Count(getItems())) {
// All items are problematic.
getCollapseSnapshots().setIsChangable(false);
getCollapseSnapshots().setEntity(true);
getCollapseSnapshots()
.setMessage(
"Note that all snapshots will be collapsed due to different storage types");
} else {
// Some items are problematic.
getCollapseSnapshots()
.setMessage(
"Use a separate import operation for the marked VMs or\nApply \"Collapse Snapshots\" for all VMs");
}
} else {
// No problematic items.
getCollapseSnapshots().setIsChangable(true);
getCollapseSnapshots().setMessage(null);
}
}
public void VolumeType_SelectedItemChanged(DiskImage disk,
VolumeType tempVolumeType) {
for (Object item : getItems()) {
VM vm = (VM) item;
java.util.HashMap<String, DiskImageBase> diskDictionary = new java.util.HashMap<String, DiskImageBase>();
for (java.util.Map.Entry<String, DiskImage> a : vm.getDiskMap()
.entrySet()) {
if (a.getValue().getQueryableId().equals(disk.getQueryableId())) {
a.getValue().setvolume_type(tempVolumeType);
break;
}
}
}
}
public ArrayList<String> getAvailableStorageDomainsByDiskId(Guid diskId) {
ArrayList<String> storageDomains = null;
ArrayList<Guid> storageDomainsIds = getImportDiskListModel().getAvailableStorageDomainsByDiskId(diskId);
if (storageDomainsIds != null) {
storageDomains = new ArrayList<String>();
for (Guid storageId : storageDomainsIds) {
if (Linq.IsActiveStorageDomain(getStorageById(storageId))) {
storageDomains.add(getStorageNameById(storageId));
}
}
}
if (storageDomains != null) {
Collections.sort(storageDomains);
}
return storageDomains;
}
public String getStorageNameById(NGuid storageId) {
String storageName = "";
for (Object storageDomain : getAllDestinationStorage().getItems()) {
storage_domains storage = (storage_domains) storageDomain;
if (storage.getId().equals(storageId)) {
storageName = storage.getstorage_name();
}
}
return storageName;
}
public storage_domains getStorageById(Guid storageId) {
for (storage_domains storage : allDestStorages) {
if (storage.getId().equals(storageId)) {
return storage;
}
}
return null;
}
}
| Dhandapani/gluster-ovirt | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/ImportVmModel.java | Java | apache-2.0 | 23,592 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Ais.Internal.Dcm.ModernUIV2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Ais.Internal.Dcm.ModernUIV2")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| AppliedIS/wams-manager | Source/Ais.Internal.Dcm/Ais.Internal.Dcm.ModernUIV2/Properties/AssemblyInfo.cs | C# | apache-2.0 | 2,263 |
# Accelerator backends
It's pretty straightforward to describe a `Tensor` calculation, but when and how that calculation
is performed will depend on which backend is used for the `Tensor`s and when the results
are needed on the host CPU.
Behind the scenes, operations on `Tensor`s are dispatched to accelerators like GPUs or
[TPUs](https://cloud.google.com/tpu), or run on the CPU when no accelerator is available. This
happens automatically for you, and makes it easy to perform complex parallel calculations using
a high-level interface. However, it can be useful to understand how this dispatch occurs and be
able to customize it for optimal performance.
Swift for TensorFlow has two backends for performing accelerated computation: TensorFlow eager mode
and X10. The default backend is TensorFlow eager mode, but that can be overridden. An
[interactive tutorial](https://colab.research.google.com/github/tensorflow/swift/blob/main/docs/site/tutorials/introducing_x10.ipynb)
is available that walks you through the use of these different backends.
## TensorFlow eager mode
The TensorFlow eager mode backend leverages
[the TensorFlow C API](https://www.tensorflow.org/install/lang_c) to send each `Tensor` operation
to a GPU or CPU as it is encountered. The result of that operation is then retrieved and passed on
to the next operation.
This operation-by-operation dispatch is straightforward to understand and requires no explicit
configuration within your code. However, in many cases it does not result in optimal performance
due to the overhead from sending off many small operations, combined with the lack of operation
fusion and optimization that can occur when graphs of operations are present. Finally, TensorFlow eager mode is incompatible with TPUs, and can only be used with CPUs and GPUs.
## X10 (XLA-based tracing)
X10 is the name of the Swift for TensorFlow backend that uses lazy tensor tracing and [the XLA
optimizing compiler](https://www.tensorflow.org/xla) to in many cases significantly improve
performance over operation-by-operation dispatch. Additionally, it adds compatibility for
[TPUs](https://cloud.google.com/tpu), accelerators specifically optimized for the kinds of
calculations found within machine learning models.
The use of X10 for `Tensor` calculations is not the default, so you need to opt in to this backend.
That is done by specifying that a `Tensor` is placed on an XLA device:
```swift
let tensor1 = Tensor<Float>([0.0, 1.0, 2.0], on: Device.defaultXLA)
let tensor2 = Tensor<Float>([1.5, 2.5, 3.5], on: Device.defaultXLA)
```
After that point, describing a calculation is exactly the same as for TensorFlow eager mode:
```swift
let tensor3 = tensor1 + tensor2
```
Further detail can be provided when creating a `Tensor`, such as what kind of accelerator to use
and even which one, if several are available. For example, a `Tensor` can be created on the second
TPU device (assuming it is visible to the host the program is running on) using the following:
```swift
let tpuTensor = Tensor<Float>([0.0, 1.0, 2.0], on: Device(kind: .TPU, ordinal: 1, backend: .XLA))
```
No implicit movement of `Tensor`s between devices is performed, so if two `Tensor`s on different
devices are used in an operation together, a runtime error will occur. To manually copy the
contents of a `Tensor` to a new device, you can use the `Tensor(copying:to:)` initializer. Some
larger-scale structures that contain `Tensor`s within them, like models and optimizers, have helper
functions for moving all of their interior `Tensor`s to a new device in one step.
Unlike TensorFlow eager mode, operations using the X10 backend are not individually dispatched as
they are encountered. Instead, dispatching to an accelerator is only triggered by either reading
calculated values back to the host or by placing an explicit barrier. The way this works is that
the runtime starts from the value being read to the host (or the last calculation before a manual
barrier) and traces the graph of calculations that result in that value.
This traced graph is then converted to the XLA HLO intermediate representation and passed to the
XLA compiler to be optimized and compiled for execution on the accelerator. From there, the entire
calculation is sent to the accelerator and the end result obtained.
Calculation is a time-consuming process, so X10 is best used with massively parallel calculations
that are expressed via a graph and that are performed many times. Hash values and caching are used so that identical graphs are only compiled once for every unique configuration.
For machine learning models, the training process often involves a loop where the model is
subjected to the same series of calculations over and over. You'll want each of these passes to be
seen as a repetition of the same trace, rather than one long graph with repeated units inside it.
This is enabled by the manual insertion of a call to `LazyTensorBarrier()` function at the
locations in your code where you wish for a trace to end.
### Mixed-precision support in X10
Training with mixed precision via X10 is supported and both low-level and
high-level API are provided to control it. The
[low-level API](https://github.com/tensorflow/swift-apis/blob/main/Sources/TensorFlow/Core/MixedPrecision.swift)
offers two computed properties: `toReducedPrecision` and `toFullPrecision` which
convert between full and reduced precision, along with `isReducedPrecision`
to query the precision. Besides `Tensor`s, models and optimizers can be converted
between full and reduced precision using this API.
Note that conversion to reduced precision doesn't change the logical type of a
`Tensor`. If `t` is a `Tensor<Float>`, `t.toReducedPrecision` is also a
`Tensor<Float>` with a reduced-precision underlying representation.
As with devices, operations between tensors of different precisions are not
allowed. This avoids silent and unwanted promotion to 32-bit floats, which would be hard
to detect by the user.
| tensorflow/swift | docs/site/guide/backends.md | Markdown | apache-2.0 | 6,016 |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Wpf.Mvvm.TestHarness")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Wpf.Mvvm.TestHarness")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")] | oriches/Simple.Wpf.FSharp.Repl | Wpf.Mvvm.TestHarness/Properties/AssemblyInfo.cs | C# | apache-2.0 | 2,236 |
package com.pengrad.telegrambot.request;
import com.pengrad.telegrambot.response.BaseResponse;
/**
* Mirco Ianese
* 07 December 2021
*/
public class UnbanChatSenderChat extends BaseRequest<UnbanChatSenderChat, BaseResponse> {
public UnbanChatSenderChat(Object chatId, long sender_chat_id) {
super(BaseResponse.class);
add("chat_id", chatId).add("sender_chat_id", sender_chat_id);
}
}
| pengrad/java-telegram-bot-api | library/src/main/java/com/pengrad/telegrambot/request/UnbanChatSenderChat.java | Java | apache-2.0 | 415 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace DevZH.UI
{
[StructLayout(LayoutKind.Sequential)]
public struct InitOptions
{
public UIntPtr Size;
}
}
| noliar/DevZH.UI | src/DevZH.UI/InitOptions.cs | C# | apache-2.0 | 275 |
/**
* @author: Alberto Cerqueira
* @email: [email protected]
*/
jQuery.controller = function() {
var controllerClass = function() {
this.init = (function(){
$("#gravar").click(function(){
_self.gravar();
return false;
});
});
this.gravar = (function() {
$("#manterEntidade").ajaxSubmit({
url : systemURL,
dataType : "json",
success : (function(jsonReturn){
var consequence = jsonReturn.consequence;
if (consequence == "ERRO") {
alert(jsonReturn.message);
} else if (consequence == "SUCESSO") {
alert(jsonReturn.message + ": " + jsonReturn.dado.toString());
} else if(consequence == "MUITOS_ERROS"){
var mensagem = [''];
jQuery.each(jsonReturn.dado, function(i, dado) {
mensagem.push(dado.localizedMessage + "\n");
});
alert(mensagem.join(''));
}
//location.reload();
}),
error : (function(XMLHttpRequest, textStatus, errorThrown){
alert(errorConexao);
})
});
});
var _self = this;
};
return new controllerClass();
}; | g6tech/spring-corp-test | project/viewria/WebContent/app/controller/controller.js | JavaScript | apache-2.0 | 1,076 |
/*
* Copyright (c) 2017-2018. the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.allan.easycache.config;
import li.allan.easycache.CacheKeyGenerator;
import li.allan.easycache.LocalCacheConfig;
/**
* @author lialun
*/
public class ConfigProperties {
private LocalCacheConfig localCacheConfig;
private CacheKeyGenerator cacheKeyGenerator;
public LocalCacheConfig getLocalCacheConfig() {
return localCacheConfig;
}
public void setLocalCacheConfig(LocalCacheConfig localCacheConfig) {
this.localCacheConfig = localCacheConfig;
}
public CacheKeyGenerator getCacheKeyGenerator() {
return cacheKeyGenerator;
}
public void setCacheKeyGenerator(CacheKeyGenerator cacheKeyGenerator) {
this.cacheKeyGenerator = cacheKeyGenerator;
}
}
| lialun/EasyCache | easycache/src/main/java/li/allan/easycache/config/ConfigProperties.java | Java | apache-2.0 | 1,360 |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from solum.api.controllers import common_types
from solum.api.controllers.v1.datamodel import types as api_types
#from solum.openstack.common import log as logging
#LOG = logging.getLogger(__name__)
class Extensions(api_types.Base):
"""extensions resource"""
extension_links = [common_types.Link]
"""This attribute contains Links to extension resources that contain
information about the extensions supported by this Platform."""
def __init__(self, **kwds):
# LOG.debug("extensions constructor: %s" % kwds)
super(Extensions, self).__init__(**kwds)
| gilbertpilz/solum | solum/api/controllers/camp/v1_1/datamodel/extensions.py | Python | apache-2.0 | 1,139 |
<div class='row row-pad'>
<div class='col-sm-2 col-md-2 col-lg-2 text-center'>
<h5>Quick Menu</h5>
</div>
<div class='col-sm-8 col-md-8 col-lg-8 text-center'>
<h5>Videos</h5>
</div>
<div class='col-sm-2 col-md-2 col-lg-2 text-center'>
<h5>Following</h5>
</div>
</div>
<div class='row row-pad'>
<div class='col-sm-2 col-md-2 col-lg-2'>
<?= $videoNav ?>
</div>
<div class='col-sm-8 col-md-8 col-lg-8'>
<div class='row well row-pad'>
<?php if (count($videos) > 0): ?>
<div class='row scroll-h'>
<div class='scroll-h-inner row-pad'>
<?php foreach ($videos as $video): ?>
<span class='vid-thumb-container'>
<a href="/videos/single/<?= $video->id ?>">
<h4><?= $video->title; ?></h4>
<img class='vid-thumb' src=<?= $video->thumbnail ?>>
</a>
</span>
<?php endforeach; ?>
</div>
</div>
<?php else: ?>
<div class='well well-sm'>
It looks like this user has no videos yet!
</div>
<?php endif; ?>
</div>
</div>
<div class='col-sm-2 col-md-2 col-lg-2'>
<?= $friendsNav ?>
</div>
</div> | karlmoser/Video-Annotation | web/public/application/views/parts/main.php | PHP | apache-2.0 | 1,103 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.appsync.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appsync-2017-07-25/GetFunction" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetFunctionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The <code>Function</code> object.
* </p>
*/
private FunctionConfiguration functionConfiguration;
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @param functionConfiguration
* The <code>Function</code> object.
*/
public void setFunctionConfiguration(FunctionConfiguration functionConfiguration) {
this.functionConfiguration = functionConfiguration;
}
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @return The <code>Function</code> object.
*/
public FunctionConfiguration getFunctionConfiguration() {
return this.functionConfiguration;
}
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @param functionConfiguration
* The <code>Function</code> object.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetFunctionResult withFunctionConfiguration(FunctionConfiguration functionConfiguration) {
setFunctionConfiguration(functionConfiguration);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFunctionConfiguration() != null)
sb.append("FunctionConfiguration: ").append(getFunctionConfiguration());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetFunctionResult == false)
return false;
GetFunctionResult other = (GetFunctionResult) obj;
if (other.getFunctionConfiguration() == null ^ this.getFunctionConfiguration() == null)
return false;
if (other.getFunctionConfiguration() != null && other.getFunctionConfiguration().equals(this.getFunctionConfiguration()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFunctionConfiguration() == null) ? 0 : getFunctionConfiguration().hashCode());
return hashCode;
}
@Override
public GetFunctionResult clone() {
try {
return (GetFunctionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-appsync/src/main/java/com/amazonaws/services/appsync/model/GetFunctionResult.java | Java | apache-2.0 | 4,022 |
/*
* Copyright 2008-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovy.lang;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Field annotation to simplify lazy initialization.
* <p>
* Example usage without any special modifiers just defers initialization until the first call but is not thread-safe:
* <pre>
* {@code @Lazy} T x
* </pre>
* becomes
* <pre>
* private T $x
*
* T getX() {
* if ($x != null)
* return $x
* else {
* $x = new T()
* return $x
* }
* }
* </pre>
*
* If the field is declared volatile then initialization will be synchronized using
* the <a href="http://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a> pattern as shown here:
*
* <pre>
* {@code @Lazy} volatile T x
* </pre>
* becomes
* <pre>
* private volatile T $x
*
* T getX() {
* T $x_local = $x
* if ($x_local != null)
* return $x_local
* else {
* synchronized(this) {
* if ($x == null) {
* $x = new T()
* }
* return $x
* }
* }
* }
* </pre>
*
* By default a field will be initialized by calling its default constructor.
*
* If the field has an initial value expression then this expression will be used instead of calling the default constructor.
* In particular, it is possible to use closure <code>{ ... } ()</code> syntax as follows:
*
* <pre>
* {@code @Lazy} T x = { [1, 2, 3] } ()
* </pre>
* becomes
* <pre>
* private T $x
*
* T getX() {
* T $x_local = $x
* if ($x_local != null)
* return $x_local
* else {
* synchronized(this) {
* if ($x == null) {
* $x = { [1, 2, 3] } ()
* }
* return $x
* }
* }
* }
* </pre>
* <p>
* <code>@Lazy(soft=true)</code> will use a soft reference instead of the field and use the above rules each time re-initialization is required.
* <p>
* If the <code>soft</code> flag for the annotation is not set but the field is static, then
* the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom">initialization on demand holder idiom</a> is
* used as follows:
* <pre>
* {@code @Lazy} static FieldType field
* {@code @Lazy} static Date date1
* {@code @Lazy} static Date date2 = { new Date().updated(year: 2000) }()
* {@code @Lazy} static Date date3 = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
* </pre>
* becomes these methods and inners classes within the class containing the above definitions:
* <pre>
* private static class FieldTypeHolder_field {
* private static final FieldType INSTANCE = new FieldType()
* }
*
* private static class DateHolder_date1 {
* private static final Date INSTANCE = new Date()
* }
*
* private static class DateHolder_date2 {
* private static final Date INSTANCE = { new Date().updated(year: 2000) }()
* }
*
* private static class DateHolder_date3 {
* private static final Date INSTANCE = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
* }
*
* static FieldType getField() {
* return FieldTypeHolder_field.INSTANCE
* }
*
* static Date getDate1() {
* return DateHolder_date1.INSTANCE
* }
*
* static Date getDate2() {
* return DateHolder_date2.INSTANCE
* }
*
* static Date getDate3() {
* return DateHolder_date3.INSTANCE
* }
* </pre>
*
* @author Alex Tkachman
* @author Paul King
*/
@java.lang.annotation.Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.LazyASTTransformation")
public @interface Lazy {
/**
* @return if field should be soft referenced instead of hard referenced
*/
boolean soft () default false;
}
| Selventa/model-builder | tools/groovy/src/src/main/groovy/lang/Lazy.java | Java | apache-2.0 | 4,644 |
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.event.listener;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.artifact_cache.ArtifactCacheConnectEvent;
import com.facebook.buck.artifact_cache.CacheResult;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.event.CommandEvent;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEventFetchData;
import com.facebook.buck.event.ArtifactCompressionEvent;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusFactory;
import com.facebook.buck.event.ChromeTraceEvent;
import com.facebook.buck.event.CompilerPluginDurationEvent;
import com.facebook.buck.event.PerfEventId;
import com.facebook.buck.event.SimplePerfEvent;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.jvm.java.AnnotationProcessingEvent;
import com.facebook.buck.jvm.java.tracing.JavacPhaseEvent;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.BuildRuleKeys;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleStatus;
import com.facebook.buck.rules.BuildRuleSuccessType;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeBuildRule;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.StepEvent;
import com.facebook.buck.timing.Clock;
import com.facebook.buck.timing.FakeClock;
import com.facebook.buck.timing.IncrementingFakeClock;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.perf.PerfStatsTracking;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
public class ChromeTraceBuildListenerTest {
private static final long TIMESTAMP_NANOS = 1409702151000000000L;
private static final String EXPECTED_DIR =
"buck-out/log/2014-09-02_23h55m51s_no_sub_command_BUILD_ID/";
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
private InvocationInfo invocationInfo;
@Before
public void setUp() throws IOException {
invocationInfo = InvocationInfo.builder()
.setTimestampMillis(TimeUnit.NANOSECONDS.toMillis(TIMESTAMP_NANOS))
.setBuckLogDir(tmpDir.getRoot().toPath().resolve("buck-out/log"))
.setBuildId(new BuildId("BUILD_ID"))
.setSubCommand("no_sub_command")
.setIsDaemon(false)
.setSuperConsoleEnabled(false)
.build();
}
@Test
public void testDeleteFiles() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
String tracePath = invocationInfo.getLogDirectoryPath().resolve("build.trace").toString();
File traceFile = new File(tracePath);
projectFilesystem.createParentDirs(tracePath);
traceFile.createNewFile();
traceFile.setLastModified(0);
for (int i = 0; i < 10; ++i) {
File oldResult = new File(
String.format("%s/build.100%d.trace", invocationInfo.getLogDirectoryPath(), i));
oldResult.createNewFile();
oldResult.setLastModified(TimeUnit.SECONDS.toMillis(i));
}
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 3,
false);
listener.outputTrace(invocationInfo.getBuildId());
ImmutableList<String> files = FluentIterable.
from(Arrays.asList(projectFilesystem.listFiles(invocationInfo.getLogDirectoryPath()))).
filter(input -> input.toString().endsWith(".trace")).
transform(File::getName).
toList();
assertEquals(4, files.size());
assertEquals(
ImmutableSortedSet.of(
"build.trace",
"build.1009.trace",
"build.1008.trace",
"build.2014-09-02.16-55-51.BUILD_ID.trace"),
ImmutableSortedSet.copyOf(files));
}
@Test
public void testBuildJson() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ObjectMapper mapper = ObjectMappers.newDefaultInstance();
BuildId buildId = new BuildId("ChromeTraceBuildListenerTestBuildId");
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
mapper,
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 42,
false);
BuildTarget target = BuildTargetFactory.newInstance("//fake:rule");
FakeBuildRule rule = new FakeBuildRule(
target,
new SourcePathResolver(
new BuildRuleResolver(
TargetGraph.EMPTY,
new DefaultTargetNodeToBuildRuleTransformer())
),
ImmutableSortedSet.of());
RuleKey ruleKey = new RuleKey("abc123");
String stepShortName = "fakeStep";
String stepDescription = "I'm a Fake Step!";
UUID stepUuid = UUID.randomUUID();
ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of(target);
Iterable<String> buildArgs = Iterables.transform(buildTargets, Object::toString);
Clock fakeClock = new IncrementingFakeClock(TimeUnit.MILLISECONDS.toNanos(1));
BuckEventBus eventBus = BuckEventBusFactory.newInstance(fakeClock, buildId);
eventBus.register(listener);
CommandEvent.Started commandEventStarted = CommandEvent.started(
"party",
ImmutableList.of("arg1", "arg2"),
/* isDaemon */ true);
eventBus.post(commandEventStarted);
eventBus.post(new PerfStatsTracking.MemoryPerfStatsEvent(
/* freeMemoryBytes */ 1024 * 1024L,
/* totalMemoryBytes */ 3 * 1024 * 1024L,
/* timeSpentInGcMs */ -1,
/* currentMemoryBytesUsageByPool */ ImmutableMap.of("flower", 42L * 1024 * 1024)));
ArtifactCacheConnectEvent.Started artifactCacheConnectEventStarted =
ArtifactCacheConnectEvent.started();
eventBus.post(artifactCacheConnectEventStarted);
eventBus.post(ArtifactCacheConnectEvent.finished(artifactCacheConnectEventStarted));
BuildEvent.Started buildEventStarted = BuildEvent.started(buildArgs);
eventBus.post(buildEventStarted);
HttpArtifactCacheEvent.Started artifactCacheEventStarted =
HttpArtifactCacheEvent.newFetchStartedEvent(ruleKey);
eventBus.post(artifactCacheEventStarted);
eventBus.post(
HttpArtifactCacheEvent.newFinishedEventBuilder(artifactCacheEventStarted)
.setFetchDataBuilder(
HttpArtifactCacheEventFetchData.builder()
.setFetchResult(CacheResult.hit("http")))
.build());
ArtifactCompressionEvent.Started artifactCompressionStartedEvent =
ArtifactCompressionEvent.started(
ArtifactCompressionEvent.Operation.COMPRESS, ImmutableSet.of(ruleKey));
eventBus.post(artifactCompressionStartedEvent);
eventBus.post(ArtifactCompressionEvent.finished(artifactCompressionStartedEvent));
eventBus.post(BuildRuleEvent.started(rule));
eventBus.post(StepEvent.started(stepShortName, stepDescription, stepUuid));
JavacPhaseEvent.Started runProcessorsStartedEvent = JavacPhaseEvent.started(
target,
JavacPhaseEvent.Phase.RUN_ANNOTATION_PROCESSORS,
ImmutableMap.of());
eventBus.post(runProcessorsStartedEvent);
String annotationProcessorName = "com.facebook.FakeProcessor";
AnnotationProcessingEvent.Operation operation = AnnotationProcessingEvent.Operation.PROCESS;
int annotationRound = 1;
boolean isLastRound = false;
AnnotationProcessingEvent.Started annotationProcessingEventStarted =
AnnotationProcessingEvent.started(
target,
annotationProcessorName,
operation,
annotationRound,
isLastRound);
eventBus.post(annotationProcessingEventStarted);
HttpArtifactCacheEvent.Scheduled httpScheduled = HttpArtifactCacheEvent.newStoreScheduledEvent(
Optional.of("TARGET_ONE"), ImmutableSet.of(ruleKey));
HttpArtifactCacheEvent.Started httpStarted =
HttpArtifactCacheEvent.newStoreStartedEvent(httpScheduled);
eventBus.post(httpStarted);
HttpArtifactCacheEvent.Finished httpFinished =
HttpArtifactCacheEvent.newFinishedEventBuilder(httpStarted).build();
eventBus.post(httpFinished);
final CompilerPluginDurationEvent.Started processingPartOneStarted =
CompilerPluginDurationEvent.started(
target,
annotationProcessorName,
"processingPartOne",
ImmutableMap.of());
eventBus.post(processingPartOneStarted);
eventBus.post(
CompilerPluginDurationEvent.finished(
processingPartOneStarted,
ImmutableMap.of()));
eventBus.post(AnnotationProcessingEvent.finished(annotationProcessingEventStarted));
eventBus.post(
JavacPhaseEvent.finished(runProcessorsStartedEvent, ImmutableMap.of()));
eventBus.post(StepEvent.finished(
StepEvent.started(stepShortName, stepDescription, stepUuid),
0));
eventBus.post(
BuildRuleEvent.finished(
rule,
BuildRuleKeys.of(ruleKey),
BuildRuleStatus.SUCCESS,
CacheResult.miss(),
Optional.of(BuildRuleSuccessType.BUILT_LOCALLY),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty()));
try (final SimplePerfEvent.Scope scope1 = SimplePerfEvent.scope(
eventBus,
PerfEventId.of("planning"),
ImmutableMap.<String, Object>of("nefarious", "true"))) {
try (final SimplePerfEvent.Scope scope2 = SimplePerfEvent.scope(
eventBus,
PerfEventId.of("scheming"))) {
scope2.appendFinishedInfo("success", "false");
}
}
eventBus.post(BuildEvent.finished(buildEventStarted, 0));
eventBus.post(CommandEvent.finished(commandEventStarted, /* exitCode */ 0));
listener.outputTrace(new BuildId("BUILD_ID"));
File resultFile = new File(tmpDir.getRoot(), "buck-out/log/build.trace");
List<ChromeTraceEvent> originalResultList = mapper.readValue(
resultFile,
new TypeReference<List<ChromeTraceEvent>>() {});
List<ChromeTraceEvent> resultListCopy = new ArrayList<>();
resultListCopy.addAll(originalResultList);
ImmutableMap<String, String> emptyArgs = ImmutableMap.of();
assertNextResult(
resultListCopy,
"process_name",
ChromeTraceEvent.Phase.METADATA,
ImmutableMap.of("name", "buck"));
assertNextResult(
resultListCopy,
"party",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("command_args", "arg1 arg2"));
assertNextResult(
resultListCopy,
"memory",
ChromeTraceEvent.Phase.COUNTER,
ImmutableMap.of(
"used_memory_mb", "2",
"free_memory_mb", "1",
"total_memory_mb", "3",
"time_spent_in_gc_sec", "0",
"pool_flower_mb", "42"));
assertNextResult(
resultListCopy,
"artifact_connect",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"artifact_connect",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"build",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"http_artifact_fetch",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("rule_key", "abc123"));
assertNextResult(
resultListCopy,
"http_artifact_fetch",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"rule_key", "abc123",
"success", "true",
"cache_result", "HTTP_HIT"));
assertNextResult(
resultListCopy,
"artifact_compress",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("rule_key", "abc123"));
assertNextResult(
resultListCopy,
"artifact_compress",
ChromeTraceEvent.Phase.END,
ImmutableMap.of("rule_key", "abc123"));
// BuildRuleEvent.Started
assertNextResult(
resultListCopy,
"//fake:rule",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of());
assertNextResult(
resultListCopy,
"fakeStep",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"run annotation processors",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"com.facebook.FakeProcessor.process",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"http_artifact_store",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of(
"rule_key", "abc123"));
assertNextResult(
resultListCopy,
"http_artifact_store",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"success", "true",
"rule_key", "abc123"));
assertNextResult(
resultListCopy,
"processingPartOne",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"processingPartOne",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"com.facebook.FakeProcessor.process",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"run annotation processors",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"fakeStep",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"description", "I'm a Fake Step!",
"exit_code", "0"));
assertNextResult(
resultListCopy,
"//fake:rule",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"cache_result", "miss",
"success_type", "BUILT_LOCALLY"));
assertNextResult(
resultListCopy,
"planning",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("nefarious", "true"));
assertNextResult(
resultListCopy,
"scheming",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"scheming",
ChromeTraceEvent.Phase.END,
ImmutableMap.of("success", "false"));
assertNextResult(
resultListCopy,
"planning",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"build",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"party",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"command_args", "arg1 arg2",
"daemon", "true"));
assertEquals(0, resultListCopy.size());
}
private static void assertNextResult(
List<ChromeTraceEvent> resultList,
String expectedName,
ChromeTraceEvent.Phase expectedPhase,
ImmutableMap<String, String> expectedArgs) {
assertTrue(resultList.size() > 0);
assertEquals(expectedName, resultList.get(0).getName());
assertEquals(expectedPhase, resultList.get(0).getPhase());
assertEquals(expectedArgs, resultList.get(0).getArgs());
resultList.remove(0);
}
@Test
public void testOutputFailed() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
assumeTrue("Can make the root directory read-only", tmpDir.getRoot().setReadOnly());
try {
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 3,
false);
listener.outputTrace(invocationInfo.getBuildId());
fail("Expected an exception.");
} catch (HumanReadableException e) {
assertEquals(
"Unable to write trace file: java.nio.file.AccessDeniedException: " +
projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()),
e.getMessage());
} finally {
tmpDir.getRoot().setWritable(true);
}
}
@Test
public void outputFileUsesCurrentTime() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 1,
false);
listener.outputTrace(invocationInfo.getBuildId());
assertTrue(
projectFilesystem.exists(
Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace")));
}
@Test
public void canCompressTraces() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 1,
true);
listener.outputTrace(invocationInfo.getBuildId());
Path tracePath = Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace.gz");
assertTrue(projectFilesystem.exists(tracePath));
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(projectFilesystem.newFileInputStream(tracePath))));
List<?> elements = new Gson().fromJson(reader, List.class);
assertThat(elements, notNullValue());
}
}
| justinmuller/buck | test/com/facebook/buck/event/listener/ChromeTraceBuildListenerTest.java | Java | apache-2.0 | 20,351 |
<?php
/**
* Budget delivery methods.
* @package Google_Api_Ads_AdWords_v201605
* @subpackage v201605
*/
class BudgetBudgetDeliveryMethod
{
const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
const XSI_TYPE = "Budget.BudgetDeliveryMethod";
/**
* Gets the namesapce of this class
* @return string the namespace of this class
*/
public function getNamespace()
{
return self::WSDL_NAMESPACE;
}
/**
* Gets the xsi:type name of this class
* @return string the xsi:type name of this class
*/
public function getXsiTypeName()
{
return self::XSI_TYPE;
}
public function __construct()
{
}
} | SonicGD/google-adwords-api-light | Google/Api/Ads/AdWords/v201605/classes/BudgetBudgetDeliveryMethod.php | PHP | apache-2.0 | 716 |
/*
* Copyright (C) 2016 CaMnter [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.camnter.savevolley.network.adapter.core;
import com.camnter.savevolley.network.core.http.SaveHttpEntity;
/**
* Description:SaveHttpEntityAdapter
* Created by:CaMnter
* Time:2016-05-27 14:10
*/
public interface SaveHttpEntityAdapter<T> {
SaveHttpEntity adaptiveEntity(T t);
}
| CaMnter/SaveVolley | savevolley-network-adapter/src/main/java/com/camnter/savevolley/network/adapter/core/SaveHttpEntityAdapter.java | Java | apache-2.0 | 925 |
# Install script for directory: /home/york/Program/MachineLearning/nn/two_spiral/src
# Set the install prefix
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
if(BUILD_TYPE)
string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
else()
set(CMAKE_INSTALL_CONFIG_NAME "")
endif()
message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()
# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
if(COMPONENT)
message(STATUS "Install component: \"${COMPONENT}\"")
set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
else()
set(CMAKE_INSTALL_COMPONENT)
endif()
endif()
# Install shared libraries without execute permission?
if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
set(CMAKE_INSTALL_SO_NO_EXE "0")
endif()
if(CMAKE_INSTALL_COMPONENT)
set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt")
else()
set(CMAKE_INSTALL_MANIFEST "install_manifest.txt")
endif()
string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT
"${CMAKE_INSTALL_MANIFEST_FILES}")
file(WRITE "/home/york/Program/MachineLearning/nn/two_spiral/src/${CMAKE_INSTALL_MANIFEST}"
"${CMAKE_INSTALL_MANIFEST_CONTENT}")
| SwordYork/MachineLearning | nn/two_spiral/src/cmake_install.cmake | CMake | apache-2.0 | 1,415 |
---
layout: base
title: 'Statistics of Definite in UD_French'
udver: '2'
---
## Treebank Statistics: UD_French: Features: `Definite`
This feature is universal.
It occurs with 2 different values: `Def`, `Ind`.
53514 tokens (13%) have a non-empty value of `Definite`.
29 types (0%) occur at least once with a non-empty value of `Definite`.
6 lemmas (0%) occur at least once with a non-empty value of `Definite`.
The feature is used with 1 part-of-speech tags: <tt><a href="fr-pos-DET.html">DET</a></tt> (53514; 13% instances).
### `DET`
53514 <tt><a href="fr-pos-DET.html">DET</a></tt> tokens (87% of all `DET` tokens) have a non-empty value of `Definite`.
The most frequent other feature values with which `DET` and `Definite` co-occurred: <tt><a href="fr-feat-PronType.html">PronType</a></tt><tt>=Art</tt> (53432; 100%), <tt><a href="fr-feat-Number.html">Number</a></tt><tt>=Sing</tt> (41368; 77%), <tt><a href="fr-feat-Gender.html">Gender</a></tt><tt>=Masc</tt> (28229; 53%).
`DET` tokens may have the following values of `Definite`:
* `Def` (43357; 81% of non-empty `Definite`): <em>le, la, les, l', the, l, là</em>
* `Ind` (10157; 19% of non-empty `Definite`): <em>un, une, des, de, d', telle, in</em>
* `EMPTY` (8225): <em>son, sa, cette, ses, ce, leur, ces, plusieurs, leurs, tous</em>
| UniversalDependencies/docs | treebanks/fr_gsd/fr-feat-Definite.md | Markdown | apache-2.0 | 1,302 |
---
layout: postag
title: 'INTJ'
shortdef: 'interjection'
---
### Definition
An interjection is a word that is used most often as an exclamation or
part of an exclamation. It typically expresses an emotional reaction,
is not syntactically related to other accompanying expressions, and
may include a combination of sounds not otherwise found in the
language.
### Examples
(Note that no direct translation of interjections is possible.
The approximate translations below are for orientation purposes and they
cannot serve to judge the part of speech from the English perspective.)
- _ах _ “oh”
- _ого _ “wow”
- _ну _ “well”
- _ради бога _ “for God's sake”
<!-- Interlanguage links updated St lis 3 20:58:10 CET 2021 -->
| UniversalDependencies/docs | _ru/pos/INTJ.md | Markdown | apache-2.0 | 776 |
# Plesioneuron translucens Holttum SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Thelypteridaceae/Plesioneuron/Plesioneuron translucens/README.md | Markdown | apache-2.0 | 182 |
#include <iostream>
#include <fstream>
#include "disassembly/flowgraph.hpp"
#include "disassembly/functionfeaturegenerator.hpp"
#include "searchbackend/functionsimhashfeaturedump.hpp"
// Writes a DOT file for a given graphlet.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB,
const Flowgraph& graphlet) {
char buf[256];
sprintf(buf, "/var/tmp/%16.16lx%16.16lx.dot", hashA, hashB);
graphlet.WriteDot(std::string(buf));
}
// Writes a JSON file for a given MnemTuple.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB,
const MnemTuple& tuple) {
char buf[256];
sprintf(buf, "/var/tmp/%16.16lx%16.16lx.json", hashA, hashB);
std::ofstream jsonfile;
jsonfile.open(std::string(buf));
jsonfile << "[ " << std::get<0>(tuple) << ", " << std::get<1>(tuple) << ", "
<< std::get<2>(tuple) << " ]" << std::endl;
}
// Writes an immediate that was encountered.
void WriteFeatureDictionaryEntry(uint64_t hashA, uint64_t hashB, uint64_t
immediate) {
std::ofstream immediates;
immediates.open("/var/tmp/immediates.txt",
std::ofstream::out | std::ofstream::app);
immediates << std::hex << hashA << " " << hashB << " " << immediate
<< std::endl;
}
| googleprojectzero/functionsimsearch | searchbackend/functionsimhashfeaturedump.cpp | C++ | apache-2.0 | 1,200 |
/*******************************************************************************
* Copyright 2007-2013 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package xworker.dataObject.http;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
public class DataObjectHttpUtils {
/**
* 通过给定的DataObject从httpRequest中分析参数。
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object parseHttpRequestData(ActionContext actionContext){
DataObject theData = (DataObject) actionContext.get("theData");
Thing self = (Thing) actionContext.get("self");
if(theData == null){
theData = new DataObject(self);
}
HttpServletRequest request = (HttpServletRequest) actionContext.get("request");
Map paramMap = request.getParameterMap();
for(Thing attribute : self.getChilds("attribute")){
String name = attribute.getString("name");
if(paramMap.containsKey(name)){
theData.put(name, request.getParameter(name));
}else if("truefalse".equals(attribute.getString("inputtype"))){
//checkbox特殊处理
theData.put(name, "false");
}
}
return theData;
}
} | x-meta/xworker | xworker_dataobject/src/main/java/xworker/dataObject/http/DataObjectHttpUtils.java | Java | apache-2.0 | 2,037 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 17.11.2006
* Time: 17:36:42
*/
package com.intellij.openapi.vcs.changes.patch;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class PatchFileType implements FileType {
public static final PatchFileType INSTANCE = new PatchFileType();
public static final String NAME = "PATCH";
@NotNull
@NonNls
public String getName() {
return NAME;
}
@NotNull
public String getDescription() {
return VcsBundle.message("patch.file.type.description");
}
@NotNull
@NonNls
public String getDefaultExtension() {
return "patch";
}
@Nullable
public Icon getIcon() {
return AllIcons.Nodes.Pointcut;
}
public boolean isBinary() {
return false;
}
public boolean isReadOnly() {
return false;
}
@Nullable
@NonNls
public String getCharset(@NotNull VirtualFile file, final byte[] content) {
return null;
}
}
| ernestp/consulo | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java | Java | apache-2.0 | 1,803 |
.footer__text {
font-family: Nunito, sans-serif;
font-size: 20px;
color: black;
font-weight: 900;
line-height: 60px;
padding: 0px 00px;
margin: 0px;
text-align: center;
}
.footer__text-right {
text-align: center;
}
@media only screen and (min-width: 320px) {
.footer__text {
}
.footer__text-right {
}
}
@media only screen and (min-width: 480px) {
.footer__text {
}
.footer__text-right {
}
}
@media only screen and (min-width: 768px) {
.footer__text {
}
.footer__text-right {
}
}
@media only screen and (min-width: 992px) {
.footer__text {
}
.footer__text-right {
float: right;
padding: 0px 10px 0px 0px;
}
}
@media only screen and (min-width: 1200px) {
.footer__text {
}
.footer__text-right {
}
} | javimosch/bastack | src/client/ba/css/footer.css | CSS | apache-2.0 | 849 |
package io.ray.streaming.runtime.core.processor;
import io.ray.streaming.message.Record;
import io.ray.streaming.operator.SourceOperator;
/**
* The processor for the stream sources, containing a SourceOperator.
*
* @param <T> The type of source data.
*/
public class SourceProcessor<T> extends StreamProcessor<Record, SourceOperator<T>> {
public SourceProcessor(SourceOperator<T> operator) {
super(operator);
}
@Override
public void process(Record record) {
throw new UnsupportedOperationException("SourceProcessor should not process record");
}
public void fetch() {
operator.fetch();
}
@Override
public void close() {}
}
| pcmoritz/ray-1 | streaming/java/streaming-runtime/src/main/java/io/ray/streaming/runtime/core/processor/SourceProcessor.java | Java | apache-2.0 | 663 |
<div class="row">
<div class="col-md-12 no-padding">
<div class="col-lg-4 col-md-12">
<?php
$this->renderPartial('pod/description',array( "project" => $project, "tags" => $tags, "countries" => $countries,"isAdmin"=> $admin)); ?>
</div>
<div class ="col-lg-4 col-md-12">
<?php
$this->renderPartial('../pod/sliderPhoto', array("itemId" => (string)$project["_id"], "type" => PHType::TYPE_PROJECTS, "isAdmin"=> $admin));
?>
</div>
<div class ="col-lg-4 col-md-12">
<?php $this->renderPartial('pod/contributors',array( "contributors" => $contributors, "organizationTypes" => $organizationTypes, "project" => $project, "admin" => $admin)); ?>
</div>
</div>
<?php if (!empty($tasks) OR $admin==true){ ?>
<div class ="col-lg-8 col-md-8 timesheetphp">
</div>
<?php }
if (!empty($properties) OR $admin==true){ ?>
<div class ="col-lg-4 col-md-12">
<?php $this->renderPartial('pod/projectChart',array("itemId" => (string)$project["_id"], "properties" => $properties, "admin" =>$admin)); ?>
</div>
<?php } ?>
<div class="col-sm-6 col-xs-12 roomsPod">
<div class="panel panel-white pulsate">
<div class="panel-heading border-light ">
<h4 class="panel-title"> <i class='fa fa-cog fa-spin fa-2x icon-big text-center'></i> Loading Rooms Section</h4>
<div class="space5"></div>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12 needsPod">
<!--<div class="panel panel-white pulsate">
<div class="panel-heading border-light ">
<h4 class="panel-title"> <i class='fa fa-cog fa-spin fa-2x icon-big text-center'></i> Loading Something Section</h4>
<div class="space5"></div>
</div>
</div>-->
</div>
<div class="col-sm-6 col-xs-12">
<?php $this->renderPartial('../pod/eventsList',array( "events" => $events,
"contextId" => (String) $project["_id"],
"contextType" => Project::CONTROLLER,
"authorised" => $admin
)); ?>
</div>
</div>
<?php $this->renderPartial('/sig/generic/mapLibs'); ?>
<script type="text/javascript">
var contextMap = {};
contextMap["project"] = <?php echo json_encode($project)?>;
//contextMap["events"] = <?php //echo json_encode($events) ?>;
var idToSend = contextMap["project"]["_id"]["$id"]
contextMap["people"] = <?php echo json_encode($people) ?>;
contextMap["organizations"] = <?php echo json_encode($organizations) ?>;
var images = <?php echo json_encode($images) ?>;
var contentKeyBase = "<?php echo $contentKeyBase ?>";
jQuery(document).ready(function() {
bindBtnFollow();
getAjax(".roomsPod",baseUrl+"/"+moduleId+"/rooms/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>",null,"html");
getAjax(".timesheetphp",baseUrl+"/"+moduleId+"/gantt/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>/isAdmin/<?php echo $admin?>",null,"html");
getAjax(".needsPod",baseUrl+"/"+moduleId+"/needs/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>/isAdmin/<?php echo $admin?>",null,"html");
})
function bindBtnFollow(){
$(".disconnectBtn").off().on("click",function () {
$(this).empty();
$(this).html('<i class=" disconnectBtnIcon fa fa-spinner fa-spin"></i>');
var btnClick = $(this);
var idToDisconnect = $(this).data("id");
var typeToDisconnect = $(this).data("type");
var ownerLink = $(this).data("ownerlink");
var urlToSend = baseUrl+"/"+moduleId+"/person/disconnect/id/"+idToDisconnect+"/type/"+typeToDisconnect+"/ownerLink/"+ownerLink;
if("undefined" != typeof $(this).data("targetlink")){
var targetLink = $(this).data("targetlink");
urlToSend += "/targetLink/"+targetLink;
}
bootbox.confirm("Are you sure you want to delete <span class='text-red'>"+$(this).data("name")+"</span> connection ?",
function(result) {
if (!result) {
btnClick.empty();
btnClick.html('<i class=" disconnectBtnIcon fa fa-unlink"></i>');
return;
}
$.ajax({
type: "POST",
url: urlToSend,
dataType : "json"
})
.done(function (data)
{
if ( data && data.result ) {
toastr.info("LINK DIVORCED SUCCESFULLY!!");
$("#"+typeToDisconnect+idToDisconnect).remove();
$("#linkBtns").empty();
$("#linkBtns").html("<a href='javascript:;' class='connectBtn tooltips ' id='addAttendingRelation' data-placement='top' data-ownerlink='"+ownerLink+"' data-original-title='I contribute to this event' ><i class=' connectBtnIcon fa fa-link '></i>CONTRIBUTE</a></li>");
bindBtnFollow();
} else {
toastr.info("something went wrong!! please try again.");
$(".disconnectBtn").removeClass("fa-spinner fa-spin").addClass("fa-link");
}
});
});
});
$(".connectBtn").off().on("click",function () {
$(".connectBtnIcon").removeClass("fa-link").addClass("fa-spinner fa-spin");
var idConnect = "<?php echo (string)$project['_id'] ?>";
var ownerLink = $(this).data("ownerlink");
var urlToSend = baseUrl+"/"+moduleId+"/person/follows/id/"+idConnect+"/type/<?php echo Project::COLLECTION ?>/ownerLink/"+ownerLink;
if("undefined" != typeof $(this).data("targetlink")){
var targetLink = $(this).data("targetlink");
urlToSend += "/targetLink/"+targetLink;
}
$.ajax({
type: "POST",
url: urlToSend,
dataType : "json"
})
.done(function (data)
{
if ( data && data.result ) {
toastr.info("REALTION APPLIED SUCCESFULLY!! ");
$(".connectBtn").fadeOut();
$("#linkBtns").empty();
$("#linkBtns").html("<a href='javascript:;' class='disconnectBtn text-red tooltips' data-name='"+contextMap["project"]["name"]+" 'data-id='"+contextMap["project"]["_id"]["$id"]+"' data-type='<?php echo Project::COLLECTION ?>' data-ownerlink='"+ownerLink+"' data-placement='top' data-original-title='I no more contributing' ><i class='disconnectBtnIcon fa fa-unlink'></i>UNCONTRIBUTE</a>")
bindBtnFollow();
} else {
toastr.info("something went wrong!! please try again.");
$(".connectBtnIcon").removeClass("fa-spinner fa-spin").addClass("fa-link");
}
});
});
}
</script> | pixelhumain/network | views/project/dashboard.php | PHP | apache-2.0 | 6,465 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<span>Time:</span>
<ul>
<li>From controller: ${time}</li>
<li>From Beetl</li>
</ul>
<span>Message: ${message}</span>
<span>submit: ${submit}</span>
</body>
</html>
| kingsmiler/jeefw | springmvc-examples/springmvc-annotation-beetl/src/main/webapp/WEB-INF/templates/welcome.html | HTML | apache-2.0 | 325 |
/**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.mockito.Mockito.*;
/**
* Tests for {@link PartialSortedKeyStatisticsAttributeIndex}.
*
* @author niall.gallagher
*/
public class PartialSortedKeyStatisticsAttributeIndexTest {
@Test
public void testGetDistinctKeys1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(noQueryOptions());
}
@Test
public void testGetDistinctKeys2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeysDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValues1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(noQueryOptions());
}
@Test
public void testGetKeysAndValues2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetCountForKey() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountForKey(1, noQueryOptions());
verify(backingIndex, times(1)).getCountForKey(1, noQueryOptions());
}
@Test
public void testGetCountOfDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountOfDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getCountOfDistinctKeys(noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeys(noQueryOptions());
}
static PartialSortedKeyStatisticsAttributeIndex<Integer, Car> wrapWithPartialIndex(final SortedKeyStatisticsAttributeIndex<Integer, Car> mockedBackingIndex) {
return new PartialSortedKeyStatisticsAttributeIndex<Integer, Car>(Car.CAR_ID, QueryFactory.between(Car.CAR_ID, 2, 5)) {
@Override
protected SortedKeyStatisticsAttributeIndex<Integer, Car> createBackingIndex() {
return mockedBackingIndex;
}
};
}
@SuppressWarnings("unchecked")
static SortedKeyStatisticsAttributeIndex<Integer, Car> mockBackingIndex() {
return mock(SortedKeyStatisticsAttributeIndex.class);
}
} | npgall/cqengine | code/src/test/java/com/googlecode/cqengine/index/support/PartialSortedKeyStatisticsAttributeIndexTest.java | Java | apache-2.0 | 6,673 |
/*
* Copyright (c) 2010-2013 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.common.policy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.lang.Validate;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordLifeTimeType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
*
* @author mamut
*
*/
public class PasswordPolicyUtils {
private static final transient Trace LOGGER = TraceManager.getTrace(PasswordPolicyUtils.class);
private static final String DOT_CLASS = PasswordPolicyUtils.class.getName() + ".";
private static final String OPERATION_PASSWORD_VALIDATION = DOT_CLASS + "passwordValidation";
/**
* add defined default values
*
* @param pp
* @return
*/
public static void normalize(ValuePolicyType pp) {
if (null == pp) {
throw new IllegalArgumentException("Password policy cannot be null");
}
if (null == pp.getStringPolicy()) {
StringPolicyType sp = new StringPolicyType();
pp.setStringPolicy(StringPolicyUtils.normalize(sp));
} else {
pp.setStringPolicy(StringPolicyUtils.normalize(pp.getStringPolicy()));
}
if (null == pp.getLifetime()) {
PasswordLifeTimeType lt = new PasswordLifeTimeType();
lt.setExpiration(-1);
lt.setWarnBeforeExpiration(0);
lt.setLockAfterExpiration(0);
lt.setMinPasswordAge(0);
lt.setPasswordHistoryLength(0);
}
return;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param policies
* - Password List of policies used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, List <ValuePolicyType> policies, OperationResult result) {
boolean ret=true;
//iterate through policies
for (ValuePolicyType pp: policies) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(String password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password, pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(ProtectedStringType password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password.getClearValue(), pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, ValuePolicyType pp, OperationResult result) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
return op.isSuccess();
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used
* @return - Operation result of this validation
*/
public static OperationResult validatePassword(String password, ValuePolicyType pp) {
// check input params
// if (null == pp) {
// throw new IllegalArgumentException("No policy provided: NULL");
// }
//
// if (null == password) {
// throw new IllegalArgumentException("Password for validaiton is null.");
// }
Validate.notNull(pp, "Password policy must not be null.");
Validate.notNull(password, "Password to validate must not be null.");
OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION);
ret.addParam("policyName", pp.getName());
normalize(pp);
LimitationsType lims = pp.getStringPolicy().getLimitations();
StringBuilder message = new StringBuilder();
// Test minimal length
if (lims.getMinLength() == null){
lims.setMinLength(0);
}
if (lims.getMinLength() > password.length()) {
String msg = "Required minimal size (" + lims.getMinLength() + ") of password is not met (password length: "
+ password.length() + ")";
ret.addSubresult(new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal length
if (lims.getMaxLength() != null) {
if (lims.getMaxLength() < password.length()) {
String msg = "Required maximal size (" + lims.getMaxLength()
+ ") of password was exceeded (password length: " + password.length() + ").";
ret.addSubresult(new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// Test uniqueness criteria
HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password));
if (lims.getMinUniqueChars() != null) {
if (lims.getMinUniqueChars() > tmp.size()) {
String msg = "Required minimal count of unique characters ("
+ lims.getMinUniqueChars()
+ ") in password are not met (unique characters in password " + tmp.size() + ")";
ret.addSubresult(new OperationResult("Check minimal count of unique chars",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult(
// "Check minimal count of unique chars. Password satisfies minimal required unique characters.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// check limitation
HashSet<String> allValidChars = new HashSet<String>(128);
ArrayList<String> validChars = null;
ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password);
if (lims.getLimit() == null || lims.getLimit().isEmpty()){
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
for (StringLimitType l : lims.getLimit()) {
OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription());
if (null != l.getCharacterClass().getValue()) {
validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue());
} else {
validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(pp
.getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef()));
}
// memorize validChars
allValidChars.addAll(validChars);
// Count how many character for this limitation are there
int count = 0;
for (String s : passwd) {
if (validChars.contains(s)) {
count++;
}
}
// Test minimal occurrence
if (l.getMinOccurs() == null){
l.setMinOccurs(0);
}
if (l.getMinOccurs() > count) {
String msg = "Required minimal occurrence (" + l.getMinOccurs()
+ ") of characters ("+l.getDescription()+") in password is not met (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal occurrence
if (l.getMaxOccurs() != null) {
if (l.getMaxOccurs() < count) {
String msg = "Required maximal occurrence (" + l.getMaxOccurs()
+ ") of characters ("+l.getDescription()+") in password was exceeded (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult(
// "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS,
// "PASSED"));
// }
}
// test if first character is valid
if (l.isMustBeFirst() == null){
l.setMustBeFirst(false);
}
if (l.isMustBeFirst() && !validChars.contains(password.substring(0, 1))) {
String msg = "First character is not from allowed set. Allowed set: "
+ validChars.toString();
limitResult.addSubresult(new OperationResult("Check valid first char",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check valid first char in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
limitResult.computeStatus();
ret.addSubresult(limitResult);
}
// Check if there is no invalid character
StringBuilder sb = new StringBuilder();
for (String s : passwd) {
if (!allValidChars.contains(s)) {
// memorize all invalid characters
sb.append(s);
}
}
if (sb.length() > 0) {
String msg = "Characters [ " + sb
+ " ] are not allowed to be use in password";
ret.addSubresult(new OperationResult("Check if password does not contain invalid characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
}
| sabriarabacioglu/engerek | infra/common/src/main/java/com/evolveum/midpoint/common/policy/PasswordPolicyUtils.java | Java | apache-2.0 | 12,321 |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Manifest, type: :model do
let(:monograph) do
create(:public_monograph) do |m|
m.ordered_members << file_set
m.save!
m
end
end
let(:file_set) do
create(:public_file_set) do |f|
f.original_file = original_file
f.save!
f
end
end
let(:original_file) do
Hydra::PCDM::File.new do |f|
f.content = File.open(File.join(fixture_path, 'kitty.tif'))
f.original_name = 'kitty.tif'
f.mime_type = 'image/tiff'
f.file_size = File.size(File.join(fixture_path, 'kitty.tif'))
f.width = 200
f.height = 150
end
end
let(:current_user) { create(:platform_admin) }
# NOTE: #create is dependent on Carrierwave and was not tested.
before do
allow($stdout).to receive(:puts) # Don't print status messages during specs
end
it 'no csv file' do
implicit = described_class.from_monograph(monograph.id)
expect(implicit.id).to eq monograph.id
expect(implicit.persisted?).to be false
expect(implicit.filename).to be nil
explicit = described_class.from_monograph_manifest(monograph.id)
expect(explicit.id).to eq monograph.id
expect(explicit.persisted?).to be false
expect(explicit.filename).to be nil
expect(implicit == explicit).to be false
end
it 'csv file' do
implicit = described_class.from_monograph(monograph.id)
file_dir = implicit.csv.store_dir
FileUtils.mkdir_p(file_dir) unless Dir.exist?(file_dir)
FileUtils.rm_rf(Dir.glob("#{file_dir}/*"))
file_name = "#{monograph.id}.csv"
file_path = File.join(file_dir, file_name)
file = File.new(file_path, "w")
exporter = Export::Exporter.new(monograph.id)
file.write(exporter.export)
file.close
expect(implicit.persisted?).to be true
expect(implicit.filename).to eq file_name
explicit = described_class.from_monograph_manifest(monograph.id)
expect(explicit.persisted?).to be true
expect(explicit.filename).to eq file_name
expect(implicit == explicit).to be true
expect(explicit.table_rows.count).to eq 2
expect(explicit.table_rows[0].count).to eq 4
expect(explicit.table_rows[0][3]["title"].first).to eq monograph.title.first
explicit.table_rows[0][3]["title"] = ["NEW TITLE"]
expect(implicit == explicit).to be false
explicit.destroy(current_user)
expect(implicit.id).to eq monograph.id
expect(implicit.persisted?).to be false
expect(implicit.filename).to be nil
expect(explicit.id).to eq monograph.id
expect(explicit.persisted?).to be false
expect(explicit.filename).to be nil
end
end
| mlibrary/heliotrope | spec/models/manifest_spec.rb | Ruby | apache-2.0 | 2,666 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.linalg;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.family.TType;
/**
* Returns the batched diagonal part of a batched tensor.
* Returns a tensor with the {@code k[0]}-th to {@code k[1]}-th diagonals of the batched
* {@code input}.
* <p>Assume {@code input} has {@code r} dimensions {@code [I, J, ..., L, M, N]}.
* Let {@code max_diag_len} be the maximum length among all diagonals to be extracted,
* {@code max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))}
* Let {@code num_diags} be the number of diagonals to extract,
* {@code num_diags = k[1] - k[0] + 1}.
* <p>If {@code num_diags == 1}, the output tensor is of rank {@code r - 1} with shape
* {@code [I, J, ..., L, max_diag_len]} and values:
* <pre>
* diagonal[i, j, ..., l, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code y = max(-k[1], 0)}, {@code x = max(k[1], 0)}.
* <p>Otherwise, the output tensor has rank {@code r} with dimensions
* {@code [I, J, ..., L, num_diags, max_diag_len]} with values:
* <pre>
* diagonal[i, j, ..., l, m, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code d = k[1] - m}, {@code y = max(-d, 0)}, and {@code x = max(d, 0)}.
* <p>The input must be at least a matrix.
* <p>For example:
* <pre>
* input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)
* [5, 6, 7, 8],
* [9, 8, 7, 6]],
* [[5, 4, 3, 2],
* [1, 2, 3, 4],
* [5, 6, 7, 8]]])
*
* # A main diagonal from each batch.
* tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)
* [5, 2, 7]]
*
* # A superdiagonal from each batch.
* tf.matrix_diag_part(input, k = 1)
* ==> [[2, 7, 6], # Output shape: (2, 3)
* [4, 3, 8]]
*
* # A tridiagonal band from each batch.
* tf.matrix_diag_part(input, k = (-1, 1))
* ==> [[[2, 7, 6], # Output shape: (2, 3, 3)
* [1, 6, 7],
* [5, 8, 0]],
* [[4, 3, 8],
* [5, 2, 7],
* [1, 6, 0]]]
*
* # Padding value = 9
* tf.matrix_diag_part(input, k = (1, 3), padding_value = 9)
* ==> [[[4, 9, 9], # Output shape: (2, 3, 3)
* [3, 8, 9],
* [2, 7, 6]],
* [[2, 9, 9],
* [3, 4, 9],
* [4, 3, 8]]]
* </pre>
*
* @param <T> data type for {@code diagonal} output
*/
@OpMetadata(
opType = MatrixDiagPart.OP_NAME,
inputsClass = MatrixDiagPart.Inputs.class
)
@Operator(
group = "linalg"
)
public final class MatrixDiagPart<T extends TType> extends RawOp implements Operand<T> {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "MatrixDiagPartV2";
private Output<T> diagonal;
public MatrixDiagPart(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
diagonal = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new MatrixDiagPartV2 operation.
*
* @param scope current scope
* @param input Rank {@code r} tensor where {@code r >= 2}.
* @param k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
* @param paddingValue The value to fill the area outside the specified diagonal band with.
* Default is 0.
* @param <T> data type for {@code MatrixDiagPartV2} output and operands
* @return a new instance of MatrixDiagPart
*/
@Endpoint(
describeByClass = true
)
public static <T extends TType> MatrixDiagPart<T> create(Scope scope, Operand<T> input,
Operand<TInt32> k, Operand<T> paddingValue) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "MatrixDiagPart");
opBuilder.addInput(input.asOutput());
opBuilder.addInput(k.asOutput());
opBuilder.addInput(paddingValue.asOutput());
return new MatrixDiagPart<>(opBuilder.build());
}
/**
* Gets diagonal.
* The extracted diagonal(s).
* @return diagonal.
*/
public Output<T> diagonal() {
return diagonal;
}
@Override
public Output<T> asOutput() {
return diagonal;
}
@OpInputsMetadata(
outputsClass = MatrixDiagPart.class
)
public static class Inputs<T extends TType> extends RawOpInputs<MatrixDiagPart<T>> {
/**
* Rank {@code r} tensor where {@code r >= 2}.
*/
public final Operand<T> input;
/**
* Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
*/
public final Operand<TInt32> k;
/**
* The value to fill the area outside the specified diagonal band with.
* Default is 0.
*/
public final Operand<T> paddingValue;
/**
* The T attribute
*/
public final DataType T;
public Inputs(GraphOperation op) {
super(new MatrixDiagPart<>(op), op, Arrays.asList("T"));
int inputIndex = 0;
input = (Operand<T>) op.input(inputIndex++);
k = (Operand<TInt32>) op.input(inputIndex++);
paddingValue = (Operand<T>) op.input(inputIndex++);
T = op.attributes().getAttrType("T");
}
}
}
| tensorflow/java | tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/linalg/MatrixDiagPart.java | Java | apache-2.0 | 7,043 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.control;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.junit.jupiter.api.Test;
import org.zaproxy.zap.control.AddOn.BundleData;
import org.zaproxy.zap.control.AddOn.HelpSetData;
import org.zaproxy.zap.control.AddOn.ValidationResult;
import org.zaproxy.zap.utils.ZapXmlConfiguration;
/** Unit test for {@link AddOn}. */
class AddOnUnitTest extends AddOnTestUtils {
private static final File ZAP_VERSIONS_XML =
getResourcePath("ZapVersions-deps.xml", AddOnUnitTest.class).toFile();
@Test
void testAlpha2UpdatesAlpha1() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnA1));
}
@Test
void testAlpha1DoesNotUpdateAlpha2() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "1"));
assertFalse(addOnA1.isUpdateTo(addOnA2));
}
@Test
void testAlpha2UpdatesBeta1() throws Exception {
AddOn addOnB1 = new AddOn(createAddOnFile("test-beta-1.zap", "beta", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnB1));
}
@Test
void testAlpha2DoesNotUpdateTestyAlpha1() throws Exception {
// Given
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("testy-alpha-2.zap", "alpha", "1"));
// When
IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, () -> addOnA2.isUpdateTo(addOnA1));
// Then
assertThat(e.getMessage(), containsString("Different addons"));
}
@Test
void shouldBeUpdateIfSameVersionWithHigherStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOnHigherStatus.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfSameVersionWithLowerStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOn.isUpdateTo(addOnHigherStatus);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfFileIsNewerWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = newestAddOn.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfFileIsOlderWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = addOn.isUpdateTo(newestAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfOtherAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOn.isUpdateTo(addOnWithoutFile);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfCurrentAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOnWithoutFile.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void testCanLoadAddOnNotBefore() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertFalse(ao.canLoadInVersion("1.4.0"));
assertFalse(ao.canLoadInVersion("2.0.alpha"));
}
@Test
void testCanLoadAddOnNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
ao.setNotFromVersion("2.8.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.8.0"));
assertFalse(ao.canLoadInVersion("2.8.0.1"));
assertFalse(ao.canLoadInVersion("2.9.0"));
}
@Test
void testCanLoadAddOnNotBeforeNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotFromVersion("2.7.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.6.0"));
assertFalse(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.7.0.1"));
assertFalse(ao.canLoadInVersion("2.8.0"));
}
@Test
void shouldNotBeAddOnFileNameIfNull() throws Exception {
// Given
String fileName = null;
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnFileNameIfNotEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.txt";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldBeAddOnFileNameIfEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.zap";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldBeAddOnFileNameEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
String fileName = "addon.ZAP";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldNotBeAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfFileNameNotEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.txt", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfAddOnDoesNotHaveManifestFile() throws Exception {
// Given
Path file = createEmptyAddOnFile("addon.zap");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldBeAddOnIfPathEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldBeAddOnEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
Path file = createAddOnFile("addon.ZAP", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfPathHasNoFileName() throws Exception {
// Given
Path file = Paths.get("/");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfFileDoesNotHaveZapExtension() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zip"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_FILE_NAME)));
}
@Test
void shouldNotBeValidAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNotReadable() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
assumeTrue(
Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class),
"Test requires support for POSIX file attributes.");
Set<PosixFilePermission> perms =
Files.readAttributes(file, PosixFileAttributes.class).permissions();
perms.remove(PosixFilePermission.OWNER_READ);
Files.setPosixFilePermissions(file, perms);
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfNotZipFile() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(
result.getValidity(), is(equalTo(ValidationResult.Validity.UNREADABLE_ZIP_FILE)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfItHasNoManifest() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry("Not a manifest"));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.MISSING_MANIFEST)));
}
@Test
void shouldNotBeValidAddOnIfManifestIsMalformed() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry(AddOn.MANIFEST_FILE_NAME));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_MANIFEST)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfHasMissingLib() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>missing.jar</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldNotBeValidAddOnIfHasLibWithMissingName() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>dir/</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldBeValidAddOnIfValid() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.VALID)));
assertThat(result.getManifest(), is(notNullValue()));
}
@Test
void shouldFailToCreateAddOnFromNullFile() {
// Given
Path file = null;
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_PATH.name()));
}
@Test
void shouldFailToCreateAddOnFromFileWithInvalidFileName() throws Exception {
// Given
String invalidFileName = "addon.txt";
Path file = createAddOnFile(invalidFileName, "alpha", "1");
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_FILE_NAME.name()));
}
@Test
@SuppressWarnings("deprecation")
void shouldCreateAddOnFromFileAndUseManifestData() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "beta", "1.6.7");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.beta)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.6.7")));
assertThat(addOn.getFileVersion(), is(equalTo(1)));
}
@Test
void shouldCreateAddOnWithDotsInId() throws Exception {
// Given
Path file = createAddOnFile("addon.x.zap", "release", "1.0.0");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon.x")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.0.0")));
}
@Test
void shouldIgnoreStatusInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha.zap", "release", "1");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
}
@Test
@SuppressWarnings("deprecation")
void shouldIgnoreVersionInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha-2.zap", "alpha", "3.2.10");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getVersion().toString(), is(equalTo("3.2.10")));
assertThat(addOn.getFileVersion(), is(equalTo(3)));
}
@Test
void shouldReturnNormalisedFileName() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "2.8.1");
AddOn addOn = new AddOn(file);
// When
String normalisedFileName = addOn.getNormalisedFileName();
// Then
assertThat(normalisedFileName, is(equalTo("addon-2.8.1.zap")));
}
@Test
void shouldHaveNoReleaseDate() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
String releaseDate = addOn.getReleaseDate();
// Then
assertThat(releaseDate, is(nullValue()));
}
@Test
void shouldHaveCorrectSize() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
long size = addOn.getSize();
// Then
assertThat(size, is(equalTo(189L)));
}
@Test
void shouldHaveEmptyBundleByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(true)));
assertThat(bundleData.getBaseName(), is(equalTo("")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundle() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle>")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundleWithPrefix() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle prefix=\"msgs\">")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("msgs")));
}
@Test
void shouldHaveEmptyHelpSetByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(true)));
assertThat(helpSetData.getBaseName(), is(equalTo("")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSet() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset>")
.append("org.zaproxy.help.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSetWithLocaleToken() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset localetoken=\"%LC%\">")
.append("org.zaproxy.help%LC%.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help%LC%.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("%LC%")));
}
@Test
void shouldDependOnDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(dependency);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDependIfNoDependencies() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("AddOn-release-1.zap", "release", "1"));
AddOn nonDependency = createAddOn("AddOn3", createZapVersionsXml());
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDirectDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnItSelf() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn sameAddOn = createAddOn("AddOn1", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(sameAddOn);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldDependOnDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, dependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, nonDirectDependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency1 = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency2 = createAddOn("AddOn9", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency1, nonDependency2});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldBeUpdateToOlderVersionIfNewer() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = newerAddOn.isUpdateTo(olderAddOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateToNewerVersionIfOlder() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = olderAddOn.isUpdateTo(newerAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeAbleToRunIfItHasNoMinimumJavaVersion() throws Exception {
// Given
String minimumJavaVersion = null;
String runningJavaVersion = "1.8";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MajorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MinorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldNotBeAbleToRunInJava9MajorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldNotBeAbleToRunInJava9MinorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldReturnLibsInManifest() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "dir/lib2.jar";
Path file = createAddOnWithLibs(lib1, lib2);
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getLibs(), contains(new AddOn.Lib(lib1), new AddOn.Lib(lib2)));
}
@Test
void shouldNotBeRunnableIfLibsAreNotInFileSystem() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnWithLibs("lib1.jar", "lib2.jar"));
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(false)));
assertThat(reqs.hasMissingLibs(), is(equalTo(true)));
assertThat(reqs.getAddOnMissingLibs(), is(equalTo(addOn)));
}
@Test
void shouldBeRunnableIfLibsAreInFileSystem() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "lib2.jar";
AddOn addOn = new AddOn(createAddOnWithLibs(lib1, lib2));
Path libsDir = newTempDir("libsDir");
addOn.getLibs().get(0).setFileSystemUrl(libsDir.resolve(lib1).toUri().toURL());
addOn.getLibs().get(1).setFileSystemUrl(libsDir.resolve(lib2).toUri().toURL());
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(true)));
assertThat(reqs.hasMissingLibs(), is(equalTo(false)));
assertThat(reqs.getAddOnMissingLibs(), is(nullValue()));
}
@Test
void shouldCreateAddOnLibFromRootJarPath() throws Exception {
// Given
String jarPath = "lib.jar";
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(jarPath)));
}
@Test
void shouldCreateAddOnLibFromNonRootJarPath() throws Exception {
// Given
String name = "lib.jar";
String jarPath = "dir/" + name;
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(name)));
}
@Test
void shouldNotHaveFileSystemUrlInAddOnLibByDefault() throws Exception {
// Given / When
AddOn.Lib lib = new AddOn.Lib("lib.jar");
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
@Test
void shouldSetFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
URL fsUrl = new URL("file:///some/path");
// When
lib.setFileSystemUrl(fsUrl);
// Then
assertThat(lib.getFileSystemUrl(), is(equalTo(fsUrl)));
}
@Test
void shouldSetNullFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
lib.setFileSystemUrl(new URL("file:///some/path"));
// When
lib.setFileSystemUrl(null);
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
private static ZapXmlConfiguration createZapVersionsXml() throws Exception {
ZapXmlConfiguration zapVersionsXml = new ZapXmlConfiguration(ZAP_VERSIONS_XML);
zapVersionsXml.setExpressionEngine(new XPathExpressionEngine());
return zapVersionsXml;
}
}
| zaproxy/zaproxy | zap/src/test/java/org/zaproxy/zap/control/AddOnUnitTest.java | Java | apache-2.0 | 36,238 |
package com.qinyadan.monitor.network.util;
import java.util.Map;
import com.qinyadan.monitor.network.control.ControlMessageDecoder;
import com.qinyadan.monitor.network.control.ControlMessageEncoder;
import com.qinyadan.monitor.network.control.ProtocolException;
public final class ControlMessageEncodingUtils {
private static final ControlMessageEncoder encoder = new ControlMessageEncoder();
private static final ControlMessageDecoder decoder = new ControlMessageDecoder();
private ControlMessageEncodingUtils() {
}
public static byte[] encode(Map<String, Object> value) throws ProtocolException {
return encoder.encode(value);
}
public static Object decode(byte[] in) throws ProtocolException {
return decoder.decode(in);
}
}
| O2O-Market/Market-monitor | market-network/src/main/java/com/qinyadan/monitor/network/util/ControlMessageEncodingUtils.java | Java | apache-2.0 | 809 |
<h2>Ask a question:</h2>
<div class="question-form">
<mat-form-field>
<mat-label>Your question:</mat-label>
<textarea
maxlength="280"
style="height: 120px;"
required
matInput
#q
(keydown.control.enter)="addQuestion(q)"
(keydown.command.enter)="addQuestion(q)"
></textarea>
</mat-form-field>
<button
mat-raised-button
[disabled]="q.value.trim() === ''"
(click)="addQuestion(q)"
>
Submit
</button>
</div>
<ng-container *ngIf="questionsService.requireApproval$ | async">
<ng-container
*ngIf="questionsService.myUnapprovedQuestions$ | async as unapproved"
>
<mat-expansion-panel *ngIf="unapproved.length">
<mat-expansion-panel-header>
<mat-panel-title>
Your questions pending approval: {{ unapproved.length }}
</mat-panel-title>
</mat-expansion-panel-header>
<ng-container *ngFor="let question of unapproved">
<codelab-question
[question]="question"
[showControls]="false"
></codelab-question>
</ng-container>
</mat-expansion-panel>
</ng-container>
</ng-container>
<ng-container *ngIf="questionsService.publicQuestions$ | async as questions">
<ng-container *ngIf="questions.length">
<h2>All questions:</h2>
<codelab-question
*ngIf="questionsService.starredQuestion$ | async as question"
tabindex="0"
[question]="question"
class="starred"
></codelab-question>
<codelab-question-list [questions]="questions"></codelab-question-list>
</ng-container>
</ng-container>
| nycJSorg/angular-presentation | libs/utils/src/lib/sync/components/questions/questions-viewer/questions-viewer.component.html | HTML | apache-2.0 | 1,591 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.